Compare commits

...
390 Commits
Author SHA1 Message Date
Denys Vlasenko 1a64f6a20a Bump version to 1.36.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-05-19 00:31:04 +02:00
Akos Somfai 38d2d26a5f lineedit: fix crash when icanon set with -echo
When icanon is set with -echo (e.g. ssh from an emacs shell) then
S.state will remain null but later it will be deferenced causing ash to
crash. Fix: additional check on state.

Signed-off-by: Akos Somfai <akos.somfai@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko 384cd2e436 sleep: fix error exit when called as "sh" builtin
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko ce839dea92 ash: fix sleep built-in not running INT trap immediately on ^C
function                                             old     new   delta
sleep_for_duration                                   169     149     -20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko d661cb1977 ash: sleep builtin with no arguments should not exit
function                                             old     new   delta
sleep_main                                           116     143     +27
.rodata                                           105245  105268     +23
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 50/0)               Total: 50 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko 515adcc9f3 hush: printf builtin with no arguments should not exit
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko 90f5f2a190 ash: fix still-broken new mail detection
padvance() exit condition is return value < 0, not == 0.
After MAIL changing twice, the logic erroneously
concluded that "you have new mail".

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko 07bc5de67b ash: fix broken new mail detection
Mea culpa, in "Do not allocate stack string in padvance" commit
(I left an extraneous "break" statement).

function                                             old     new   delta
cmdloop                                              329     398     +69

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Ron Yorston 64e967fabb lineedit: fix matching of directories when searching PATH
Commit 8baa643a3 (lineedit: match local directories when searching
PATH) included subdirectories of the current directory in the search
when tab-completing commands.

Unfortunately a short time later commit 1d180cd74 (lineedit: use
strncmp instead of is_prefixed_with (we know the length)) broke
this feature by returning an incorrect length for the array of paths.

Fix the length and reinstate matching of subdirectories.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-04-25 16:47:22 +02:00
Denys Vlasenko 8d198665a0 libbb/sha: fix sha-NI instruction detection
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-03-29 15:50:40 +02:00
Denys Vlasenko c0bb90e2fe unzip: clear SUID/GID bits, implement -K to not clear them
function                                             old     new   delta
unzip_main                                          2656    2715     +59
packed_usage                                       34517   34552     +35
.rodata                                           105250  105251      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 95/0)               Total: 95 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-03-28 17:42:00 +02:00
Sören Tempel f15dfd86c4 ed: don't use memcpy with overlapping memory regions
The memcpy invocations in the subCommand function, modified by this
commit, previously used memcpy with overlapping memory regions. This is
undefined behavior. On Alpine Linux, it causes BusyBox ed to crash since
we compile BusyBox with -D_FORTIFY_SOURCE=2 and our fortify-headers
implementation catches this source of undefined behavior [0]. The issue
can only be triggered if the replacement string is the same size or
shorter than the old string.

Looking at the code, it seems to me that a memmove(3) is what was
actually intended here, this commit modifies the code accordingly.

[0]: https://gitlab.alpinelinux.org/alpine/aports/-/issues/13504

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-05 16:26:49 +01:00
Denys Vlasenko 70f77e4617 Bump version to 1.36.0
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-03 15:15:41 +01:00
Denys Vlasenko 969e008168 hush: code shrink
function                                             old     new   delta
run_list                                            1032    1012     -20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-03 14:08:18 +01:00
Denys Vlasenko d488a5218b ash: trivial code shrink
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-03 13:39:14 +01:00
Denys Vlasenko bcb90b9c41 xxd: use bb_simple_perror_msg... where appropriate
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-03 08:30:12 +01:00
Denys Vlasenko 27be0e8cfe shell: fix compile failures in some configs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-03 08:28:16 +01:00
Denys Vlasenko 8ed57db65b Makefile.flags: add resolv to LDLIBS for linux compilers too (not only gnu ones)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 17:10:04 +01:00
Denys Vlasenko 9b2d766e0e sed: fix double-free in FEATURE_CLEAN_UP=y configs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 17:05:55 +01:00
Denys Vlasenko cadf57b3af mv: fix error in !VERBOSE configs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 17:04:44 +01:00
Denys Vlasenko e7977df2ca libbb/loop: fix compile failure (name collision)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 17:03:44 +01:00
Denys Vlasenko fb0c000567 testsuite/sha1sum.tests: fix false positive failure
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 17:02:17 +01:00
Denys Vlasenko dc068abad5 testsuite/tree.tests: fix false positive failure
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 17:01:14 +01:00
Denys Vlasenko adb1c7dcfe xxd: fix use of non-initialized data
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2023-01-02 16:59:40 +01:00
Denys Vlasenko c4d296aa7c xargs: implement -o, closes 15146
function                                             old     new   delta
.rodata                                           105225  105259     +34
d6_listen_socket                                     150     180     +30
packed_usage                                       34512   34532     +20
d6_read_interface                                    595     581     -14
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 84/-14)             Total: 70 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-22 10:38:08 +01:00
Denys Vlasenko 02ca565646 udhcpc6: fix binding to network aliases
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-15 23:57:27 +01:00
Denys Vlasenko 6c2ddf808e udhcp: add a few comments, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-15 13:34:52 +01:00
Denys Vlasenko 242d056230 udhcpc6: use a different default config script
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-15 11:51:16 +01:00
Denys Vlasenko 301ef96892 udhcpc6: align FF02__1_2[]
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-15 11:49:00 +01:00
Natanael Copa 3636d52cbe more: accept and ignore -e
Accept and ignore -e which is specified in POSIX.
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/more.html

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-14 16:05:43 +01:00
Denys Vlasenko e977853e70 udhcpc6: add some comments
RFCs for DHCPv6 are written rather badly...

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-14 00:36:59 +01:00
Denys Vlasenko 9898db4c94 udhcpc6: remove stray comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-13 23:21:59 +01:00
Denys Vlasenko 7710250e4a libbb: shrink del_loop()
function                                             old     new   delta
del_loop                                              52      49      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-13 16:00:00 +01:00
Denys Vlasenko a55bd1c484 loop: restore the correct return vaule of set_loop()
It is only used by mount's error path, though...

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-13 15:52:52 +01:00
Denys Vlasenko 45734a2351 loop: optionally use ioctl(LOOP_CONFIGURE) to set up loopdevs
LOOP_CONFIGURE is added to Linux 5.8

function                                             old     new   delta
NO_LOOP_CONFIGURE (old code):
set_loop                                             784     782      -2
LOOP_CONFIGURE:
set_loop                                             784     653    -131
TRY_LOOP_CONFIGURE:
set_loop                                             784     811     +27

Based on a patch by Xiaoming Ni <nixiaoming@huawei.com>

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-13 15:21:28 +01:00
Denys Vlasenko 9df54deead testsuite/mount.tests: accomodate umount failure seen on 5.18.0
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-13 15:12:31 +01:00
Xiaoming Ni a1856934ba loop: refactor: extract subfunction set_loopdev_params()
Extract subfunction set_loop_info() from set_loop()

function                                             old     new   delta
set_loop                                             760     784     +24

Signed-off-by: Xiaoming Ni <nixiaoming@huawei.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-13 14:26:20 +01:00
Xiaoming Ni 7dc76c9f21 loop: simplify code of LOOP_SET_FD failure
function                                             old     new   delta
set_loop                                             790     760     -30

Signed-off-by: Xiaoming Ni <nixiaoming@huawei.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-12 19:03:06 +01:00
Xiaoming Ni ddccf6cd2f loop: refactor: extract subfunction get_next_free_loop()
Extract subfunction get_next_free_loop() from set_loop()

Also fix miss free(try) when stat(try) and mknod fail

function                                             old     new   delta
set_loop                                             807     790     -17

Fixes: 3448914e8cc5 ("mount,losetup: use /dev/loop-control is it exists")
Signed-off-by: Xiaoming Ni <nixiaoming@huawei.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-12 18:57:09 +01:00
Brandon Maier 90456a6aa3 xxd: fix typo in trivial usage
Signed-off-by: Brandon Maier <brandon.maier@collins.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-12-08 17:13:11 +01:00
Peter Kaestle 7ade421b1a unzip -l: add missed big-endian conversions date and time
When calling unzip -l the date and time output was missing big-endian
conversions.

Signed-off-by: Peter Kaestle <peter.kaestle@nokia.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-11-29 14:44:39 +01:00
Denys Vlasenko 99476502f9 Remove "select PLATFORM_LINUX"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-11-29 14:14:06 +01:00
Samuel Thibault 77216c368f Fix non-Linux builds
Various tools are Linuxish and should thus only attempted to build on
Linux only. Some features are also Linux-only.

Also, libresolv is used on all GNU platforms, notably GNU/Hurd and
GNU/kfreeBSD.

Signed-off-by: Samuel Thibault <samuel.thibault@ens-lyon.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-11-29 14:10:22 +01:00
Dario Binacchi 75fbff1326 fbset: support setting pixel clock rate
Only in case the FEATURE_FBSET_FANCY configuration is enabled.

function                                             old     new   delta
fbset_main                                           733     766     +33

Signed-off-by: Dario Binacchi <dario.binacchi@amarulasolutions.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-11-16 13:40:34 +01:00
Dario Binacchi e8dfa0c1be fbset: abort on not handled options
Not all options are actually implemented. In this case, return a message
and an error code to make it clear that the requested command has not
been executed.

function                                             old     new   delta
.rodata                                           105200  105224     +24
fbset_main                                           747     733     -14
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 24/-14)             Total: 10 bytes

Signed-off-by: Dario Binacchi <dario.binacchi@amarulasolutions.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-11-16 13:39:35 +01:00
Xiaoming Ni cb8d2ea8c9 loop: fix a race when a free loop device is snatched
When /dev/loop-control exists and *device is empty,
the mount may fail if a concurrent mount is running.

function                                             old     new   delta
set_loop                                             809     807      -2

Signed-off-by: Xiaoming Ni <nixiaoming@huawei.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-11-15 14:54:05 +01:00
Louis Sautier 707a7ef4c7 pkill: add -e to display the name and PID of the process being killed
This mimics the behaviour of pkill -e / --echo from procps.

function                                             old     new   delta
.rodata                                           105179  105200     +21
packed_usage                                       34523   34516      -7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 21/-7)              Total: 14 bytes

Signed-off-by: Louis Sautier <sautier.louis@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-10-14 14:33:34 +02:00
Denys Vlasenko c8c1fcdba1 tls: move definitions around, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-09-08 16:56:54 +02:00
Denys Vlasenko 9bab580cd4 tls: include signature_algorithms extension in client hello message
function                                             old     new   delta
tls_xread_record                                     629     645     +16
.rodata                                           105167  105179     +12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 28/0)               Total: 28 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-09-08 16:31:44 +02:00
Ludwig Nussel 526625bc83 libbb: mark stack in assembly files read-only
Signed-off-by: Ludwig Nussel <ludwig.nussel@suse.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-30 17:21:53 +02:00
Denys Vlasenko dd79e1d4d3 fix [ --help ] and [[ --help ]]
function                                             old     new   delta
show_usage_if_dash_dash_help                          72      79      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-30 17:12:34 +02:00
Denys Vlasenko fe73c8d557 *: style fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-30 16:41:17 +02:00
Shawn Landden 58598eb709 ash: optional sleep builtin
function                                             old     new   delta
sleepcmd                                               -      10     +10
builtintab                                           352     360      +8
.rodata                                           105264  105271      +7
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/0 up/down: 25/0)               Total: 25 bytes

Signed-off-by: Shawn Landden <shawnlandden@tutanota.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-27 19:56:21 +02:00
Aaro Koskinen d432049f28 devmem: add 128-bit width
Add 128-bit width if the compiler provides the needed type.

function                                             old     new   delta
devmem_main                                          405     464     +59
.rodata                                           109025  109043     +18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 77/0)               Total: 77 bytes

Signed-off-by: Aaro Koskinen <aaro.koskinen@nokia.com>
Signed-off-by: Aaro Koskinen <aaro.koskinen@iki.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-26 17:09:47 +02:00
Denys Vlasenko 1a1220a5b0 tree: unicode tweak (use normal space char, 0x20)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-26 14:54:45 +02:00
Denys Vlasenko b30d345cfd tree: make it unicode-aware
function                                             old     new   delta
tree_print                                           396     420     +24
.rodata                                           105251  105266     +15
tree_main                                             86      91      +5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 44/0)               Total: 44 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-26 14:41:42 +02:00
Denys Vlasenko 5eceafb1f8 xxd -r: handle offsets
function                                             old     new   delta
xxd_main                                            1076    1439    +363
.rodata                                           105239  105251     +12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 375/0)             Total: 375 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-22 17:28:43 +02:00
Denys Vlasenko 0011a6bc20 xxd: add two more testcases
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-22 15:57:57 +02:00
Denys Vlasenko f318adaaab xxd -r: without -p, stop at more than one whitespace, closes 14786
function                                             old     new   delta
xxd_main                                             888    1076    +188

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-22 15:40:47 +02:00
Ron Yorston 5a9d2b6e02 libbb: make '--help' handling more consistent
Running an applet with '--help' as its only argument is treated
as a special case.  If additional arguments follow '--help' the
behaviour is inconsistent:

- applets which call single_argv() print help and do nothing else;

- applets which call getopt() report "unrecognized option '--help'"
  and print help anyway;

- expr says "expr: syntax error" and doesn't print help;

- printenv silently ignores '--help', prints any other variables
  and doesn't print help;

- realpath says "--help: No such file or directory", prints the path
  of any other files and doesn't print help.

If the first argument is '--help' ignore any other arguments and print
help.  This is more consistent and most likely what the user wanted.

See also commit 6bdfbc4cb (libbb: fix '--help' handling in
FEATURE_SH_NOFORK=y).

function                                             old     new   delta
show_usage_if_dash_dash_help                          75      69      -6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-6)               Total: -6 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-22 14:05:01 +02:00
Denys Vlasenko 41d5f800a1 bc: hopefully fix bug 14956 (use-after-free)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-18 16:23:55 +02:00
Sören Tempel 7c2a3bdde0 ash: fix use-after-free in bash pattern substitution
function                                             old     new   delta
subevalvar                                          1566    1564      -2

Signed-off-by: Sören Tempel <soeren@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 18:27:41 +02:00
Denys Vlasenko 84b89b4c22 udhcpc6: downgrade "opening listen socket" log level to 2
This matches udhcpc for IPv4.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 18:04:51 +02:00
Denys Vlasenko 75aaa8b311 udhcpc6: fix sending of renew messages
function                                             old     new   delta
d6_listen_socket                                       -     150    +150

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 15:33:51 +02:00
Grob Grobmann 3147552a23 vi: add 'ZQ' quitting command
Busybox vi provides the 'ZZ' command to save and close
the similar 'ZQ' command just exits without saving.

function                                             old     new   delta
do_cmd                                              4222    4244     +22

Signed-off-by: Grob Grobmann <grobgrobmann@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 15:05:12 +02:00
Henrique Rodrigues 9eddf164bf ping: fix typo in --help text
Signed-off-by: Henrique Rodrigues <henrique.rodrigues@ist.utl.pt>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 14:34:38 +02:00
Denys Vlasenko daa66ed62c ash: fix use-after-free in pattern substituon code
Patch by soeren@soeren-tempel.net

The idx variable points to a value in the stack string (as managed
by STPUTC). STPUTC may resize this stack string via realloc(3). If
this happens, the idx pointer needs to be updated. Otherwise,
dereferencing idx may result in a use-after free.

function                                             old     new   delta
subevalvar                                          1562    1566      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 12:41:18 +02:00
Denys Vlasenko 1c54552842 ash: fix ifs cleanup on error paths
Patch by Alex Gorinson <algore3698@gmail.com>

function                                             old     new   delta
evalvar                                              477     495     +18
varvalue                                             603     618     +15
subevalvar                                          1557    1572     +15
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 48/0)               Total: 48 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-08-02 11:18:11 +02:00
Denys Vlasenko 5479c435fd sort: fix sort -s -u, closes 14871
function                                             old     new   delta
sort_main                                            851     856      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-29 16:40:00 +02:00
Denys Vlasenko 00f2a35b83 sort: fix -k2M (wasn't skipping leading whitespace)
function                                             old     new   delta
compare_keys                                         848     862     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-29 16:05:50 +02:00
Denys Vlasenko 9b6eb2a8ef udhcpc6: add missed big-endian conversions
function                                             old     new   delta
option_to_env                                        686     694      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-13 16:15:04 +02:00
Denys Vlasenko 7b969bb2ad tls: P256: remove NOP macro sp_256_norm_8()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-13 16:11:17 +02:00
Natanael Copa e63d7cdfda awk: fix use after free (CVE-2022-30065)
fixes https://bugs.busybox.net/show_bug.cgi?id=14781

function                                             old     new   delta
evaluate                                            3343    3357     +14

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-11 17:18:07 +02:00
Denys Vlasenko 3ad3aa6441 shaNNNsum: accept one-space "HASH FILENAME" format for -c, closes 14866
function                                             old     new   delta
md5_sha1_sum_main                                    496     501      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-11 14:36:39 +02:00
Ron Yorston 298ac9507b lineedit: get PWD from ash
The line editing code and ash disagree when the current directory
is changed to a symbolic link:

   ~ $ mkdir real
   ~ $ ln -s real link
   ~ $ cd link
   ~/real $ pwd
   /home/rmyf36/link

Note the prompt says we're in ~/real.  Bash does:

   [rmy@random ~]$ cd link
   [rmy@random link]$ pwd
   /home/rmyf36/link

Ash uses the name supplied by the user while the line editing code
calls getcwd(3).  The discrepancy can be avoided by fetching the
value of PWD from ash.

Hush calls getcwd(3) when the directory is changed
so there's no disagreement with the line editing code.

There is no standard how shells should handle cd'ing into
symlinks.

function                                             old     new   delta
parse_and_put_prompt                                 838     869     +31

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-07-03 21:41:38 +02:00
Roger Knecht 20a4f70eca tree: new applet
Adds the tree program to list directories and files in a tree structure.

function                                             old     new   delta
tree_print                                             -     343    +343
scandir64                                              -     330    +330
scandir                                                -     330    +330
tree_main                                              -      86     +86
.rodata                                           105150  105228     +78
packed_usage                                       34511   34557     +46
alphasort64                                            -      31     +31
alphasort                                              -      31     +31
strcoll                                                -       5      +5
applet_names                                        2801    2806      +5
applet_main                                         1616    1620      +4
applet_suid                                          101     102      +1
applet_install_loc                                   202     203      +1
------------------------------------------------------------------------------
(add/remove: 11/0 grow/shrink: 6/0 up/down: 1291/0)          Total: 1291 bytes

Signed-off-by: Roger Knecht <rknecht@pm.me>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-06-30 17:18:12 +02:00
Ron Yorston 2617a5e4c6 vi: handle autoindent in 'cc' command
When the 'cc' command is invoked with autoindent enabled it
should use the indent of the first line being changed.

The size of the indent has to be established before char_insert()
is called as the lines being changed are deleted.  Introduce a
new global variable, newindent, to handle this.  The indentcol
global is now effectively a static variable in char_insert().

function                                             old     new   delta
do_cmd                                              4247    4308     +61
vi_main                                              416     422      +6
char_insert                                          891     875     -16
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 67/-16)             Total: 51 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-06-26 19:38:31 +02:00
Ron Yorston af3b585815 vi: fix regression in autoindent handling
Suppose autoindent is enabled and we have a line with an initial
tab where we want to split the words onto separate lines:

	split the words

One way to do this is with the sequence 'f r<CR>;r<CR>', but in
BusyBox vi the result is:

	split

	he
words

This is a regression introduced by commit 9659a8db1 (vi: remove
autoindent from otherwise empty lines).  The amount of indentation
is being recorded when the 'r' command inserts a newline but
isn't subsequently reset.  A fix is to only record the indent
when in insert or replace mode.  Proper handling of the 'o' and
'O' commands then requires them to switch to insert mode before
calling char_insert() to insert a newline.

function                                             old     new   delta
char_insert                                          884     891      +7
do_cmd                                              4243    4247      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-06-26 19:38:28 +02:00
Ron Yorston 7d1c7d8337 ash,hush: use HOME for tab completion and prompts
ash and hush correctly use the value of HOME for tilde expansion.
However the line editing code in libbb obtains the user's home
directory by calling getpwuid().  Thus tildes in tab completion
and prompts may be interpreted differently than in tilde expansion.

When the line editing code is invoked from a shell make it use the
shell's interpretation of tilde.  This is similar to how GNU readline
and bash collaborate.

function                                             old     new   delta
get_homedir_or_NULL                                   29      72     +43
optschanged                                          119     126      +7
hush_main                                           1204    1211      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 57/0)               Total: 57 bytes

v2: Always check for HOME before trying the password database:  this
    is what GNU readline does.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-06-26 18:05:50 +02:00
Ron Yorston 95fec31be6 libbb: restore special handling of nomsg errors
The functions bb_perror_nomsg() and bb_perror_nomsg_and_die() are
used to print error messages where no specific information is
available.  For example:

   $ busybox mktemp -p /
   mktemp: (null): Permission denied

mktemp(3) doesn't tell us the name of the file it tried to create.

However, printing '(null)' is a regression introduced by commit
6937487be (libbb: reduce the overhead of single parameter bb_error_msg()
calls).  Restore the previous behaviour by reverting the changes to
the two functions mentioned:

   $ busybox mktemp -p /
   mktemp: Permission denied

function                                             old     new   delta
bb_perror_nomsg_and_die                                7      14      +7
bb_perror_nomsg                                        7      14      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 14/0)               Total: 14 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-06-26 17:17:02 +02:00
Denys Vlasenko 8d67007a4d top: improve large PID display in memory ('s') mode
function                                             old     new   delta
display_topmem_process_list                          530     564     +34

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-12 11:44:47 +02:00
Denys Vlasenko b9c2108b26 examples/var_service/dhcp_if: make helper scripts more talkative
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-12 11:07:12 +02:00
Denys Vlasenko 1099a27696 top: code shrink
function                                             old     new   delta
display_process_list                                1186    1168     -18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-10 14:04:34 +02:00
Denys Vlasenko 69f82e305b top: code shrink
function                                             old     new   delta
display_process_list                                1191    1186      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-10 13:51:09 +02:00
Denys Vlasenko 294881d2e9 top: fix display of large PID/PPID
function                                             old     new   delta
display_process_list                                1077    1191    +114
.rodata                                           104803  104807      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 118/0)             Total: 118 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-10 12:56:28 +02:00
Denys Vlasenko 67fd6be0bb seedrng: do not hash in a constant string, it's not adding entropy
function                                             old     new   delta
seedrng_main                                         906     880     -26
.rodata                                           104899  104873     -26
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-52)             Total: -52 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-03 12:48:50 +02:00
Denys Vlasenko 3bfbcb5807 seedrng: restore error check on fsync
Or else security people will never stop nagging us.

function                                             old     new   delta
seedrng_main                                         884     906     +22

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-02 15:03:32 +02:00
Denys Vlasenko 5ba56e8b95 seedrng: it's not a part of util-linux, move to miscutils
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-02 14:53:14 +02:00
Denys Vlasenko 1a290f889c init: do not set HOME
function                                             old     new   delta
.rodata                                           104906  104899      -7
init_main                                            786     776     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-17)             Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-02 14:47:53 +02:00
David Leonard 4642cf5b38 tsort: new applet
function                                             old     new   delta
tsort_main                                             -     578    +578
.rodata                                           104884  104906     +22
applet_names                                        2759    2765      +6
applet_main                                         1596    1600      +4
packed_usage                                       34290   34288      -2
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 3/1 up/down: 610/-2)            Total: 608 bytes

Signed-off-by: David Leonard <d+busybox@adaptive-enterprises.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-02 14:25:36 +02:00
Paul Fox 52a7bf6fa6 crond: implement support for setting PATH in crontab files
It's very inconvenient for a cron user not to be able to set a
"personal" PATH for their cron jobs, as is possible with other crons

function                                             old     new   delta
load_crontab                                         868     942     +74
.rodata                                           104878  104884      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 80/0)               Total: 80 bytes

Signed-off-by: Paul Fox <pgf@foxharp.boston.ma.us>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-02 12:28:48 +02:00
Denys Vlasenko 9b6f44e040 style fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 17:06:00 +02:00
Bernhard Reutner-Fischer a157c4c978 seedrng: manually inline seed_rng
We can now remove a separate buffer

function                                             old     new   delta
seedrng_main                                         930     884     -46

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 17:02:20 +02:00
Denys Vlasenko 54867fec12 seedrng: shorten --help, assorted small cleanups
function                                             old     new   delta
packed_usage                                       34295   34290      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 16:51:06 +02:00
Denys Vlasenko b5624be6df seedrng: reduce MAX_SEED_LEN from 512 to 256
As proposed by Jason.
getrandom() is more likely to block on reads larger than this.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 16:37:39 +02:00
Denys Vlasenko 7471658038 seedrng: do not hash lengths, they are very predictable
function                                             old     new   delta
seedrng_main                                         982     930     -52

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 02:06:20 +02:00
Denys Vlasenko fb4546c7af seedrng: code shrink
function                                             old     new   delta
seedrng_main                                         994     982     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 01:58:57 +02:00
Denys Vlasenko d5bd2e57a7 seedrng: explain why we need locking and fsync'ing
Also, do not test for locking errors: on Linux, they do not happen.

function                                             old     new   delta
.rodata                                           104900  104878     -22
seedrng_main                                        1022     994     -28

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-05-01 01:50:44 +02:00
Denys Vlasenko 0bca489b24 seedrng: remove redundant assignment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 23:53:28 +02:00
Denys Vlasenko 4648754119 seedrng: re-add fsync after unlink, and explain its purpose
function                                             old     new   delta
seedrng_main                                        1003    1022     +19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 23:17:58 +02:00
Denys Vlasenko 267178c628 seedrng: include fiel/dir names in error messages
function                                             old     new   delta
.rodata                                           104898  104900      +2
seedrng_main                                        1011    1003      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 2/-8)               Total: -6 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 15:50:45 +02:00
Denys Vlasenko d49da38aa3 seedrng: use more xfuncs where appropriate
function                                             old     new   delta
.rodata                                           104929  104898     -31
seedrng_main                                        1050    1011     -39

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 15:45:53 +02:00
Denys Vlasenko 2cbfd01c15 seedrng: code shrink
Struct initializers do this double init:
># util-linux/seedrng.c:88:              struct pollfd random_fd = {
        movl    $0, 132(%esp)   #, random_fd
        movl    $0, 136(%esp)   #, random_fd
...
># util-linux/seedrng.c:88:              struct pollfd random_fd = {
        movl    %eax, 140(%esp) # _110, random_fd.fd
        movw    $1, 144(%esp)   #, random_fd.events

and close(random_fd.fd) needs to pull the item from the stack:
        pushl   132(%esp)       # random_fd.fd
        call    close   #

function                                             old     new   delta
seedrng_main                                        1076    1050     -26

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 15:38:44 +02:00
Denys Vlasenko 52f3cf7e5f seedrng: simplify read_new_seed() to not have error return
gcc in fact detects this and does this transformation
when generating code - no object code changes.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 15:33:28 +02:00
Denys Vlasenko 282b61a649 seedrng: prepare read_new_seed() to not need a "success" retval
We do not expect /dev/[u]random to be not openable/readable.
If they are, just bail out (something is obviously very wrong).

function                                             old     new   delta
seedrng_main                                        1077    1076      -1
.rodata                                           104939  104929     -10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 15:25:55 +02:00
Denys Vlasenko 0fa16fc7a2 seedrng: do not try to continue on unexpected errors (just exit)
function                                             old     new   delta
.rodata                                           104946  104938      -8
seedrng_main                                        1225    1077    -148
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-156)           Total: -156 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 15:17:32 +02:00
Denys Vlasenko 002d6ee46d ifplugd: split -a into -a and -A, latter disables upping in iface creation
-a meant both "don't up iface before each link detection" and "don't up iface
when it newly appears". But they are not the same.

I have a dock station where eth1 appears when I attach the notebook to it
(looks like it's hanging off a USB bus). IOW: appearance of this interface
is functionally equivalent to attaching ethernet cable.
ifplugd meant to be able to *automatically* handle this case.
Currently, with -a, it couldn't: newly appearing iface stayed down,
user had to manually up it.

function                                             old     new   delta
packed_usage                                       34253   34296     +43
.rodata                                           104876  104877      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 44/0)               Total: 44 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-30 14:33:14 +02:00
Denys Vlasenko 8456c21c09 seedrng: chdir to the SEED_DIRECTORY - avoid concat_path_file's
function                                             old     new   delta
seedrng_main                                        1273    1225     -48

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-27 17:53:12 +02:00
Denys Vlasenko c82a0cd2b0 seedrng: shorten strings
function                                             old     new   delta
.rodata                                           104894  104876     -18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-27 17:33:15 +02:00
Denys Vlasenko 401356511c seedrng: remove unnecessary zero-filling of local variables
function                                             old     new   delta
seedrng_main                                        1292    1273     -19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-27 17:20:43 +02:00
Denys Vlasenko 6da9947358 seedrng: remove unnecessary zero-filling of local variables
function                                             old     new   delta
seedrng_main                                        1323    1292     -31

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-27 17:09:38 +02:00
Denys Vlasenko 137b205722 seedrng: shrink --help text
function                                             old     new   delta
packed_usage                                       34280   34253     -27

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-27 16:54:18 +02:00
Denys Vlasenko 0cdd6f5792 libbb: fix fallout from nth_string() robustification, closes 14726
function                                             old     new   delta
parse_common                                         187     228     +41

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-04-27 15:33:55 +02:00
Bernhard Reutner-Fischer 7fbfb2050f kbuild: Prefer -Oz over -Os
-Oz Optimize aggressively for size rather than speed.

with gcc-12 so far (i think only https://gcc.gnu.org/PR32803 and 103773 )
"shorter load imm on x86_64":
(add/remove: 0/0 grow/shrink: 4/1670 up/down: 6/-13196)    Total: -13190 bytes
   text	   data	    bss	    dec	    hex	filename
 975753	   4227	   1816	 981796	  efb24	busybox_old
 962442	   4227	   1816	 968485	  ec725	busybox_unstripped

with clang-15:
(add/remove: 394/34 grow/shrink: 161/1856 up/down: 18644/-98946)Total: -80302 bytes
   text	   data	    bss	    dec	    hex	filename
1120994	  16066	   1696	1138756	 116044	busybox_old
1040689	  16026	   1696	1058411	 10266b	busybox_unstripped

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-24 19:18:57 +02:00
Jason A. Donenfeld 05c366a560 seedrng: prune header includes
Remove redundant includes.
We have platform specific handling in libbb.h and platform.h so we can
handle quirks in a central place.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-24 10:03:59 +02:00
Jason A. Donenfeld f9ea8ba5ed seedrng: code-golf even smaller
Since we're passing 0 as the timeout, we don't need safe_poll. Remove
cleanup at end of program, since OS does that, which lets us simplify
control flow. Factor repeated function calls into ternary loop.

function                                             old     new   delta
seedrng_main                                        1061    1459    +398
seed_from_file_if_exists                             468       -    -468
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 398/-468)          Total: -70 bytes
   text    data     bss     dec     hex filename
1052781   16515    1816 1071112  105808 busybox_old
1052711   16515    1816 1071042  1057c2 busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-24 10:01:07 +02:00
Bernhard Reutner-Fischer 831c754c91 kbuild: fix building sha256
Pass down the correct EXTRA_CFLAGS to the compiler driver when building
assembler source.
Otherwise building busybox for a multilib other than the default failed
to link since hash_md5_sha256_x86-64_shaNI.o and
hash_md5_sha_x86-64_shaNI.o were built for the default arch which might
not what we requested in the EXTRA_CFLAGS.

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-21 13:37:10 +02:00
Ron Yorston c93eb1a95b vi: fix backspace over tab in commands
Colon and search commands are entered on the status line.  Since
the cursor position wasn't being tracked backspacing over a tab
resulted in a mismatch between the actual and apparent content
of the command.

function                                             old     new   delta
get_input_line                                       178     180      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 2/0)                 Total: 2 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 16:06:04 +02:00
Jason A. Donenfeld 57fea029cc seedrng: compress format strings with %s arguments
- Avoid an xstrdup call with seed_dir.
- Compress format strings with %s arguments.
- Open /dev/urandom for add entropy ioctl rather than /dev/random, so that
  /dev/random is only used for the already-sightly-flawed poll() check for
  creditability.

function                                             old     new   delta
seedrng_main                                         948     958     +10
seed_from_file_if_exists                             410     417      +7
.rodata                                           108338  108206    -132
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 17/-132)          Total: -115 bytes
   text	   data	    bss	    dec	    hex	filename
 975829	   4227	   1816	 981872	  efb70	busybox_old
 975714	   4227	   1816	 981757	  efafd	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:43:04 +02:00
Jason A. Donenfeld 3cb40f89de seedrng: avoid needless runtime strlen() call
- Avoid needless runtime strlen() call, bloating binary.
- Replace failed seed string with series of nulls.

function                                             old     new   delta
.rodata                                           108350  108338     -12
static.seedrng_prefix                                 26       -     -26
seedrng_main                                        1000     948     -52
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 0/2 up/down: 0/-90)             Total: -90 bytes
   text	   data	    bss	    dec	    hex	filename
 975919	   4227	   1816	 981962	  efbca	busybox_old
 975829	   4227	   1816	 981872	  efb70	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:43:00 +02:00
Jason A. Donenfeld ce9a345632 seedrng: use predefined strings where possible
- Use predefined strings where possible.
- Open /dev/random with O_RDONLY for ioctl().

function                                             old     new   delta
seed_from_file_if_exists                             413     410      -3
.rodata                                           108407  108350     -57
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-60)             Total: -60 bytes
   text	   data	    bss	    dec	    hex	filename
 975979	   4227	   1816	 982022	  efc06	busybox_old
 975919	   4227	   1816	 981962	  efbca	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:43:00 +02:00
Jason A. Donenfeld 398bb3861a seedrng: further reduce size
- Remove all games with errno to further reduce code size.
- Combine error messages that don't benefit from being separated.
- Lock directory fd instead of separate file.

function                                             old     new   delta
static.longopts                                       38      26     -12
seed_from_file_if_exists                             426     413     -13
packed_usage                                       34519   34480     -39
.rodata                                           108484  108407     -77
seedrng_main                                        1088    1000     -88
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/5 up/down: 0/-229)           Total: -229 bytes
   text	   data	    bss	    dec	    hex	filename
 976208	   4227	   1816	 982251	  efceb	busybox_old
 975979	   4227	   1816	 982022	  efc06	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:43:00 +02:00
Jason A. Donenfeld 3c60711f83 seedrng: remove some global variables
- Remove global variables and pass dfd by value, opened once instead of
  twice, which shaves off some more bytes.

function                                             old     new   delta
seedrng_main                                        1086    1088      +2
seed_dir                                               8       -      -8
non_creditable_seed                                    8       -      -8
lock_file                                              8       -      -8
creditable_seed                                        8       -      -8
seed_from_file_if_exists                             456     426     -30
------------------------------------------------------------------------------
(add/remove: 0/4 grow/shrink: 1/1 up/down: 2/-62)             Total: -60 bytes
   text	   data	    bss	    dec	    hex	filename
 976236	   4227	   1848	 982311	  efd27	busybox_old
 976208	   4227	   1816	 982251	  efceb	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:43:00 +02:00
Jason A. Donenfeld 31ec481baf seedrng: hoist bb_strtoul out of min/max
- Hoist bb_strtoul out of min/max to prevent quadruple evaluation.
- Don't use separate variables for boottime/realtime.
- Make use of ENABLE_FEATURE_CLEAN_UP where appropriate.
- Order hash initialization after lock taking per Bernhard's taste.
- Add comment description of theory of operation.

function                                             old     new   delta
seed_from_file_if_exists                             533     456     -77
seedrng_main                                        1218    1086    -132
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-209)           Total: -209 bytes
   text	   data	    bss	    dec	    hex	filename
 976445	   4227	   1848	 982520	  efdf8	busybox_old
 976236	   4227	   1848	 982311	  efd27	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:42:53 +02:00
Jason A. Donenfeld 4538578996 seedrng: use libbb functions
- Make extensive use of libbb.h functions, which simplify a lot of code
  and reduce binary size considerably.
- Use the already existing PID_FILE_PATH variable.

function                                             old     new   delta
seed_from_file_if_exists                             697     533    -164
.rodata                                           108665  108484    -181
seedrng_main                                        1463    1218    -245
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-590)           Total: -590 bytes
   text	   data	    bss	    dec	    hex	filename
 977035	   4227	   1848	 983110	  f0046	busybox_old
 976445	   4227	   1848	 982520	  efdf8	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:22:55 +02:00
Jason A. Donenfeld 4b407bacd4 seedrng: import SeedRNG utility for kernel RNG seed files
The RNG can't actually be seeded from a shell script, due to the
reliance on ioctls and the fact that entropy written into the
unprivileged /dev/urandom device is not immediately mixed in, making
subsequent seed reads dangerous. For this reason, the seedrng project
provides a basic "C script" meant to be copy and pasted into projects
like Busybox and tweaked as needed: <https://git.zx2c4.com/seedrng/about/>.

The SeedRNG construction has been part of systemd's seeder since
January, and recently was added to Android, OpenRC, and Void's Runit,
with more integrations on their way depending on context. Virtually
every single Busybox-based distro I have seen seeds things in wrong,
incomplete, or otherwise dangerous way. For example, fixing this issue
in Buildroot requires first for Busybox to have this fix.

This commit imports it into Busybox and wires up the basic config. The
utility itself is tiny, and unlike the example code from the SeedRNG
project, we can re-use libbb's existing hash functions, rather than
having to ship a standalone BLAKE2s, which makes this even smaller.

function                                             old     new   delta
seedrng_main                                           -    1463   +1463
.rodata                                           107858  108665    +807
seed_from_file_if_exists                               -     697    +697
packed_usage                                       34414   34519    +105
static.longopts                                        -      38     +38
static.seedrng_prefix                                  -      26     +26
seed_dir                                               -       8      +8
non_creditable_seed                                    -       8      +8
lock_file                                              -       8      +8
creditable_seed                                        -       8      +8
applet_names                                        2747    2755      +8
applet_main                                         3192    3200      +8
------------------------------------------------------------------------------
(add/remove: 9/0 grow/shrink: 4/0 up/down: 3184/0)           Total: 3184 bytes
   text	   data	    bss	    dec	    hex	filename
 973776	   4219	   1816	 979811	  ef363	busybox_old
 977035	   4227	   1848	 983110	  f0046	busybox_unstripped

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2022-04-20 15:20:29 +02:00
Ron Yorston fc7868602e vi: improved handling of backspace in replace mode
In replace mode ('R' command) the backspace character should get
special treatment:

- backspace only goes back to the start of the replacement;
- backspacing over replaced characters restores the original text.

Prior to this commit BusyBox vi deleted the characters both before
and after the cursor in replace mode.

function                                             old     new   delta
undo_pop                                               -     235    +235
char_insert                                          858     884     +26
indicate_error                                        81      84      +3
find_range                                           654     657      +3
static.text_yank                                      77      79      +2
do_cmd                                              4486    4243    -243
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 4/1 up/down: 269/-243)           Total: 26 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-03-04 22:57:05 +01:00
Denys Vlasenko 55f969a006 taskset: fix printf format mismatch in !FEATURE_TASKSET_FANCY config. closes 14616
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-03-01 10:49:17 +01:00
Denys Vlasenko 5fe20cf321 ash: do not truncate failed tilde expansion on unknown user names
Do not skip over "*p = c;" statement.

Testcase: echo ~~nouser/qwe

function                                             old     new   delta
argstr                                              1396    1406     +10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-03-01 10:10:22 +01:00
Denys Vlasenko 7750b5a25a ash: fix unsafe use of mempcpy
function                                             old     new   delta
subevalvar                                          1549    1557      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-03-01 09:56:54 +01:00
Sören Tempel fa52ac9781 ash: don't read past end of var in subvareval for bash substitutions
Without this patch, BusyBox handles bash pattern substitutions without
a terminating '/' character incorrectly.

Consider the following shell script:

	_bootstrapver=5.0.211-r0
	_referencesdir="/usr/${_bootstrapver/-*}/Sources"
	echo $_referencesdir

This should output `/usr/5.0.211/Sources`. However, without this patch
it instead outputs `/usr/5.0.211Sources`. This is due to the fact that
BusyBox expects the bash pattern substitutions to always be terminated
with a '/' (at least in this part of subvareval) and thus reads passed
the substitution itself and consumes the '/' character which is part of
the literal string. If there is no '/' after the substitution then
BusyBox might perform an out-of-bounds read under certain circumstances.

When replacing the bash pattern substitution with `${_bootstrapver/-*/}`,
or with this patch applied, ash outputs the correct value.

Signed-off-by: Sören Tempel <soeren@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-03-01 08:47:43 +01:00
Denys Vlasenko 1891fdda59 libbb/sha1: update config help text with new performance numbers
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-18 17:09:51 +01:00
Denys Vlasenko c2e7780e52 libbb/sha256: explicitly use sha256rnds2's %xmm0 (MSG) argument
Else, the code seemingly does not use MSG.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-12 00:52:12 +01:00
Denys Vlasenko 1f272c06d0 whitespace fixes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-11 23:03:27 +01:00
Denys Vlasenko dda77e8376 libbb/sha1: revert last commit: pshufb is a SSSE3 insn, can't use it
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-11 14:53:26 +01:00
Denys Vlasenko 8154146be4 libbb/sha1: shrink unrolled x86-64 code
function                                             old     new   delta
sha1_process_block64                                3481    3384     -97

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-11 06:08:27 +01:00
Denys Vlasenko 6f56fa1713 libbb/sha: improve comments
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-10 15:38:10 +01:00
Denys Vlasenko 6a6c1c0ea9 whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-09 11:29:23 +01:00
Denys Vlasenko caa9c4f707 libbb/sha256: code shrink in x86 assembly
function                                             old     new   delta
sha256_process_block64_shaNI 32-bit                  676     673      -3
sha256_process_block64_shaNI 64-bit                  680     677      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-09 01:50:22 +01:00
Denys Vlasenko 11bcea7ac0 libbb/sha256: code shrink in 64-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         701     680     -21

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-09 01:42:49 +01:00
Denys Vlasenko 461a994b09 libbb/sha256: code shrink in 32-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         697     676     -21

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-09 01:30:23 +01:00
Denys Vlasenko c0ff0d4528 libbb/sha256: code shrink in 32-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         713     697     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-09 00:33:39 +01:00
Denys Vlasenko eb8d5f3b8f libbb/sha1: shrink x86 hardware accelerated hashing (32-bit)
function                                             old     new   delta
sha1_process_block64_shaNI                           511     507      -4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-08 15:34:02 +01:00
Denys Vlasenko eb52e7fa52 libbb/sha1: shrink x86 hardware accelerated hashing (32-bit)
function                                             old     new   delta
sha1_process_block64_shaNI                           517     511      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-08 15:23:26 +01:00
Denys Vlasenko 71a1cccaad libbb/sha1: shrink x86 hardware accelerated hashing
function                                             old     new   delta
sha1_process_block64_shaNI 32-bit                    524     517      -7
sha1_process_block64_shaNI 64-bit                    510     508      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-08 08:22:17 +01:00
Denys Vlasenko 4923f74e58 libbb/sha1: shrink unrolled x86-64 code
function                                             old     new   delta
sha1_process_block64                                3482    3481      -1
.rodata                                           108460  108412     -48
------------------------------------------------------------------------------
(add/remove: 1/4 grow/shrink: 0/2 up/down: 0/-49)             Total: -49 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-08 03:29:16 +01:00
Denys Vlasenko c193cbd6df libbb/sha1: shrink and speed up unrolled x86-64 code
function                                             old     new   delta
sha1_process_block64                                3514    3482     -32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-07 02:34:04 +01:00
Denys Vlasenko 987be932ed *: slap on a few ALIGN_PTR where appropriate
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-06 20:07:12 +01:00
Denys Vlasenko ca466f385a *: slap on a few ALIGN* where appropriate
The result of looking at "grep -F -B2 '*fill*' busybox_unstripped.map"

function                                             old     new   delta
.rodata                                           108586  108460    -126
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-126)           Total: -126 bytes
   text	   data	    bss	    dec	    hex	filename
 970412	   4219	   1848	 976479	  ee65f	busybox_old
 970286	   4219	   1848	 976353	  ee5e1	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-06 19:53:10 +01:00
Denys Vlasenko 4f40735c87 libbb/sha256: code shrink in 32-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         722     713      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-06 00:56:13 +01:00
Denys Vlasenko 31c1c31077 libbb/sha256: code shrink in 64-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         706     701      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-06 00:33:42 +01:00
Denys Vlasenko a1429fbb8c libbb/sha256: code shrink in 64-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         730     706     -24

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-03 15:17:42 +01:00
Denys Vlasenko de6cb4bed8 libbb/sha256: code shrink in 32-bit x86
function                                             old     new   delta
sha256_process_block64_shaNI                         747     722     -25

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-03 15:11:23 +01:00
Denys Vlasenko 6472ac9428 libbb/sha256: optional x86 hardware accelerated hashing
64 bit:
function                                             old     new   delta
sha256_process_block64_shaNI                           -     730    +730
.rodata                                           108314  108586    +272
sha256_begin                                          31      83     +52
------------------------------------------------------------------------------
(add/remove: 5/1 grow/shrink: 2/0 up/down: 1055/-1)          Total: 1054 bytes

32 bit:
function                                             old     new   delta
sha256_process_block64_shaNI                           -     747    +747
.rodata                                           104318  104590    +272
sha256_begin                                          29      84     +55
------------------------------------------------------------------------------
(add/remove: 5/1 grow/shrink: 2/0 up/down: 1075/-1)          Total: 1074 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-02-03 14:58:02 +01:00
Denys Vlasenko 205042c07a libbb/sha1: in unrolled x86-64 code, pass initial W[] in registers, not on stack
This can be faster on some CPUs.
On Skylake, evidently load latency from L1 (or store-to-load
forwarding in LSU) is fast enough to completely hide
memory reference latencies here.

function                                             old     new   delta
sha1_process_block64                                3495    3514     +19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-25 17:21:45 +01:00
Denys Vlasenko 99e22d230d cut: build fix for FEATURE_CUT_REGEX
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-24 07:07:17 +01:00
Khem Raj 117a8c9b7a apply const trick to ptr_to_globals
This was missing in the previous attempt to fix it via [1]

This helps fix segfaults when compiling with clang ( seen on riscv64 )

[  452.428349] less[270]: unhandled signal 11 code 0x1 at 0x000000000000000c in busybox.nosuid[2ab7491000+ba000]
[  452.430246] CPU: 3 PID: 270 Comm: less Not tainted 5.15.13-yocto-standard #1
[  452.431323] Hardware name: riscv-virtio,qemu (DT)
[  452.431925] epc : 0000002ab74a19ee ra : 0000002ab74a19dc sp : 0000003fec6ec980
[  452.432725]  gp : 0000002ab754dcb0 tp : 0000003f88783800 t0 : 0000003f8878d4a0
[  452.433744]  t1 : 0000002ab749b00c t2 : 0000000000000000 s0 : 0000003fec6ecc38
[  452.434732]  s1 : 000000000000004c a0 : 00000000ffffffff a1 : 0000002ab754dde0
[  452.435861]  a2 : 0000000000000000 a3 : 0000000000000100 a4 : 0000002ab754f3a0
[  452.436787]  a5 : 0000002ab754f3a0 a6 : 0000000000000000 a7 : 0000002ab754f2a0
[  452.437974]  s2 : 0000000000000002 s3 : 0000002ab754b6c8 s4 : 0000002ab749b60e
[  452.438781]  s5 : 0000000000000000 s6 : 0000002ab754b6c8 s7 : 0000003f88943060
[  452.439723]  s8 : 0000003f88944050 s9 : 0000002ad8502e88 s10: 0000002ad8502de8
[  452.440538]  s11: 0000000000000014 t3 : 0000003f887fceb6 t4 : 0000003f8893af0c
[  452.441438]  t5 : 0000000000000000 t6 : 0000003f88923000

[1] https://git.busybox.net/busybox/commit/?id=1f925038a

Signed-off-by: Khem Raj <raj.khem@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 23:13:44 +01:00
Timo Teräs 78fdf4d22d mkfs.vfat: fix volume label to be padded with space
The specification requires volume label to be space padded.

Latest fsck.vfat will remove the zero padded volume label
as invalid. See also:
https://github.com/dosfstools/dosfstools/issues/172

Make the default label also "NO NAME" which has the special meaning
that label is not set.

function                                             old     new   delta
mkfs_vfat_main                                      1470    1502     +32
static.NO_NAME_11                                      -      12     +12
.rodata                                           104309  104318      +9
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/0 up/down: 53/0)               Total: 53 bytes

Signed-off-by: Timo Teräs <timo.teras@iki.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 23:07:07 +01:00
Walter Lozano 6dd6a6c42d Add support for long options to cmp
In order to improve compatibility with GNU cmp add support for long
options to busybox cmp.

function                                             old     new   delta
static.cmp_longopts                                    -      36     +36
cmp_main                                             589     594      +5
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 41/0)               Total: 41 bytes

Signed-off-by: Walter Lozano <walter.lozano@collabora.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 20:24:32 +01:00
Denys Vlasenko f12fb1e409 sed: fix handling of escaped delimiters in s/// replacement
function                                             old     new   delta
parse_regex_delim                                    111     140     +29

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 19:04:27 +01:00
Denys Vlasenko e998c7c032 sed: fix handling of escaped delimiters in s/// search pattern, closes 14541
function                                             old     new   delta
copy_parsing_escapes                                  67      96     +29
parse_regex_delim                                    109     111      +2
get_address                                          213     215      +2
add_cmd                                             1176    1178      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 35/0)               Total: 35 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 18:48:49 +01:00
Denys Vlasenko 33a9f34df5 add busybox_ldscript.README.txt
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 15:46:05 +01:00
Denys Vlasenko 39369ff460 libbb/sha1: use SSE2 in unrolled x86-64 code. ~10% faster
function                                             old     new   delta
.rodata                                           108241  108305     +64
sha1_process_block64                                3502    3495      -7
------------------------------------------------------------------------------
(add/remove: 5/0 grow/shrink: 1/1 up/down: 64/-7)              Total: 57 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-23 12:57:27 +01:00
Denys Vlasenko 1e825acf8d libbb: shrink lineedit_read_key()
function                                             old     new   delta
lineedit_read_key                                    237     231      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-18 00:36:42 +01:00
Denys Vlasenko 8ad2acf352 fix "defined but not used" warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-17 23:59:46 +01:00
Denys Vlasenko 12566e7f9b ash,hush: fix handling of SIGINT while waiting for interactive input
function                                             old     new   delta
lineedit_read_key                                    160     237     +77
__pgetc                                              522     589     +67
fgetc_interactive                                    244     309     +65
safe_read_key                                          -      39     +39
read_key                                             588     607     +19
record_pending_signo                                  23      32      +9
signal_handler                                        75      81      +6
.rodata                                           104312  104309      -3
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 6/1 up/down: 282/-3)            Total: 279 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-17 11:46:23 +01:00
Denys Vlasenko a277506a64 shell: add comments about SIGINT-related problems
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-16 23:54:46 +01:00
Denys Vlasenko c2788f88f4 libbb: introduce and use chdir_or_warn()
function                                             old     new   delta
chdir_or_warn                                          -      37     +37
send_cgi_and_exit                                    720     711      -9
xchdir                                                27      15     -12
setup_environment                                    233     217     -16
fork_job                                             449     433     -16
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 37/-53)            Total: -16 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-13 12:56:10 +01:00
Denys Vlasenko 931c55f9e2 libbb: invert the meaning of SETUP_ENV_NO_CHDIR -> SETUP_ENV_CHDIR
Double negatives are hard to grok.

function                                             old     new   delta
login_main                                           986     988      +2
su_main                                              474     470      -4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 2/-4)               Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-13 12:50:48 +01:00
Denys Vlasenko b3eec1651f sulogin: util-linux does not say "normal startup" on Ctrl-D
function                                             old     new   delta
sulogin_main                                         341     331     -10
.rodata                                           104327  104312     -15
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-25)             Total: -25 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-13 01:43:11 +01:00
Denys Vlasenko 96771ec5f5 sulogin: start _login_ shell only with -p
Also, shorten/eliminate messages to be closer to util-linux.

function                                             old     new   delta
packed_usage                                       34233   34238      +5
sulogin_main                                         340     341      +1
.rodata                                           104380  104327     -53
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 6/-53)             Total: -47 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-13 01:38:47 +01:00
Denys Vlasenko 68b402ee51 ash: ^C with SIG_INGed SIGINT should not exit the shell
function                                             old     new   delta
__pgetc                                              501     522     +21

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-13 01:15:10 +01:00
Denys Vlasenko d162a7b978 sulogin: increase util-linux compatibility
Change to root's HOME. Set some envvars. Steal ctty if necessary and possible.

function                                             old     new   delta
sulogin_main                                         240     340    +100
setup_environment                                    225     233      +8
su_main                                              479     474      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 108/-5)            Total: 103 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-12 23:19:11 +01:00
Denys Vlasenko 004cefa918 reset: better --help text
function                                             old     new   delta
packed_usage                                       34175   34233     +58

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-12 17:21:14 +01:00
Denys Vlasenko 524fecf7c3 nmeter: %[md] %[mw] - dirty file-backed pages, writeback pages
function                                             old     new   delta
collect_mem                                          333     387     +54
.rodata                                           104369  104380     +11
packed_usage                                       34184   34175      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 65/-9)              Total: 56 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-11 19:32:16 +01:00
Denys Vlasenko ff8fda8482 ls: implement ls -sh (human-readable allocated blocks)
function                                             old     new   delta
display_single                                       979    1018     +39

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-08 22:59:49 +01:00
Denys Vlasenko 143356876b libbb/sha1: add a comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-08 22:43:24 +01:00
Denys Vlasenko e2952dfaff awk: input numbers are never octal or hex (only program consts can be)
function                                             old     new   delta
next_token                                           825     930    +105
getvar_i                                             114     129     +15
nextchar                                              49      53      +4
my_strtod                                            138       -    -138
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 3/0 up/down: 124/-138)          Total: -14 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-08 22:42:35 +01:00
Emanuele Giacomelli 84a1305888 XXXsum: handle binary sums with " " in the path
If a line specifies a binary checksum whose path contains two adjacent
spaces, when checking digests with -c the two spaces will be used as the
separator between the digest and the pathname instead of " *", as shown:

$ echo foo > "/tmp/two  spaces"
$ md5sum -b "/tmp/two  spaces"   # This is GNU md5sum
d3b07384d113edec49eaa6238ad5ff00 */tmp/two  spaces
$ md5sum -b "/tmp/two  spaces" | ./busybox md5sum -c
md5sum: can't open 'spaces': No such file or directory
spaces: FAILED
md5sum: WARNING: 1 of 1 computed checksums did NOT match

function                                             old     new   delta
md5_sha1_sum_main                                    503     496      -7

Signed-off-by: Emanuele Giacomelli <emanuele.giacomelli@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-08 17:16:00 +01:00
Denys Vlasenko e7ff29402d libbb/sha1: simplify cpuid code
function                                             old     new   delta
sha1_begin                                           107     106      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-08 01:25:23 +01:00
Denys Vlasenko 805ececa61 whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-08 00:41:09 +01:00
Denys Vlasenko 0bab5da37e libbb/sha1: tweak comments
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-07 14:55:31 +01:00
Denys Vlasenko 89092c61bc powertop: fix cpuid asm: ebx saving/restoring is properly done by gcc
function                                             old     new   delta
print_intel_cstates                                  481     477      -4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-07 01:33:46 +01:00
Denys Vlasenko a96ccbefe4 libbb/sha1: optional i686 hardware accelerates hashing
function                                             old     new   delta
sha1_process_block64_shaNI                             -     524    +524
sha1_begin                                            57     114     +57
.rodata                                           104353  104369     +16
static.shaNI                                           -       1      +1
------------------------------------------------------------------------------
(add/remove: 4/0 grow/shrink: 2/0 up/down: 598/0)             Total: 598 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-07 01:32:13 +01:00
Denys Vlasenko 711e20ecb8 libbb/sha1: optional x86-64 hardware accelerates hashing
function                                             old     new   delta
sha1_process_block64_shaNI                             -     510    +510
sha1_begin                                            52     107     +55
.rodata                                           108285  108301     +16
static.shaNI                                           -       1      +1
------------------------------------------------------------------------------
(add/remove: 4/0 grow/shrink: 2/0 up/down: 582/0)             Total: 582 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-07 00:43:59 +01:00
Vincent Stehlé a93668cc42 fdisk: recognize EBBR protective partitions
The MBR partition type 0xF8 is used by the Arm EBBR specification[1] for
protective partitions over fixed-location firmware images.

[1]: https://github.com/ARM-software/ebbr

Signed-off-by: Vincent Stehlé <vincent.stehle@arm.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-06 10:55:53 +01:00
Denys Vlasenko 6062c0d19b libbb: change xstrndup, xmemdup to take size_t as size parameter
Also, remove entirely usually-disabled paranoia check (was also using
wrong config option to enable itself).

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-05 23:03:54 +01:00
Denys Vlasenko db5546ca10 libbb: code shrink: introduce and use [_]exit_SUCCESS()
function                                             old     new   delta
exit_SUCCESS                                           -       7      +7
_exit_SUCCESS                                          -       7      +7
run_pipe                                            1562    1567      +5
pseudo_exec_argv                                     399     400      +1
finish                                                86      87      +1
start_stop_daemon_main                              1109    1107      -2
shutdown_on_signal                                    38      36      -2
runsv_main                                          1662    1660      -2
redirect                                            1070    1068      -2
read_line                                             79      77      -2
pause_and_low_level_reboot                            54      52      -2
list_i2c_busses_and_exit                             483     481      -2
less_exit                                             12      10      -2
identify                                            4123    4121      -2
grep_file                                           1161    1159      -2
getty_main                                          1519    1517      -2
fsck_minix_main                                     2681    2679      -2
free_session                                         132     130      -2
fdisk_main                                          4739    4737      -2
clean_up_and_exit                                     53      51      -2
bsd_select                                          1566    1564      -2
bb_daemonize_or_rexec                                198     196      -2
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 3/17 up/down: 21/-34)           Total: -13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-05 22:16:06 +01:00
Denys Vlasenko 076f5e064f less: code shrink
function                                             old     new   delta
restore_tty                                            -      29     +29
less_main                                           2107    2105      -2
getch_nowait                                         253     251      -2
buffer_print                                         614     612      -2
less_exit                                             51      12     -39
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 29/-45)            Total: -16 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-05 22:04:21 +01:00
Denys Vlasenko 34e0bb3931 sort: support -h
function                                             old     new   delta
static.scale_suffix                                    -      62     +62
.rodata                                           104304  104336     +32
compare_keys                                         820     848     +28
packed_usage                                       34159   34184     +25
static.suffix                                          -       9      +9
sort_opt_str                                          37      38      +1
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 4/0 up/down: 157/0)             Total: 157 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-05 12:05:55 +01:00
Denys Vlasenko cc7d2e2178 sort: fix -s -r interaction: 'stable' order is not affected by -r
function                                             old     new   delta
compare_keys                                         818     820      +2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 23:53:21 +01:00
Denys Vlasenko dfd8aafcf5 libbb: fflush_stdout_and_exit(0) still exits with _error_ (not 0!) if fflush fails
function                                             old     new   delta
fflush_stdout_and_exit                                36      40      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 23:36:16 +01:00
Denys Vlasenko 31f45c1b36 libbb: factor out fflush_stdout_and_exit(EXIT_SUCCESS)
function                                             old     new   delta
fflush_stdout_and_exit_SUCCESS                         -       7      +7
xxd_main                                             890     888      -2
vlock_main                                           353     351      -2
uuencode_main                                        318     316      -2
uniq_main                                            427     425      -2
uname_main                                           250     248      -2
sort_main                                            853     851      -2
shuf_main                                            500     498      -2
route_main                                           238     236      -2
readlink_main                                        113     111      -2
nice_main                                            156     154      -2
last_main                                            957     955      -2
ipcs_main                                            960     958      -2
env_main                                             209     207      -2
chrt_main                                            464     462      -2
cal_main                                             921     919      -2
baseNUM_main                                         650     648      -2
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/16 up/down: 7/-32)            Total: -25 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 23:31:58 +01:00
Denys Vlasenko 286b33721d sed: correctly handle 'w FILE' commands writing to the same file
function                                             old     new   delta
sed_xfopen_w                                           -      84     +84

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 19:42:36 +01:00
Denys Vlasenko ed2af2e82d build system: detect if build host has no bzip2
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 14:32:41 +01:00
Denys Vlasenko c3cfcc9242 libbb/sha1: x86_64 version: reorder prologue/epilogue insns
Not clear exactly why, but this increases hashing speed
on Skylake from 454 MB/s to 464 MB/s.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 01:45:52 +01:00
Denys Vlasenko 1fc520ed28 md5/shaXsum: use FEATURE_COPYBUF_KB to size the buffer instead of fixed 4k
function                                             old     new   delta
md5_sha1_sum_main                                    536     565     +29
hash_file                                            419     401     -18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 29/-18)             Total: 11 bytes

In my test, for unrolled sha1, COPYBUF_KB=64 increases throughput
from 367 MB/s to 457 MB/s.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-04 00:51:04 +01:00
Denys Vlasenko 7abb2bb96e libbb/sha1: x86_64 version: tidying up, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-03 17:02:48 +01:00
Denys Vlasenko 4387077f8e typo fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-03 13:14:09 +01:00
Denys Vlasenko 947bef0dea libbb/sha1: x86_64 version: generate from a script, optimize a bit
function                                             old     new   delta
sha1_process_block64                                3569    3502     -67

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-03 13:10:30 +01:00
Denys Vlasenko 05fd13ebec libbb/sha1: x86_64 version: move to a separate .S file, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-03 12:57:36 +01:00
Denys Vlasenko 5c0c558231 libbb/sha1: code shrink in medium-speed version
function                                             old     new   delta
sha1_process_block64                                 654     641     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-02 01:56:35 +01:00
Denys Vlasenko 4d4f1f2096 libbb/sha1: x86_64 version: bswap in 64-bit chunks
function                                             old     new   delta
sha1_process_block64                                3562    3570      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-01 15:42:15 +01:00
Denys Vlasenko d643010fee libbb/sha1: shrink x86_64 version - use r8..15 for W[8..15]
function                                             old     new   delta
sha1_process_block64                                3683    3562    -121

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-01 15:01:53 +01:00
Denys Vlasenko 5f68170204 libbb/sha1: assembly versions for x86
32 bits:
function                                             old     new   delta
sha1_process_block64                                3950    3657    -293
64 bits:
sha1_process_block64                                4167    3683    -484

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2022-01-01 13:57:34 +01:00
Denys Vlasenko f09d088fdf libbb/sha1: shrink and speed up fully unrolled version
function                                             old     new   delta
sha1_process_block64                                4149    3950    -199

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-31 17:07:47 +01:00
Denys Vlasenko 0b62a08777 libbb/sha1: add config-selectable partially unrolled version
function                                             old     new   delta
sha1_process_block64                                 364     732    +368
static.rconsts                                        16       -     -16
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 368/-16)           Total: 352 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-30 18:54:02 +01:00
Denys Vlasenko 25aadc893d libbb/sha1: add config-selectable fully unrolled version, closes 14391
function                                             old     new   delta
sha1_process_block64                                 364    4167   +3803
static.rconsts                                        16       -     -16
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 3803/-16)         Total: 3787 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-30 13:17:16 +01:00
Sören Tempel 9173c9cce4 ed: add support for -s command-line option as mandated by POSIX
Apart from the -p option, POSIX also mandates an -s option which
suppresses the output of byte counts for the e, E, r, and w command.
From these commands, Busybox ed presently only implements the r and w
commands. This commit ensures that these two command do not output any
bytes counts when the -s option is passed. The shell escape command,
also effected by the -s option, is not implemented by Busybox at the
moment.

function                                             old     new   delta
packed_usage                                       34096   34115     +19
doCommands                                          1887    1900     +13
readLines                                            388     397      +9
.rodata                                           104196  104200      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 45/0)               Total: 45 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-29 19:01:32 +01:00
Denys Vlasenko 0e2cb6d1e2 echo: add FIXME comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-29 07:26:23 +01:00
Denys Vlasenko 0fcc7f5f73 scripts/echo.c: fix NUL handling in "abc\0 def"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-28 21:05:59 +01:00
Denys Vlasenko f1d06462e8 libbb: cose shrink in sha1
function                                             old     new   delta
sha1_process_block64                                 356     342     -14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-28 09:05:12 +01:00
Denys Vlasenko 44075929a8 Start 1.36.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-26 18:40:55 +01:00
Denys Vlasenko e512aeb0fb Bump version to 1.35.0
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-26 17:55:58 +01:00
Denys Vlasenko 97c00ae134 httpd: fix compile failure if !FEATURE_HTTPD_RANGES
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-26 14:29:37 +01:00
Dominique Martinet 4fe954c148 sed: do not ignore 'g' modifier when match starts with ^
It is perfectly valid to start a regex with ^ and have other patterns
with \| that can match more than once, e.g. the following example
should print ca, as illustrated with gnu sed:
$ echo 'abca' | sed -e 's/^a\|b//g'
ca

busybox before patch:
$ echo 'abca' | busybox sed -e 's/^a\|b//g'
bca

busybox after patch:
$ echo 'abca' | ./busybox sed -e 's/^a\|b//g'
ca

regcomp handles ^ perfectly well as illustrated with the second 'a' that
did not match in the example, we ca leave the non-repeating to it if
appropriate.
The check had been added before using regcomp and was required at the
time (f36635cec6) but no longer makes sense now.

(tested with glibc and musl libc)

function                                             old     new   delta
add_cmd                                             1189    1176     -13

Signed-off-by: Dominique Martinet <asmadeus@codewreck.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-25 04:20:28 +01:00
Sören Tempel a05a3d5932 ed: align output of read command with POSIX.1-2008
POSIX.1-2008 mandates the following regarding the read command:

	If the read is successful, and -s was not specified, the number
	of bytes read shall be written to standard output in the
	following format:

	    "%d\n", <number of bytes read>

This commit aligns the output of busybox ed with POSIX.1-2008 by
removing the file name from the output for the read command.

This slipped through in 4836a0708fd0aaeb82871a3762b40fcf4b61e812.

function                                             old     new   delta
.rodata                                           104203  104196      -7
readLines                                            409     388     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-28)             Total: -28 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-19 23:17:52 +01:00
Sören Tempel f26eb796e2 ed: fix current line number for file passed via the command-line
POSIX.1-2008 mandates the following regarding the file command-line
argument:

	If the file argument is given, ed shall simulate an e command
	on the file named by the pathname […]

The specification for the e command mandates the following behaviour
regarding the current line number in POSIX.1-2008:

	The current line number shall be set to the address of the last
	line of the buffer.

However, without this commit, busybox ed will set the current line
number to 1 if a file is given on the command-line and this file is not
empty (lastNum != 0). This is incorrect and fixed in this commit by not
modifying the current line number in ed_main(). As such, the current
line number will be zero for empty files and otherwise be set to the
address of the last line of the buffer.

function                                             old     new   delta
ed_main                                              144     128     -16

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-19 23:16:02 +01:00
Matthew Slowe 7d49fedc86 timeout: add support for "timeout -k KILL_SECS"
function                                             old     new   delta
timeout_main                                         307     373     +66
timeout_wait                                           -      42     +42
.rodata                                           104201  104203      +2
packed_usage                                       34097   34096      -1
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/1 up/down: 110/-1)            Total: 109 bytes

Signed-off-by: Matthew Slowe <foo@mafoo.org.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 23:11:17 +01:00
Denys Vlasenko c1eac153e8 cmp: code shrink
function                                             old     new   delta
.rodata                                           104203  104201      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 22:43:45 +01:00
Sören Tempel bfd8738154 ed: add support for -p command-line option as mandated by POSIX
The POSIX.1-2008 specification of ed(1) mandates two command-line
options: -p (for specifying a prompt string) and -s (to suppress writing
of byte counts). This commit adds support for the former. Furthermore,
it also changes the default prompt string to an empty string (instead
of ": ") since this is also mandated by POSIX:

	-p string Use string as the prompt string when in command mode.
	          By default, there shall be no prompt string.

function                                             old     new   delta
ed_main                                              112     144     +32
packed_usage                                       34074   34097     +23
doCommands                                          1889    1887      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 55/-2)              Total: 53 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 22:35:25 +01:00
Walter Lozano 579894bfd2 cmp: add support for -n
Add support to for "-n" to cmp in order to compare at most n bytes.

function                                             old     new   delta
cmp_main                                             552     589     +37
.rodata                                           104198  104203      +5
packed_usage                                       34102   34074     -28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 42/-28)             Total: 14 bytes

Signed-off-by: Walter Lozano <walter.lozano@collabora.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 22:07:06 +01:00
Denys Vlasenko 00d10cb6eb docs/embedded-scripts.txt: whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:38:02 +01:00
Aaro Koskinen aaade69ce9 find: implement -samefile
function                                             old     new   delta
parse_params                                        1461    1606    +145
func_samefile                                          -      42     +42
packed_usage                                       34079   34102     +23
static.params                                        261     271     +10
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 3/0 up/down: 220/0)             Total: 220 bytes

Signed-off-by: Aaro Koskinen <aaro.koskinen@iki.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:33:15 +01:00
Ron Yorston 7105e4afdd printf: allow 0 as a flag and allow multiple flags
The '%' character in a format specification may be followed by
one or more flags from the list "+- #0".  BusyBox printf didn't
support the '0' flag or allow multiple flags to be provided.
As a result the formats '%0*d' and '%0 d' were considered to be
invalid.

The lack of support for '0' was pointed out by Andrew Snyder on the
musl mailing list:

   https://www.openwall.com/lists/musl/2021/12/14/2

function                                             old     new   delta
printf_main                                          860     891     +31
.rodata                                            99281   99282      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 32/0)               Total: 32 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:13:26 +01:00
Denys Vlasenko b720629dfe httpd: do not send Last-Modified / ETag / Content-Length for error pages
function                                             old     new   delta
send_headers                                         713     701     -12
send_headers_and_exit                                 20      34     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 21:02:16 +01:00
Denys Vlasenko 70683faf38 httpd: don't send Content-Length in error pages header
function                                             old     new   delta
send_headers                                         701     713     +12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-17 20:37:58 +01:00
Peter Korsgaard cb91a818c8 libarchive/get_header_ar.c: fix extraction of archives from binutils in deterministic mode
GNU binutils in deterministic mode (ar rD or built with
--enable-deterministic-archives) hard codes file mode to 0644 (NOT 0100644)
since https://github.com/bminor/binutils-gdb/commit/36e4dce69dd2

This confuses busybox ar x (data_extract_all):

touch a; ar rD a.ar a
ar: creating a.ar

busybox ar x a.ar
ar: unrecognized file type
hexdump -C a.ar
00000000  21 3c 61 72 63 68 3e 0a  61 2f 20 20 20 20 20 20  |!<arch>.a/      |
00000010  20 20 20 20 20 20 20 20  30 20 20 20 20 20 20 20  |        0       |
00000020  20 20 20 20 30 20 20 20  20 20 30 20 20 20 20 20  |    0     0     |
00000030  36 34 34 20 20 20 20 20  30 20 20 20 20 20 20 20  |644     0       |
00000040  20 20 60 0a                                       |  `.|

As a workaround, force the mode bits to S_IFREG, as nothing else makes sense
for ar.

function                                             old     new   delta
get_header_ar                                        539     542      +3

Signed-off-by: Peter Korsgaard <peter@korsgaard.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 23:34:43 +01:00
Denys Vlasenko e67b80f473 udhcpc6: fix udhcp_find_option to actually find DHCP6 options
udhcp_insert_new_option treats code for IPv6 as follows:

new->data[D6_OPT_CODE] = code >> 8;
new->data[D6_OPT_CODE + 1] = code & 0xff;

udhcp_find_option tests the code as follows:

while (opt_list && opt_list->data[OPT_CODE] < code)
...
if (opt_list && opt_list->data[OPT_CODE] == code)

So yes, OPT_CODE and D6_OPT_CODE are both 0, but the D6_OPT_CLIENTID =
1 value means that the 1 is in the seconds byte, and udhcp_find_option
is only looking at the first byte,  So the send_d6_release can never
find it the created option.

function                                             old     new   delta
udhcp_find_option                                     28      53     +25
attach_option                                        276     284      +8
udhcpc6_main                                        2602    2607      +5
perform_d6_release                                   262     267      +5
udhcpd_main                                         1518    1520      +2
udhcpc_main                                         2542    2544      +2
add_serverid_and_clientid_options                     46      48      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 7/0 up/down: 49/0)               Total: 49 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 17:13:54 +01:00
Martin Kaiser 9b67880719 Makefile.flags: use all cflags for crypt and rt checks
To check if libcrypt and librt are available, we check if we can
compile and link a simple test program.

These checks do not match the actual linking if CONFIG_STATIC is enabled.
For CONFIG_STATIC, CFLAGS_busybox is set to -static. The checks don't use
CFLAGS_busybox and detect a shared libcrypt or librt. If we link busybox
later and we have no static libcrypt or librt, linking will fail.

Update the libcrypt and librt checks to use CFLAGS_busybox.

Signed-off-by: Martin Kaiser <martin@kaiser.cx>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 13:16:40 +01:00
Ildar Shaimordanov b9fba185c5 wget: allow end-users to customize Content-Type for --post-data and --post-file
More explanation in this PR:
https://github.com/rmyorston/busybox-w32/pull/233

The real use-case:
wget https://api.github.com/markdown/raw --header "Content-Type: text/plain"

function                                             old     new   delta
wget_main                                           2560    2581     +21
wget_user_headers                                     62      76     +14
.rodata                                           104196  104197      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 36/0)               Total: 36 bytes

Signed-off-by: Ildar Shaimordanov <ildar.shaimordanov@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 03:22:43 +01:00
Denys Vlasenko c7b90dc4d1 uudecode: special-case "/dev/stdout", closes 14241
function                                             old     new   delta
uudecode_main                                        295     322     +27

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-12 00:34:15 +01:00
Denys Vlasenko 27df6aeef2 tls: P256: factor out "multiply then reduce" operation
function                                             old     new   delta
sp_256_mont_mul_and_reduce_8                           -      44     +44
sp_256_ecc_mulmod_8                                  517     442     -75
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 44/-75)            Total: -31 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-11 23:27:40 +01:00
Denys Vlasenko b240733ae7 tls: x25519: code shrink by factoring out common code
function                                             old     new   delta
fe_reduce                                              -      37     +37
lm_add                                                67      43     -24
fe_mul_c                                              62      38     -24
fe_mul__distinct                                     138     112     -26
curve25519                                           800     767     -33
lm_sub                                                98      64     -34
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/5 up/down: 37/-141)          Total: -104 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-12-01 15:09:44 +01:00
Denys Vlasenko 8514b4166d tls: P256: enable 64-bit version of montgomery reduction
After more testing, (1) I'm more sure it is indeed correct, and
(2) it is a significant speedup - we do a lot of those multiplications.

function                                             old     new   delta
sp_512to256_mont_reduce_8                            191     223     +32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 21:43:51 +01:00
Denys Vlasenko 90b0d33044 tls: P256: add 64-bit montgomery reduce (disabled), small optimization in 32-bit code
function                                             old     new   delta
sp_512to256_mont_reduce_8                            191     185      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 15:44:08 +01:00
Denys Vlasenko 832626227e tls: P256: add comment on logic in sp_512to256_mont_reduce_8, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 12:55:20 +01:00
Denys Vlasenko 00b5051cd2 libbb: code shrink in des encryption, in setup_salt()
function                                             old     new   delta
pw_encrypt                                           978     971      -7
.rodata                                           108208  108192     -16
des_crypt                                           1211    1181     -30
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-53)             Total: -53 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 12:21:23 +01:00
Denys Vlasenko cfb615781d tls: P256: simplify sp_256_mont_inv_8 (no need for a temporary)
function                                             old     new   delta
sp_256_ecc_mulmod_8                                  543     517     -26

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 11:15:34 +01:00
Bernhard Reutner-Fischer bfefa6ab6c libarchive: remove duplicate forward declaration
Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2021-11-28 10:53:22 +01:00
Denys Vlasenko 1b93c7c4ec tls: P256: pad struct sp_point to 64 bits (on 64-bit arches)
function                                             old     new   delta
curve_P256_compute_pubkey_and_premaster              198     190      -8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-28 02:56:02 +01:00
Denys Vlasenko 0b13ab66f4 tls: P256: trivial x86-64 fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 19:36:23 +01:00
Denys Vlasenko f92ae1dc4b tls: P256: change logic so that we don't need double-wide vectors everywhere
Change sp_256to512z_mont_{mul,sqr}_8 to not require/zero upper 256 bits.
There is only one place where we actually used that (and that's why there
used to be zeroing memset of top half!). Fix up that place.
As a bonus, 256x256->512 multiply no longer needs to care for
"r overlaps a or b" case.

This shrinks sp_point structure as well, not just temporaries.

function                                             old     new   delta
sp_256to512z_mont_mul_8                              150       -    -150
sp_256_mont_mul_8                                      -     147    +147
sp_256to512z_mont_sqr_8                                7       -      -7
sp_256_mont_sqr_8                                      -       7      +7
sp_256_ecc_mulmod_8                                  494     543     +49
sp_512to256_mont_reduce_8                            243     249      +6
sp_256_point_from_bin2x32                             73      70      -3
sp_256_proj_point_dbl_8                              353     345      -8
sp_256_proj_point_add_8                              544     499     -45
------------------------------------------------------------------------------
(add/remove: 2/2 grow/shrink: 2/3 up/down: 209/-213)           Total: -4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 19:27:03 +01:00
Denys Vlasenko 9c671fe3dd tls: P256: do not open-code copying of struct variables
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 18:42:27 +01:00
Denys Vlasenko dcfd8d3d10 tls: P256: fix sp_256_div2_8 - it wouldn't use a[] if low bit is 0
It worked by chance because the only caller passed both parameters
as two pointers to the same array.
My fault (I made this error when converting from 26-bit code).

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 16:24:49 +01:00
Denys Vlasenko 8cbb70365f tls: P256: remove redundant zeroing in sp_256_map_8
Previous change made it obvious that we zero out already-zeroed high bits

function                                             old     new   delta
sp_256_ecc_mulmod_8                                  534     494     -40

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:50:40 +01:00
Denys Vlasenko 4415f7bc06 tls: P256: explain which functions use double-wide arrays, no code changes
function                                             old     new   delta
sp_512to256_mont_reduce_8                              -     243    +243
sp_256to512z_mont_mul_8                                -     150    +150
sp_256to512z_mont_sqr_8                                -       7      +7
sp_256_mont_sqr_8                                      7       -      -7
sp_256_mont_mul_8                                    150       -    -150
sp_256_mont_reduce_8                                 243       -    -243
------------------------------------------------------------------------------
(add/remove: 3/3 grow/shrink: 0/0 up/down: 400/-400)            Total: 0 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:47:26 +01:00
Denys Vlasenko bbda85c74b tls: P256: remove constant-time trick in sp_256_proj_point_add_8
function                                             old     new   delta
sp_256_proj_point_add_8                              576     544     -32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:06:57 +01:00
Denys Vlasenko 26c8522522 tls: P256: do not open-code copying of struct variables
function                                             old     new   delta
sp_256_ecc_mulmod_8                                  536     534      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 15:00:14 +01:00
Denys Vlasenko 446d136109 tls: tweak debug printout
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 12:03:43 +01:00
Denys Vlasenko 4bc9da1071 tls: P256: 64-bit optimizations
function                                             old     new   delta
sp_256_proj_point_dbl_8                              421     428      +7
sp_256_point_from_bin2x32                             78      84      +6
sp_256_cmp_8                                          38      42      +4
sp_256_to_bin_8                                       28      31      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 20/0)               Total: 20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-27 11:28:11 +01:00
Denys Vlasenko 15f7d618ea which: add -a to help text
function                                             old     new   delta
packed_usage                                       34075   34079      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-09 13:51:22 +01:00
Ariadne Conill 836b79211d cpio: add support for --renumber-inodes like GNU cpio
The --renumber-inodes option renumbers the inodes starting from 1,
so that the sequence of inodes is always stable.  This helps with
reproducibility.

function                                             old     new   delta
cpio_o                                               961    1045     +84
.rodata                                            78422   78440     +18
bbconfig_config_bz2                                 6168    6164      -4
packed_usage                                       25764   25756      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/2 up/down: 102/-12)            Total: 90 bytes

Signed-off-by: Ariadne Conill <ariadne@dereferenced.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 17:56:17 +02:00
Ariadne Conill 8aa5585ff4 cpio: add support for --ignore-devno like GNU cpio
The --ignore-devno option is used to set device numbers to (0, 0).
This can be useful in verifying whether a CPIO archive is reproducible.

function                                             old     new   delta
cpio_o                                               922     961     +39
.rodata                                            78407   78422     +15
bbconfig_config_bz2                                 6161    6167      +6
packed_usage                                       25770   25764      -6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 60/-6)              Total: 54 bytes

Signed-off-by: Ariadne Conill <ariadne@dereferenced.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 17:53:15 +02:00
Denys Vlasenko aaf3d5ba74 shell: tweak --help
Even though formally it is -s [ARGS], "sh -s" without ARGS
is the same as just "sh". And we are already over 80 chars wide
for ash --help, so make it shorter.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 11:25:42 +02:00
Denys Vlasenko 62f1eed1e1 hush: in a comment, document what -i might be doing
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-13 00:09:07 +02:00
Sören Tempel c33bbcb92f ed: align output of read/write commands with POSIX-1.2008
POSIX.1-2008 mandates the following regarding the write command:

	If the command is successful, the number of bytes written shall
	be written to standard output, unless the -s option was
	specified, in the following format:

		"%d\n", <number of bytes written>

function                                             old     new   delta
readLines                                            447     409     -38
doCommands                                          1940    1889     -51
.rodata                                           104219  104163     -56
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-145)           Total: -145 bytes

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-12 17:32:03 +02:00
Denys Vlasenko 94c78aa0b9 config system: move some options closer to relevalnt tool subdirectories
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-12 13:23:29 +02:00
Denys Vlasenko 7c3e96d4b3 shell: use more compact SHELL_ASH / HUSH config defines. no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-12 01:24:32 +02:00
Denys Vlasenko f4fcd74a6e shell: do not read user database for every prompt - only for those which need it
function                                             old     new   delta
get_user_strings                                       -      52     +52
get_homedir_or_NULL                                    -      23     +23
parse_and_put_prompt                                 823     838     +15
null_str                                               1       -      -1
complete_cmd_dir_file                                814     812      -2
deinit_S                                              51      42      -9
read_line_input                                     3059    3015     -44
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 1/3 up/down: 90/-56)             Total: 34 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 23:08:31 +02:00
Denys Vlasenko 6ba1f2d0bc tar: prevent malicious archives with enormous long name sizes OOMing the machine
function                                             old     new   delta
get_header_tar                                      1707    1752     +45

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 19:28:39 +02:00
Denys Vlasenko aec8fbfb83 whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 19:11:06 +02:00
Denys Vlasenko 5acf5e1f87 shell: fix script's comm field if ENABLE_FEATURE_PREFER_APPLETS=y
function                                             old     new   delta
re_execed_comm                                         -      46     +46
main                                                  72      86     +14
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 60/0)               Total: 60 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 18:44:00 +02:00
Denys Vlasenko 23aba8a9a6 tls: code shrink curve25519
function                                             old     new   delta
fe_select                                             39       -     -39
curve25519                                           849     800     -49
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 0/1 up/down: 0/-88)             Total: -88 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 16:31:47 +02:00
Denys Vlasenko 74ee3f2f73 tls: remove unused tls_symmetric.h (was used by old "big" AES code)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-11 13:46:30 +02:00
Bernhard Reutner-Fischer 376b2ceff6 chrt: silence analyzer warning
warning: use of uninitialized value ‘priority’ [CWE-457] [-Wanalyzer-use-of-uninitialized-value]

chrt_main                                            499     496      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-3)               Total: -3 bytes
   text	   data	    bss	    dec	    hex	filename
 972157	   4235	   1840	 978232	  eed38	busybox_old
 972154	   4235	   1840	 978229	  eed35	busybox_unstripped

Signed-off-by: Bernhard Reutner-Fischer <rep.dot.nop@gmail.com>
2021-10-10 17:29:18 +02:00
Denys Vlasenko d8e39b5917 find: code shrink -{m,a,c}{time,min}
function                                             old     new   delta
time_cmp                                               -     181    +181
func_mmin                                            171      31    -140
func_mtime                                           180      34    -146
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 181/-286)         Total: -105 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-10 15:18:12 +02:00
Denys Vlasenko d3dbf4ac05 *: add more beneficial NOINLINEs
function                                             old     new   delta
dec_main                                               -    1729   +1729  -41 bytes
fallbackQSort3                                         -     671    +671  -70 bytes
verify_sun                                             -     481    +481 -107 bytes
verify                                              1330     742    -588
fallbackSort                                        1469     728    -741
unpack_xz_stream                                    2306     536   -1770
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 0/3 up/down: 2881/-3099)       Total: -218 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-10 14:32:05 +02:00
Denys Vlasenko 53b2fdcdba *: add NOINLINEs where code noticeably shrinks
function                                             old     new   delta
display                                               85    1463   +1378  -73 bytes
select_and_cluster                                     -    1088   +1088 -139 bytes
parse_reply                                            -     979    +979 -109 bytes
zbc_num_sqrt                                           -     632    +632 -191 bytes
show_bridge_port                                       -     585    +585  -56 bytes
sp_256_proj_point_add_8                                -     576    +576  -45 bytes
encode_then_append_var_plusminus                       -     554    +554 -118 bytes
read_mode_db                                           -     537    +537  -47 bytes
fbset_main                                          1331     747    -584
sp_256_ecc_mulmod_8                                 1157     536    -621
brctl_main                                          2189    1548    -641
expand_one_var                                      2544    1872    -672
zxc_vm_process                                      6412    5589    -823
send_queries                                        1813     725   -1088
recv_and_process_peer_pkt                           2245    1018   -1227
bb_dump_dump                                        1531      80   -1451
------------------------------------------------------------------------------
(add/remove: 7/0 grow/shrink: 1/8 up/down: 6329/-7107)       Total: -778 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-10 13:50:53 +02:00
YU Jincheng 5156b24553 Make const ptr assign as function call in clang
- This can act as memory barrier in clang to avoid
  read before assign of a const ptr

Signed-off-by: LoveSy <shana@zju.edu.cn>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 22:30:45 +02:00
Ismael Luceno 04ad683bf9 find: implement -amin, -atime, -cmin, and -ctime
function                                             old     new   delta
func_mtime                                           130     180     +50
func_mmin                                            121     171     +50
static.params                                        235     261     +26
parse_params                                        1435    1461     +26
packed_usage                                       34025   34033      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/0 up/down: 160/0)             Total: 160 bytes

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 21:45:59 +02:00
Denys Vlasenko 49bcf9f40c hush: speed up ${x//\*/|} too
function                                             old     new   delta
expand_one_var                                      2502    2544     +42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 03:52:04 +02:00
Denys Vlasenko 5aaeb550b7 ash: speed up ${x//\*/|} too, make it independent of ASH_OPTIMIZE_FOR_SIZE
function                                             old     new   delta
subevalvar                                          1503    1545     +42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 03:33:22 +02:00
Alin Mr 21e8dbfd9d ash.c: speedup ${s:} substring (no quotes)
This trivial patch makes ${s:...} at least as fast as ${s#??..}
in simple tests. It's probably faster for longer substrings,
but then one wouldn't use ${s#"1024???s"} anyway -
one would switch away from sh.

function                                             old     new   delta
subevalvar                                          1457    1503     +46

Signed-off-by: Alin Mr <almr.oss@outlook.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 02:15:52 +02:00
Ron Yorston 94eb1c4dc6 libbb: better coreutils compatibility for realpath
Add some tests which coreutils realpath pass but BusyBox realpath
fails (bar one).  Adjust xmalloc_realpath_coreutils() so the tests
pass:

- Expand symbolic links before testing whether the last path component
  exists.

- When the link target is a relative path canonicalize it by passing
  it through xmalloc_realpath_coreutils() as already happens for
  absolute paths.

- Ignore trailing slashes when finding the last path component and
  correctly handle the case where the only slash is at the start of
  the path.  This requires ignoring superfluous leading slashes.

- Undo all changes to the path so error messages from the caller show
  the original filename.

function                                             old     new   delta
xmalloc_realpath_coreutils                           214     313     +99

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-09 01:47:12 +02:00
Denys Vlasenko 86ba007b84 xxd: fix -p -r, closes 13881
function                                             old     new   delta
xxd_main                                             893     890      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 23:03:54 +02:00
Denys Vlasenko d315a77a79 resize: use tcgetattr(TCSAFLUSH) instead of TCSANOW, closes 13811
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 22:18:24 +02:00
Andrej Valek ecac9853f2 mktemp: add --tmpdir option
Make mktemp more compatible with coreutils.
- add "--tmpdir" option
- add long variants for "d,q,u" options

Note: Upstream ca-certificate update script started using this option.

function                                             old     new   delta
.rodata                                           104179  104219     +40
mktemp_main                                          186     194      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 48/0)               Total: 48 bytes

Signed-off-by: Andrej Valek <andrej.valek@siemens.com>
Signed-off-by: Peter Marko <peter.marko@siemens.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 21:02:56 +02:00
Denys Vlasenko b198e9aa93 tar: improve comments, add FIXMEs. no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 19:34:20 +02:00
Denys Vlasenko 049775b2ef libbb.h: fix logic selecting incorrect BB_STRTOOFF for !LFS configs
BB_STRTOOFF() was equal to bb_strtou(). On x86_64, it's incorrect.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 15:54:40 +02:00
Denys Vlasenko 84874785c2 httpd: if range is not specified, correctly fall back to read/write loop
range_start was staying -1, and comparison meant to detect
"is it the first sendfile that failed, or not the first?"
was making incorrect decision. The result: nothing is sent.

function                                             old     new   delta
send_file_and_exit                                   865     877     +12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 15:41:08 +02:00
Denys Vlasenko 50c5b36dd7 help: s/Don't daemonize/Run in foreground/g
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 15:02:53 +02:00
Denys Vlasenko d2e0d3f514 mdev: tweak --help
function                                             old     new   delta
packed_usage                                       33993   34008     +15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 14:30:50 +02:00
Denys Vlasenko cf4dc4a09d mount: "mount -o rw ...." should not fall back to RO mount
The reported case was an attempt to remount,rw a CD-ROM:

  mount -o remount,rw /mnt/sr0

which "succeeded" by falling back to RO:

  mount("/dev/sr0", "/mnt/sr0", 0x412862, MS_REMOUNT|MS_SILENT|MS_RELATIME, "nojoliet,check=s,map=n,blocksize"...) = -1 EROFS (Read-only file system)
  ...
  mount("/dev/sr0", "/mnt/sr0", 0x412862, MS_RDONLY|MS_REMOUNT|MS_SILENT|MS_RELATIME, "nojoliet,check=s,map=n,blocksize"...) = 0

Clearly, not what was intended!

function                                             old     new   delta
parse_mount_options                                  241     267     +26
mount_main                                          1198    1211     +13
singlemount                                         1301    1313     +12
inetd_main                                          1919    1911      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 51/-8)              Total: 43 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-08 02:20:10 +02:00
Nicholas Niro c28313bb17 ip: added support for setting netns on devices
function                                             old     new   delta
set_netns                                              -     130    +130
do_iplink                                           1252    1315     +63
.rodata                                           104173  104179      +6
packed_usage                                       34020   33993     -27
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/1 up/down: 199/-27)           Total: 172 bytes

Signed-off-by: Nicholas Niro <blowfist@xroutine.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 23:24:56 +02:00
Denys Vlasenko eb048a450c ps: fix -o pid=PID,args interpreting entire "PID,args" as header
procps-ng 3.3.15 does not do this.
(It could, allowing commas in headers and requiring
"ps -opid=PID -oargs" form for this case, but it does not).

function                                             old     new   delta
parse_o                                              167     190     +23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 21:55:16 +02:00
Ismael Luceno 421c8767ba find: Unify time comparisons
Split the common part into a function, to be reused.

The tail call is optimized, meaning now mmin/mtime just prepare arguments
and jump into the common code, thus near zero overhead.

This reduces code size slightly, e.g. on x86_64:
   text    data     bss     dec     hex filename
   4806       0       0    4806    12c6 findutils/find.o.orig
   4782       0       0    4782    12ae findutils/find.o

Of course, the savings are even greater when implementing atime/ctime
variants.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 16:40:37 +02:00
Ismael Luceno 0084c44799 config: find: Fix mtime/mmin description
s/modified time/modification time/

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 16:38:32 +02:00
YU Jinchengandcanyie 1f925038ab *: generalize "const trick"
While at it, change all "__asm__" to "asm"

Co-authored-by: canyie <31466456+canyie@users.noreply.github.com>
Signed-off-by: YU Jincheng <shana@zju.edu.cn>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-07 15:22:35 +02:00
Denys Vlasenko 17e6fb06b3 tls: whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 21:22:36 +02:00
Denys Vlasenko 5e9c617021 tls: P256: sp_256_sub_8_p256_mod always subtracts in-place, use that
i386:

function                                             old     new   delta
sp_256_mont_reduce_8                                 245     243      -2
sp_256_mont_dbl_8                                     26      24      -2
sp_256_ecc_mulmod_8                                 1161    1157      -4
sp_256_proj_point_dbl_8                              359     353      -6
sp_256_sub_8_p256_mod                                 71      32     -39
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/5 up/down: 0/-53)             Total: -53 bytes

non-asm code:

function                                             old     new   delta
sp_256_sub_8_p256_mod                                  -      12     +12
sp_256_mont_reduce_8                                 250     243      -7
sp_256_mont_dbl_8                                     31      24      -7
sp_256_ecc_mulmod_8                                 1171    1157     -14
sp_256_proj_point_dbl_8                              374     353     -21
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 12/-49)            Total: -37 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 20:19:30 +02:00
Denys Vlasenko 87e3f2e9f8 tls: P256: x86-64 optimized sp_256_sub_8_p256_mod
function                                             old     new   delta
sp_256_sub_8_p256_mod                                  -      53     +53
sp_256_mont_reduce_8                                 223     217      -6
sp_256_mont_dbl_8                                     38      32      -6
sp_256_ecc_mulmod_8                                 1535    1529      -6
sp_256_proj_point_dbl_8                              469     454     -15
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 53/-33)             Total: 20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 19:59:39 +02:00
Denys Vlasenko 911344a998 tls: P256: x86-64 assembly
function                                             old     new   delta
sp_256_mont_mul_8                                    127     155     +28
sp_256_proj_point_dbl_8                              448     469     +21
sp_256_mont_sub_8                                     23      35     +12
sp_256_mont_dbl_8                                     26      38     +12
sp_256_sub_8                                          44      49      +5
sp_256_ecc_mulmod_8                                 1530    1535      +5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 6/0 up/down: 83/0)               Total: 83 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 17:17:34 +02:00
Denys Vlasenko 22fd8fd3f4 tls: P256: tweak arm assembly (currently disabled)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 16:10:49 +02:00
Denys Vlasenko d74993d31d tls: P@256: remove "header comment is kept intact" comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 14:28:47 +02:00
Denys Vlasenko 567eefcaf8 tls: P256: do not dumplicate sp_256_sub_8()
function                                             old     new   delta
sp_256_proj_point_dbl_8                              359     374     +15
sp_256_ecc_mulmod_8                                 1159    1171     +12
sp_256_mont_reduce_8                                 245     250      +5
sp_256_mont_dbl_8                                     26      31      +5
sp_256_sub_8_p256_mod                                 43       -     -43
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 4/0 up/down: 37/-43)             Total: -6 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 14:25:54 +02:00
Denys Vlasenko 00f2cceb6a tls: P256: shrink sp_256_mul_add_8 a bit more
function                                             old     new   delta
sp_256_mont_reduce_8                                 257     245     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 10:15:29 +02:00
Denys Vlasenko c784284615 tls: P256: propagate constants, create dedicated "subtract p256_mod" function
8 instances of this subtraction probably warrant a few bytes more of code.

function                                             old     new   delta
sp_256_sub_8_p256_mod                                  -      71     +71
sp_256_mont_sub_8                                      -      29     +29
sp_256_mont_dbl_8                                      -      26     +26
sp_256_mont_reduce_8                                 262     257      -5
sp_256_ecc_mulmod_8                                 1171    1161     -10
sp_256_proj_point_dbl_8                              374     359     -15
static.sp_256_mont_sub_8                              29       -     -29
static.sp_256_mont_dbl_8                              31       -     -31
------------------------------------------------------------------------------
(add/remove: 3/2 grow/shrink: 0/3 up/down: 126/-90)            Total: 36 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 01:11:48 +02:00
Denys Vlasenko 2430fcfd8d tls: optimize sp_256_mont_reduce_8 in P256
The code size decrease is small, but we eliminate ALL multiplies!

function                                             old     new   delta
sp_256_mont_reduce_8                                 268     262      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-06 00:24:03 +02:00
Denys Vlasenko bbd723ebec tls: optimize sp_256_mul_8 in P256
function                                             old     new   delta
sp_256_mont_mul_8                                    151     150      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 23:19:18 +02:00
Denys Vlasenko 3b411ebbfc tls: replace "26-bit" P256 code with 32-bit one.
function                                             old     new   delta
sp_256_ecc_mulmod_8                                    -    1171   +1171
sp_256_mod_mul_norm_8                                  -     834    +834
sp_256_proj_point_dbl_8                                -     374    +374
sp_256_mont_reduce_8                                   -     268    +268
sp_256_mont_mul_8                                      -     151    +151
sp_256_sub_8                                           -      76     +76
sp_256_add_8                                           -      76     +76
sp_256_cmp_8                                           -      38     +38
static.sp_256_mont_dbl_8                               -      31     +31
static.sp_256_mont_sub_8                               -      29     +29
sp_256_to_bin_8                                        -      28     +28
sp_256_point_from_bin2x32                             50      73     +23
sp_256_mont_sqr_8                                      -       7      +7
sp_256_mont_sqr_10                                     7       -      -7
p256_mod                                              40      32      -8
curve_P256_compute_pubkey_and_premaster              186     167     -19
sp_256_sub_10                                         22       -     -22
sp_256_add_10                                         22       -     -22
sp_256_cmp_10                                         24       -     -24
sp_256_norm_10                                        31       -     -31
static.sp_256_mont_sub_10                             49       -     -49
static.sp_256_mont_dbl_10                             52       -     -52
static.sp_256_mul_add_10                              82       -     -82
sp_256_from_bin_10                                   119       -    -119
sp_256_to_bin_10                                     120       -    -120
sp_256_mont_reduce_10                                178       -    -178
sp_256_mont_mul_10                                   214       -    -214
sp_256_proj_point_dbl_10                             451       -    -451
sp_256_ecc_mulmod_10                                1216       -   -1216
sp_256_mod_mul_norm_10                              1305       -   -1305
------------------------------------------------------------------------------
(add/remove: 12/15 grow/shrink: 1/2 up/down: 3106/-3919)     Total: -813 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 20:01:38 +02:00
Denys Vlasenko 55578f2fb7 tls: fix the case of sp_256_mont_tpl_10() leaving striay high bits
It has no effect on correctness, but interferes with compating internal state
of different implementations.

function                                             old     new   delta
sp_256_proj_point_dbl_10                             443     451      +8
static.sp_256_mont_sub_10                             46      49      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 19:46:39 +02:00
Denys Vlasenko 81d8af1970 tls: fix (what looks like) a rare corner case bug in P256
function                                             old     new   delta
static.sp_256_mont_sub_10                             30      46     +16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 17:31:33 +02:00
Denys Vlasenko 92402d5e0a tls: remove one overzealous debugging statement
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 14:01:52 +02:00
Denys Vlasenko 137864f559 tls: add debugging scaffolding to P256 code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 13:50:11 +02:00
Denys Vlasenko 389329efbe tls: another P256 code shrink
Propagate constant arrays and scalars deeper down call chain.
Use sp_256_mont_mul_10 to implement sp_256_mont_sqr_10.

function                                             old     new   delta
sp_256_mont_mul_10                                     -     214    +214
sp_256_mont_reduce_10                                  -     178    +178
sp_256_mont_sqr_10                                     -       7      +7
static.sp_256_mont_reduce_10                         178       -    -178
static.sp_256_mont_mul_10                            214       -    -214
static.sp_256_mont_sqr_10                            234       -    -234
------------------------------------------------------------------------------
(add/remove: 3/3 grow/shrink: 0/0 up/down: 399/-626)         Total: -227 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 13:39:33 +02:00
Denys Vlasenko e730505034 tls: P256 code shrink
function                                             old     new   delta
sp_256_to_bin_10                                       -     120    +120
sp_256_from_bin_10                                     -     119    +119
sp_256_proj_point_dbl_10                             446     443      -3
curve_P256_compute_pubkey_and_premaster              191     186      -5
sp_256_point_from_bin2x32                             62      50     -12
sp_256_to_bin                                        120       -    -120
static.sp_256_from_bin                               149       -    -149
------------------------------------------------------------------------------
(add/remove: 2/2 grow/shrink: 0/3 up/down: 239/-289)          Total: -50 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-05 13:32:04 +02:00
Denys Vlasenko 934bb01d51 tls: "server cert is not RSA" is a fatal error
function                                             old     new   delta
tls_handshake                                       2022    2019      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 22:03:09 +02:00
Ron Yorston ed9aa89269 wget: implement --post-file
Add the --post-file option to send form data from a file.  As with
--post-data it's up to the user to ensure that the data is encoded
as appropriate:  all wget does is stuff the provided data into
the request.

The --post-data and --post-file options are mutually exclusive and
only one instance of either may be given.

Additionally:

- update the usage message to include missing details of the --post-data
  and --header options;

- free POST data if FEATURE_CLEAN_UP is enabled.

function                                             old     new   delta
packed_usage                                       34158   34214     +56
wget_main                                           2762    2805     +43
.rodata                                            99225   99240     +15
static.wget_longopts                                 266     278     +12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 126/0)             Total: 126 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 14:55:18 +02:00
Denys Vlasenko 1f5a44d20c tls: add scaffolding to selectively disable ciphers. no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 14:27:10 +02:00
Denys Vlasenko 7714518f1a tls: code shrink P256 code
function                                             old     new   delta
sp_256_to_bin                                        148     120     -28

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-10-01 13:51:39 +02:00
Denys Vlasenko ac36e70074 tls: remove unused define
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:03:23 +02:00
Ismael Luceno 35727f5741 less: Ignore -X
The flag disables termcap init/deinit of the terminal, which the applet
doesn't do anyway.

Signed-off-by: Ismael Luceno <ismael@iodev.co.uk>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-28 23:22:47 +02:00
Denys Vlasenko 5b026d1ecf ash: fix compile breakage in !ENABLE_ASH_ALIAS config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-28 17:41:56 +02:00
Denys Vlasenko 03ed86b39e libbb: code shrink in main() and scripted_main()
function                                             old     new   delta
main                                                  68      65      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-3)               Total: -3 bytes
   text	   data	    bss	    dec	    hex	filename
   1472	    560	     16	   2048	    800	busybox_old
   1398	    552	     16	   1966	    7ae	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-28 17:40:59 +02:00
Denys Vlasenko 1be73dd9ad shell: fix parsing of $(( (v)++ + NUM ))
function                                             old     new   delta
evaluate_string                                      988    1011     +23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-26 13:29:25 +02:00
Denys Vlasenko 62e433131b shell: enable more tests which are passing now
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-25 22:35:17 +02:00
Denys Vlasenko d84a604830 shell: fix arithmentic evaluation of "++7" and such (it is + + 7, i.e. 7)
function                                             old     new   delta
evaluate_string                                      945     988     +43

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-25 22:04:45 +02:00
Denys Vlasenko 627821e42b libbb/lineedit: tweak #if indenting, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-25 19:36:35 +02:00
Ron Yorston 56f0e886db cal: implement -m
Some people prefer the week to start on Monday.  Add the '-m'
option to support this.

function                                             old     new   delta
cal_main                                             926     966     +40
day_array                                            316     337     +21
packed_usage                                       34151   34158      +7
.rodata                                            99224   99225      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 69/0)               Total: 69 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-21 15:25:37 +02:00
Ron Yorston f27a6a94a7 libbb: code shrink parse_datestr (again)
Commit 9fe1548bb (date,touch: allow timezone offsets in dates)
mentioned the similarity between '@' format dates and those with
timezone offsets.  It didn't notice that as a result there's
common code which can be shared.

function                                             old     new   delta
parse_datestr                                        730     687     -43
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-43)             Total: -43 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-18 22:55:46 +02:00
Denys Vlasenko 6d2463ac01 libbb/lineedit: do not escape %^=+}]:, escape ~? in tab completion
function                                             old     new   delta
.rodata                                           104185  104180      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 17:33:32 +02:00
Denys Vlasenko 6279aec03d libbb: clarify what bb_mode_string() generates
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 17:10:38 +02:00
Ron Yorston 3a65435eaa libbb: ensure mode_string is NUL terminated
If the mode_string array is no longer static we can't rely on
it being NUL terminated.

function                                             old     new   delta
bb_mode_string                                       115     118      +3

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 16:51:01 +02:00
Denys Vlasenko 59ac467dc6 libbb: eliminate a static data array in bb_mode_string()
function                                             old     new   delta
print_stat                                           861     869      +8
header_verbose_list_ar                                73      77      +4
display_single                                       975     979      +4
header_verbose_list                                  237     239      +2
bb_mode_string                                       124     115      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/1 up/down: 18/-9)               Total: 9 bytes
   text	   data	    bss	    dec	    hex	filename
1043136	    559	   5052	1048747	 1000ab	busybox_old
1043153	    559	   5020	1048732	 10009c	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 01:18:31 +02:00
Denys Vlasenko 4958c18134 libbb: code shrink bb_parse_mode
function                                             old     new   delta
bb_parse_mode                                        393     398      +5
static.who_mask                                       16       8      -8
static.perm_mask                                      24      12     -12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 5/-20)             Total: -15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 00:47:23 +02:00
Denys Vlasenko 2df4e0a370 chmod: correctly report changed modes
Chmod used to incorrectly report as changed even files for which the
mode did not change. This was caused by extra bits in the st_mode, that
were not present when parsed from passed argument in the form of octal
number.

Patch by Wolf <wolf@wolfsden.cz>.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 00:39:21 +02:00
Ron Yorston 9fe1548bbf date,touch: allow timezone offsets in dates
Allow ISO 8601 style dates to include a timezone offset.  Like
the '@' format these dates aren't relative to the user's current
timezone and shouldn't be subject to DST adjustment.

- The implementation uses the strptime() '%z' format specifier.
  This an extension which may not be available so the use of
  timezones is a configuration option.

- The 'touch' applet has been updated to respect whether DST
  adjustment is required, matching 'date'.

function                                             old     new   delta
parse_datestr                                        624     730    +106
static.fmt_str                                       106     136     +30
touch_main                                           388     392      +4
date_main                                            818     819      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 141/0)             Total: 141 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-17 00:11:30 +02:00
Ron Yorston 83e20cb81c getopt: code shrink
function                                             old     new   delta
.rodata                                            99277   99290     +13
normalize                                            177     142     -35
getopt_main                                          675     622     -53
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 13/-88)            Total: -75 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-16 01:09:32 +02:00
Denys Vlasenko 704c596563 ash: introduce bash-like $FUNCNAME
Patch adapted from Roberto A. Foglietta <roberto.foglietta@gmail.com>
work.

function                                             old     new   delta
lookupvar                                            106     150     +44
evalfun                                              369     408     +39
ash_main                                            1218    1242     +24
varinit_data                                         156     168     +12
.rodata                                           104162  104172     +10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/0 up/down: 129/0)             Total: 129 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-15 19:31:44 +02:00
Ron Yorston 3512ef8018 libbb: code shrink parse_datestr
The default build uses strptime() in parse_datestr() to support the
'month_name d HH:MM:SS YYYY' format of GNU date.  If we've linked
with strptime() there's an advantage is using it for other formats
too.

There's no change to the non-default, non-DESKTOP build.

function                                             old     new   delta
fmt_str                                                -     106    +106
.rodata                                            99216   99145     -71
parse_datestr                                        948     624    -324
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 106/-395)         Total: -289 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-15 08:09:45 +02:00
Ron Yorston 5726df5f94 ash: let ignoreeof only affect interactive shells
Commit fb7d6c89 from Harald van Dijk's gwsh variant of ash
(https://github.com/hvdijk/gwsh):

    ignoreeof is documented as only having an effect for interactive shells,
    but is implemented as having mostly the same effect for interactive
    shells as for non-interactive shells. Change the implementation to match
    the documentation.

    Test case:

      $SHELL -o ignoreeof /dev/null

function                                             old     new   delta
cmdloop                                              359     361      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 2/0)                 Total: 2 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-14 08:25:58 +02:00
Ron Yorston 50239a665c ash: stopped jobs should only prevent exit from interactive shell
When the user tries to exit an interactive shell with stopped jobs
present the shell issues a warning and only exits if the user
insists by trying to exit again.

This shouldn't apply to non-interactive shells.

Reported-by: Roberto A. Foglietta <roberto.foglietta@gmail.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-14 08:16:15 +02:00
Ron Yorston 0beee20977 ash: fix ignoreeof option
The ignoreeof option should prevent an interactive shell from
exiting on EOF.  This hasn't worked in BusyBox ash since commit
727752d2d (ash: better fix for ash -c 'echo 5&' and ash -c 'sleep 5&'
with testcase).

Commit 3b4d04b77e (ash: input: Allow two consecutive calls to pungetc)
pulled in improved support for multiple calls to pungetc from dash,
thus rendering much of commit 727752d2d obsolete.  Removing this old
code fixes the problem with ignoreeof.

function                                             old     new   delta
__pgetc                                              605     587     -18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-18)             Total: -18 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-14 08:16:15 +02:00
Denys Vlasenko 9346ea9550 df: "support" -H as an alias of -h
function                                             old     new   delta
df_main                                             1065    1068      +3
.rodata                                           104232  104233      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 4/0)                 Total: 4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-11 00:47:03 +02:00
Denys Vlasenko 40f2dd7dd2 httpd: fix config deps
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-10 10:07:42 +02:00
Denys Vlasenko c00bcf2d2c libbb: reuse "bad port" error message string
function                                             old     new   delta
.rodata                                           104251  104232     -19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-10 09:48:55 +02:00
Denys Vlasenko c421388dca blkdiscard: accept -f (force) as no-op
function                                             old     new   delta
.rodata                                           104250  104251      +1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-10 00:20:05 +02:00
Denys Vlasenko 0599e0f87b basename: implement -a and -s SUFFIX
function                                             old     new   delta
basename_main                                        145     207     +62
packed_usage                                       33914   33950     +36
.rodata                                           104241  104250      +9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 107/0)             Total: 107 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 23:45:13 +02:00
Denys Vlasenko 7ab9cd2398 libbb: make bb_lookup_port() abort on bad port names
Also, no need to preserve errno

function                                             old     new   delta
.rodata                                           104247  104241      -6
bb_lookup_port                                        97      83     -14
nc_main                                             1039    1018     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-41)             Total: -41 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 22:00:44 +02:00
Sergey Ponomarev 82c5eb8e46 httpd,telnetd: make default port configurable
BusyBox on Termux can't use ports less than 1024 it's patched to change default port for httpd to 8080 and telnetd to 8023.

https://github.com/termux/termux-packages/blob/master/packages/busybox/0011-networking-telnetd-default-port.patch
https://github.com/termux/termux-packages/blob/master/packages/busybox/0010-networking-httpd-default-port.patch

To avoid such patches we can make port configurable.

function                                             old     new   delta
packed_usage                                       33920   33914      -6

Signed-off-by: Sergey Ponomarev <stokito@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 21:42:48 +02:00
Denys Vlasenko 857800c655 awk: never return NULL from awk_printf()
function                                             old     new   delta
awk_printf                                           651     628     -23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 19:26:39 +02:00
Denys Vlasenko e60c56932e awk: code shrink
function                                             old     new   delta
awk_printf                                           652     651      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 19:13:32 +02:00
Denys Vlasenko 8a0adba9f6 awk: code shrink: avoid duplicate NUL checks and strlen()
function                                             old     new   delta
awk_printf                                           665     652     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 18:58:39 +02:00
Ron Yorston 305a30d80b awk: fix read beyond end of buffer
Commit 7d06d6e18 (awk: fix printf %%) can cause awk printf to read
beyond the end of a strduped buffer:

  2349      while (*f && *f != '%')
  2350          f++;
  2351      c = *++f;

If the loop terminates because a NUL character is detected the
character after the NUL is read.  This can result in failures
depending on the value of that character.

function                                             old     new   delta
awk_printf                                           672     665      -7

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 18:12:21 +02:00
Denys Vlasenko eb60777769 ash: eval: Prevent recursive PS4 expansion
Date: Wed, 27 May 2020 13:19:10 +1000
eval: Prevent recursive PS4 expansion

    Yaroslav Halchenko <yoh@onerussian.com> wrote:
    > I like to (ab)use PS4 and set -x for tracing execution of scripts.
    > Reporting time and PID is very useful in this context.
    >
    > I am not 100% certain if bash's behavior (of actually running the command
    > embedded within PS4 string, probably eval'ing it) is actually POSIX
    > compliant, posh seems to not do that; but I think it is definitely not
    > desired for dash to just stall:
    >
    > - the script:
    > #!/bin/sh
    > set -x
    > export PS4='+ $(date +%T.%N) [$$] '
    > echo "lets go"
    > sleep 1
    > echo "done $var"
    >
    > - bash:
    > /tmp > bash --posix test.sh
    > +export 'PS4=+ $(date +%T.%N) [$$] '
    > +PS4='+ $(date +%T.%N) [$$] '
    > + 09:15:48.982296333 [2764323] echo 'lets go'
    > lets go
    > + 09:15:48.987829613 [2764323] sleep 1
    > + 09:15:49.994485037 [2764323] echo 'done '
    > done
    >
    ...
    > - dash: (stalls it set -x)
    > /tmp > dash test.sh
    > +export PS4=+ $(date +%T.%N) [$$]
    > ^C^C

    This patch fixes the infinite loop caused by repeated expansions
    of PS4.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-09 16:29:37 +02:00
Denys Vlasenko 48cb983b13 ash: parser: Get rid of PEOA
Upstream commit:

    Date: Wed, 27 May 2020 12:19:13 +1000
    parser: Get rid of PEOA

    PEOA is a special character used to mark an alias as being finished
    so that we don't enter an infinite loop with nested aliases.  It
    complicates the parser because we have to ensure that it is skipped
    where necessary and not copied to the resulting token text.

    This patch removes it and instead delays the marking of aliases
    until the second pgetc.  This has the same effect as the current
    PEOA code while keeping the complexities within the input code.

This adds ~32 bytes of global data:

function                                             old     new   delta
__pgetc                                                -     512    +512
freestrings                                            -      95     +95
popfile                                               86     110     +24
pushstring                                           141     160     +19
basepf                                                76      84      +8
syntax_index_table                                   258     257      -1
S_I_T                                                 30      28      -2
.rodata                                           104255  104247      -8
pgetc_without_PEOA                                    13       -     -13
xxreadtoken                                          230     215     -15
popstring                                            158     120     -38
readtoken1                                          3110    3045     -65
pgetc                                                547      22    -525
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 3/7 up/down: 658/-667)           Total: -9 bytes
   text	   data	    bss	    dec	    hex	filename
1043102	    559	   5020	1048681	 100069	busybox_old
1043085	    559	   5052	1048696	 100078	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 09:52:04 +02:00
Denys Vlasenko 8c68ae8416 ash: parser: Fix alias expansion after heredoc or newlines
Upstream commit:

    Date: Wed, 29 Apr 2020 00:19:59 +1000
    parser: Fix alias expansion after heredoc or newlines

    This script should print OK:

        alias a="case x in " b=x
        a
        b) echo BAD;; esac

        alias BEGIN={ END=}
        BEGIN
    	cat <<- EOF > /dev/null
    		$(:)
    	EOF
        END
        : <<- EOF &&
    		$(:)
        EOF
        BEGIN
    	echo OK
        END

    However, because the value of checkkwd is either zeroed when it
    shouldn't, or isn't zeroed when it should, dash currently gets
    it wrong in every case.

    This patch fixes it by saving checkkwd and zeroing it where needed.

function                                             old     new   delta
readtoken                                            157     176     +19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 01:43:12 +02:00
Denys Vlasenko c540256127 ash: use pgetc_eatbnl() in more places, take 3
Adding previously skipped "readtoken1(pgetc_eatbnl(), syntax_type..." change
from upstream commit:

    Date:   Thu Mar 8 08:37:11 2018 +0100
    parser: use pgetc_eatbnl() in more places

    dash has a pgetc_eatbnl function in parser.c which skips any
    backslash-newline combinations. It's not used everywhere it could be.
    There is also some duplicated backslash-newline handling elsewhere in
    parser.c. Replace most of the calls to pgetc() with calls to
    pgetc_eatbnl() and remove the duplicated backslash-newline handling.

Testcase:
	PS1='\
	:::'
should result in ::: prompt, not <newline>::: prompt

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 01:13:40 +02:00
Denys Vlasenko 1c06ddd8bb ash: parser: Save and restore heredoclist in expandstr
Upstream commit:

    Date: Sun, 17 May 2020 23:36:25 +1000
    parser: Save and restore heredoclist in expandstr

    On Sun, May 17, 2020 at 01:19:28PM +0100, Harald van Dijk wrote:
    > This still does not restore the state completely. It does not clean up any
    > pending heredocs. I see:
    >
    >   $ PS1='$(<<EOF "'
    >   src/dash: 1: Syntax error: Unterminated quoted string
    >   $(<<EOF ":
    >   >
    >
    > That is, after entering the ':' command, the shell is still trying to read
    > the heredoc from the prompt.

    This patch saves and restores the heredoclist in expandstr.

    It also removes a bunch of unnecessary volatiles as those variables
    are only referenced in case of a longjmp other than one started by
    a signal like SIGINT.

function                                             old     new   delta
expandstr                                            268     255     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 00:56:53 +02:00
Denys Vlasenko 30af5938af ash: parser: Fix handling of empty aliases
Upstream commit:

    Date: Tue, 28 Apr 2020 01:15:26 +1000
    parser: Fix handling of empty aliases

    Dash was incorrectly handling empty aliases. When attempting to use an
    empty alias with nothing else, I'm (incorrectly) prompted for more
    input:

    ```
    $ alias empty=''
    $ empty
    >
    ```

    Other shells (e.g., bash, yash) correctly handle the lone, empty alias as an
    empty command:

    ```
    $ alias empty=''
    $ empty
    $
    ```

    The problem here is that we incorrectly enter the loop eating TNLs
    in readtoken().  This patch fixes it by setting checkkwd correctly.

function                                             old     new   delta
list                                                 351     355      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-08 00:39:16 +02:00
Denys Vlasenko 6a9b3f7acf shuf: add a TODO, code shrink
function                                             old     new   delta
shuf_main                                            501     500      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 22:51:42 +02:00
Denys Vlasenko 574b9c446d hush: fix var_LINENO3.tests failure
function                                             old     new   delta
parse_and_run_string                                  40      62     +22
i_getch                                              105     102      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 22/-3)              Total: 19 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 21:44:44 +02:00
Denys Vlasenko bcff3a7b5a shell/ash_test/run-all: unset locale/language variables
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 18:24:08 +02:00
Denys Vlasenko 64aa86b720 ash: LINENO starts from 0 in -c SCRIPT mode
The var_LINENO3.tests fails for hush: it does start from 0, but does not increment.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 18:16:45 +02:00
Denys Vlasenko d6c9cbc072 ash: fix LINENO in functions
From larger patch by Roberto A. Foglietta <roberto.foglietta@gmail.com>

function                                             old     new   delta
evalfun                                              348     369     +21
ash_main                                            1202    1218     +16
setinputstring                                        65      73      +8
lookupvar                                            116     106     -10
evaltree                                             772     753     -19
evalsubshell                                         192     173     -19
evalfor                                              175     156     -19
evalcase                                             273     254     -19
evalcommand                                         1560    1536     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/6 up/down: 45/-110)           Total: -65 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 18:01:49 +02:00
Denys Vlasenko 0d7dfa9012 ash: support testsuite for !FEATURE_SUID_CONFIG_QUIET configs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 17:34:58 +02:00
Denys Vlasenko e53c7dbafc hush: fix set -n to act immediately, not just after run_list()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 02:25:52 +02:00
Denys Vlasenko f415e21a7d ash: eval: Do not cache value of eflag in evaltree
Upsteam commit:

    Date: Mon, 17 May 2021 15:19:23 +0800
    eval: Do not cache value of eflag in evaltree

    Patrick Brünn <P.Bruenn@beckhoff.com> wrote:
    > Since we are migrating to Debian bullseye, we discovered a new behavior
    > with our scripts, which look like this:
    >>cleanup() {
    >>        set +e
    >>        rmdir ""
    >>}
    >>set -eu
    >>trap 'cleanup' EXIT INT TERM
    >>echo 'Hello world!'
    >
    > With old dash v0.5.10.2 this script would return 0 as we expected it.
    > But since commit 62cf6955f8abe875752d7163f6f3adbc7e49ebae it returns
    > the last exit code of our cleanup function.
    ...
    Thanks for the report.  This is actually a fairly old bug with
    set -e that's just been exposed by the exit status change.  What's
    really happening is that cleanup itself is triggering a set -e
    exit incorrectly because evaltree cached the value of eflag prior
    to the function call.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 02:01:03 +02:00
Denys Vlasenko 41beb53787 ash: eval: Check nflag in evaltree instead of cmdloop
Upstream commit:

    Date: Thu, 4 Jun 2020 21:53:55 +1000
    eval: Check nflag in evaltree instead of cmdloop

    This patch moves the nflag check from cmdloop into evaltree.  This
    is so that nflag will be in force even if we enter the shell via a
    path other than cmdloop, e.g., through sh -c.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 01:52:21 +02:00
Roberto A. Foglietta e0bf3df020 ash: add bash-like ERR trap and set -E
While at it, stop incrementing LINENO inside traps

function                                             old     new   delta
evaltree                                             567     762    +195
evalfun                                              268     348     +80
trapcmd                                              286     333     +47
dotrap                                               129     157     +28
exitshell                                            120     139     +19
readtoken1                                          3096    3110     +14
nlprompt                                              25      39     +14
nlnoprompt                                            19      33     +14
.rodata                                           104245  104255     +10
forkchild                                            610     617      +7
optletters_optnames                                   64      68      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 11/0 up/down: 432/0)            Total: 432 bytes

Signed-off-by: Roberto A. Foglietta <roberto.foglietta@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-07 01:28:50 +02:00
Denys Vlasenko 4b032a4d6c chat: hopefully fix infinite spinning on input EOF
function                                             old     new   delta
chat_main                                           1295    1303      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-06 17:38:18 +02:00
Daniel Thau 7d06d6e186 awk: fix printf %%
A refactor of the awk printf code in
e2e3802987
appears to have broken the printf interpretation of two percent signs,
which normally outputs only one percent sign.

The patch below brings busybox awk printf behavior back into alignment
with the pre-e2e380 behavior, the busybox printf util, and other common
(awk and non-awk) printf implementations.

function                                             old     new   delta
awk_printf                                           626     672     +46

Signed-off-by: Daniel Thau <danthau at bedrocklinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-05 03:42:51 +02:00
Denys Vlasenko f4ba69d476 shuf: make -i 99999999990-100000000000 work even on 32 bits
function                                             old     new   delta
shuf_main                                            443     501     +58
.rodata                                           104238  104245      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 65/0)               Total: 65 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-04 17:00:22 +02:00
Denys Vlasenko 8aa626ffff udhcp: add comments, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-04 01:50:42 +02:00
Denys Vlasenko d7e39f26d7 examples/var_service/fw/run: allow extif's to be more than one iface
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 23:53:48 +02:00
Ron Yorston 4a36ef11ac ash: regressions in process substitution
Stacy Harper reports that this script:

   test() { . /tmp/bb_test; }
   echo "export TEST=foo" >/tmp/bb_test
   test 2>/dev/null
   echo "$TEST"

correctly prints 'foo' in BusyBox 1.33 but hangs in 1.34.

Bisection suggested the problem was caused by commit a1b0d3856 (ash: add
process substitution in bash-compatibility mode).  Removing the call to
unwindredir() in cmdloop() introduced in that commit makes the script
work again.

Additionally, these examples of process substitution:

   while true; do cat <(echo hi); done
   f() { while true; do cat <(echo hi); done }
   f

result in running out of file descriptors.  This is a regression from
v5 of the process substitution patch caused by changes to evalcommand()
not being transferred to v6.

function                                             old     new   delta
static.pushredir                                       -      99     +99
evalcommand                                         1729    1750     +21
exitreset                                             69      86     +17
cmdloop                                              372     365      -7
unwindredir                                           28       -     -28
pushredir                                            112       -    -112
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 2/1 up/down: 137/-147)          Total: -10 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 17:49:00 +02:00
Denys Vlasenko f02691939e dhcprelay: change two more variables to unsigned
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 17:09:12 +02:00
Denys Vlasenko 3f2d969db9 udhcp: clarify aspects of relay operation, add TODOs and FIXMEs, tweak --help
function                                             old     new   delta
packed_usage                                       33891   33920     +29
dhcprelay_main                                       943     926     -17
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 29/-17)             Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 16:24:52 +02:00
Denys Vlasenko 62d0c8e028 udhcpd: check config file for bad IP ranges (start > end)
function                                             old     new   delta
.rodata                                           104209  104238     +29
read_config                                          208     225     +17
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 46/0)               Total: 46 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 14:40:54 +02:00
Denys Vlasenko d99dee944e udhcpd: update --help to include -a MSEC
function                                             old     new   delta
packed_usage                                       33886   33891      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-02 14:02:23 +02:00
Ron Yorston a51d953b95 vi: further changes to colon addresses
Improved error messages:

- specify when a search fails or a mark isn't set;
- warn when line addresses are out of range or when a range of
  lines is reversed.

Addresses are limited to the number of lines in the file so a
command like ':2000000000' (go to the two billionth line) no
longer causes a long pause.

Improved vi compatibility of '+' and '-' operators that aren't
followed immediately by a number:

   :4+++=       7
   :3-2=        1
   :3 - 2=      4 (yes, really!)

In a command like ':,$' the empty address before the separator now
correctly refers to the current line.  (The similar case ':1,' was
already being handled.)

And all with a tidy reduction in bloat (32-bit build):

function                                             old     new   delta
colon                                               4029    4069     +40
.rodata                                            99348   99253     -95
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 40/-95)            Total: -55 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-29 20:07:20 +02:00
Denys Vlasenko 6d3da732a5 bzip: make ftab[] and crc32table[] member arrays of EState, do not allocate
function                                             old     new   delta
mainSort                                             941     986     +45
fallbackSort                                        1471    1469      -2
add_pair_to_block                                    194     188      -6
compressStream                                       543     515     -28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 45/-36)              Total: 9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-29 15:32:42 +02:00
Denys Vlasenko 49a2e484b5 shuf: in -i RANGE, accept numbers up to width of pointers
function                                             old     new   delta
.rodata                                           108468  108474      +6
shuf_main                                            555     542     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-29 14:39:01 +02:00
Denys Vlasenko 60f4843468 shuf: with -i LOW-HIGH, do not allow any argv's
function                                             old     new   delta
shuf_main                                            436     441      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 15:52:34 +02:00
Denys Vlasenko d59f539d57 shuf: tweak --help text
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 15:48:22 +02:00
Denys Vlasenko 1b661122a8 mount: code shrink
function                                             old     new   delta
append_mount_options                                 174     157     -17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 02:31:26 +02:00
Denys Vlasenko dbdf9e0ab1 mount: with -w, do not fall back to read-only mounts
function                                             old     new   delta
mount_it_now                                         364     358      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-23 02:30:13 +02:00
Ron Yorston 922b58b3e4 tar,smemcap: silence compiler warning
gcc 11.2.1 complains that the tar header checksum might overflow
the checksum field.  It won't and using an unsigned int for the
calculation seems to convince the compiler too.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 15:44:57 +02:00
Denys Vlasenko 1e7ca18591 Regularize "NUL terminated input" --help texts
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 15:43:29 +02:00
Ron Yorston 8817e285b7 shuf: speed-up when limited output is requested
A user noted that the following command was slower than they
expected:

   busybox shuf -i "1500000000-$(date +%s)" -n 5

At time of writing the range contains 128 million values.  On my
system this takes 7.7s whereas 'shuf' from coreutils takes a
handful of milliseconds.

Optimise BusyBox 'shuf' for cases where -n is specified by stopping
shuffling once the required number of lines have been processed.
On my system the time for the example is reduced to 0.4s.

function                                             old     new   delta
shuf_main                                            520     540     +20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 20/0)               Total: 20 bytes

v2: Code shrink.  Since outlines <= numlines:
    - the loop in shuffle_lines() only needs to test the value of
      outlines;
    - shuffle_lines() can be called unconditionally.
    Update timing to allow for the 13 million seconds elapsed since v1.

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 15:40:21 +02:00
Ron Yorston 74c4f356ae vi: code shrink print_literal()
Simplify the function print_literal() which is used to format a
string that may contain unprintable characters or control
characters.

- Unprintable characters were being displayed in normal text rather
  than the bold used for the rest of the message.  This doesn't seem
  particularly helpful and it upsets the calculation of the width
  of the message in show_status_line().  Use '?' rather than '.' for
  unprintable characters.

- Newlines in the string were displayed as both '^J' and '$', which
  is somewhat redundant.

function                                             old     new   delta
not_implemented                                      199     108     -91
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-91)             Total: -91 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 00:09:57 +02:00
Ron Yorston 08ad934ac4 vi: searches in colon commands should wrap
The '/' and '?' search commands wrap to the other end of the buffer
if the search target isn't found.  When searches are used to specify
addresses in colon commands they should do the same.

(In traditional vi and vim this behaviour is controlled by the
'wrapscan' option.  BusyBox vi doesn't have this option and always
uses the default behaviour.)

function                                             old     new   delta
colon                                               4033    4077     +44
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 44/0)               Total: 44 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 00:09:57 +02:00
Ron Yorston 4357569fdc rev: correct output for long input lines
The input buffer is initialised to a reasonable size and extended
if necessary.  When this happened the offset into the buffer wasn't
reset to zero so subsequent lines were appended to the long line.

Fix this and add some tests.

function                                             old     new   delta
rev_main                                             377     368      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-9)               Total: -9 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-22 00:08:18 +02:00
Denys Vlasenko 62d5a1e56f tar,smemcap: commonalyze checksumming code for tar header
function                                             old     new   delta
chksum_and_xwrite_tar_header                           -      99     +99
writeheader                                          280     199     -81
chksum_and_xwrite                                    102       -    -102
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 0/1 up/down: 99/-183)           Total: -84 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 17:58:49 +02:00
Ron Yorston 38e9c8c95b vi: don't right shift empty lines
The right shift command ('>') shouldn't affect empty lines.

function                                             old     new   delta
do_cmd                                              4860    4894     +34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 34/0)               Total: 34 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 15:26:09 +02:00
Ron Yorston f9217cd235 vi: support ~/.exrc
Run initialisation commands from ~/.exrc.  As with EXINIT these
commands are processed before the first file is loaded.

Commands starting with double quotes are ignored.  This is how
comments are often included in .exrc.

function                                             old     new   delta
vi_main                                              268     406    +138
colon                                               4033    4071     +38
.rodata                                           108411  108442     +31
packed_usage                                       34128   34118     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 207/-10)           Total: 197 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 15:26:09 +02:00
Ron Yorston f07772f19e vi: changes to handling of -c and EXINIT
Rewrite handling of command line arguments so any number of -c
commands will be processed.  Previously only two -c commands
were allowed (or one if EXINIT was set).

Process commands from EXINIT before the first file is read into
memory, as specified by POSIX.

function                                             old     new   delta
run_cmds                                               -      77     +77
.rodata                                           108410  108411      +1
vi_main                                              305     268     -37
edit_file                                            816     764     -52
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/2 up/down: 78/-89)            Total: -11 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 15:26:09 +02:00
Denys Vlasenko 29b53ef03f udhcp: fix build breakage on MIPS
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 13:38:16 +02:00
Denys Vlasenko 9d286a0a55 Start 1.35.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-19 15:06:57 +02:00
285 changed files with 9920 additions and 3291 deletions

No files matched your search

+3
View File
@@ -181,3 +181,6 @@ Jie Zhang <jie.zhang@analog.com>
Maxime Coste <mawww@kakoune.org>
paste implementation
Roger Knecht <rknecht@pm.me>
tree
+2 -10
View File
@@ -1,6 +1,6 @@
VERSION = 1
PATCHLEVEL = 34
SUBLEVEL = 0
PATCHLEVEL = 36
SUBLEVEL = 1
EXTRAVERSION =
NAME = Unnamed
@@ -1301,14 +1301,6 @@ quiet_cmd_rmdirs = $(if $(wildcard $(rm-dirs)),CLEAN $(wildcard $(rm-dirs)))
quiet_cmd_rmfiles = $(if $(wildcard $(rm-files)),CLEAN $(wildcard $(rm-files)))
cmd_rmfiles = rm -f $(rm-files)
a_flags = -Wp,-MD,$(depfile) $(AFLAGS) $(AFLAGS_KERNEL) \
$(NOSTDINC_FLAGS) $(CPPFLAGS) \
$(modkern_aflags) $(EXTRA_AFLAGS) $(AFLAGS_$(*F).o)
quiet_cmd_as_o_S = AS $@
cmd_as_o_S = $(CC) $(a_flags) -c -o $@ $<
# read all saved command lines
targets := $(wildcard $(sort $(targets)))
+7 -4
View File
@@ -87,14 +87,14 @@ endif
#CFLAGS += $(call cc-option,-Wconversion,)
ifneq ($(CONFIG_DEBUG),y)
CFLAGS += $(call cc-option,-Os,$(call cc-option,-O2,))
CFLAGS += $(call cc-option,-Oz,$(call cc-option,-Os,$(call cc-option,-O2,)))
else
CFLAGS += $(call cc-option,-g,)
#CFLAGS += "-D_FORTIFY_SOURCE=2"
ifeq ($(CONFIG_DEBUG_PESSIMIZE),y)
CFLAGS += $(call cc-option,-O0,)
else
CFLAGS += $(call cc-option,-Os,$(call cc-option,-O2,))
CFLAGS += $(call cc-option,-Oz,$(call cc-option,-Os,$(call cc-option,-O2,)))
endif
endif
ifeq ($(CONFIG_DEBUG_SANITIZE),y)
@@ -151,8 +151,8 @@ LDLIBS += m
# gcc-4.2.1 fails if we try to feed C source on stdin:
# echo 'int main(void){return 0;}' | $(CC) $(CFLAGS) -lcrypt -o /dev/null -xc -
# fall back to using a temp file:
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) -lcrypt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
RT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) $(CFLAGS_busybox) -lcrypt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
RT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) $(CFLAGS_busybox) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
endif
@@ -187,6 +187,9 @@ ifeq ($(CONFIG_FEATURE_NSLOOKUP_BIG),y)
ifneq (,$(findstring linux,$(shell $(CC) $(CFLAGS) -dumpmachine)))
LDLIBS += resolv
endif
ifneq (,$(findstring gnu,$(shell $(CC) $(CFLAGS) -dumpmachine)))
LDLIBS += resolv
endif
endif
ifeq ($(CONFIG_EFENCE),y)
+2 -1
View File
@@ -196,9 +196,10 @@ static int write_ar_archive(archive_handle_t *handle)
static void FAST_FUNC header_verbose_list_ar(const file_header_t *file_header)
{
const char *mode = bb_mode_string(file_header->mode);
char mode[12];
char *mtime;
bb_mode_string(mode, file_header->mode);
mtime = ctime(&file_header->mtime);
mtime[16] = ' ';
memmove(&mtime[17], &mtime[20], 4);
+35
View File
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2021 Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_FEATURE_TAR_CREATE) += chksum_and_xwrite_tar_header.o
//kbuild:lib-$(CONFIG_SMEMCAP) += chksum_and_xwrite_tar_header.o
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC chksum_and_xwrite_tar_header(int fd, struct tar_header_t *hp)
{
/* POSIX says that checksum is done on unsigned bytes
* (Sun and HP-UX gets it wrong... more details in
* GNU tar source) */
const unsigned char *cp;
unsigned int chksum, size;
strcpy(hp->magic, "ustar ");
/* Calculate and store the checksum (the sum of all of the bytes of
* the header). The checksum field must be filled with blanks for the
* calculation. The checksum field is formatted differently from the
* other fields: it has 6 digits, a NUL, then a space -- rather than
* digits, followed by a NUL like the other fields... */
memset(hp->chksum, ' ', sizeof(hp->chksum));
cp = (const unsigned char *) hp;
chksum = 0;
size = sizeof(*hp);
do { chksum += *cp++; } while (--size);
sprintf(hp->chksum, "%06o", chksum);
xwrite(fd, hp, sizeof(*hp));
}
+53 -1
View File
@@ -38,6 +38,20 @@
//config: depends on FEATURE_CPIO_O
//config: help
//config: Passthrough mode. Rarely used.
//config:
//config:config FEATURE_CPIO_IGNORE_DEVNO
//config: bool "Support --ignore-devno like GNU cpio"
//config: default y
//config: depends on FEATURE_CPIO_O && LONG_OPTS
//config: help
//config: Optionally ignore device numbers when creating archives.
//config:
//config:config FEATURE_CPIO_RENUMBER_INODES
//config: bool "Support --renumber-inodes like GNU cpio"
//config: default y
//config: depends on FEATURE_CPIO_O && LONG_OPTS
//config: help
//config: Optionally renumber inodes when creating archives.
//applet:IF_CPIO(APPLET(cpio, BB_DIR_BIN, BB_SUID_DROP))
@@ -74,7 +88,13 @@
//usage: "\n -F FILE Input (-t,-i,-p) or output (-o) file"
//usage: "\n -R USER[:GRP] Set owner of created files"
//usage: "\n -L Dereference symlinks"
//usage: "\n -0 Input is separated by NULs"
//usage: "\n -0 NUL terminated input"
//usage: IF_FEATURE_CPIO_IGNORE_DEVNO(
//usage: "\n --ignore-devno"
//usage: )
//usage: IF_FEATURE_CPIO_RENUMBER_INODES(
//usage: "\n --renumber-inodes"
//usage: )
/* GNU cpio 2.9 --help (abridged):
@@ -162,17 +182,22 @@ enum {
IF_FEATURE_CPIO_P(OPTBIT_PASSTHROUGH,)
IF_LONG_OPTS( OPTBIT_QUIET ,)
IF_LONG_OPTS( OPTBIT_2STDOUT ,)
IF_FEATURE_CPIO_IGNORE_DEVNO(OPTBIT_IGNORE_DEVNO,)
IF_FEATURE_CPIO_RENUMBER_INODES(OPTBIT_RENUMBER_INODES,)
OPT_CREATE = IF_FEATURE_CPIO_O((1 << OPTBIT_CREATE )) + 0,
OPT_FORMAT = IF_FEATURE_CPIO_O((1 << OPTBIT_FORMAT )) + 0,
OPT_PASSTHROUGH = IF_FEATURE_CPIO_P((1 << OPTBIT_PASSTHROUGH)) + 0,
OPT_QUIET = IF_LONG_OPTS( (1 << OPTBIT_QUIET )) + 0,
OPT_2STDOUT = IF_LONG_OPTS( (1 << OPTBIT_2STDOUT )) + 0,
OPT_IGNORE_DEVNO = IF_FEATURE_CPIO_IGNORE_DEVNO((1 << OPTBIT_IGNORE_DEVNO)) + 0,
OPT_RENUMBER_INODES = IF_FEATURE_CPIO_RENUMBER_INODES((1 << OPTBIT_RENUMBER_INODES)) + 0,
};
#define OPTION_STR "it0uvdmLF:R:"
struct globals {
struct bb_uidgid_t owner_ugid;
ino_t next_inode;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
void BUG_cpio_globals_too_big(void);
@@ -206,6 +231,9 @@ static NOINLINE int cpio_o(void)
struct inodes_s *next;
struct name_s *names;
struct stat st;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
ino_t mapped_inode;
#endif
};
struct inodes_s *links = NULL;
@@ -260,6 +288,10 @@ static NOINLINE int cpio_o(void)
l = xzalloc(sizeof(*l));
l->st = st;
l->next = links;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
if (option_mask32 & OPT_RENUMBER_INODES)
l->mapped_inode = ++G.next_inode;
#endif
links = l;
break;
}
@@ -278,6 +310,11 @@ static NOINLINE int cpio_o(void)
free(line);
continue;
}
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
else if (option_mask32 & OPT_RENUMBER_INODES) {
st.st_ino = ++G.next_inode;
}
#endif
} else { /* line == NULL: EOF */
next_link:
if (links) {
@@ -285,6 +322,10 @@ static NOINLINE int cpio_o(void)
st = links->st;
name = links->names->name;
links->names = links->names->next;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
if (links->mapped_inode)
st.st_ino = links->mapped_inode;
#endif
/* GNU cpio is reported to emit file data
* only for the last instance. Mimic that. */
if (links->names == NULL)
@@ -304,6 +345,11 @@ static NOINLINE int cpio_o(void)
}
}
#if ENABLE_FEATURE_CPIO_IGNORE_DEVNO
if (option_mask32 & OPT_IGNORE_DEVNO)
st.st_dev = st.st_rdev = 0;
#endif
bytes += printf("070701"
"%08X%08X%08X%08X%08X%08X%08X"
"%08X%08X%08X%08X" /* GNU cpio uses uppercase hex */
@@ -379,6 +425,12 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
"null\0" No_argument "0"
"quiet\0" No_argument "\xff"
"to-stdout\0" No_argument "\xfe"
#if ENABLE_FEATURE_CPIO_IGNORE_DEVNO
"ignore-devno\0" No_argument "\xfd"
#endif
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
"renumber-inodes\0" No_argument "\xfc"
#endif
;
#endif
+1 -1
View File
@@ -1115,7 +1115,7 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
if (package_edge->type == EDGE_PRE_DEPENDS
|| package_edge->type == EDGE_DEPENDS
) {
int result=1;
int result = 1;
status_num = 0;
/* If we are inside an alternative then check
+1 -1
View File
@@ -107,7 +107,7 @@ void fallbackSimpleSort(uint32_t* fmap,
#define FALLBACK_QSORT_SMALL_THRESH 10
#define FALLBACK_QSORT_STACK_SIZE 100
static
static NOINLINE
void fallbackQSort3(uint32_t* fmap,
uint32_t* eclass,
int32_t loSt,
+3 -4
View File
@@ -99,9 +99,8 @@ void BZ2_bzCompressInit(bz_stream *strm, int blockSize100k)
s->ptr = (uint32_t*)s->arr1;
s->arr2 = xmalloc((n + BZ_N_OVERSHOOT) * sizeof(uint32_t));
s->block = (uint8_t*)s->arr2;
s->ftab = xmalloc(65537 * sizeof(uint32_t));
s->crc32table = crc32_filltable(NULL, 1);
crc32_filltable(s->crc32table, 1);
s->state = BZ_S_INPUT;
s->mode = BZ_M_RUNNING;
@@ -369,8 +368,8 @@ void BZ2_bzCompressEnd(bz_stream *strm)
s = strm->state;
free(s->arr1);
free(s->arr2);
free(s->ftab);
free(s->crc32table);
//free(s->ftab); // made it array member of s
//free(s->crc32table); // ditto
free(s);
}
+7 -4
View File
@@ -134,7 +134,7 @@ typedef struct EState {
/* for doing the block sorting */
uint32_t *arr1;
uint32_t *arr2;
uint32_t *ftab;
//uint32_t *ftab; //moved into this struct, see below
uint16_t *quadrant;
int32_t budget;
@@ -160,9 +160,6 @@ typedef struct EState {
uint32_t bsBuff;
int32_t bsLive;
/* guess what */
uint32_t *crc32table;
/* block and combined CRCs */
uint32_t blockCRC;
uint32_t combinedCRC;
@@ -185,6 +182,12 @@ typedef struct EState {
uint8_t len[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
/* guess what */
uint32_t crc32table[256];
/* for doing the block sorting */
uint32_t ftab[65537];
/* stack-saving measures: these can be local, but they are too big */
int32_t sendMTFValues__code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
int32_t sendMTFValues__rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
+1 -1
View File
@@ -654,7 +654,7 @@ static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* Subtract the 1 copy we'd output anyway to get extras */
--bd->writeCopies;
}
} /* for(;;) */
} /* for (;;) */
/* Decompression of this input block completed successfully */
bd->writeCRC = CRC = ~CRC;
+5 -1
View File
@@ -92,8 +92,12 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
/* Only size is always present, the rest may be missing in
* long filename pseudo file. Thus we decode the rest
* after dealing with long filename pseudo file.
*
* GNU binutils in deterministic mode hard codes mode to 0644 (NOT
* 0100644). AR archives can only contain files, so force file
* mode.
*/
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode));
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode)) | S_IFREG;
typed->gid = read_num(ar.formatted.gid, 10, sizeof(ar.formatted.gid));
typed->uid = read_num(ar.formatted.uid, 10, sizeof(ar.formatted.uid));
typed->mtime = read_num(ar.formatted.date, 10, sizeof(ar.formatted.date));
+11 -3
View File
@@ -147,6 +147,14 @@ static void process_pax_hdr(archive_handle_t *archive_handle, unsigned sz, int g
#endif
}
#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
static void die_if_bad_fnamesize(off_t sz)
{
if ((uoff_t)sz > 0xfff) /* more than 4k?! no funny business please */
bb_simple_error_msg_and_die("bad archive");
}
#endif
char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
{
file_header_t *file_header = archive_handle->file_header;
@@ -331,8 +339,6 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
file_header->name = xstrdup(tar.name);
}
/* Set bits 12-15 of the files mode */
/* (typeflag was not trashed because chksum does not use getOctal) */
switch (tar_typeflag) {
case '1': /* hardlink */
/* we mark hardlinks as regular files with zero size and a link name */
@@ -341,7 +347,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
* ... For tar archives written by pre POSIX.1-1988
* implementations, the size field usually contains the size of
* the file and needs to be ignored as no data may follow this
* header type. For POSIX.1- 1988 compliant archives, the size
* header type. For POSIX.1-1988 compliant archives, the size
* field needs to be 0. For POSIX.1-2001 compliant archives,
* the size field may be non zero, indicating that file data is
* included in the archive.
@@ -390,6 +396,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
/* free: paranoia: tar with several consecutive longnames */
free(p_longname);
/* For paranoia reasons we allocate extra NUL char */
die_if_bad_fnamesize(file_header->size);
p_longname = xzalloc(file_header->size + 1);
/* We read ASCIZ string, including NUL */
xread(archive_handle->src_fd, p_longname, file_header->size);
@@ -400,6 +407,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
goto again;
case 'K':
free(p_linkname);
die_if_bad_fnamesize(file_header->size);
p_linkname = xzalloc(file_header->size + 1);
xread(archive_handle->src_fd, p_linkname, file_header->size);
archive_handle->offset += file_header->size;
+3 -2
View File
@@ -9,6 +9,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
{
struct tm tm_time;
struct tm *ptm = &tm_time; //localtime(&file_header->mtime);
char modestr[12];
#if ENABLE_FEATURE_TAR_UNAME_GNAME
char uid[sizeof(int)*3 + 2];
@@ -29,7 +30,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
group = utoa(file_header->gid);
}
printf("%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
bb_mode_string(modestr, file_header->mode),
user,
group,
file_header->size,
@@ -46,7 +47,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
localtime_r(&file_header->mtime, ptm);
printf("%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
bb_mode_string(modestr, file_header->mode),
(unsigned)file_header->uid,
(unsigned)file_header->gid,
file_header->size,
+1 -1
View File
@@ -545,7 +545,7 @@ static enum xz_ret XZ_FUNC dec_block_header(struct xz_dec *s)
return XZ_OK;
}
static enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
static NOINLINE enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
{
enum xz_ret ret;
+2 -29
View File
@@ -254,32 +254,6 @@ static void putOctal(char *cp, int len, off_t value)
}
#define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
static void chksum_and_xwrite(int fd, struct tar_header_t* hp)
{
/* POSIX says that checksum is done on unsigned bytes
* (Sun and HP-UX gets it wrong... more details in
* GNU tar source) */
const unsigned char *cp;
int chksum, size;
strcpy(hp->magic, "ustar ");
/* Calculate and store the checksum (i.e., the sum of all of the bytes of
* the header). The checksum field must be filled with blanks for the
* calculation. The checksum field is formatted differently from the
* other fields: it has 6 digits, a null, then a space -- rather than
* digits, followed by a null like the other fields... */
memset(hp->chksum, ' ', sizeof(hp->chksum));
cp = (const unsigned char *) hp;
chksum = 0;
size = sizeof(*hp);
do { chksum += *cp++; } while (--size);
putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
/* Now write the header out to disk */
xwrite(fd, hp, sizeof(*hp));
}
# if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
static void writeLongname(int fd, int type, const char *name, int dir)
{
@@ -310,7 +284,7 @@ static void writeLongname(int fd, int type, const char *name, int dir)
/* + dir: account for possible '/' */
PUT_OCTAL(header.size, size);
chksum_and_xwrite(fd, &header);
chksum_and_xwrite_tar_header(fd, &header);
/* Write filename[/] and pad the block. */
/* dir=0: writes 'name<NUL>', pads */
@@ -441,8 +415,7 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
header_name, S_ISDIR(statbuf->st_mode));
# endif
/* Now write the header out to disk */
chksum_and_xwrite(tbInfo->tarFd, &header);
chksum_and_xwrite_tar_header(tbInfo->tarFd, &header);
/* Now do the verbose thing (or not) */
if (tbInfo->verboseFlag) {
+14 -3
View File
@@ -56,7 +56,7 @@
//kbuild:lib-$(CONFIG_UNZIP) += unzip.o
//usage:#define unzip_trivial_usage
//usage: "[-lnojpq] FILE[.zip] [FILE]... [-x FILE]... [-d DIR]"
//usage: "[-lnojpqK] FILE[.zip] [FILE]... [-x FILE]... [-d DIR]"
//usage:#define unzip_full_usage "\n\n"
//usage: "Extract FILEs from ZIP archive\n"
//usage: "\n -l List contents (with -q for short form)"
@@ -66,6 +66,7 @@
//usage: "\n -p Write to stdout"
//usage: "\n -t Test"
//usage: "\n -q Quiet"
//usage: "\n -K Do not clear SUID bit"
//usage: "\n -x FILE Exclude FILEs"
//usage: "\n -d DIR Extract into DIR"
@@ -118,6 +119,8 @@ typedef union {
#define FIX_ENDIANNESS_ZIP(zip) \
do { if (BB_BIG_ENDIAN) { \
(zip).fmt.method = SWAP_LE16((zip).fmt.method ); \
(zip).fmt.modtime = SWAP_LE16((zip).fmt.modtime ); \
(zip).fmt.moddate = SWAP_LE16((zip).fmt.moddate ); \
(zip).fmt.crc32 = SWAP_LE32((zip).fmt.crc32 ); \
(zip).fmt.cmpsize = SWAP_LE32((zip).fmt.cmpsize ); \
(zip).fmt.ucmpsize = SWAP_LE32((zip).fmt.ucmpsize ); \
@@ -492,6 +495,7 @@ int unzip_main(int argc, char **argv)
OPT_l = (1 << 0),
OPT_x = (1 << 1),
OPT_j = (1 << 2),
OPT_K = (1 << 3),
};
unsigned opts;
smallint quiet = 0;
@@ -557,7 +561,7 @@ int unzip_main(int argc, char **argv)
opts = 0;
/* '-' makes getopt return 1 for non-options */
while ((i = getopt(argc, argv, "-d:lnotpqxjv")) != -1) {
while ((i = getopt(argc, argv, "-d:lnotpqxjvK")) != -1) {
switch (i) {
case 'd': /* Extract to base directory */
base_dir = optarg;
@@ -600,6 +604,10 @@ int unzip_main(int argc, char **argv)
opts |= OPT_j;
break;
case 'K':
opts |= OPT_K;
break;
case 1:
if (!src_fn) {
/* The zip file */
@@ -817,7 +825,10 @@ int unzip_main(int argc, char **argv)
# endif
if ((cdf.fmt.version_made_by >> 8) == 3) {
/* This archive is created on Unix */
dir_mode = file_mode = (cdf.fmt.external_attributes >> 16);
file_mode = (cdf.fmt.external_attributes >> 16);
if (!(opts & OPT_K))
file_mode &= ~(mode_t)(S_ISUID | S_ISGID);
dir_mode = file_mode;
}
}
#endif
+47
View File
@@ -0,0 +1,47 @@
/* Add SORT_BY_ALIGNMENT to linker script (found in busybox_unstripped.out):
## .rodata : { *(.rodata SORT_BY_ALIGNMENT(.rodata.*) .gnu.linkonce.r.*) }
## .data : { *(.data SORT_BY_ALIGNMENT(.data.*) .gnu.linkonce.d.*) }
## .bss : { *(.bss SORT_BY_ALIGNMENT(.bss.*) .gnu.linkonce.b.*) }
## This will eliminate most of the padding (~3kb).
## Hmm, "ld --sort-section alignment" should do it too.
##
## There is a ld hack which is meant to decrease disk usage
## at the cost of more RAM usage (??!!) in standard ld script:
## . = ALIGN (0x1000) - ((0x1000 - .) & (0x1000 - 1)); . = DATA_SEGMENT_ALIGN (0x1000, 0x1000);
## Replace it with:
## . = ALIGN (0x1000); . = DATA_SEGMENT_ALIGN (0x1000, 0x1000);
## to unconditionally align .data to the next page boundary,
## instead of "next page, plus current offset in this page"
*/
/* To reduce the number of VMAs each bbox process has,
## move *(.bss SORT_BY_ALIGNMENT(.bss.*) ...)
## part from .bss : {...} block to .data : { ... } block.
## (This usually increases .data section by only one page).
## Result:
##
## text data bss dec hex filename
## 1050792 560 7580 1058932 102874 busybox.bss
## 1050792 8149 0 1058941 10287d busybox.nobss
##
## $ exec busybox.bss pmap $$
## 0000000008048000 1028K r-xp /path/to/busybox.bss
## 0000000008149000 8K rw-p /path/to/busybox.bss
## 000000000814b000 4K rw-p [ anon ] <---- this VMA is eliminated
## 00000000085f5000 4K ---p [heap]
## 00000000085f6000 4K rw-p [heap]
## 00000000f7778000 8K rw-p [ anon ]
## 00000000f777a000 12K r--p [vvar]
## 00000000f777d000 8K r-xp [vdso]
## 00000000ff7e9000 132K rw-p [stack]
##
## $ exec busybox.nobss pmap $$
## 0000000008048000 1028K r-xp /path/to/busybox.nobss
## 0000000008149000 12K rw-p /path/to/busybox.nobss
## 00000000086f0000 4K ---p [heap]
## 00000000086f1000 4K rw-p [heap]
## 00000000f7783000 8K rw-p [ anon ]
## 00000000f7785000 12K r--p [vvar]
## 00000000f7788000 8K r-xp [vdso]
## 00000000ffac0000 132K rw-p [stack]
*/
+2 -2
View File
@@ -21,7 +21,7 @@
//usage:#define reset_trivial_usage
//usage: ""
//usage:#define reset_full_usage "\n\n"
//usage: "Reset the screen"
//usage: "Reset terminal (ESC codes) and termios (signals, buffering, echo)"
/* "Standard" version of this tool is in ncurses package */
@@ -36,7 +36,7 @@ int stty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int reset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int reset_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
{
static const char *const args[] = {
static const char *const args[] ALIGN_PTR = {
"stty", "sane", NULL
};
+13 -1
View File
@@ -74,7 +74,19 @@ int resize_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
+ (1 << SIGTERM)
+ (1 << SIGALRM)
, onintr);
tcsetattr(STDERR_FILENO, TCSANOW, &new);
/* Users report:
* The resize command messes up the terminal.
* In my case it looks like it is hanging and
* I need to press ctrl-c to get a prompt.
* Actually the program does not hang but just
* the terminal is messed up.
* Replaced TCSANOW with TCSAFLUSH:
* "the change occurs after all output written to fd
* has been transmitted, and all input that has been
* received but not read will be discarded before
* the change is made.
*/
tcsetattr(STDERR_FILENO, TCSAFLUSH, &new);
/* save_cursor_pos 7
* scroll_whole_screen [r
+15 -4
View File
@@ -5,10 +5,6 @@
menu "Coreutils"
INSERT
comment "Common options"
config FEATURE_VERBOSE
bool "Support verbose options (usually -v) for various applets"
default y
@@ -17,6 +13,19 @@ config FEATURE_VERBOSE
Also enables long option (--verbose) if it exists.
Without this option, -v is accepted but ignored.
comment "Common options for date and touch"
config FEATURE_TIMEZONE
bool "Allow timezone in dates"
default y
depends on DESKTOP
help
Permit the use of timezones when parsing user-provided data
strings, e.g. '1996-04-09 12:45:00 -0500'.
This requires support for the '%z' extension to strptime() which
may not be available in all implementations.
comment "Common options for cp and mv"
depends on CP || MV
@@ -37,4 +46,6 @@ config FEATURE_HUMAN_READABLE
help
Allow df, du, and ls to have human readable output.
INSERT
endmenu
+38 -24
View File
@@ -29,9 +29,11 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
//usage:#define basename_trivial_usage
//usage: "FILE [SUFFIX]"
//usage: "FILE [SUFFIX] | -a FILE... | -s SUFFIX FILE..."
//usage:#define basename_full_usage "\n\n"
//usage: "Strip directory path and .SUFFIX from FILE"
//usage: "Strip directory path and SUFFIX from FILE\n"
//usage: "\n -a All arguments are FILEs"
//usage: "\n -s SUFFIX Remove SUFFIX (implies -a)"
//usage:
//usage:#define basename_example_usage
//usage: "$ basename /usr/local/bin/foo\n"
@@ -48,31 +50,43 @@
int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int basename_main(int argc UNUSED_PARAM, char **argv)
{
size_t m, n;
char *s;
unsigned opts;
const char *suffix = NULL;
if (argv[1] && strcmp(argv[1], "--") == 0) {
argv++;
}
if (!argv[1])
bb_show_usage();
/* '+': stop at first non-option */
opts = getopt32(argv, "^+" "as:"
"\0" "-1" /* At least one argument */
, &suffix
);
argv += optind;
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*++argv);
do {
char *s;
size_t m;
m = strlen(s);
if (*++argv) {
if (argv[1])
bb_show_usage();
n = strlen(*argv);
if ((m > n) && (strcmp(s+m-n, *argv) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*argv++);
m = strlen(s);
if (!opts) {
if (*argv) {
suffix = *argv;
if (argv[1])
bb_show_usage();
}
}
}
if (suffix) {
size_t n = strlen(suffix);
if ((m > n) && (strcmp(s + m - n, suffix) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
}
}
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
/* NB: != is correct here: */
if (full_write(STDOUT_FILENO, s, m) != (ssize_t)m)
return EXIT_FAILURE;
} while (opts && *argv);
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
/* NB: != is correct here: */
return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
return EXIT_SUCCESS;
}
+4 -2
View File
@@ -88,10 +88,12 @@ static int FAST_FUNC fileAction(struct recursive_state *state,
if (chmod(fileName, newmode) == 0) {
if (OPT_VERBOSE
|| (OPT_CHANGED && statbuf->st_mode != newmode)
|| (OPT_CHANGED
&& (statbuf->st_mode & 07777) != (newmode & 07777))
) {
char modestr[12];
printf("mode of '%s' changed to %04o (%s)\n", fileName,
newmode & 07777, bb_mode_string(newmode)+1);
newmode & 07777, bb_mode_string(modestr, newmode)+1);
}
return TRUE;
}
+1 -1
View File
@@ -167,7 +167,7 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
if (!cl_pos && !dcount && !shoe) {
if (option_mask32 & CUT_OPT_SUPPRESS_FLGS)
goto next_line;
} else if (dcount<cut_lists[cl_pos].startpos)
} else if (dcount < cut_lists[cl_pos].startpos)
start = linelen;
end = linelen;
} else {
+4 -3
View File
@@ -266,6 +266,7 @@ int date_main(int argc UNUSED_PARAM, char **argv)
/* If date string is given, update tm_time, and maybe set date */
if (date_str != NULL) {
int check_dst = 1;
/* Zero out fields - take her back to midnight! */
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
@@ -276,12 +277,12 @@ int date_main(int argc UNUSED_PARAM, char **argv)
if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
} else {
parse_datestr(date_str, &tm_time);
check_dst = parse_datestr(date_str, &tm_time);
}
/* Correct any day of week and day of year etc. fields */
/* Be sure to recheck dst (but not if date is time_t format) */
if (date_str[0] != '@')
/* Be sure to recheck dst (but not if date is UTC) */
if (check_dst)
tm_time.tm_isdst = -1;
ts.tv_sec = validate_tm_time(date_str, &tm_time);
ts.tv_nsec = 0;
+18 -2
View File
@@ -200,6 +200,7 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
}
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
static int clear_O_DIRECT(int fd)
{
if (errno == EINVAL) {
@@ -211,6 +212,7 @@ static int clear_O_DIRECT(int fd)
}
return 0;
}
# endif
#endif
static ssize_t dd_read(void *ibuf, size_t ibs)
@@ -225,8 +227,10 @@ static ssize_t dd_read(void *ibuf, size_t ibs)
#endif
n = safe_read(ifd, ibuf, ibs);
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
if (n < 0 && (G.flags & FLAG_IDIRECT) && clear_O_DIRECT(ifd))
goto read_again;
# endif
#endif
return n;
}
@@ -239,8 +243,10 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
IF_FEATURE_DD_IBS_OBS(write_again:)
n = full_write(ofd, buf, len);
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
if (n < 0 && (G.flags & FLAG_ODIRECT) && clear_O_DIRECT(ofd))
goto write_again;
# endif
#endif
#if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
@@ -501,8 +507,13 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (infile) {
int iflag = O_RDONLY;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_IDIRECT)
if (G.flags & FLAG_IDIRECT) {
# ifdef O_DIRECT
iflag |= O_DIRECT;
# else
bb_error_msg_and_die("O_DIRECT not supported on this platform");
# endif
}
#endif
xmove_fd(xopen(infile, iflag), ifd);
} else {
@@ -516,8 +527,13 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (G.flags & FLAG_APPEND)
oflag |= O_APPEND;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_ODIRECT)
if (G.flags & FLAG_ODIRECT) {
# ifdef O_DIRECT
oflag |= O_DIRECT;
# else
bb_error_msg_and_die("O_DIRECT not supported on this platform");
# endif
}
#endif
xmove_fd(xopen(outfile, oflag), ofd);
+35 -11
View File
@@ -32,6 +32,26 @@
//config: -a Show all filesystems
//config: -i Inodes
//config: -B <SIZE> Blocksize
//config:
//config:config FEATURE_SKIP_ROOTFS
//config: bool "Skip rootfs in mount table"
//config: default y
//config: depends on DF
//config: help
//config: Ignore rootfs entry in mount table.
//config:
//config: In Linux, kernel has a special filesystem, rootfs, which is initially
//config: mounted on /. It contains initramfs data, if kernel is configured
//config: to have one. Usually, another file system is mounted over / early
//config: in boot process, and therefore most tools which manipulate
//config: mount table, such as df, will skip rootfs entry.
//config:
//config: However, some systems do not mount anything on /.
//config: If you need to configure busybox for one of these systems,
//config: you may find it useful to turn this option off to make df show
//config: initramfs statistics.
//config:
//config: Otherwise, choose Y.
//applet:IF_DF(APPLET_NOEXEC(df, df, BB_DIR_BIN, BB_SUID_DROP, df))
@@ -99,15 +119,16 @@ int df_main(int argc UNUSED_PARAM, char **argv)
struct mntent *mount_entry;
struct statvfs s;
enum {
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_t = (1 << 3),
OPT_ALL = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 6) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_t = (1 << 3),
OPT_ALL = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 6) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_HUMANDEC = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (6 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
@@ -124,7 +145,7 @@ int df_main(int argc UNUSED_PARAM, char **argv)
opt = getopt32(argv, "^"
"kPTt:"
IF_FEATURE_DF_FANCY("aiB:")
IF_FEATURE_HUMAN_READABLE("hm")
IF_FEATURE_HUMAN_READABLE("hHm")
"\0"
#if ENABLE_FEATURE_HUMAN_READABLE && ENABLE_FEATURE_DF_FANCY
"k-mB:m-Bk:B-km"
@@ -151,8 +172,11 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
if (opt & OPT_HUMAN) {
if (opt & (OPT_HUMAN|OPT_HUMANDEC)) {
df_disp_hr = 0;
//TODO: need to add support in make_human_readable_str() for "decimal human readable"
//if (opt & OPT_HUMANDEC)
// df_disp_hr--;
disp_units_hdr = " Size";
}
if (opt & OPT_INODE)
+2
View File
@@ -321,6 +321,8 @@ int echo_main(int argc, char **argv)
if (*arg == '0' && (unsigned char)(arg[1] - '0') < 8) {
arg++;
}
//FIXME? we also accept non-0 starting sequences (see echo-prints-slash_41 test)
// echo -ne '-\41-' prints "-!-". bash 5.0.17 does not (prints "-\41-").
/* bb_process_escape_sequence can handle nul correctly */
c = bb_process_escape_sequence( (void*) &arg);
}
+1 -1
View File
@@ -100,7 +100,7 @@ int env_main(int argc UNUSED_PARAM, char **argv)
}
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
/*
+3 -3
View File
@@ -76,7 +76,7 @@ print_except_N_last_bytes(FILE *fp, unsigned count)
{
unsigned char *circle = xmalloc(++count);
unsigned head = 0;
for(;;) {
for (;;) {
int c;
c = getc(fp);
if (c == EOF)
@@ -105,7 +105,7 @@ print_except_N_last_lines(FILE *fp, unsigned count)
{
char **circle = xzalloc((++count) * sizeof(circle[0]));
unsigned head = 0;
for(;;) {
for (;;) {
char *c;
c = xmalloc_fgets(fp);
if (!c)
@@ -127,7 +127,7 @@ print_except_N_last_lines(FILE *fp, unsigned count)
}
ret:
head = 0;
for(;;) {
for (;;) {
free(circle[head++]);
if (head == count)
break;
+12 -4
View File
@@ -498,12 +498,20 @@ static NOINLINE unsigned display_single(const struct dnode *dn)
if (opt & OPT_i) /* show inode# */
column += printf("%7llu ", (long long) dn->dn_ino);
//TODO: -h should affect -s too:
if (opt & OPT_s) /* show allocated blocks */
column += printf("%6"OFF_FMT"u ", (off_t) (dn->dn_blocks >> 1));
if (opt & OPT_s) { /* show allocated blocks */
if (opt & OPT_h) {
column += printf("%"HUMAN_READABLE_MAX_WIDTH_STR"s ",
/* print size, show one fractional, use suffixes */
make_human_readable_str((off_t)dn->dn_blocks << 9, 1, 0)
);
} else {
column += printf("%6"OFF_FMT"u ", (off_t)(dn->dn_blocks >> 1));
}
}
if (opt & OPT_l) {
/* long listing: show mode */
column += printf("%-10s ", (char *) bb_mode_string(dn->dn_mode));
char modestr[12];
column += printf("%-10s ", bb_mode_string(modestr, dn->dn_mode));
/* long listing: show number of links */
column += printf("%4lu ", (long) dn->dn_nlink);
/* long listing: show user/group */
+23 -15
View File
@@ -151,10 +151,12 @@ static unsigned char *hash_bin_to_hex(unsigned char *hash_value,
return (unsigned char *)hex_value;
}
#define BUFSZ (CONFIG_FEATURE_COPYBUF_KB < 4 ? 4096 : CONFIG_FEATURE_COPYBUF_KB * 1024)
#if !ENABLE_SHA3SUM
# define hash_file(f,w) hash_file(f)
# define hash_file(b,f,w) hash_file(b,f)
#endif
static uint8_t *hash_file(const char *filename, unsigned sha3_width)
static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned sha3_width)
{
int src_fd, hash_len, count;
union _ctx_ {
@@ -227,8 +229,7 @@ static uint8_t *hash_file(const char *filename, unsigned sha3_width)
}
{
RESERVE_CONFIG_UBUFFER(in_buf, 4096);
while ((count = safe_read(src_fd, in_buf, 4096)) > 0) {
while ((count = safe_read(src_fd, in_buf, BUFSZ)) > 0) {
update(&context, in_buf, count);
}
hash_value = NULL;
@@ -238,7 +239,6 @@ static uint8_t *hash_file(const char *filename, unsigned sha3_width)
final(&context, in_buf);
hash_value = hash_bin_to_hex(in_buf, hash_len);
}
RELEASE_CONFIG_BUFFER(in_buf);
}
if (src_fd != STDIN_FILENO) {
@@ -251,6 +251,7 @@ static uint8_t *hash_file(const char *filename, unsigned sha3_width)
int md5_sha1_sum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
{
unsigned char *in_buf;
int return_value = EXIT_SUCCESS;
unsigned flags;
#if ENABLE_SHA3SUM
@@ -279,6 +280,12 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
if (!*argv)
*--argv = (char*)"-";
/* The buffer is not alloc/freed for each input file:
* for big values of COPYBUF_KB, this helps to keep its pages
* pre-faulted and possibly even fully cached on local CPU.
*/
in_buf = xmalloc(BUFSZ);
do {
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK && (flags & FLAG_CHECK)) {
FILE *pre_computed_stream;
@@ -293,12 +300,8 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
char *filename_ptr;
count_total++;
filename_ptr = strstr(line, " ");
/* handle format for binary checksums */
if (filename_ptr == NULL) {
filename_ptr = strstr(line, " *");
}
if (filename_ptr == NULL) {
filename_ptr = strchr(line, ' ');
if (!filename_ptr) {
if (flags & FLAG_WARN) {
bb_simple_error_msg("invalid format");
}
@@ -307,10 +310,15 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
free(line);
continue;
}
*filename_ptr = '\0';
filename_ptr += 2;
*filename_ptr++ = '\0';
/* coreutils 9.1 allows "HASH FILENAME" format,
* with only one space. Skip the 'correct'
* " " or " *" delimiter if it is there:
*/
if (*filename_ptr == ' ' || *filename_ptr == '*')
filename_ptr++;
hash_value = hash_file(filename_ptr, sha3_width);
hash_value = hash_file(in_buf, filename_ptr, sha3_width);
if (hash_value && (strcmp((char*)hash_value, line) == 0)) {
if (!(flags & FLAG_SILENT))
@@ -339,7 +347,7 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
}
fclose_if_not_stdin(pre_computed_stream);
} else {
uint8_t *hash_value = hash_file(*argv, sha3_width);
uint8_t *hash_value = hash_file(in_buf, *argv, sha3_width);
if (hash_value == NULL) {
return_value = EXIT_FAILURE;
} else {
+15 -1
View File
@@ -72,13 +72,27 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
OPT_t = 1 << 2,
OPT_p = 1 << 3,
OPT_u = 1 << 4,
OPT_tmpdir = (1 << 5) * ENABLE_LONG_OPTS,
};
path = getenv("TMPDIR");
if (!path || path[0] == '\0')
path = "/tmp";
#if ENABLE_LONG_OPTS
opts = getopt32long(argv, "^"
"dqtp:u"
"\0"
"?1" /* 1 arg max */,
"directory\0" No_argument "d"
"quiet\0" No_argument "q"
"dry-run\0" No_argument "u"
"tmpdir\0" Optional_argument "\xff"
, &path, &path
);
#else
opts = getopt32(argv, "^" "dqtp:u" "\0" "?1"/*1 arg max*/, &path);
#endif
chp = argv[optind];
if (!chp) {
@@ -95,7 +109,7 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
goto error;
}
#endif
if (opts & (OPT_t|OPT_p))
if (opts & (OPT_t|OPT_p|OPT_tmpdir))
chp = concat_path_file(path, chp);
if (opts & OPT_u) {
+2 -2
View File
@@ -71,9 +71,9 @@ int mv_main(int argc, char **argv)
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
IF_FEATURE_VERBOSE(
"verbose\0" No_argument "v",
&last
"verbose\0" No_argument "v"
)
, &last
);
argc -= optind;
argv += optind;
+1 -1
View File
@@ -33,7 +33,7 @@ int nice_main(int argc UNUSED_PARAM, char **argv)
if (!*++argv) { /* No args, so (GNU) output current nice value. */
printf("%d\n", old_priority);
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
adjustment = 10; /* Set default adjustment. */
+1 -1
View File
@@ -144,7 +144,7 @@ odoffset(dumper_t *dumper, int argc, char ***argvp)
}
}
static const char *const add_strings[] = {
static const char *const add_strings[] ALIGN_PTR = {
"16/1 \"%3_u \" \"\\n\"", /* a */
"8/2 \" %06o \" \"\\n\"", /* B, o */
"16/1 \"%03o \" \"\\n\"", /* b */
+2 -2
View File
@@ -313,7 +313,7 @@ static char **print_formatted(char *f, char **argv, int *conv_err)
}
break;
}
if (*f && strchr("-+ #", *f)) {
while (*f && strchr("-+ #0", *f)) {
++f;
++direc_length;
}
@@ -428,7 +428,7 @@ int printf_main(int argc UNUSED_PARAM, char **argv)
if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && !argv[1][2])
argv++;
if (!argv[1]) {
if (ENABLE_ASH_PRINTF
if ((ENABLE_ASH_PRINTF || ENABLE_HUSH_PRINTF)
&& applet_name[0] != 'p'
) {
bb_simple_error_msg("usage: printf FORMAT [ARGUMENT...]");
+1 -1
View File
@@ -96,5 +96,5 @@ int readlink_main(int argc UNUSED_PARAM, char **argv)
printf((opt & 2) ? "%s" : "%s\n", buf);
free(buf);
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
+59 -40
View File
@@ -17,14 +17,14 @@
//kbuild:lib-$(CONFIG_SHUF) += shuf.o
//usage:#define shuf_trivial_usage
//usage: "[-e|-i L-H] [-n NUM] [-o FILE] [-z] [FILE|ARG...]"
//usage: "[-n NUM] [-o FILE] [-z] [FILE | -e [ARG...] | -i L-H]"
//usage:#define shuf_full_usage "\n\n"
//usage: "Randomly permute lines\n"
//usage: "\n -e Treat ARGs as lines"
//usage: "\n -i L-H Treat numbers L-H as lines"
//usage: "\n -n NUM Output at most NUM lines"
//usage: "\n -o FILE Write to FILE, not standard output"
//usage: "\n -z End lines with zero byte, not newline"
//usage: "\n -z NUL terminated output"
//usage: "\n -e Treat ARGs as lines"
//usage: "\n -i L-H Treat numbers L-H as lines"
#include "libbb.h"
@@ -39,24 +39,30 @@
/*
* Use the Fisher-Yates shuffle algorithm on an array of lines.
* If the required number of output lines is less than the total
* we can stop shuffling early.
*/
static void shuffle_lines(char **lines, unsigned numlines)
static void shuffle_lines(char **lines, unsigned numlines, unsigned outlines)
{
unsigned i;
unsigned r;
char *tmp;
srand(monotonic_us());
for (i = numlines-1; i > 0; i--) {
r = rand();
while (outlines != 0) {
char *tmp;
unsigned r = rand();
/* RAND_MAX can be as small as 32767 */
if (i > RAND_MAX)
if (numlines > RAND_MAX)
r ^= rand() << 15;
r %= i + 1;
tmp = lines[i];
lines[i] = lines[r];
r %= numlines;
//TODO: the above method is seriously non-uniform when numlines is very large.
//For example, with numlines of 0xf0000000,
//values of (r % numlines) in [0, 0x0fffffff] range
//are more likely: e.g. r=1 and r=0xf0000001 both map to 1,
//whereas only one value, r=0xefffffff, maps to 0xefffffff.
numlines--;
tmp = lines[numlines];
lines[numlines] = lines[r];
lines[r] = tmp;
outlines--;
}
}
@@ -65,9 +71,10 @@ int shuf_main(int argc, char **argv)
{
unsigned opts;
char *opt_i_str, *opt_n_str, *opt_o_str;
unsigned i;
char **lines;
unsigned numlines;
unsigned long long lo = lo;
unsigned numlines, outlines;
unsigned i;
char eol;
opts = getopt32(argv, "^"
@@ -87,35 +94,48 @@ int shuf_main(int argc, char **argv)
} else
if (opts & OPT_i) {
/* create a range of numbers */
unsigned long long hi;
char *dash;
unsigned lo, hi;
if (argv[0])
bb_show_usage();
dash = strchr(opt_i_str, '-');
if (!dash) {
bb_error_msg_and_die("bad range '%s'", opt_i_str);
}
*dash = '\0';
lo = xatou(opt_i_str);
hi = xatou(dash + 1);
lo = xatoull(opt_i_str);
hi = xatoull(dash + 1);
*dash = '-';
if (hi < lo) {
if (hi < lo)
bb_error_msg_and_die("bad range '%s'", opt_i_str);
hi -= lo;
if (sizeof(size_t) > sizeof(numlines)) {
if (hi >= UINT_MAX)
bb_error_msg_and_die("bad range '%s'", opt_i_str);
} else {
if (hi >= UINT_MAX / sizeof(lines[0]))
bb_error_msg_and_die("bad range '%s'", opt_i_str);
}
numlines = (hi+1) - lo;
lines = xmalloc(numlines * sizeof(lines[0]));
numlines = hi + 1;
lines = xmalloc((size_t)numlines * sizeof(lines[0]));
for (i = 0; i < numlines; i++) {
lines[i] = (char*)(uintptr_t)lo;
lo++;
lines[i] = (char*)(uintptr_t)i;
}
} else {
/* default - read lines from stdin or the input file */
FILE *fp;
const char *fname = "-";
if (argc > 1)
bb_show_usage();
if (argv[0]) {
if (argv[1])
bb_show_usage();
fname = argv[0];
}
fp = xfopen_stdin(argv[0] ? argv[0] : "-");
fp = xfopen_stdin(fname);
lines = NULL;
numlines = 0;
for (;;) {
@@ -128,29 +148,28 @@ int shuf_main(int argc, char **argv)
fclose_if_not_stdin(fp);
}
if (numlines != 0)
shuffle_lines(lines, numlines);
outlines = numlines;
if (opts & OPT_n) {
outlines = xatou(opt_n_str);
if (outlines > numlines)
outlines = numlines;
}
shuffle_lines(lines, numlines, outlines);
if (opts & OPT_o)
xmove_fd(xopen(opt_o_str, O_WRONLY|O_CREAT|O_TRUNC), STDOUT_FILENO);
if (opts & OPT_n) {
unsigned maxlines;
maxlines = xatou(opt_n_str);
if (numlines > maxlines)
numlines = maxlines;
}
eol = '\n';
if (opts & OPT_z)
eol = '\0';
for (i = 0; i < numlines; i++) {
for (i = numlines - outlines; i < numlines; i++) {
if (opts & OPT_i)
printf("%u%c", (unsigned)(uintptr_t)lines[i], eol);
printf("%llu%c", lo + (uintptr_t)lines[i], eol);
else
printf("%s%c", lines[i], eol);
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
+16 -1
View File
@@ -37,6 +37,7 @@
//applet:IF_SLEEP(APPLET(sleep, BB_DIR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_SLEEP) += sleep.o
//kbuild:lib-$(CONFIG_ASH_SLEEP) += sleep.o
/* BB_AUDIT SUSv3 compliant */
/* BB_AUDIT GNU issues -- fancy version matches except args must be ints. */
@@ -64,15 +65,29 @@ int sleep_main(int argc UNUSED_PARAM, char **argv)
{
duration_t duration;
/* Note: sleep_main may be directly called from ash as a builtin.
* This brings some complications:
* + we can't use xfunc here
* + we can't use bb_show_usage
* + applet_name can be the name of the shell
*/
++argv;
if (!*argv)
if (!*argv) {
/* Without this, bare "sleep" in ash shows _ash_ --help */
/* (ash can be the "sh" applet as well, so check 2nd char) */
if (ENABLE_ASH_SLEEP && applet_name[1] != 'l') {
bb_simple_error_msg("sleep: missing operand");
return EXIT_FAILURE;
}
bb_show_usage();
}
/* GNU sleep accepts "inf", "INF", "infinity" and "INFINITY" */
if (strncasecmp(argv[0], "inf", 3) == 0)
for (;;)
sleep(INT_MAX);
//FIXME: in ash, "sleep 123qwerty" as a builtin aborts the shell
#if ENABLE_FEATURE_FANCY_SLEEP
duration = 0;
do {
+75 -39
View File
@@ -18,7 +18,7 @@
//config: sort is used to sort lines of text in specified files.
//config:
//config:config FEATURE_SORT_BIG
//config: bool "Full SuSv3 compliant sort (support -ktcbdfiogM)"
//config: bool "Full SuSv3 compliant sort (support -ktcbdfioghM)"
//config: default y
//config: depends on SORT
//config: help
@@ -43,7 +43,7 @@
//usage:#define sort_trivial_usage
//usage: "[-nru"
//usage: IF_FEATURE_SORT_BIG("gMcszbdfiokt] [-o FILE] [-k START[.OFS][OPTS][,END[.OFS][OPTS]] [-t CHAR")
//usage: IF_FEATURE_SORT_BIG("ghMcszbdfiokt] [-o FILE] [-k START[.OFS][OPTS][,END[.OFS][OPTS]] [-t CHAR")
//usage: "] [FILE]..."
//usage:#define sort_full_usage "\n\n"
//usage: "Sort lines of text\n"
@@ -59,6 +59,7 @@
//usage: "\n -n Sort numbers"
//usage: IF_FEATURE_SORT_BIG(
//usage: "\n -g General numerical sort"
//usage: "\n -h Sort human readable numbers (2K 1G)"
//usage: "\n -M Sort month"
//usage: "\n -V Sort version"
//usage: "\n -t CHAR Field separator"
@@ -94,31 +95,32 @@
enum {
FLAG_n = 1 << 0, /* Numeric sort */
FLAG_g = 1 << 1, /* Sort using strtod() */
FLAG_M = 1 << 2, /* Sort date */
FLAG_V = 1 << 3, /* Sort version */
FLAG_h = 1 << 2, /* Sort using strtod(), plus KMGT suffixes */
FLAG_M = 1 << 3, /* Sort date */
FLAG_V = 1 << 4, /* Sort version */
/* ucsz apply to root level only, not keys. b at root level implies bb */
FLAG_u = 1 << 4, /* Unique */
FLAG_c = 1 << 5, /* Check: no output, exit(!ordered) */
FLAG_s = 1 << 6, /* Stable sort, no ascii fallback at end */
FLAG_z = 1 << 7, /* Input and output is NUL terminated, not \n */
FLAG_u = 1 << 5, /* Unique */
FLAG_c = 1 << 6, /* Check: no output, exit(!ordered) */
FLAG_s = 1 << 7, /* Stable sort, no ascii fallback at end */
FLAG_z = 1 << 8, /* Input and output is NUL terminated, not \n */
/* These can be applied to search keys, the previous four can't */
FLAG_b = 1 << 8, /* Ignore leading blanks */
FLAG_r = 1 << 9, /* Reverse */
FLAG_d = 1 << 10, /* Ignore !(isalnum()|isspace()) */
FLAG_f = 1 << 11, /* Force uppercase */
FLAG_i = 1 << 12, /* Ignore !isprint() */
FLAG_m = 1 << 13, /* ignored: merge already sorted files; do not sort */
FLAG_S = 1 << 14, /* ignored: -S, --buffer-size=SIZE */
FLAG_T = 1 << 15, /* ignored: -T, --temporary-directory=DIR */
FLAG_o = 1 << 16,
FLAG_k = 1 << 17,
FLAG_t = 1 << 18,
FLAG_b = 1 << 9, /* Ignore leading blanks */
FLAG_r = 1 << 10, /* Reverse */
FLAG_d = 1 << 11, /* Ignore !(isalnum()|isspace()) */
FLAG_f = 1 << 12, /* Force uppercase */
FLAG_i = 1 << 13, /* Ignore !isprint() */
FLAG_m = 1 << 14, /* ignored: merge already sorted files; do not sort */
FLAG_S = 1 << 15, /* ignored: -S, --buffer-size=SIZE */
FLAG_T = 1 << 16, /* ignored: -T, --temporary-directory=DIR */
FLAG_o = 1 << 17,
FLAG_k = 1 << 18,
FLAG_t = 1 << 19,
FLAG_bb = 0x80000000, /* Ignore trailing blanks */
FLAG_no_tie_break = 0x40000000,
};
static const char sort_opt_str[] ALIGN1 = "^"
"ngMVucszbrdfimS:T:o:k:*t:"
"nghMVucszbrdfimS:T:o:k:*t:"
"\0" "o--o:t--t"/*-t, -o: at most one of each*/;
/*
* OPT_STR must not be string literal, needs to have stable address:
@@ -253,6 +255,25 @@ static struct sort_key *add_key(void)
#define GET_LINE(fp) xmalloc_fgetline(fp)
#endif
#if ENABLE_FEATURE_SORT_BIG
static int scale_suffix(const char *tail)
{
static const char suffix[] ALIGN1 = "kmgtpezy";
const char *s;
int n;
if (!tail[0])
return -1;
s = strchr(suffix, tail[0] | 0x20);
if (!s)
return -1;
n = s - suffix;
if (n != 0 && tail[0] >= 'a')
return -1; /* mg... not accepted, only MG... */
return n;
}
#endif
/* Iterate through keys list and perform comparisons */
static int compare_keys(const void *xarg, const void *yarg)
{
@@ -275,7 +296,7 @@ static int compare_keys(const void *xarg, const void *yarg)
y = *(char **)yarg;
#endif
/* Perform actual comparison */
switch (flags & (FLAG_n | FLAG_g | FLAG_M | FLAG_V)) {
switch (flags & (FLAG_n | FLAG_g | FLAG_h | FLAG_M | FLAG_V)) {
default:
bb_simple_error_msg_and_die("unknown sort type");
break;
@@ -293,7 +314,8 @@ static int compare_keys(const void *xarg, const void *yarg)
#endif
break;
#if ENABLE_FEATURE_SORT_BIG
case FLAG_g: {
case FLAG_g:
case FLAG_h: {
char *xx, *yy;
//TODO: needs setlocale(LC_NUMERIC, "C")?
double dx = strtod(x, &xx);
@@ -308,16 +330,26 @@ static int compare_keys(const void *xarg, const void *yarg)
retval = (dy != dy) ? 0 : -1;
else if (dy != dy)
retval = 1;
/* Check for infinity. Could underflow, but it avoids libm. */
else if (1.0 / dx == 0.0) {
if (dx < 0)
retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
else {
if (flags & FLAG_h) {
int xs = scale_suffix(xx);
int ys = scale_suffix(yy);
if (xs != ys) {
retval = xs - ys;
break;
}
}
/* Check for infinity. Could underflow, but it avoids libm. */
if (1.0 / dx == 0.0) {
if (dx < 0)
retval = (1.0 / dy == 0.0 && dy < 0) ? 0 : -1;
else
retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
} else if (1.0 / dy == 0.0)
retval = (dy < 0) ? 1 : -1;
else
retval = (1.0 / dy == 0.0 && dy > 0) ? 0 : 1;
} else if (1.0 / dy == 0.0)
retval = (dy < 0) ? 1 : -1;
else
retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
retval = (dx > dy) ? 1 : ((dx < dy) ? -1 : 0);
}
break;
}
case FLAG_M: {
@@ -325,9 +357,9 @@ static int compare_keys(const void *xarg, const void *yarg)
int dx;
char *xx, *yy;
xx = strptime(x, "%b", &thyme);
xx = strptime(skip_whitespace(x), "%b", &thyme);
dx = thyme.tm_mon;
yy = strptime(y, "%b", &thyme);
yy = strptime(skip_whitespace(y), "%b", &thyme);
if (!xx)
retval = (!yy) ? 0 : -1;
else if (!yy)
@@ -380,7 +412,9 @@ static int compare_keys(const void *xarg, const void *yarg)
/* If x > y, 1, else -1 */
retval = (x32 > y32) * 2 - 1;
} else
/* Here, -r has no effect! */
return retval;
}
if (!(option_mask32 & FLAG_no_tie_break)) {
/* fallback sort */
flags = option_mask32;
@@ -474,6 +508,7 @@ int sort_main(int argc UNUSED_PARAM, char **argv)
FLAG_allowed_for_k =
FLAG_n | /* Numeric sort */
FLAG_g | /* Sort using strtod() */
FLAG_h | /* Sort using strtod(), plus KMGT suffixes */
FLAG_M | /* Sort date */
FLAG_b | /* Ignore leading blanks */
FLAG_r | /* Reverse */
@@ -617,11 +652,12 @@ int sort_main(int argc UNUSED_PARAM, char **argv)
/* Handle -u */
if (option_mask32 & FLAG_u) {
int j = 0;
/* coreutils 6.3 drop lines for which only key is the same
* -- disabling last-resort compare, or else compare_keys()
* will be the same only for completely identical lines.
/* coreutils 6.3 drop lines for which only key is the same:
* - disabling last-resort compare, or else compare_keys()
* will be the same only for completely identical lines
* - disabling -s (same reasons)
*/
option_mask32 |= FLAG_no_tie_break;
option_mask32 = (option_mask32 | FLAG_no_tie_break) & (~FLAG_s);
for (i = 1; i < linecount; i++) {
if (compare_keys(&lines[j], &lines[i]) == 0)
free(lines[i]);
@@ -644,5 +680,5 @@ int sort_main(int argc UNUSED_PARAM, char **argv)
printf("%s%c", lines[i], ch);
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
+4 -2
View File
@@ -339,7 +339,8 @@ static void FAST_FUNC print_stat(char *pformat, const char m,
strcat(pformat, "lo");
printf(pformat, (unsigned long) (statbuf->st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)));
} else if (m == 'A') {
printfs(pformat, bb_mode_string(statbuf->st_mode));
char modestr[12];
printfs(pformat, bb_mode_string(modestr, statbuf->st_mode));
} else if (m == 'f') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statbuf->st_mode);
@@ -702,6 +703,7 @@ static bool do_stat(const char *filename, const char *format)
bb_putchar('\n');
# endif
} else {
char modestr[12];
char *linkname = NULL;
struct passwd *pw_ent;
struct group *gw_ent;
@@ -736,7 +738,7 @@ static bool do_stat(const char *filename, const char *format)
bb_putchar('\n');
printf("Access: (%04lo/%10.10s) Uid: (%5lu/%8s) Gid: (%5lu/%8s)\n",
(unsigned long) (statbuf.st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)),
bb_mode_string(statbuf.st_mode),
bb_mode_string(modestr, statbuf.st_mode),
(unsigned long) statbuf.st_uid,
(pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN",
(unsigned long) statbuf.st_gid,
+4 -5
View File
@@ -242,7 +242,7 @@ int depth;
depth--; \
return __res; \
} while (0)
static const char *const TOKSTR[] = {
static const char *const TOKSTR[] ALIGN_PTR = {
"EOI",
"FILRD",
"FILWR",
@@ -435,7 +435,7 @@ struct test_statics {
};
/* See test_ptr_hack.c */
extern struct test_statics *const test_ptr_to_statics;
extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
#define S (*test_ptr_to_statics)
#define args (S.args )
@@ -446,8 +446,7 @@ extern struct test_statics *const test_ptr_to_statics;
#define leaving (S.leaving )
#define INIT_S() do { \
(*(struct test_statics**)not_const_pp(&test_ptr_to_statics)) = xzalloc(sizeof(S)); \
barrier(); \
XZALLOC_CONST_PTR(&test_ptr_to_statics, sizeof(S)); \
} while (0)
#define DEINIT_S() do { \
free(group_array); \
@@ -860,7 +859,7 @@ static number_t primary(enum token n)
if (check_operator(args[1]) != EOI) { /* if args[1] != NULL */
if (args[2]) {
// coreutils also does this:
// if (args[3] && args[0]="-l" && args[2] is BINOP)
// if (args[3] && args[0] = "-l" && args[2] is BINOP)
// return binop(1 /* prepended by -l */);
if (last_operator->op_type == BINOP)
unnest_msg_and_return(binop(), "<primary: binop:%lld\n");
+33 -12
View File
@@ -39,13 +39,29 @@
//kbuild:lib-$(CONFIG_TIMEOUT) += timeout.o
//usage:#define timeout_trivial_usage
//usage: "[-s SIG] SECS PROG ARGS"
//usage: "[-s SIG] [-k KILL_SECS] SECS PROG ARGS"
//usage:#define timeout_full_usage "\n\n"
//usage: "Run PROG. Send SIG to it if it is not gone in SECS seconds.\n"
//usage: "Default SIG: TERM."
//usage: "If it still exists in KILL_SECS seconds, send KILL.\n"
#include "libbb.h"
static NOINLINE int timeout_wait(int timeout, pid_t pid)
{
/* Just sleep(HUGE_NUM); kill(parent) may kill wrong process! */
while (1) {
sleep1();
if (--timeout <= 0)
break;
if (kill(pid, 0)) {
/* process is gone */
return EXIT_SUCCESS;
}
}
return EXIT_FAILURE;
}
int timeout_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int timeout_main(int argc UNUSED_PARAM, char **argv)
{
@@ -53,23 +69,29 @@ int timeout_main(int argc UNUSED_PARAM, char **argv)
int status;
int parent = 0;
int timeout;
int kill_timeout;
pid_t pid;
#if !BB_MMU
char *sv1, *sv2;
#endif
const char *opt_s = "TERM";
char *opt_k = NULL;
/* -p option is not documented, it is needed to support NOMMU. */
/* -t SECONDS; -p PARENT_PID */
/* '+': stop at first non-option */
getopt32(argv, "+s:" USE_FOR_NOMMU("p:+"), &opt_s, &parent);
getopt32(argv, "+s:k:" USE_FOR_NOMMU("p:+"), &opt_s, &opt_k, &parent);
/*argv += optind; - no, wait for bb_daemonize_or_rexec! */
signo = get_signum(opt_s);
if (signo < 0)
bb_error_msg_and_die("unknown signal '%s'", opt_s);
kill_timeout = 0;
if (opt_k)
kill_timeout = parse_duration_str(opt_k);
if (!argv[optind])
bb_show_usage();
timeout = parse_duration_str(argv[optind++]);
@@ -103,17 +125,16 @@ int timeout_main(int argc UNUSED_PARAM, char **argv)
bb_daemonize_or_rexec(0, argv);
/* Here we are grandchild. Sleep, then kill grandparent */
grandchild:
/* Just sleep(HUGE_NUM); kill(parent) may kill wrong process! */
while (1) {
sleep1();
if (--timeout <= 0)
break;
if (kill(parent, 0)) {
/* process is gone */
return EXIT_SUCCESS;
}
}
if (timeout_wait(timeout, parent) == EXIT_SUCCESS)
return EXIT_SUCCESS;
kill(parent, signo);
if (kill_timeout > 0) {
if (timeout_wait(kill_timeout, parent) == EXIT_SUCCESS)
return EXIT_SUCCESS;
kill(parent, SIGKILL);
}
return EXIT_SUCCESS;
}
+4 -2
View File
@@ -140,15 +140,17 @@ int touch_main(int argc UNUSED_PARAM, char **argv)
if (opts & (OPT_d|OPT_t)) {
struct tm tm_time;
time_t t;
int check_dst;
//memset(&tm_time, 0, sizeof(tm_time));
/* Better than memset: makes "HH:MM" dates meaningful */
time(&t);
localtime_r(&t, &tm_time);
parse_datestr(date_str, &tm_time);
check_dst = parse_datestr(date_str, &tm_time);
/* Correct any day of week and day of year etc. fields */
tm_time.tm_isdst = -1; /* Be sure to recheck dst */
if (check_dst)
tm_time.tm_isdst = -1; /* recheck dst unless date is UTC */
t = validate_tm_time(date_str, &tm_time);
timebuf[1].tv_sec = timebuf[0].tv_sec = t;
+188
View File
@@ -0,0 +1,188 @@
/* vi: set sw=4 ts=4: */
/*
* tsort implementation for busybox
*
* public domain -- David Leonard, 2022
*/
//config:config TSORT
//config: bool "tsort (0.7 kb)"
//config: default y
//config: help
//config: tsort performs a topological sort.
//applet:IF_TSORT(APPLET(tsort, BB_DIR_USR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_TSORT) += tsort.o
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/tsort.html */
//usage:#define tsort_trivial_usage
//usage: "[FILE]"
//usage:#define tsort_full_usage "\n\n"
//usage: "Topological sort"
//usage:#define tsort_example_usage
//usage: "$ echo -e \"a b\\nb c\" | tsort\n"
//usage: "a\n"
//usage: "b\n"
//usage: "c\n"
#include "libbb.h"
#include "common_bufsiz.h"
struct node {
unsigned in_count;
unsigned out_count;
struct node **out;
char name[1];
};
struct globals {
struct node **nodes;
unsigned nodes_len;
};
#define G (*(struct globals*)bb_common_bufsiz1)
#define INIT_G() do { \
setup_common_bufsiz(); \
BUILD_BUG_ON(sizeof(G) > COMMON_BUFSIZE); \
G.nodes = NULL; \
G.nodes_len = 0; \
} while (0)
static struct node *
get_node(const char *name)
{
struct node *n;
unsigned a = 0;
unsigned b = G.nodes_len;
/* Binary search for name */
while (a != b) {
unsigned m = (a + b) / 2;
int cmp = strcmp(name, G.nodes[m]->name);
if (cmp == 0)
return G.nodes[m]; /* found */
if (cmp < 0) {
b = m;
} else {
a = m + 1;
}
}
/* Allocate new node */
n = xzalloc(sizeof(*n) + strlen(name));
//n->in_count = 0;
//n->out_count = 0;
//n->out = NULL;
strcpy(n->name, name);
/* Insert to maintain sort */
G.nodes = xrealloc(G.nodes, (G.nodes_len + 1) * sizeof(*G.nodes));
memmove(&G.nodes[a + 1], &G.nodes[a],
(G.nodes_len - a) * sizeof(*G.nodes));
G.nodes[a] = n;
G.nodes_len++;
return n;
}
static void
add_edge(struct node *a, struct node *b)
{
a->out = xrealloc_vector(a->out, 6, a->out_count);
a->out[a->out_count++] = b;
b->in_count++;
}
int tsort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int tsort_main(int argc UNUSED_PARAM, char **argv)
{
char *line;
size_t linesz;
ssize_t len;
struct node *a;
int cycles;
INIT_G();
if (argv[1]) {
if (argv[2])
bb_show_usage();
if (NOT_LONE_DASH(argv[1])) {
close(STDIN_FILENO); /* == 0 */
xopen(argv[1], O_RDONLY); /* fd will be 0 */
}
}
/* Read in words separated by <blank>s */
a = NULL;
line = NULL;
linesz = 0;
while ((len = getline(&line, &linesz, stdin)) != -1) {
char *s = line;
while (*(s = skip_whitespace(s)) != '\0') {
struct node *b;
char *word;
word = s;
s = skip_non_whitespace(s);
if (*s)
*s++ = '\0';
/* Create nodes and edges for each word pair */
b = get_node(word);
if (!a) {
a = b;
} else {
if (a != b)
add_edge(a, b);
a = NULL;
}
}
}
// Most other tools do not check for input read error (treat them as EOF)
// die_if_ferror(in, input_filename);
if (a)
bb_simple_error_msg_and_die("odd input");
free(line);
/*
* Kahn's algorithm:
* - find a node that has no incoming edges, print and remove it
* - repeat until the graph is empty
* - if any nodes are left, they form cycles.
*/
cycles = 0;
while (G.nodes_len) {
struct node *n;
unsigned i;
/* Search for first node with no incoming edges */
for (i = 0; i < G.nodes_len; i++) {
if (!G.nodes[i]->in_count)
break;
}
if (i == G.nodes_len) {
/* Must be a cycle; arbitraily break it at node 0 */
cycles++;
i = 0;
#ifndef TINY
bb_error_msg("cycle at %s", G.nodes[i]->name);
#endif
}
/* Remove the node (need no longer maintain sort) */
n = G.nodes[i];
G.nodes[i] = G.nodes[--G.nodes_len];
/* And remove its outgoing edges */
for (i = 0; i < n->out_count; i++)
n->out[i]->in_count--;
free(n->out);
puts(n->name);
free(n);
}
free(G.nodes);
fflush_stdout_and_exit(cycles ? 1 : 0);
}
+1 -1
View File
@@ -209,5 +209,5 @@ int uname_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
#endif
}
fflush_stdout_and_exit(EXIT_SUCCESS); /* coreutils-6.9 compat */
fflush_stdout_and_exit_SUCCESS(); /* coreutils-6.9 compat */
}
+1 -1
View File
@@ -139,5 +139,5 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
die_if_ferror(stdin, input_filename);
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
+11 -2
View File
@@ -155,7 +155,16 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
break;
}
dst_stream = stdout;
if (NOT_LONE_DASH(outname)) {
if (NOT_LONE_DASH(outname)
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/uudecode.html
* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/uuencode.html
* The above says that output file name specified in input file
* or overridden by -o OUTFILE can be special "/dev/stdout" string.
* This usually works "implicitly": many systems have /dev/stdout.
* If ENABLE_DESKTOP, support that explicitly:
*/
&& (!ENABLE_DESKTOP || strcmp(outname, "/dev/stdout") != 0)
) {
dst_stream = xfopen_for_write(outname);
fchmod(fileno(dst_stream), mode & (S_IRWXU | S_IRWXG | S_IRWXO));
}
@@ -343,7 +352,7 @@ int baseNUM_main(int argc UNUSED_PARAM, char **argv)
#undef src_buf
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
#endif
+1 -1
View File
@@ -78,5 +78,5 @@ int uuencode_main(int argc UNUSED_PARAM, char **argv)
}
printf(tbl == bb_uuenc_tbl_std ? "\n`\nend\n" : "\n====\n");
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit_SUCCESS();
}
+2 -2
View File
@@ -519,7 +519,7 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
/* why _exit? the child may have changed the stack,
* so "return 0" may do bad things
*/
_exit(EXIT_SUCCESS);
_exit_SUCCESS();
}
/* Child */
setsid(); /* detach from controlling tty */
@@ -531,7 +531,7 @@ int start_stop_daemon_main(int argc UNUSED_PARAM, char **argv)
*/
pid = xvfork();
if (pid != 0)
_exit(EXIT_SUCCESS); /* Parent */
_exit_SUCCESS(); /* Parent */
}
if (opt & OPT_MAKEPID) {
/* User wants _us_ to make the pidfile */
+3 -2
View File
@@ -17,9 +17,10 @@
//kbuild:lib-$(CONFIG_WHICH) += which.o
//usage:#define which_trivial_usage
//usage: "COMMAND..."
//usage: "[-a] COMMAND..."
//usage:#define which_full_usage "\n\n"
//usage: "Locate COMMAND"
//usage: "Locate COMMAND\n"
//usage: "\n -a Show all matches"
//usage:
//usage:#define which_example_usage
//usage: "$ which login\n"
+8 -8
View File
@@ -55,19 +55,19 @@ Next we need the configuration data. This is very similar to the example
code for the native applet:
//config:config MU
//config: bool "MU"
//config: default y
//config: help
//config: Returns an indeterminate value.
//config: bool "MU"
//config: default y
//config: help
//config: Returns an indeterminate value.
//applet:IF_MU(APPLET_SCRIPTED(mu, scripted, BB_DIR_USR_BIN, BB_SUID_DROP, mu))
//usage:#define mu_trivial_usage
//usage: "[-abcde] FILE..."
//usage: "[-abcde] FILE..."
//usage:#define mu_full_usage
//usage: "Returns an indeterminate value\n"
//usage: "\n -a First function"
//usage: "\n -b Second function"
//usage: "Returns an indeterminate value\n"
//usage: "\n -a First function"
//usage: "\n -b Second function"
The only difference is that the applet is specified as being of type
APPLET_SCRIPTED. It would also be useful to include details of any
+2 -2
View File
@@ -24,7 +24,7 @@ POSIX Tools not supported:
gencat, getconf, iconv, join, link, locale, localedef, lp, m4,
mailx, newgrp, nl, pathchk, pax, pr, qalter, qdel, qhold, qmove,
qmsg, qrerun, qrls, qselect, qsig, qstat, qsub, tabs, talk, tput,
tsort, unlink, uucp, uustat, uux
unlink, uucp, uustat, uux
POSIX Tools not supported (DEVELOPMENT):
admin, cflow, ctags, cxref, delta, fort77, get, lex, make, nm, prs, rmdel,
@@ -690,7 +690,7 @@ uniq Busybox specific options:
uudecode POSIX options
option | exists | compliant | remarks
-o outfile | no | no |
-o outfile | yes | no |
uudecode Busybox specific options: None
uuencode POSIX options
+1 -1
View File
@@ -190,7 +190,7 @@ struct globals {
* Required for the uber-silly devfs /dev/ide/host1/bus2/target3/lun3
* pathames.
*/
static const char *const devfs_hier[] = {
static const char *const devfs_hier[] ALIGN_PTR = {
"host", "bus", "target", "lun", NULL
};
#endif
+61 -23
View File
@@ -848,7 +848,7 @@ static char *nextword(char **s)
static char nextchar(char **s)
{
char c, *pps;
again:
c = *(*s)++;
pps = *s;
if (c == '\\')
@@ -859,8 +859,11 @@ static char nextchar(char **s)
*/
if (c == '\\' && *s == pps) { /* unrecognized \z? */
c = *(*s); /* yes, fetch z */
if (c)
(*s)++; /* advance unless z = NUL */
if (c) { /* advance unless z = NUL */
(*s)++;
if (c == '\n') /* \<newline>? eat it */
goto again;
}
}
return c;
}
@@ -882,7 +885,13 @@ static ALWAYS_INLINE int isalnum_(int c)
static double my_strtod(char **pp)
{
char *cp = *pp;
if (ENABLE_DESKTOP && cp[0] == '0') {
return strtod(cp, pp);
}
#if ENABLE_DESKTOP
static double my_strtod_or_hexoct(char **pp)
{
char *cp = *pp;
if (cp[0] == '0') {
/* Might be hex or octal integer: 0x123abc or 07777 */
char c = (cp[1] | 0x20);
if (c == 'x' || isdigit(cp[1])) {
@@ -901,6 +910,9 @@ static double my_strtod(char **pp)
}
return strtod(cp, pp);
}
#else
# define my_strtod_or_hexoct(p) my_strtod(p)
#endif
/* -------- working with variables (set/get/copy/etc) -------- */
@@ -1014,6 +1026,7 @@ static double getvar_i(var *v)
if (s && *s) {
debug_printf_eval("getvar_i: '%s'->", s);
v->number = my_strtod(&s);
/* ^^^ hex/oct NOT allowed here! */
debug_printf_eval("%f (s:'%s')\n", v->number, s);
if (v->type & VF_USER) {
//TODO: skip_spaces() also skips backslash+newline, is it intended here?
@@ -1125,10 +1138,10 @@ static uint32_t next_token(uint32_t expected)
if (*p == '\0') {
tc = TC_EOF;
debug_printf_parse("%s: token found: TC_EOF\n", __func__);
} else if (*p == '\"') {
} else if (*p == '"') {
/* it's a string */
char *s = t_string = ++p;
while (*p != '\"') {
while (*p != '"') {
char *pp;
if (*p == '\0' || *p == '\n')
syntax_error(EMSG_UNEXP_EOS);
@@ -1166,7 +1179,8 @@ static uint32_t next_token(uint32_t expected)
} else if (*p == '.' || isdigit(*p)) {
/* it's a number */
char *pp = p;
t_double = my_strtod(&pp);
t_double = my_strtod_or_hexoct(&pp);
/* ^^^ awk only allows hex/oct consts in _program_, not in _input_ */
p = pp;
if (*p == '.')
syntax_error(EMSG_UNEXP_TOKEN);
@@ -2338,36 +2352,55 @@ static char *awk_printf(node *n, size_t *len)
b = NULL;
i = 0;
while (*f) { /* "print one format spec" loop */
while (1) { /* "print one format spec" loop */
char *s;
char c;
char sv;
var *arg;
size_t slen;
/* Find end of the next format spec, or end of line */
s = f;
while (*f && (*f != '%' || *++f == '%'))
f++;
while (*f && !isalpha(*f)) {
if (*f == '*')
syntax_error("%*x formats are not supported");
while (1) {
c = *f;
if (!c) /* no percent chars found at all */
goto nul;
f++;
if (c == '%')
break;
}
/* we are past % in "....%..." */
c = *f;
if (!c) {
/* Tail of fmt with no percent chars,
* or "....%" (percent seen, but no format specifier char found)
*/
slen = strlen(s);
goto tail;
if (!c) /* "....%" */
goto nul;
if (c == '%') { /* "....%%...." */
slen = f - s;
s = xstrndup(s, slen);
f++;
goto append; /* print "....%" part verbatim */
}
sv = *++f;
*f = '\0';
while (1) {
if (isalpha(c))
break;
if (c == '*')
syntax_error("%*x formats are not supported");
c = *++f;
if (!c) { /* "....%...." and no letter found after % */
/* Example: awk 'BEGIN { printf "^^^%^^^\n"; }' */
nul:
slen = f - s;
goto tail; /* print remaining string, exit loop */
}
}
/* we are at A in "....%...A..." */
arg = evaluate(nextarg(&n), TMPVAR);
/* Result can be arbitrarily long. Example:
* printf "%99999s", "BOOM"
*/
sv = *++f;
*f = '\0';
if (c == 'c') {
char cc = is_numeric(arg) ? getvar_i(arg) : *getvar_s(arg);
char *r = xasprintf(s, cc ? cc : '^' /* else strlen will be wrong */);
@@ -2386,13 +2419,14 @@ static char *awk_printf(node *n, size_t *len)
} else if (strchr("eEfFgGaA", c)) {
s = xasprintf(s, d);
} else {
//TODO: GNU Awk 5.0.1: printf "%W" prints "%W", does not error out
syntax_error(EMSG_INV_FMT);
}
}
slen = strlen(s);
}
*f = sv;
append:
if (i == 0) {
b = s;
i = slen;
@@ -2402,7 +2436,7 @@ static char *awk_printf(node *n, size_t *len)
b = xrealloc(b, i + slen + 1);
strcpy(b + i, s);
i += slen;
if (!c) /* tail? */
if (!c) /* s is NOT allocated and this is the last part of string? */
break;
free(s);
}
@@ -3094,6 +3128,9 @@ static var *evaluate(node *op, var *res)
case XC( OC_MOVE ):
debug_printf_eval("MOVE\n");
/* make sure that we never return a temp var */
if (L.v == TMPVAR0)
L.v = res;
/* if source is a temporary string, jusk relink it to dest */
if (R.v == TMPVAR1
&& !(R.v->type & VF_NUMBER)
@@ -3483,6 +3520,7 @@ static var *evaluate(node *op, var *res)
i = (Ld == 0);
break;
}
debug_printf_eval("COMPARE result: %d\n", (i == 0) ^ (opn & 1));
setvar_i(res, (i == 0) ^ (opn & 1));
break;
}
+27 -3
View File
@@ -18,12 +18,13 @@
//kbuild:lib-$(CONFIG_CMP) += cmp.o
//usage:#define cmp_trivial_usage
//usage: "[-ls] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage: "[-ls] [-n NUM] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage:#define cmp_full_usage "\n\n"
//usage: "Compare FILE1 with FILE2 (or stdin)\n"
//usage: "\n -l Write the byte numbers (decimal) and values (octal)"
//usage: "\n for all differing bytes"
//usage: "\n -s Quiet"
//usage: "\n -n NUM Compare at most NUM bytes"
/* BB_AUDIT SUSv3 (virtually) compliant -- uses nicer GNU format for -l. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cmp.html */
@@ -35,9 +36,10 @@ static const char fmt_differ[] ALIGN1 = "%s %s differ: char %"OFF_FMT"u, line %u
// This fmt_l_opt uses gnu-isms. SUSv3 would be "%.0s%.0s%"OFF_FMT"u %o %o\n"
static const char fmt_l_opt[] ALIGN1 = "%.0s%.0s%"OFF_FMT"u %3o %3o\n";
#define OPT_STR "sl"
#define OPT_STR "sln:+"
#define CMP_OPT_s (1<<0)
#define CMP_OPT_l (1<<1)
#define CMP_OPT_n (1<<2)
int cmp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cmp_main(int argc UNUSED_PARAM, char **argv)
@@ -50,14 +52,34 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
int c1, c2;
unsigned opt;
int retval = 0;
int max_count = -1;
#if !ENABLE_LONG_OPTS
opt = getopt32(argv, "^"
OPT_STR
"\0" "-1"
IF_DESKTOP(":?4")
IF_NOT_DESKTOP(":?2")
":l--s:s--l"
":l--s:s--l",
&max_count
);
#else
static const char cmp_longopts[] ALIGN1 =
"bytes\0" Required_argument "n"
"quiet\0" No_argument "s"
"silent\0" No_argument "s"
"verbose\0" No_argument "l"
;
opt = getopt32long(argv, "^"
OPT_STR
"\0" "-1"
IF_DESKTOP(":?4")
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
cmp_longopts,
&max_count
);
#endif
argv += optind;
filename1 = *argv;
@@ -95,6 +117,8 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
while (skip2) { getc(fp2); skip2--; }
}
do {
if (max_count >= 0 && --max_count < 0)
break;
c1 = getc(fp1);
c2 = getc(fp2);
++char_pos;
+36 -24
View File
@@ -18,7 +18,7 @@
//applet:IF_ED(APPLET(ed, BB_DIR_BIN, BB_SUID_DROP))
//usage:#define ed_trivial_usage "[FILE]"
//usage:#define ed_trivial_usage "[-p PROMPT] [-s] [FILE]"
//usage:#define ed_full_usage ""
#include "libbb.h"
@@ -48,6 +48,7 @@ struct globals {
char *bufBase;
char *bufPtr;
char *fileName;
const char *prompt;
LINE lines;
smallint dirty;
int marks[26];
@@ -57,6 +58,7 @@ struct globals {
#define bufBase (G.bufBase )
#define bufPtr (G.bufPtr )
#define fileName (G.fileName )
#define prompt (G.prompt )
#define curNum (G.curNum )
#define lastNum (G.lastNum )
#define bufUsed (G.bufUsed )
@@ -69,6 +71,11 @@ struct globals {
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
} while (0)
#define OPTION_STR "sp:"
enum {
OPT_s = (1 << 0),
};
static int bad_nums(int num1, int num2, const char *for_what)
{
if ((num1 < 1) || (num2 > lastNum) || (num1 > num2)) {
@@ -380,7 +387,8 @@ static void addLines(int num)
static int readLines(const char *file, int num)
{
int fd, cc;
int len, lineCount, charCount;
int len;
unsigned charCount;
char *cp;
if ((num < 1) || (num > lastNum + 1)) {
@@ -396,13 +404,9 @@ static int readLines(const char *file, int num)
bufPtr = bufBase;
bufUsed = 0;
lineCount = 0;
charCount = 0;
cc = 0;
printf("\"%s\", ", file);
fflush_all();
do {
cp = memchr(bufPtr, '\n', bufUsed);
@@ -415,7 +419,6 @@ static int readLines(const char *file, int num)
bufPtr += len;
bufUsed -= len;
charCount += len;
lineCount++;
num++;
continue;
}
@@ -449,15 +452,19 @@ static int readLines(const char *file, int num)
close(fd);
return -1;
}
lineCount++;
charCount += bufUsed;
}
close(fd);
printf("%d lines%s, %d chars\n", lineCount,
(bufUsed ? " (incomplete)" : ""), charCount);
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ed.html
* "Read Command"
* "...the number of bytes read shall be written to standard output
* in the following format:
* "%d\n", <number of bytes read>
*/
if (!(option_mask32 & OPT_s))
printf("%u\n", charCount);
return TRUE;
}
@@ -468,12 +475,12 @@ static int readLines(const char *file, int num)
static int writeLines(const char *file, int num1, int num2)
{
LINE *lp;
int fd, lineCount, charCount;
int fd;
unsigned charCount;
if (bad_nums(num1, num2, "write"))
return FALSE;
lineCount = 0;
charCount = 0;
fd = creat(file, 0666);
@@ -482,9 +489,6 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
printf("\"%s\", ", file);
fflush_all();
lp = findLine(num1);
if (lp == NULL) {
close(fd);
@@ -498,7 +502,6 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
charCount += lp->len;
lineCount++;
lp = lp->next;
}
@@ -507,7 +510,14 @@ static int writeLines(const char *file, int num1, int num2)
return FALSE;
}
printf("%d lines, %d chars\n", lineCount, charCount);
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ed.html
* "Write Command"
* "...the number of bytes written shall be written to standard output,
* unless the -s option was specified, in the following format:
* "%d\n", <number of bytes written>
*/
if (!(option_mask32 & OPT_s))
printf("%u\n", charCount);
return TRUE;
}
@@ -710,7 +720,7 @@ static void subCommand(const char *cmd, int num1, int num2)
if (deltaLen <= 0) {
memcpy(&lp->data[offset], newStr, newLen);
if (deltaLen) {
memcpy(&lp->data[offset + newLen],
memmove(&lp->data[offset + newLen],
&lp->data[offset + oldLen],
lp->len - offset - oldLen);
@@ -789,7 +799,7 @@ static void doCommands(void)
* 0 on ctrl-C,
* >0 length of input string, including terminating '\n'
*/
len = read_line_input(NULL, ": ", buf, sizeof(buf));
len = read_line_input(NULL, prompt, buf, sizeof(buf));
if (len <= 0)
return;
while (len && isspace(buf[--len]))
@@ -1001,13 +1011,15 @@ int ed_main(int argc UNUSED_PARAM, char **argv)
lines.next = &lines;
lines.prev = &lines;
if (argv[1]) {
fileName = xstrdup(argv[1]);
prompt = ""; /* no prompt by default */
getopt32(argv, OPTION_STR, &prompt);
argv += optind;
if (argv[0]) {
fileName = xstrdup(argv[0]);
if (!readLines(fileName, 1)) {
return EXIT_SUCCESS;
}
if (lastNum)
setCurNum(1);
dirty = FALSE;
}
+9 -9
View File
@@ -138,9 +138,9 @@ static void do_line(void *data)
{
struct double_list *dlist = data;
if (TT.state>1 && *dlist->data != TT.state)
if (TT.state > 1 && *dlist->data != TT.state)
fdprintf(TT.state == 2 ? 2 : TT.fileout,
"%s\n", dlist->data+(TT.state>3 ? 1 : 0));
"%s\n", dlist->data + (TT.state > 3 ? 1 : 0));
if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
@@ -221,7 +221,7 @@ static int apply_one_hunk(void)
// Match EOF if there aren't as many ending context lines as beginning
for (plist = TT.current_hunk; plist; plist = plist->next) {
if (plist->data[0]==' ') matcheof++;
if (plist->data[0] == ' ') matcheof++;
else matcheof = 0;
if (PATCH_DEBUG) fdprintf(2, "HUNK:%s\n", plist->data);
}
@@ -418,7 +418,7 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
}
// Loop through the lines in the patch
for(;;) {
for (;;) {
char *patchline;
patchline = xmalloc_fgetline(stdin);
@@ -433,15 +433,15 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// Are we assembling a hunk?
if (state >= 2) {
if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
if (*patchline == ' ' || *patchline == '+' || *patchline == '-') {
dlist_add(&TT.current_hunk, patchline);
if (*patchline != '+') oldlen--;
if (*patchline != '-') newlen--;
// Context line?
if (*patchline==' ' && state==2) TT.context++;
else state=3;
if (*patchline == ' ' && state == 2) TT.context++;
else state = 3;
// If we've consumed all expected hunk lines, apply the hunk.
@@ -469,9 +469,9 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
free(*name);
// Trim date from end of filename (if any). We don't care.
for (s = patchline+4; *s && *s!='\t'; s++)
if (*s=='\\' && s[1]) s++;
if (*s == '\\' && s[1]) s++;
i = atoi(s);
if (i>1900 && i<=1970)
if (i > 1900 && i <= 1970)
*name = xstrdup("/dev/null");
else {
*s = 0;
+19 -19
View File
@@ -79,7 +79,7 @@ void TOY_llist_free(void *list, void (*freeit)(void *data))
else free(pop);
// End doubly linked list too.
if (list==pop) break;
if (list == pop) break;
}
}
@@ -137,11 +137,11 @@ char *get_rawline(int fd, long *plen, char end)
long len = 0;
for (;;) {
if (1>read(fd, &c, 1)) break;
if (1 > read(fd, &c, 1)) break;
if (!(len & 63)) buf=xrealloc(buf, len+65);
if ((buf[len++]=c) == end) break;
if ((buf[len++] = c) == end) break;
}
if (buf) buf[len]=0;
if (buf) buf[len] = 0;
if (plen) *plen = len;
return buf;
@@ -153,7 +153,7 @@ char *get_line(int fd)
long len;
char *buf = get_rawline(fd, &len, '\n');
if (buf && buf[--len]=='\n') buf[len]=0;
if (buf && buf[--len] == '\n') buf[len] = 0;
return buf;
}
@@ -165,10 +165,10 @@ void xsendfile(int in, int out)
long len;
char buf[4096];
if (in<0) return;
if (in < 0) return;
for (;;) {
len = safe_read(in, buf, 4096);
if (len<1) break;
if (len < 1) break;
xwrite(out, buf, len);
}
}
@@ -179,7 +179,7 @@ void replace_tempfile(int fdin, int fdout, char **tempname)
{
char *temp = xstrdup(*tempname);
temp[strlen(temp)-6]=0;
temp[strlen(temp)-6] = 0;
if (fdin != -1) {
xsendfile(fdin, fdout);
xclose(fdin);
@@ -263,9 +263,9 @@ static void do_line(void *data)
{
struct double_list *dlist = (struct double_list *)data;
if (TT.state>1 && *dlist->data != TT.state)
if (TT.state > 1 && *dlist->data != TT.state)
fdprintf(TT.state == 2 ? 2 : TT.fileout,
"%s\n", dlist->data+(TT.state>3 ? 1 : 0));
"%s\n", dlist->data + (TT.state > 3 ? 1 : 0));
if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
@@ -314,7 +314,7 @@ static int apply_one_hunk(void)
// Match EOF if there aren't as many ending context lines as beginning
for (plist = TT.current_hunk; plist; plist = plist->next) {
if (plist->data[0]==' ') matcheof++;
if (plist->data[0] == ' ') matcheof++;
else matcheof = 0;
if (PATCH_DEBUG) fdprintf(2, "HUNK:%s\n", plist->data);
}
@@ -385,7 +385,7 @@ static int apply_one_hunk(void)
// If we've reached the end of the buffer without confirming a
// match, read more lines.
if (check==buf) {
if (check == buf) {
buf = 0;
break;
}
@@ -441,7 +441,7 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
TT.filein = TT.fileout = -1;
// Loop through the lines in the patch
for(;;) {
for (;;) {
char *patchline;
patchline = get_line(TT.filepatch);
@@ -456,15 +456,15 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// Are we assembling a hunk?
if (state >= 2) {
if (*patchline==' ' || *patchline=='+' || *patchline=='-') {
if (*patchline == ' ' || *patchline == '+' || *patchline == '-') {
dlist_add(&TT.current_hunk, patchline);
if (*patchline != '+') TT.oldlen--;
if (*patchline != '-') TT.newlen--;
// Context line?
if (*patchline==' ' && state==2) TT.context++;
else state=3;
if (*patchline == ' ' && state == 2) TT.context++;
else state = 3;
// If we've consumed all expected hunk lines, apply the hunk.
@@ -491,9 +491,9 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// Trim date from end of filename (if any). We don't care.
for (s = patchline+4; *s && *s!='\t'; s++)
if (*s=='\\' && s[1]) s++;
if (*s == '\\' && s[1]) s++;
i = atoi(s);
if (i>1900 && i<=1970)
if (i > 1900 && i <= 1970)
*name = xstrdup("/dev/null");
else {
*s = 0;
@@ -537,7 +537,7 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// handle -p path truncation.
for (i=0, s = name; *s;) {
if ((option_mask32 & FLAG_PATHLEN) && TT.prefix == i) break;
if (*(s++)=='/') {
if (*(s++) == '/') {
name = s;
i++;
}
+56 -15
View File
@@ -97,6 +97,12 @@ enum {
OPT_in_place = 1 << 0,
};
struct sed_FILE {
struct sed_FILE *next; /* Next (linked list, NULL terminated) */
char *fname;
FILE *fp;
};
/* Each sed command turns into one of these structures. */
typedef struct sed_cmd_s {
/* Ordered by alignment requirements: currently 36 bytes on x86 */
@@ -151,6 +157,11 @@ struct globals {
/* linked list of append lines */
llist_t *append_head;
/* linked list of FILEs opened for 'w' and s///w'.
* Needed to handle duplicate fnames: sed '/a/w F;/b/w F'
*/
struct sed_FILE *FILE_head;
char *add_cmd_line;
struct pipeline {
@@ -177,9 +188,6 @@ static void sed_free_and_close_stuff(void)
while (sed_cmd) {
sed_cmd_t *sed_cmd_next = sed_cmd->next;
if (sed_cmd->sw_file)
fclose(sed_cmd->sw_file);
/* Used to free regexps, but now there is code
* in get_address() which can reuse a regexp
* for constructs as /regexp/cmd1;//cmd2
@@ -206,11 +214,39 @@ static void sed_free_and_close_stuff(void)
if (G.current_fp)
fclose(G.current_fp);
if (G.FILE_head) {
struct sed_FILE *cur = G.FILE_head;
do {
struct sed_FILE *p;
fclose(cur->fp);
free(cur->fname);
p = cur;
cur = cur->next;
free(p);
} while (cur);
}
}
#else
void sed_free_and_close_stuff(void);
#endif
static FILE *sed_xfopen_w(const char *fname)
{
struct sed_FILE **pp = &G.FILE_head;
struct sed_FILE *cur;
while ((cur = *pp) != NULL) {
if (strcmp(cur->fname, fname) == 0)
return cur->fp;
pp = &cur->next;
}
*pp = cur = xzalloc(sizeof(*cur));
/*cur->next = NULL; - already is */
cur->fname = xstrdup(fname);
cur->fp = xfopen_for_write(fname);
return cur->fp;
}
/* If something bad happens during -i operation, delete temp file */
static void cleanup_outname(void)
@@ -219,7 +255,6 @@ static void cleanup_outname(void)
}
/* strcpy, replacing "\from" with 'to'. If to is NUL, replacing "\any" with 'any' */
static unsigned parse_escapes(char *dest, const char *string, int len, char from, char to)
{
char *d = dest;
@@ -249,7 +284,7 @@ static unsigned parse_escapes(char *dest, const char *string, int len, char from
return d - dest;
}
static char *copy_parsing_escapes(const char *string, int len)
static char *copy_parsing_escapes(const char *string, int len, char delim)
{
const char *s;
char *dest = xmalloc(len + 1);
@@ -260,10 +295,15 @@ static char *copy_parsing_escapes(const char *string, int len)
len = parse_escapes(dest, string, len, s[1], s[0]);
string = dest;
}
if (delim) {
/* we additionally unescape any instances of escaped delimiter.
* For example, in 's+9\++X+' the pattern is "9+", not "9\+".
*/
len = parse_escapes(dest, string, len, delim, delim);
}
return dest;
}
/*
* index_of_next_unescaped_regexp_delim - walks left to right through a string
* beginning at a specified index and returns the index of the next regular
@@ -320,12 +360,14 @@ static int parse_regex_delim(const char *cmdstr, char **match, char **replace)
/* save the match string */
idx = index_of_next_unescaped_regexp_delim(delimiter, cmdstr_ptr);
*match = copy_parsing_escapes(cmdstr_ptr, idx);
*match = copy_parsing_escapes(cmdstr_ptr, idx, delimiter);
/* save the replacement string */
cmdstr_ptr += idx + 1;
idx = index_of_next_unescaped_regexp_delim(- (int)delimiter, cmdstr_ptr);
*replace = copy_parsing_escapes(cmdstr_ptr, idx);
//GNU sed 4.8:
// echo 789 | sed 's&8&\&&' - 7&9 ("\&" remained "\&")
// echo 789 | sed 's1\(8\)1\1\11' - 7119 ("\1\1" become "11")
*replace = copy_parsing_escapes(cmdstr_ptr, idx, delimiter != '&' ? delimiter : 0);
return ((cmdstr_ptr - cmdstr) + idx);
}
@@ -353,7 +395,7 @@ static int get_address(const char *my_str, int *linenum, regex_t ** regex)
delimiter = *++pos;
next = index_of_next_unescaped_regexp_delim(delimiter, ++pos);
if (next != 0) {
temp = copy_parsing_escapes(pos, next);
temp = copy_parsing_escapes(pos, next, 0);
G.previous_regex_ptr = *regex = xzalloc(sizeof(regex_t));
xregcomp(*regex, temp, G.regex_type);
free(temp);
@@ -435,8 +477,7 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
switch (substr[idx]) {
/* Replace all occurrences */
case 'g':
if (match[0] != '^')
sed_cmd->which_match = 0;
sed_cmd->which_match = 0;
break;
/* Print pattern space */
case 'p':
@@ -447,7 +488,7 @@ static int parse_subst_cmd(sed_cmd_t *sed_cmd, const char *substr)
{
char *fname;
idx += parse_file_cmd(/*sed_cmd,*/ substr+idx+1, &fname);
sed_cmd->sw_file = xfopen_for_write(fname);
sed_cmd->sw_file = sed_xfopen_w(fname);
sed_cmd->sw_last_char = '\n';
free(fname);
break;
@@ -549,7 +590,7 @@ static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
cmdstr++;
}
len = strlen(cmdstr);
sed_cmd->string = copy_parsing_escapes(cmdstr, len);
sed_cmd->string = copy_parsing_escapes(cmdstr, len, 0);
cmdstr += len;
/* "\anychar" -> "anychar" */
parse_escapes(sed_cmd->string, sed_cmd->string, -1, '\0', '\0');
@@ -562,7 +603,7 @@ static const char *parse_cmd_args(sed_cmd_t *sed_cmd, const char *cmdstr)
}
cmdstr += parse_file_cmd(/*sed_cmd,*/ cmdstr, &sed_cmd->string);
if (sed_cmd->cmd == 'w') {
sed_cmd->sw_file = xfopen_for_write(sed_cmd->string);
sed_cmd->sw_file = sed_xfopen_w(sed_cmd->string);
sed_cmd->sw_last_char = '\n';
}
}
+269 -165
View File
@@ -7,7 +7,7 @@
*/
//
//Things To Do:
// $HOME/.exrc and ./.exrc
// ./.exrc
// add magic to search /foo.*bar
// add :help command
// :map macros
@@ -185,7 +185,7 @@
//usage:#define vi_full_usage "\n\n"
//usage: "Edit FILE\n"
//usage: IF_FEATURE_VI_COLON(
//usage: "\n -c CMD Initial command to run ($EXINIT also available)"
//usage: "\n -c CMD Initial command to run ($EXINIT and ~/.exrc also available)"
//usage: )
//usage: IF_FEATURE_VI_READONLY(
//usage: "\n -R Read-only"
@@ -201,6 +201,7 @@
// the CRASHME code is unmaintained, and doesn't currently build
#define ENABLE_FEATURE_VI_CRASHME 0
#define IF_FEATURE_VI_CRASHME(...)
#if ENABLE_LOCALE_SUPPORT
@@ -223,6 +224,7 @@
#endif
#define isbackspace(c) ((c) == term_orig.c_cc[VERASE] || (c) == 8 || (c) == 127)
enum {
MAX_TABSTOP = 32, // sanity limit
@@ -341,6 +343,7 @@ struct globals {
int last_modified_count; // = -1;
int cmdline_filecnt; // how many file names on cmd line
int cmdcnt; // repetition count
char *rstart; // start of text in Replace mode
unsigned rows, columns; // the terminal screen is this size
#if ENABLE_FEATURE_VI_ASK_TERMINAL
int get_rowcol_error;
@@ -377,7 +380,9 @@ struct globals {
char *last_search_pattern; // last pattern from a '/' or '?' search
#endif
#if ENABLE_FEATURE_VI_SETOPTS
int indentcol; // column of recently autoindent, 0 or -1
int char_insert__indentcol; // column of recent autoindent or 0
int newindent; // autoindent value for 'O'/'cc' commands
// or -1 to use indent from previous line
#endif
smallint cmd_error;
@@ -403,7 +408,7 @@ struct globals {
int cindex; // saved character index for up/down motion
smallint keep_index; // retain saved character index
#if ENABLE_FEATURE_VI_COLON
char *initial_cmds[3]; // currently 2 entries, NULL terminated
llist_t *initial_cmds;
#endif
// Should be just enough to hold a key sequence,
// but CRASHME mode uses it as generated command buffer too
@@ -473,6 +478,7 @@ struct globals {
#define last_modified_count (G.last_modified_count)
#define cmdline_filecnt (G.cmdline_filecnt )
#define cmdcnt (G.cmdcnt )
#define rstart (G.rstart )
#define rows (G.rows )
#define columns (G.columns )
#define crow (G.crow )
@@ -503,7 +509,8 @@ struct globals {
#define ioq_start (G.ioq_start )
#define dotcnt (G.dotcnt )
#define last_search_pattern (G.last_search_pattern)
#define indentcol (G.indentcol )
#define char_insert__indentcol (G.char_insert__indentcol)
#define newindent (G.newindent )
#define cmd_error (G.cmd_error )
#define edit_file__cur_line (G.edit_file__cur_line)
@@ -536,10 +543,11 @@ struct globals {
#define INIT_G() do { \
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
last_modified_count = -1; \
last_modified_count--; \
/* "" but has space for 2 chars: */ \
IF_FEATURE_VI_SEARCH(last_search_pattern = xzalloc(2);) \
tabstop = 8; \
IF_FEATURE_VI_SETOPTS(newindent--;) \
} while (0)
#if ENABLE_FEATURE_VI_CRASHME
@@ -1121,7 +1129,7 @@ static int readit(void) // read (maybe cursor) key from stdin
// on nonblocking stdin.
// Note: read_key sets errno to 0 on success.
again:
c = read_key(STDIN_FILENO, readbuffer, /*timeout:*/ -1);
c = safe_read_key(STDIN_FILENO, readbuffer, /*timeout:*/ -1);
if (c == -1) { // EOF/error
if (errno == EAGAIN) // paranoia
goto again;
@@ -1211,12 +1219,13 @@ static char *get_input_line(const char *prompt)
c = get_one_char();
if (c == '\n' || c == '\r' || c == 27)
break; // this is end of input
if (c == term_orig.c_cc[VERASE] || c == 8 || c == 127) {
if (isbackspace(c)) {
// user wants to erase prev char
write1("\b \b"); // erase char on screen
buf[--i] = '\0';
go_bottom_and_clear_to_eol();
if (i <= 0) // user backs up before b-o-l, exit
break;
write1(buf);
} else if (c > 0 && c < 256) { // exclude Unicode
// (TODO: need to handle Unicode)
buf[i] = c;
@@ -1376,21 +1385,14 @@ static void print_literal(char *buf, const char *s)
char *d;
unsigned char c;
buf[0] = '\0';
if (!s[0])
s = "(NULL)";
d = buf;
for (; *s; s++) {
int c_is_no_print;
c = *s;
c_is_no_print = (c & 0x80) && !Isprint(c);
if (c_is_no_print) {
strcpy(d, ESC_NORM_TEXT);
d += sizeof(ESC_NORM_TEXT)-1;
c = '.';
}
if ((c & 0x80) && !Isprint(c))
c = '?';
if (c < ' ' || c == 0x7f) {
*d++ = '^';
c |= '@'; // 0x40
@@ -1399,14 +1401,6 @@ static void print_literal(char *buf, const char *s)
}
*d++ = c;
*d = '\0';
if (c_is_no_print) {
strcpy(d, ESC_BOLD_TEXT);
d += sizeof(ESC_BOLD_TEXT)-1;
}
if (*s == '\n') {
*d++ = '$';
*d = '\0';
}
if (d - buf > MAX_INPUT_LEN - 10) // paranoia
break;
}
@@ -2123,6 +2117,7 @@ static size_t indent_len(char *p)
static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
{
#if ENABLE_FEATURE_VI_SETOPTS
# define indentcol char_insert__indentcol
size_t len;
int col, ntab, nspc;
#endif
@@ -2151,7 +2146,8 @@ static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
#if ENABLE_FEATURE_VI_SETOPTS
if (autoindent) {
len = indent_len(bol);
if (len && get_column(bol + len) == indentcol && bol[len] == '\n') {
col = get_column(bol + len);
if (len && col == indentcol && bol[len] == '\n') {
// remove autoindent from otherwise empty line
text_hole_delete(bol, bol + len - 1, undo);
p = bol;
@@ -2188,8 +2184,16 @@ static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
p += 1 + stupid_insert(p, ' ');
}
#endif
} else if (c == term_orig.c_cc[VERASE] || c == 8 || c == 127) { // Is this a BS
if (p > text) {
} else if (isbackspace(c)) {
if (cmd_mode == 2) {
// special treatment for backspace in Replace mode
if (p > rstart) {
p--;
#if ENABLE_FEATURE_VI_UNDO
undo_pop();
#endif
}
} else if (p > text) {
p--;
p = text_hole_delete(p, p, ALLOW_UNDO_QUEUED); // shrink buffer 1 char
}
@@ -2212,24 +2216,31 @@ static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
showmatching(p - 1);
}
if (autoindent && c == '\n') { // auto indent the new line
// use indent of current/previous line
bol = indentcol < 0 ? p : prev_line(p);
len = indent_len(bol);
col = get_column(bol + len);
if (newindent < 0) {
// use indent of previous line
bol = prev_line(p);
len = indent_len(bol);
col = get_column(bol + len);
if (len && col == indentcol) {
// previous line was empty except for autoindent
// move the indent to the current line
memmove(bol + 1, bol, len);
*bol = '\n';
return p;
if (len && col == indentcol) {
// previous line was empty except for autoindent
// move the indent to the current line
memmove(bol + 1, bol, len);
*bol = '\n';
return p;
}
} else {
// for 'O'/'cc' commands add indent before newly inserted NL
if (p != end - 1) // but not for 'cc' at EOF
p--;
col = newindent;
}
if (indentcol < 0)
p--; // open above, indent before newly inserted NL
if (len) {
indentcol = col;
if (col) {
// only record indent if in insert/replace mode or for
// the 'o'/'O'/'cc' commands, which are switched to
// insert mode early.
indentcol = cmd_mode != 0 ? col : 0;
if (expandtab) {
ntab = 0;
nspc = col;
@@ -2251,6 +2262,7 @@ static char *char_insert(char *p, char c, int undo) // insert the char c at 'p'
}
#if ENABLE_FEATURE_VI_SETOPTS
indentcol = 0;
# undef indentcol
#endif
return p;
}
@@ -2472,26 +2484,38 @@ static char *char_search(char *p, const char *pat, int dir_and_range)
//----- The Colon commands -------------------------------------
#if ENABLE_FEATURE_VI_COLON
static char *get_one_address(char *p, int *result) // get colon addr, if present
// Evaluate colon address expression. Returns a pointer to the
// next character or NULL on error. If 'result' contains a valid
// address 'valid' is TRUE.
static char *get_one_address(char *p, int *result, int *valid)
{
int st, num, sign, addr, new_addr;
int num, sign, addr, got_addr;
# if ENABLE_FEATURE_VI_YANKMARK || ENABLE_FEATURE_VI_SEARCH
char *q, c;
# endif
IF_FEATURE_VI_SEARCH(int dir;)
addr = -1; // assume no addr
got_addr = FALSE;
addr = count_lines(text, dot); // default to current line
sign = 0;
for (;;) {
new_addr = -1;
if (isblank(*p)) {
if (got_addr) {
addr += sign;
sign = 0;
}
p++;
} else if (*p == '.') { // the current line
} else if (!got_addr && *p == '.') { // the current line
p++;
new_addr = count_lines(text, dot);
//addr = count_lines(text, dot);
got_addr = TRUE;
} else if (!got_addr && *p == '$') { // the last line in file
p++;
addr = count_lines(text, end - 1);
got_addr = TRUE;
}
# if ENABLE_FEATURE_VI_YANKMARK
else if (*p == '\'') { // is this a mark addr
else if (!got_addr && *p == '\'') { // is this a mark addr
p++;
c = tolower(*p);
p++;
@@ -2501,13 +2525,16 @@ static char *get_one_address(char *p, int *result) // get colon addr, if present
c = c - 'a';
q = mark[(unsigned char) c];
}
if (q == NULL) // is mark valid
if (q == NULL) { // is mark valid
status_line_bold("Mark not set");
return NULL;
new_addr = count_lines(text, q);
}
addr = count_lines(text, q);
got_addr = TRUE;
}
# endif
# if ENABLE_FEATURE_VI_SEARCH
else if (*p == '/' || *p == '?') { // a search pattern
else if (!got_addr && (*p == '/' || *p == '?')) { // a search pattern
c = *p;
q = strchrnul(p + 1, c);
if (p + 1 != q) {
@@ -2526,39 +2553,45 @@ static char *get_one_address(char *p, int *result) // get colon addr, if present
dir = ((unsigned)BACK << 1) | FULL;
}
q = char_search(q, last_search_pattern + 1, dir);
if (q == NULL)
return NULL;
new_addr = count_lines(text, q);
if (q == NULL) {
// no match, continue from other end of file
q = char_search(dir > 0 ? text : end - 1,
last_search_pattern + 1, dir);
if (q == NULL) {
status_line_bold("Pattern not found");
return NULL;
}
}
addr = count_lines(text, q);
got_addr = TRUE;
}
# endif
else if (*p == '$') { // the last line in file
p++;
new_addr = count_lines(text, end - 1);
} else if (isdigit(*p)) {
sscanf(p, "%d%n", &num, &st);
p += st;
if (addr < 0) { // specific line number
else if (isdigit(*p)) {
num = 0;
while (isdigit(*p))
num = num * 10 + *p++ -'0';
if (!got_addr) { // specific line number
addr = num;
got_addr = TRUE;
} else { // offset from current addr
addr += sign >= 0 ? num : -num;
}
sign = 0;
} else if (*p == '-' || *p == '+') {
sign = *p++ == '-' ? -1 : 1;
if (addr < 0) { // default address is dot
addr = count_lines(text, dot);
if (!got_addr) { // default address is dot
//addr = count_lines(text, dot);
got_addr = TRUE;
} else {
addr += sign;
}
sign = *p++ == '-' ? -1 : 1;
} else {
addr += sign; // consume unused trailing sign
break;
}
if (new_addr >= 0) {
if (addr >= 0) // only one new address per expression
return NULL;
addr = new_addr;
}
}
*result = addr;
*valid = got_addr;
return p;
}
@@ -2567,34 +2600,40 @@ static char *get_one_address(char *p, int *result) // get colon addr, if present
// Read line addresses for a colon command. The user can enter as
// many as they like but only the last two will be used.
static char *get_address(char *p, int *b, int *e)
static char *get_address(char *p, int *b, int *e, unsigned int *got)
{
int state = GET_ADDRESS;
int valid;
int addr;
char *save_dot = dot;
//----- get the address' i.e., 1,3 'a,'b -----
for (;;) {
if (isblank(*p)) {
p++;
} else if (*p == '%' && state == GET_ADDRESS) { // alias for 1,$
} else if (state == GET_ADDRESS && *p == '%') { // alias for 1,$
p++;
*b = 1;
*e = count_lines(text, end-1);
*got = 3;
state = GET_SEPARATOR;
} else if (state == GET_ADDRESS) {
valid = FALSE;
p = get_one_address(p, &addr, &valid);
// Quit on error or if the address is invalid and isn't of
// the form ',$' or '1,' (in which case it defaults to dot).
if (p == NULL || !(valid || *p == ',' || *p == ';' || *got & 1))
break;
*b = *e;
*e = addr;
*got = (*got << 1) | 1;
state = GET_SEPARATOR;
} else if (state == GET_SEPARATOR && (*p == ',' || *p == ';')) {
if (*p == ';')
dot = find_line(*e);
p++;
*b = *e;
state = GET_ADDRESS;
} else if (state == GET_ADDRESS) {
p = get_one_address(p, e);
if (p == NULL)
break;
state = GET_SEPARATOR;
} else {
if (state == GET_SEPARATOR && *b >= 0 && *e < 0)
*e = count_lines(text, dot);
break;
}
}
@@ -2808,9 +2847,14 @@ static void colon(char *buf)
not_implemented(p);
#else
// check how many addresses we got
# define GOT_ADDRESS (got & 1)
# define GOT_RANGE ((got & 3) == 3)
char c, *buf1, *q, *r;
char *fn, cmd[MAX_INPUT_LEN], *cmdend, *args, *exp = NULL;
int i, l, li, b, e;
unsigned int got;
int useforce;
// :3154 // if (-e line 3154) goto it else stay put
@@ -2828,21 +2872,22 @@ static void colon(char *buf)
// :!<cmd> // run <cmd> then return
//
if (!buf[0])
goto ret;
if (*buf == ':')
buf++; // move past the ':'
while (*buf == ':')
buf++; // move past leading colons
while (isblank(*buf))
buf++; // move past leading blanks
if (!buf[0] || buf[0] == '"')
goto ret; // ignore empty lines or those starting with '"'
li = i = 0;
b = e = -1;
got = 0;
li = count_lines(text, end - 1);
fn = current_filename;
// look for optional address(es) :. :1 :1,9 :'q,'a :%
buf1 = buf;
buf = get_address(buf, &b, &e);
buf = get_address(buf, &b, &e, &got);
if (buf == NULL) {
status_line_bold("Bad address: %s", buf1);
goto ret;
}
@@ -2865,13 +2910,17 @@ static void colon(char *buf)
}
// assume the command will want a range, certain commands
// (read, substitute) need to adjust these assumptions
if (e < 0) {
if (!GOT_ADDRESS) {
q = text; // no addr, use 1,$ for the range
r = end - 1;
} else {
// at least one addr was given, get its details
if (e < 0 || e > li) {
status_line_bold("Invalid range");
goto ret;
}
q = r = find_line(e);
if (b < 0) {
if (!GOT_RANGE) {
// if there is only one addr, then it's the line
// number of the single line the user wants.
// Reset the end pointer to the end of that line.
@@ -2880,6 +2929,10 @@ static void colon(char *buf)
} else {
// we were given two addrs. change the
// start pointer to the addr given by user.
if (b < 0 || b > li || b > e) {
status_line_bold("Invalid range");
goto ret;
}
q = find_line(b); // what line is #b
r = end_line(r);
li = e - b + 1;
@@ -2910,12 +2963,12 @@ static void colon(char *buf)
}
# endif
else if (cmd[0] == '=' && !cmd[1]) { // where is the address
if (e < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
e = count_lines(text, dot);
}
status_line("%d", e);
} else if (strncmp(cmd, "delete", i) == 0) { // delete lines
if (e < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -2987,7 +3040,7 @@ static void colon(char *buf)
rawmode();
Hit_Return();
} else if (strncmp(cmd, "list", i) == 0) { // literal print line
if (e < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -3070,7 +3123,7 @@ static void colon(char *buf)
if (e == 0) { // user said ":0r foo"
q = text;
} else { // read after given line or current line if none given
q = next_line(e > 0 ? find_line(e) : dot);
q = next_line(GOT_ADDRESS ? find_line(e) : dot);
// read after last line
if (q == end-1)
++q;
@@ -3191,11 +3244,11 @@ static void colon(char *buf)
len_F = strlen(F);
}
if (e < 0) { // no addr given
if (!GOT_ADDRESS) { // no addr given
q = begin_line(dot); // start with cur line
r = end_line(dot);
b = e = count_lines(text, q); // cur line number
} else if (b < 0) { // one addr given
} else if (!GOT_RANGE) { // one addr given
b = e;
}
@@ -3366,7 +3419,7 @@ static void colon(char *buf)
}
# if ENABLE_FEATURE_VI_YANKMARK
} else if (strncmp(cmd, "yank", i) == 0) { // yank lines
if (b < 0) { // no addr given- use defaults
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
@@ -3676,9 +3729,9 @@ static void do_cmd(int c)
undo_queue_commit();
} else {
if (1 <= c || Isprint(c)) {
if (c != 27)
dot = yank_delete(dot, dot, PARTIAL, YANKDEL, ALLOW_UNDO); // delete char
dot = char_insert(dot, c, ALLOW_UNDO_CHAIN); // insert new char
if (c != 27 && !isbackspace(c))
dot = yank_delete(dot, dot, PARTIAL, YANKDEL, ALLOW_UNDO);
dot = char_insert(dot, c, ALLOW_UNDO_CHAIN);
}
goto dc1;
}
@@ -4089,8 +4142,8 @@ static void do_cmd(int c)
#endif
}
}
} else /* if (c == '>') */ {
// shift right -- add tab or tabstop spaces
} else if (/* c == '>' && */ p != end_line(p)) {
// shift right -- add tab or tabstop spaces on non-empty lines
char_insert(p, '\t', allow_undo);
}
#if ENABLE_FEATURE_VI_UNDO
@@ -4178,6 +4231,9 @@ static void do_cmd(int c)
case 'i': // i- insert before current char
case KEYCODE_INSERT: // Cursor Key Insert
dc_i:
#if ENABLE_FEATURE_VI_SETOPTS
newindent = -1;
#endif
cmd_mode = 1; // start inserting
undo_queue_commit(); // commit queue when cmd_mode changes
break;
@@ -4220,12 +4276,16 @@ static void do_cmd(int c)
case 'O': // O- open an empty line above
dot_begin();
#if ENABLE_FEATURE_VI_SETOPTS
indentcol = -1;
// special case: use indent of current line
newindent = get_column(dot + indent_len(dot));
#endif
goto dc3;
case 'o': // o- open an empty line below
dot_end();
dc3:
#if ENABLE_FEATURE_VI_SETOPTS
cmd_mode = 1; // switch to insert mode early
#endif
dot = char_insert(dot, '\n', ALLOW_UNDO);
if (c == 'O' && !autoindent) {
// done in char_insert() for 'O'+autoindent
@@ -4237,6 +4297,7 @@ static void do_cmd(int c)
dc5:
cmd_mode = 2;
undo_queue_commit();
rstart = dot;
break;
case KEYCODE_DELETE:
if (dot < end - 1)
@@ -4263,8 +4324,14 @@ static void do_cmd(int c)
goto dc_i; // start inserting
break;
case 'Z': // Z- if modified, {write}; exit
// ZZ means to save file (if necessary), then exit
c1 = get_one_char();
// ZQ means to exit without saving
if (c1 == 'Q') {
editing = 0;
optind = cmdline_filecnt;
break;
}
// ZZ means to save file (if necessary), then exit
if (c1 != 'Z') {
indicate_error();
break;
@@ -4339,14 +4406,22 @@ static void do_cmd(int c)
if (buftype == WHOLE) {
save_dot = p; // final cursor position is start of range
p = begin_line(p);
#if ENABLE_FEATURE_VI_SETOPTS
if (c == 'c') // special case: use indent of current line
newindent = get_column(p + indent_len(p));
#endif
q = end_line(q);
}
dot = yank_delete(p, q, buftype, yf, ALLOW_UNDO); // delete word
if (buftype == WHOLE) {
if (c == 'c') {
#if ENABLE_FEATURE_VI_SETOPTS
cmd_mode = 1; // switch to insert mode early
#endif
dot = char_insert(dot, '\n', ALLOW_UNDO_CHAIN);
// on the last line of file don't move to prev line
if (dot != (end-1)) {
// on the last line of file don't move to prev line,
// handled in char_insert() if autoindent is enabled
if (dot != (end-1) && !autoindent) {
dot_prev();
}
} else if (c == 'd') {
@@ -4708,6 +4783,21 @@ static void crash_test()
}
#endif
#if ENABLE_FEATURE_VI_COLON
static void run_cmds(char *p)
{
while (p) {
char *q = p;
p = strchr(q, '\n');
if (p)
while (*p == '\n')
*p++ = '\0';
if (strlen(q) < MAX_INPUT_LEN)
colon(q);
}
}
#endif
static void edit_file(char *fn)
{
#if ENABLE_FEATURE_VI_YANKMARK
@@ -4728,7 +4818,7 @@ static void edit_file(char *fn)
uint64_t k;
write1(ESC"[999;999H" ESC"[6n");
fflush_all();
k = read_key(STDIN_FILENO, readbuffer, /*timeout_ms:*/ 100);
k = safe_read_key(STDIN_FILENO, readbuffer, /*timeout_ms:*/ 100);
if ((int32_t)k == KEYCODE_CURSOR_POS) {
uint32_t rc = (k >> 32);
columns = (rc & 0x7fff);
@@ -4778,25 +4868,8 @@ static void edit_file(char *fn)
#endif
#if ENABLE_FEATURE_VI_COLON
{
char *p, *q;
int n = 0;
while ((p = initial_cmds[n]) != NULL) {
do {
q = p;
p = strchr(q, '\n');
if (p)
while (*p == '\n')
*p++ = '\0';
if (*q)
colon(q);
} while (p);
free(initial_cmds[n]);
initial_cmds[n] = NULL;
n++;
}
}
while (initial_cmds)
run_cmds((char *)llist_pop(&initial_cmds));
#endif
redraw(FALSE); // dont force every col re-draw
//------This is the main Vi cmd handling loop -----------------------
@@ -4859,10 +4932,29 @@ static void edit_file(char *fn)
#undef cur_line
}
#define VI_OPTSTR \
IF_FEATURE_VI_CRASHME("C") \
IF_FEATURE_VI_COLON("c:*") \
"Hh" \
IF_FEATURE_VI_READONLY("R")
enum {
IF_FEATURE_VI_CRASHME(OPTBIT_C,)
IF_FEATURE_VI_COLON(OPTBIT_c,)
OPTBIT_H,
OPTBIT_h,
IF_FEATURE_VI_READONLY(OPTBIT_R,)
OPT_C = IF_FEATURE_VI_CRASHME( (1 << OPTBIT_C)) + 0,
OPT_c = IF_FEATURE_VI_COLON( (1 << OPTBIT_c)) + 0,
OPT_H = 1 << OPTBIT_H,
OPT_h = 1 << OPTBIT_h,
OPT_R = IF_FEATURE_VI_READONLY( (1 << OPTBIT_R)) + 0,
};
int vi_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int vi_main(int argc, char **argv)
{
int c;
int opts;
INIT_G();
@@ -4886,50 +4978,62 @@ int vi_main(int argc, char **argv)
// 0: all of our options are disabled by default in vim
//vi_setops = 0;
// 1- process EXINIT variable from environment
// 2- if EXINIT is unset process $HOME/.exrc file (not inplemented yet)
// 3- process command line args
#if ENABLE_FEATURE_VI_COLON
{
char *p = getenv("EXINIT");
if (p && *p)
initial_cmds[0] = xstrndup(p, MAX_INPUT_LEN);
}
#endif
while ((c = getopt(argc, argv,
opts = getopt32(argv, VI_OPTSTR IF_FEATURE_VI_COLON(, &initial_cmds));
#if ENABLE_FEATURE_VI_CRASHME
"C"
if (opts & OPT_C)
crashme = 1;
#endif
"RHh" IF_FEATURE_VI_COLON("c:"))) != -1) {
switch (c) {
#if ENABLE_FEATURE_VI_CRASHME
case 'C':
crashme = 1;
break;
#endif
#if ENABLE_FEATURE_VI_READONLY
case 'R': // Read-only flag
SET_READONLY_MODE(readonly_mode);
break;
#endif
#if ENABLE_FEATURE_VI_COLON
case 'c': // cmd line vi command
if (*optarg)
initial_cmds[initial_cmds[0] != NULL] = xstrndup(optarg, MAX_INPUT_LEN);
break;
#endif
case 'H':
show_help();
// fall through
default:
bb_show_usage();
return 1;
}
if (opts & OPT_R)
SET_READONLY_MODE(readonly_mode);
if (opts & OPT_H)
show_help();
if (opts & (OPT_H | OPT_h)) {
bb_show_usage();
return 1;
}
argv += optind;
cmdline_filecnt = argc - optind;
// 1- process EXINIT variable from environment
// 2- if EXINIT is unset process $HOME/.exrc file
// 3- process command line args
#if ENABLE_FEATURE_VI_COLON
{
const char *exinit = getenv("EXINIT");
char *cmds = NULL;
if (exinit) {
cmds = xstrdup(exinit);
} else {
const char *home = getenv("HOME");
if (home && *home) {
char *exrc = concat_path_file(home, ".exrc");
struct stat st;
// .exrc must belong to and only be writable by user
if (stat(exrc, &st) == 0) {
if ((st.st_mode & (S_IWGRP|S_IWOTH)) == 0
&& st.st_uid == getuid()
) {
cmds = xmalloc_open_read_close(exrc, NULL);
} else {
status_line_bold(".exrc: permission denied");
}
}
free(exrc);
}
}
if (cmds) {
init_text_buffer(NULL);
run_cmds(cmds);
free(cmds);
}
}
#endif
// "Save cursor, use alternate screen buffer, clear screen"
write1(ESC"[?1049h");
// This is the main file handling loop
+3 -3
View File
@@ -102,7 +102,7 @@ enum action_t {
REBOOT
};
int main(int argc, char *argv[])
int main(int argc, char **argv)
{
struct timespec t = {0,0};
enum action_t action = SHUTDOWN;
@@ -115,7 +115,7 @@ int main(int argc, char *argv[])
if (ptr)
prog = ptr+1;
for (c=1; c < argc; c++) {
for (c = 1; c < argc; c++) {
if (argv[c][0] >= '0' && argv[c][0] <= '9') {
t.tv_sec = strtol(argv[c], NULL, 10);
continue;
@@ -124,7 +124,7 @@ int main(int argc, char *argv[])
usage();
return 1;
}
for (i=1; argv[c][i]; i++) {
for (i = 1; argv[c][i]; i++) {
switch (argv[c][i]) {
case 'h':
action = HALT;
+12 -4
View File
@@ -19,7 +19,7 @@
#let cfg=cfg+1
#if[$cfg]=...; ip[$cfg]=...; ipmask[$cfg]=.../...; gw[$cfg]=...; net[$cfg]=... dns[$cfg]=...
exec >/dev/null
#exec >/dev/null
#exec >"$0.out" # debug
exec 2>&1
@@ -31,23 +31,31 @@ test "$ip" || exit 1
if ! test "$mask"; then
case "$ip" in
10.*)
echo "mask assumed 8 for ip=$ip"
mask=8;;
192.168.*)
mask=16;;
#172.16-31.x.x
172.1[6789].*)
echo "mask assumed 12 for ip=$ip"
mask=12;;
172.2[0123456789].*)
echo "mask assumed 12 for ip=$ip"
mask=12;;
172.3[01].*)
echo "mask assumed 12 for ip=$ip"
mask=12;;
192.168.*)
echo "mask assumed 16 for ip=$ip"
mask=16;;
esac
fi
# some servers do not return router option.
# assume DHCP server is the router.
if ! test "$router"; then
test "$serverid" && router="$serverid"
if test "$serverid"; then
router="$serverid"
echo "No 'router' from the server, assuming 'serverid' is the router: $serverid"
fi
fi
{
+1 -1
View File
@@ -19,7 +19,7 @@
#let cfg=cfg+1
#ntpip[$cfg]=...
exec >/dev/null
#exec >/dev/null
#exec >"$0.out" # debug
exec 2>&1
+2 -4
View File
@@ -38,12 +38,10 @@ file_ntpconf="$service.ntpconf"
dir_ipconf="/var/run/service/fw"
dir_ntpconf="/var/run/service/ntpd"
exec >/dev/null
#exec >>"$0.out" #debug
#exec >/dev/null
#exec >"$0.out" #debug
exec 2>&1
echo "`date`: Params: $*"
if test x"$1" != x"bound" && test x"$1" != x"renew" ; then
# Reconfigure network with this interface disabled
echo "Deconfiguring"
+1 -1
View File
@@ -1,5 +1,5 @@
#!/bin/sh
# executed when service is taken down ("sv d .")
# executed when service is taken down ("svc -d .")
service=${PWD##*/}
file_ipconf="$service.ipconf"
+12 -8
View File
@@ -179,7 +179,9 @@ ipt="iptables -t nat -A OUTPUT"
# OUTGOING TRAFFIC
ipt="iptables -t nat -A POSTROUTING"
# Masquerade boxes on my private net
doit $ipt -s 192.168.0.0/24 -o $extif -j MASQUERADE
for e in $extif; do
doit $ipt -s 192.168.0.0/24 -o $e -j MASQUERADE
done
# *** mangle ***
### DEBUG
@@ -204,7 +206,9 @@ fi
doit $ipt -p tcp -j REJECT # Anything else isn't ok. REJECT = irc opens faster
# (it probes proxy ports, DROP will incur timeout delays)
ipt="iptables -t filter -A INPUT"
doit $ipt -i $extif -j iext
for e in $extif; do
doit $ipt -i $e -j iext
done
echo; echo "* Enabling forwarding"
@@ -222,12 +226,12 @@ echo; echo "* Routing:"
ip r l
echo; echo "* Firewall:"
{
echo '---FILTER--';
iptables -v -L -x -n;
echo '---NAT-----';
iptables -t nat -v -L -x -n;
echo '---MANGLE--';
iptables -t mangle -v -L -x -n;
echo '---FILTER--'
iptables -v -L -x -n
echo '---NAT-----'
iptables -t nat -v -L -x -n
echo '---MANGLE--'
iptables -t mangle -v -L -x -n
} \
| grep -v '^$' | grep -Fv 'bytes target'
echo
+160 -22
View File
@@ -67,21 +67,53 @@
//config: interpreted by other programs.
//config:
//config:config FEATURE_FIND_MTIME
//config: bool "Enable -mtime: modified time matching"
//config: bool "Enable -mtime: modification time matching"
//config: default y
//config: depends on FIND
//config: help
//config: Allow searching based on the modification time of
//config: files, in days.
//config:
//config:config FEATURE_FIND_ATIME
//config: bool "Enable -atime: access time matching"
//config: default y
//config: depends on FEATURE_FIND_MTIME
//config: help
//config: Allow searching based on the access time of
//config: files, in days.
//config:
//config:config FEATURE_FIND_CTIME
//config: bool "Enable -ctime: status change timestamp matching"
//config: default y
//config: depends on FEATURE_FIND_MTIME
//config: help
//config: Allow searching based on the status change timestamp of
//config: files, in days.
//config:
//config:config FEATURE_FIND_MMIN
//config: bool "Enable -mmin: modified time matching by minutes"
//config: bool "Enable -mmin: modification time matching by minutes"
//config: default y
//config: depends on FIND
//config: help
//config: Allow searching based on the modification time of
//config: files, in minutes.
//config:
//config:config FEATURE_FIND_AMIN
//config: bool "Enable -amin: access time matching by minutes"
//config: default y
//config: depends on FEATURE_FIND_MMIN
//config: help
//config: Allow searching based on the access time of
//config: files, in minutes.
//config:
//config:config FEATURE_FIND_CMIN
//config: bool "Enable -cmin: status change timestamp matching by minutes"
//config: default y
//config: depends on FEATURE_FIND_MMIN
//config: help
//config: Allow searching based on the status change timestamp of
//config: files, in minutes.
//config:
//config:config FEATURE_FIND_PERM
//config: bool "Enable -perm: permissions matching"
//config: default y
@@ -123,6 +155,13 @@
//config: default y
//config: depends on FIND
//config:
//config:config FEATURE_FIND_SAMEFILE
//config: bool "Enable -samefile: reference file matching"
//config: default y
//config: depends on FIND
//config: help
//config: Support the 'find -samefile' option for searching by a reference file.
//config:
//config:config FEATURE_FIND_EXEC
//config: bool "Enable -exec: execute commands"
//config: default y
@@ -296,16 +335,31 @@
//usage: "\n -mtime DAYS mtime is greater than (+N), less than (-N),"
//usage: "\n or exactly N days in the past"
//usage: )
//usage: IF_FEATURE_FIND_ATIME(
//usage: "\n -atime DAYS atime +N/-N/N days in the past"
//usage: )
//usage: IF_FEATURE_FIND_CTIME(
//usage: "\n -ctime DAYS ctime +N/-N/N days in the past"
//usage: )
//usage: IF_FEATURE_FIND_MMIN(
//usage: "\n -mmin MINS mtime is greater than (+N), less than (-N),"
//usage: "\n or exactly N minutes in the past"
//usage: )
//usage: IF_FEATURE_FIND_AMIN(
//usage: "\n -amin MINS atime +N/-N/N minutes in the past"
//usage: )
//usage: IF_FEATURE_FIND_CMIN(
//usage: "\n -cmin MINS ctime +N/-N/N minutes in the past"
//usage: )
//usage: IF_FEATURE_FIND_NEWER(
//usage: "\n -newer FILE mtime is more recent than FILE's"
//usage: )
//usage: IF_FEATURE_FIND_INUM(
//usage: "\n -inum N File has inode number N"
//usage: )
//usage: IF_FEATURE_FIND_SAMEFILE(
//usage: "\n -samefile FILE File is same as FILE"
//usage: )
//usage: IF_FEATURE_FIND_USER(
//usage: "\n -user NAME/ID File is owned by given user"
//usage: )
@@ -396,10 +450,11 @@ IF_FEATURE_FIND_PRINT0( ACTS(print0))
IF_FEATURE_FIND_TYPE( ACTS(type, int type_mask;))
IF_FEATURE_FIND_EXECUTABLE(ACTS(executable))
IF_FEATURE_FIND_PERM( ACTS(perm, char perm_char; mode_t perm_mask;))
IF_FEATURE_FIND_MTIME( ACTS(mtime, char mtime_char; unsigned mtime_days;))
IF_FEATURE_FIND_MMIN( ACTS(mmin, char mmin_char; unsigned mmin_mins;))
IF_FEATURE_FIND_MTIME( ACTS(mtime, unsigned char time_type; unsigned char mtime_char; unsigned mtime_days;))
IF_FEATURE_FIND_MMIN( ACTS(mmin, unsigned char time_type; unsigned char mmin_char; unsigned mmin_mins;))
IF_FEATURE_FIND_NEWER( ACTS(newer, time_t newer_mtime;))
IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
IF_FEATURE_FIND_SAMEFILE(ACTS(samefile, ino_t inode_num; dev_t device;))
IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
@@ -618,30 +673,61 @@ ACTF(perm)
return (statbuf->st_mode & 07777) == ap->perm_mask;
}
#endif
#if 0 \
|| ENABLE_FEATURE_FIND_AMIN \
|| ENABLE_FEATURE_FIND_ATIME \
|| ENABLE_FEATURE_FIND_CMIN \
|| ENABLE_FEATURE_FIND_CTIME \
|| ENABLE_FEATURE_FIND_MMIN \
|| ENABLE_FEATURE_FIND_MTIME
static int time_cmp(const struct stat *statbuf, unsigned type_and_char, time_t N_from_user, unsigned unit)
{
time_t ftime, file_age;
ftime = statbuf->st_mtime;
# if ENABLE_FEATURE_FIND_ATIME || ENABLE_FEATURE_FIND_CTIME
# if ENABLE_FEATURE_FIND_ATIME
if ((type_and_char >> 8) == 'a')
ftime = statbuf->st_atime;
# endif
# if ENABLE_FEATURE_FIND_CTIME
if ((type_and_char >> 8) == 'c')
ftime = statbuf->st_ctime;
# endif
type_and_char &= 0xff;
# endif
file_age = time(NULL) - ftime;
N_from_user *= unit;
switch (type_and_char) {
case '+': return file_age >= N_from_user + unit;
case '-': return file_age < N_from_user;
/* just numeric time */
default: return file_age >= N_from_user && file_age < N_from_user + unit;
}
}
#endif
#if ENABLE_FEATURE_FIND_MTIME
ACTF(mtime)
{
time_t file_age = time(NULL) - statbuf->st_mtime;
time_t mtime_secs = ap->mtime_days * 24*60*60;
if (ap->mtime_char == '+')
return file_age >= mtime_secs + 24*60*60;
if (ap->mtime_char == '-')
return file_age < mtime_secs;
/* just numeric mtime */
return file_age >= mtime_secs && file_age < (mtime_secs + 24*60*60);
return time_cmp(statbuf,
# if ENABLE_FEATURE_FIND_ATIME || ENABLE_FEATURE_FIND_CTIME
(ap->time_type << 8) |
# endif
ap->mtime_char,
ap->mtime_days, 24*60*60);
}
#endif
#if ENABLE_FEATURE_FIND_MMIN
ACTF(mmin)
{
time_t file_age = time(NULL) - statbuf->st_mtime;
time_t mmin_secs = ap->mmin_mins * 60;
if (ap->mmin_char == '+')
return file_age >= mmin_secs + 60;
if (ap->mmin_char == '-')
return file_age < mmin_secs;
/* just numeric mmin */
return file_age >= mmin_secs && file_age < (mmin_secs + 60);
return time_cmp(statbuf,
# if ENABLE_FEATURE_FIND_ATIME || ENABLE_FEATURE_FIND_CTIME
(ap->time_type << 8) |
# endif
ap->mmin_char,
ap->mmin_mins, 60);
}
#endif
#if ENABLE_FEATURE_FIND_NEWER
@@ -656,6 +742,13 @@ ACTF(inum)
return (statbuf->st_ino == ap->inode_num);
}
#endif
#if ENABLE_FEATURE_FIND_SAMEFILE
ACTF(samefile)
{
return statbuf->st_ino == ap->inode_num &&
statbuf->st_dev == ap->device;
}
#endif
#if ENABLE_FEATURE_FIND_EXEC
static int do_exec(action_exec *ap, const char *fileName)
{
@@ -1043,9 +1136,14 @@ static action*** parse_params(char **argv)
IF_FEATURE_FIND_TYPE( PARM_type ,)
IF_FEATURE_FIND_PERM( PARM_perm ,)
IF_FEATURE_FIND_MTIME( PARM_mtime ,)
IF_FEATURE_FIND_ATIME( PARM_atime ,)
IF_FEATURE_FIND_CTIME( PARM_ctime ,)
IF_FEATURE_FIND_MMIN( PARM_mmin ,)
IF_FEATURE_FIND_AMIN( PARM_amin ,)
IF_FEATURE_FIND_CMIN( PARM_cmin ,)
IF_FEATURE_FIND_NEWER( PARM_newer ,)
IF_FEATURE_FIND_INUM( PARM_inum ,)
IF_FEATURE_FIND_SAMEFILE(PARM_samefile ,)
IF_FEATURE_FIND_USER( PARM_user ,)
IF_FEATURE_FIND_GROUP( PARM_group ,)
IF_FEATURE_FIND_SIZE( PARM_size ,)
@@ -1087,9 +1185,14 @@ static action*** parse_params(char **argv)
IF_FEATURE_FIND_TYPE( "-type\0" )
IF_FEATURE_FIND_PERM( "-perm\0" )
IF_FEATURE_FIND_MTIME( "-mtime\0" )
IF_FEATURE_FIND_ATIME( "-atime\0" )
IF_FEATURE_FIND_CTIME( "-ctime\0" )
IF_FEATURE_FIND_MMIN( "-mmin\0" )
IF_FEATURE_FIND_AMIN( "-amin\0" )
IF_FEATURE_FIND_CMIN( "-cmin\0" )
IF_FEATURE_FIND_NEWER( "-newer\0" )
IF_FEATURE_FIND_INUM( "-inum\0" )
IF_FEATURE_FIND_SAMEFILE("-samefile\0")
IF_FEATURE_FIND_USER( "-user\0" )
IF_FEATURE_FIND_GROUP( "-group\0" )
IF_FEATURE_FIND_SIZE( "-size\0" )
@@ -1373,19 +1476,39 @@ static action*** parse_params(char **argv)
}
#endif
#if ENABLE_FEATURE_FIND_MTIME
else if (parm == PARM_mtime) {
else if (parm == PARM_mtime
# if ENABLE_FEATURE_FIND_ATIME
|| parm == PARM_atime
# endif
# if ENABLE_FEATURE_FIND_CTIME
|| parm == PARM_ctime
# endif
) {
action_mtime *ap;
dbg("%d", __LINE__);
ap = ALLOC_ACTION(mtime);
# if ENABLE_FEATURE_FIND_AMIN || ENABLE_FEATURE_FIND_CMIN
ap->time_type = arg[1];
# endif
ap->mtime_char = arg1[0];
ap->mtime_days = xatoul(plus_minus_num(arg1));
}
#endif
#if ENABLE_FEATURE_FIND_MMIN
else if (parm == PARM_mmin) {
else if (parm == PARM_mmin
# if ENABLE_FEATURE_FIND_AMIN
|| parm == PARM_amin
# endif
# if ENABLE_FEATURE_FIND_CMIN
|| parm == PARM_cmin
# endif
) {
action_mmin *ap;
dbg("%d", __LINE__);
ap = ALLOC_ACTION(mmin);
# if ENABLE_FEATURE_FIND_AMIN || ENABLE_FEATURE_FIND_CMIN
ap->time_type = arg[1];
# endif
ap->mmin_char = arg1[0];
ap->mmin_mins = xatoul(plus_minus_num(arg1));
}
@@ -1408,6 +1531,21 @@ static action*** parse_params(char **argv)
ap->inode_num = xatoul(arg1);
}
#endif
#if ENABLE_FEATURE_FIND_SAMEFILE
else if (parm == PARM_samefile) {
action_samefile *ap;
struct stat stbuf;
dbg("%d", __LINE__);
if (G.recurse_flags & (ACTION_FOLLOWLINKS |
ACTION_FOLLOWLINKS_L0))
xstat(arg1, &stbuf);
else if (lstat(arg1, &stbuf))
bb_perror_msg_and_die("can't stat '%s'", arg1);
ap = ALLOC_ACTION(samefile);
ap->inode_num = stbuf.st_ino;
ap->device = stbuf.st_dev;
}
#endif
#if ENABLE_FEATURE_FIND_USER
else if (parm == PARM_user) {
action_user *ap;
+2 -2
View File
@@ -83,7 +83,7 @@
//usage: "\n -F PATTERN is a literal (not regexp)"
//usage: "\n -E PATTERN is an extended regexp"
//usage: IF_EXTRA_COMPAT(
//usage: "\n -z Input is NUL terminated"
//usage: "\n -z NUL terminated input"
//usage: )
//usage: "\n -m N Match up to N times per file"
//usage: IF_FEATURE_GREP_CONTEXT(
@@ -470,7 +470,7 @@ static int grep_file(FILE *file)
* "exit immediately with zero status
* if any match is found,
* even if errors were detected" */
exit(EXIT_SUCCESS);
exit_SUCCESS();
}
/* -l "print filenames with matches": stop after the first match */
if (option_mask32 & OPT_l) {
+52 -35
View File
@@ -111,6 +111,8 @@ struct globals {
#endif
const char *eof_str;
int idx;
int fd_tty;
int fd_stdin;
#if ENABLE_FEATURE_XARGS_SUPPORT_PARALLEL
int running_procs;
int max_procs;
@@ -140,6 +142,42 @@ struct globals {
IF_FEATURE_XARGS_SUPPORT_QUOTES(G.process_stdin__q = '\0';) \
} while (0)
/* Correct regardless of combination of CONFIG_xxx */
enum {
OPTBIT_VERBOSE = 0,
OPTBIT_NO_EMPTY,
OPTBIT_UPTO_NUMBER,
OPTBIT_UPTO_SIZE,
OPTBIT_EOF_STRING,
OPTBIT_EOF_STRING1,
OPTBIT_STDIN_TTY,
IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
IF_FEATURE_XARGS_SUPPORT_TERMOPT( OPTBIT_TERMINATE ,)
IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( OPTBIT_ZEROTERM ,)
IF_FEATURE_XARGS_SUPPORT_REPL_STR( OPTBIT_REPLSTR ,)
IF_FEATURE_XARGS_SUPPORT_REPL_STR( OPTBIT_REPLSTR1 ,)
OPT_VERBOSE = 1 << OPTBIT_VERBOSE ,
OPT_NO_EMPTY = 1 << OPTBIT_NO_EMPTY ,
OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
OPT_UPTO_SIZE = 1 << OPTBIT_UPTO_SIZE ,
OPT_EOF_STRING = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
OPT_STDIN_TTY = 1 << OPTBIT_STDIN_TTY,
OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
OPT_TERMINATE = IF_FEATURE_XARGS_SUPPORT_TERMOPT( (1 << OPTBIT_TERMINATE )) + 0,
OPT_ZEROTERM = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( (1 << OPTBIT_ZEROTERM )) + 0,
OPT_REPLSTR = IF_FEATURE_XARGS_SUPPORT_REPL_STR( (1 << OPTBIT_REPLSTR )) + 0,
OPT_REPLSTR1 = IF_FEATURE_XARGS_SUPPORT_REPL_STR( (1 << OPTBIT_REPLSTR1 )) + 0,
};
#define OPTION_STR "+trn:s:e::E:o" \
IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
IF_FEATURE_XARGS_SUPPORT_TERMOPT( "x") \
IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( "0") \
IF_FEATURE_XARGS_SUPPORT_REPL_STR( "I:i::") \
IF_FEATURE_XARGS_SUPPORT_PARALLEL( "P:+") \
IF_FEATURE_XARGS_SUPPORT_ARGS_FILE( "a:")
/*
* Returns 0 if xargs should continue (but may set G.xargs_exitcode to 123).
@@ -151,6 +189,9 @@ static int xargs_exec(void)
{
int status;
if (option_mask32 & OPT_STDIN_TTY)
xdup2(G.fd_tty, STDIN_FILENO);
#if !ENABLE_FEATURE_XARGS_SUPPORT_PARALLEL
status = spawn_and_wait(G.args);
#else
@@ -237,6 +278,8 @@ static int xargs_exec(void)
ret:
if (status != 0)
G.xargs_exitcode = status;
if (option_mask32 & OPT_STDIN_TTY)
xdup2(G.fd_stdin, STDIN_FILENO);
return status;
}
@@ -537,11 +580,12 @@ static int xargs_ask_confirmation(void)
//usage:#define xargs_full_usage "\n\n"
//usage: "Run PROG on every item given by stdin\n"
//usage: IF_FEATURE_XARGS_SUPPORT_ZERO_TERM(
//usage: "\n -0 Input is separated by NULs"
//usage: "\n -0 NUL terminated input"
//usage: )
//usage: IF_FEATURE_XARGS_SUPPORT_ARGS_FILE(
//usage: "\n -a FILE Read from FILE instead of stdin"
//usage: )
//usage: "\n -o Reopen stdin as /dev/tty"
//usage: "\n -r Don't run command if input is empty"
//usage: "\n -t Print the command on stderr before execution"
//usage: IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(
@@ -563,40 +607,6 @@ static int xargs_ask_confirmation(void)
//usage: "$ ls | xargs gzip\n"
//usage: "$ find . -name '*.c' -print | xargs rm\n"
/* Correct regardless of combination of CONFIG_xxx */
enum {
OPTBIT_VERBOSE = 0,
OPTBIT_NO_EMPTY,
OPTBIT_UPTO_NUMBER,
OPTBIT_UPTO_SIZE,
OPTBIT_EOF_STRING,
OPTBIT_EOF_STRING1,
IF_FEATURE_XARGS_SUPPORT_CONFIRMATION(OPTBIT_INTERACTIVE,)
IF_FEATURE_XARGS_SUPPORT_TERMOPT( OPTBIT_TERMINATE ,)
IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( OPTBIT_ZEROTERM ,)
IF_FEATURE_XARGS_SUPPORT_REPL_STR( OPTBIT_REPLSTR ,)
IF_FEATURE_XARGS_SUPPORT_REPL_STR( OPTBIT_REPLSTR1 ,)
OPT_VERBOSE = 1 << OPTBIT_VERBOSE ,
OPT_NO_EMPTY = 1 << OPTBIT_NO_EMPTY ,
OPT_UPTO_NUMBER = 1 << OPTBIT_UPTO_NUMBER,
OPT_UPTO_SIZE = 1 << OPTBIT_UPTO_SIZE ,
OPT_EOF_STRING = 1 << OPTBIT_EOF_STRING , /* GNU: -e[<param>] */
OPT_EOF_STRING1 = 1 << OPTBIT_EOF_STRING1, /* SUS: -E<param> */
OPT_INTERACTIVE = IF_FEATURE_XARGS_SUPPORT_CONFIRMATION((1 << OPTBIT_INTERACTIVE)) + 0,
OPT_TERMINATE = IF_FEATURE_XARGS_SUPPORT_TERMOPT( (1 << OPTBIT_TERMINATE )) + 0,
OPT_ZEROTERM = IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( (1 << OPTBIT_ZEROTERM )) + 0,
OPT_REPLSTR = IF_FEATURE_XARGS_SUPPORT_REPL_STR( (1 << OPTBIT_REPLSTR )) + 0,
OPT_REPLSTR1 = IF_FEATURE_XARGS_SUPPORT_REPL_STR( (1 << OPTBIT_REPLSTR1 )) + 0,
};
#define OPTION_STR "+trn:s:e::E:" \
IF_FEATURE_XARGS_SUPPORT_CONFIRMATION("p") \
IF_FEATURE_XARGS_SUPPORT_TERMOPT( "x") \
IF_FEATURE_XARGS_SUPPORT_ZERO_TERM( "0") \
IF_FEATURE_XARGS_SUPPORT_REPL_STR( "I:i::") \
IF_FEATURE_XARGS_SUPPORT_PARALLEL( "P:+") \
IF_FEATURE_XARGS_SUPPORT_ARGS_FILE( "a:")
int xargs_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int xargs_main(int argc UNUSED_PARAM, char **argv)
{
@@ -726,6 +736,13 @@ int xargs_main(int argc UNUSED_PARAM, char **argv)
store_param(argv[i]);
}
if (opt & OPT_STDIN_TTY) {
G.fd_tty = xopen(CURRENT_TTY, O_RDONLY);
close_on_exec_on(G.fd_tty);
G.fd_stdin = dup(STDIN_FILENO);
close_on_exec_on(G.fd_stdin);
}
initial_idx = G.idx;
while (1) {
char *rem;
+1 -1
View File
@@ -167,6 +167,7 @@ typedef struct tar_header_t { /* byte offset */
struct BUG_tar_header {
char c[sizeof(tar_header_t) == TAR_BLOCK_SIZE ? 1 : -1];
};
void chksum_and_xwrite_tar_header(int fd, struct tar_header_t *hp) FAST_FUNC;
extern const char cpio_TRAILER[];
@@ -194,7 +195,6 @@ char get_header_ar(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_cpio(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_gz(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_xz(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_bz2(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_lzma(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_tar_xz(archive_handle_t *archive_handle) FAST_FUNC;
+87 -52
View File
@@ -305,9 +305,13 @@ typedef unsigned long long uoff_t;
# endif
#else
/* CONFIG_LFS is off */
# if UINT_MAX == 0xffffffff
/* While sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
* gcc will throw warnings on printf("%d", off_t). Crap... */
/* sizeof(off_t) == sizeof(long).
* May or may not be == sizeof(int). If it is, use xatoi_positive()
* and bb_strtou() instead of xatoul_range() and bb_strtoul().
* Even if sizeof(off_t) == sizeof(int), off_t is typedef'ed to long anyway.
* gcc will throw warnings on printf("%d", off_t)... Have to use %ld etc.
*/
# if UINT_MAX == ULONG_MAX
typedef unsigned long uoff_t;
# define XATOOFF(a) xatoi_positive(a)
# define BB_STRTOOFF bb_strtou
@@ -365,13 +369,27 @@ struct BUG_off_t_size_is_misdetected {
#endif
#endif
/* We use a trick to have more optimized code (fewer pointer reloads
* and reduced binary size by a few kilobytes) like:
* ash.c: extern struct globals *const ash_ptr_to_globals;
* ash_ptr_hack.c: struct globals *ash_ptr_to_globals;
* This way, compiler in ash.c knows the pointer can not change.
*
* However, this may break on weird arches or toolchains. In this case,
* set "-DBB_GLOBAL_CONST=''" in CONFIG_EXTRA_CFLAGS to disable
* this optimization.
*/
#ifndef BB_GLOBAL_CONST
# define BB_GLOBAL_CONST const
#endif
#if defined(errno)
/* If errno is a define, assume it's "define errno (*__errno_location())"
* and we will cache it's result in this variable */
extern int *const bb_errno;
#undef errno
#define errno (*bb_errno)
#define bb_cached_errno_ptr 1
extern int *BB_GLOBAL_CONST bb_errno;
# undef errno
# define errno (*bb_errno)
# define bb_cached_errno_ptr 1
#endif
#if !(ULONG_MAX > 0xffffffff)
@@ -411,8 +429,8 @@ void *xrealloc(void *old, size_t size) FAST_FUNC;
xrealloc_vector_helper((vector), (sizeof((vector)[0]) << 8) + (shift), (idx))
void* xrealloc_vector_helper(void *vector, unsigned sizeof_and_shift, int idx) FAST_FUNC;
char *xstrdup(const char *s) FAST_FUNC RETURNS_MALLOC;
char *xstrndup(const char *s, int n) FAST_FUNC RETURNS_MALLOC;
void *xmemdup(const void *s, int n) FAST_FUNC RETURNS_MALLOC;
char *xstrndup(const char *s, size_t n) FAST_FUNC RETURNS_MALLOC;
void *xmemdup(const void *s, size_t n) FAST_FUNC RETURNS_MALLOC;
void *mmap_read(int fd, size_t size) FAST_FUNC;
void *mmap_anon(size_t size) FAST_FUNC;
void *xmmap_anon(size_t size) FAST_FUNC;
@@ -440,9 +458,8 @@ void *xmmap_anon(size_t size) FAST_FUNC;
# define cached_pagesize(var) (var)
#endif
//TODO: supply a pointer to char[11] buffer (avoid statics)?
extern const char *bb_mode_string(mode_t mode) FAST_FUNC;
/* Generate ls-style "mode string" like "-rwsr-xr-x" or "drwxrwxrwt" */
extern char *bb_mode_string(char buf[11], mode_t mode) FAST_FUNC;
extern int is_directory(const char *name, int followLinks) FAST_FUNC;
enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing them! */
FILEUTILS_PRESERVE_STATUS = 1 << 0, /* -p */
@@ -561,7 +578,7 @@ DIR *xopendir(const char *path) FAST_FUNC;
DIR *warn_opendir(const char *path) FAST_FUNC;
char *xmalloc_realpath(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_realpath_coreutils(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_realpath_coreutils(char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_readlink(const char *path) FAST_FUNC RETURNS_MALLOC;
char *xmalloc_readlink_or_warn(const char *path) FAST_FUNC RETURNS_MALLOC;
/* !RETURNS_MALLOC: it's a realloc-like function */
@@ -628,6 +645,7 @@ void xsetgid(gid_t gid) FAST_FUNC;
void xsetuid(uid_t uid) FAST_FUNC;
void xsetegid(gid_t egid) FAST_FUNC;
void xseteuid(uid_t euid) FAST_FUNC;
int chdir_or_warn(const char *path) FAST_FUNC;
void xchdir(const char *path) FAST_FUNC;
void xfchdir(int fd) FAST_FUNC;
void xchroot(const char *path) FAST_FUNC;
@@ -690,7 +708,7 @@ struct BUG_too_small {
};
void parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
int parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
time_t validate_tm_time(const char *date_str, struct tm *ptm) FAST_FUNC;
char *strftime_HHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
char *strftime_YYYYMMDDHHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
@@ -1037,6 +1055,7 @@ void die_if_ferror(FILE *file, const char *msg) FAST_FUNC;
void die_if_ferror_stdout(void) FAST_FUNC;
int fflush_all(void) FAST_FUNC;
void fflush_stdout_and_exit(int retval) NORETURN FAST_FUNC;
void fflush_stdout_and_exit_SUCCESS(void) NORETURN FAST_FUNC;
int fclose_if_not_stdin(FILE *file) FAST_FUNC;
FILE* xfopen(const char *filename, const char *mode) FAST_FUNC;
/* Prints warning to stderr and returns NULL on failure: */
@@ -1254,10 +1273,14 @@ void run_applet_no_and_exit(int a, const char *name, char **argv) NORETURN FAST_
#endif
void show_usage_if_dash_dash_help(int applet_no, char **argv) FAST_FUNC;
#if defined(__linux__)
int re_execed_comm(void) FAST_FUNC;
void set_task_comm(const char *comm) FAST_FUNC;
#else
# define re_execed_comm() 0
# define set_task_comm(name) ((void)0)
#endif
void exit_SUCCESS(void) NORETURN FAST_FUNC;
void _exit_SUCCESS(void) NORETURN FAST_FUNC;
/* Helpers for daemonization.
*
@@ -1483,18 +1506,11 @@ int scripted_main(int argc, char** argv) MAIN_EXTERNALLY_VISIBLE;
/* Applets which are useful from another applets */
int bb_cat(char** argv) FAST_FUNC;
int ash_main(int argc, char** argv)
#if ENABLE_ASH || ENABLE_SH_IS_ASH || ENABLE_BASH_IS_ASH
MAIN_EXTERNALLY_VISIBLE
#endif
;
int hush_main(int argc, char** argv)
#if ENABLE_HUSH || ENABLE_SH_IS_HUSH || ENABLE_BASH_IS_HUSH
MAIN_EXTERNALLY_VISIBLE
#endif
;
int ash_main(int argc, char** argv) IF_SHELL_ASH(MAIN_EXTERNALLY_VISIBLE);
int hush_main(int argc, char** argv) IF_SHELL_HUSH(MAIN_EXTERNALLY_VISIBLE);
/* If shell needs them, they exist even if not enabled as applets */
int echo_main(int argc, char** argv) IF_ECHO(MAIN_EXTERNALLY_VISIBLE);
int sleep_main(int argc, char **argv) IF_SLEEP(MAIN_EXTERNALLY_VISIBLE);
int printf_main(int argc, char **argv) IF_PRINTF(MAIN_EXTERNALLY_VISIBLE);
int test_main(int argc, char **argv)
#if ENABLE_TEST || ENABLE_TEST1 || ENABLE_TEST2
@@ -1607,7 +1623,7 @@ char *bb_ask_noecho_stdin(const char *prompt) FAST_FUNC;
int bb_ask_y_confirmation_FILE(FILE *fp) FAST_FUNC;
int bb_ask_y_confirmation(void) FAST_FUNC;
/* Returns -1 if input is invalid. current_mode is a base for e.g. "u+rw" */
/* Returns -1 if input is invalid. cur_mode is a base for e.g. "u+rw" */
int bb_parse_mode(const char* s, unsigned cur_mode) FAST_FUNC;
/*
@@ -1712,15 +1728,16 @@ extern void selinux_or_die(void) FAST_FUNC;
/* setup_environment:
* if chdir pw->pw_dir: ok: else if to_tmp == 1: goto /tmp else: goto / or die
* if clear_env = 1: cd(pw->pw_dir), clear environment, then set
* if SETUP_ENV_CHDIR:
* if cd(pw->pw_dir): ok: else if SETUP_ENV_TO_TMP: cd(/tmp) else: cd(/) or die
* if SETUP_ENV_CLEARENV: cd(pw->pw_dir), clear environment, then set
* TERM=(old value)
* USER=pw->pw_name, LOGNAME=pw->pw_name
* PATH=bb_default_[root_]path
* HOME=pw->pw_dir
* SHELL=shell
* else if change_env = 1:
* if not root (if pw->pw_uid != 0):
* else if SETUP_ENV_CHANGEENV | SETUP_ENV_CHANGEENV_LOGNAME:
* if not root (if pw->pw_uid != 0) or if SETUP_ENV_CHANGEENV_LOGNAME:
* USER=pw->pw_name, LOGNAME=pw->pw_name
* HOME=pw->pw_dir
* SHELL=shell
@@ -1729,10 +1746,11 @@ extern void selinux_or_die(void) FAST_FUNC;
* NB: CHANGEENV and CLEARENV use setenv() - this leaks memory!
* If setup_environment() is used is vforked child, this leaks memory _in parent too_!
*/
#define SETUP_ENV_CHANGEENV (1 << 0)
#define SETUP_ENV_CLEARENV (1 << 1)
#define SETUP_ENV_TO_TMP (1 << 2)
#define SETUP_ENV_NO_CHDIR (1 << 4)
#define SETUP_ENV_CHANGEENV (1 << 0)
#define SETUP_ENV_CHANGEENV_LOGNAME (1 << 1)
#define SETUP_ENV_CLEARENV (1 << 2)
#define SETUP_ENV_TO_TMP (1 << 3)
#define SETUP_ENV_CHDIR (1 << 4)
void setup_environment(const char *shell, int flags, const struct passwd *pw) FAST_FUNC;
void nuke_str(char *str) FAST_FUNC;
#if ENABLE_FEATURE_SECURETTY && !ENABLE_PAM
@@ -1883,6 +1901,8 @@ enum {
* (unless fd is in non-blocking mode),
* subsequent reads will time out after a few milliseconds.
* Return of -1 means EOF or error (errno == 0 on EOF).
* Nonzero errno is not preserved across the call:
* if there was no error, errno will be cleared to 0.
* buffer[0] is used as a counter of buffered chars and must be 0
* on first call.
* timeout:
@@ -1891,6 +1911,8 @@ enum {
* >=0: poll() for TIMEOUT milliseconds, return -1/EAGAIN on timeout
*/
int64_t read_key(int fd, char *buffer, int timeout) FAST_FUNC;
/* This version loops on EINTR: */
int64_t safe_read_key(int fd, char *buffer, int timeout) FAST_FUNC;
void read_key_ungets(char *buffer, const char *str, unsigned len) FAST_FUNC;
@@ -1903,6 +1925,7 @@ unsigned size_from_HISTFILESIZE(const char *hp) FAST_FUNC;
# define MAX_HISTORY 0
# endif
typedef const char *get_exe_name_t(int i) FAST_FUNC;
typedef const char *sh_get_var_t(const char *name) FAST_FUNC;
typedef struct line_input_t {
int flags;
int timeout;
@@ -1916,11 +1939,16 @@ typedef struct line_input_t {
# if ENABLE_SHELL_ASH || ENABLE_SHELL_HUSH
/* function to fetch additional application-specific names to match */
get_exe_name_t *get_exe_name;
# define EDITING_HAS_get_exe_name 1
# else
# define EDITING_HAS_get_exe_name 0
# endif
# endif
# if (ENABLE_FEATURE_USERNAME_COMPLETION || ENABLE_FEATURE_EDITING_FANCY_PROMPT) \
&& (ENABLE_SHELL_ASH || ENABLE_SHELL_HUSH)
/* function to fetch value of shell variable */
sh_get_var_t *sh_get_var;
# define EDITING_HAS_sh_get_var 1
# else
# define EDITING_HAS_sh_get_var 0
# endif
# if MAX_HISTORY
int cnt_history;
int cur_history;
@@ -1944,7 +1972,8 @@ enum {
USERNAME_COMPLETION = 4 * ENABLE_FEATURE_USERNAME_COMPLETION,
VI_MODE = 8 * ENABLE_FEATURE_EDITING_VI,
WITH_PATH_LOOKUP = 0x10,
FOR_SHELL = DO_HISTORY | TAB_COMPLETION | USERNAME_COMPLETION,
LI_INTERRUPTIBLE = 0x20,
FOR_SHELL = DO_HISTORY | TAB_COMPLETION | USERNAME_COMPLETION | LI_INTERRUPTIBLE,
};
line_input_t *new_line_input_t(int flags) FAST_FUNC;
#if ENABLE_FEATURE_EDITING_SAVEHISTORY
@@ -1971,11 +2000,6 @@ int read_line_input(const char* prompt, char* command, int maxsize) FAST_FUNC;
read_line_input(prompt, command, maxsize)
#endif
#ifndef EDITING_HAS_get_exe_name
# define EDITING_HAS_get_exe_name 0
#endif
#ifndef COMM_LEN
# ifdef TASK_COMM_LEN
enum { COMM_LEN = TASK_COMM_LEN };
@@ -2263,13 +2287,16 @@ extern const char bb_PATH_root_path[] ALIGN1; /* BB_PATH_ROOT_PATH */
extern const int const_int_0;
//extern const int const_int_1;
/* This struct is deliberately not defined. */
/* See docs/keep_data_small.txt */
struct globals;
/* '*const' ptr makes gcc optimize code much better.
* Magic prevents ptr_to_globals from going into rodata.
* If you want to assign a value, use SET_PTR_TO_GLOBALS(x) */
extern struct globals *const ptr_to_globals;
extern struct globals *BB_GLOBAL_CONST ptr_to_globals;
#define barrier() asm volatile ("":::"memory")
#if defined(__clang_major__) && __clang_major__ >= 9
/* Clang/llvm drops assignment to "constant" storage. Silently.
@@ -2278,30 +2305,38 @@ extern struct globals *const ptr_to_globals;
static ALWAYS_INLINE void* not_const_pp(const void *p)
{
void *pp;
__asm__ __volatile__(
asm volatile (
"# forget that p points to const"
: /*outputs*/ "=r" (pp)
: /*inputs*/ "0" (p)
);
return pp;
}
#else
static ALWAYS_INLINE void* not_const_pp(const void *p) { return (void*)p; }
#endif
/* At least gcc 3.4.6 on mipsel system needs optimization barrier */
#define barrier() __asm__ __volatile__("":::"memory")
#define SET_PTR_TO_GLOBALS(x) do { \
(*(struct globals**)not_const_pp(&ptr_to_globals)) = (void*)(x); \
# define ASSIGN_CONST_PTR(pptr, v) do { \
*(void**)not_const_pp(pptr) = (void*)(v); \
barrier(); \
} while (0)
/* XZALLOC_CONST_PTR() is an out-of-line function to prevent
* clang from reading pointer before it is assigned.
*/
void XZALLOC_CONST_PTR(const void *pptr, size_t size) FAST_FUNC;
#else
# define ASSIGN_CONST_PTR(pptr, v) do { \
*(void**)(pptr) = (void*)(v); \
/* At least gcc 3.4.6 on mipsel needs optimization barrier */ \
barrier(); \
} while (0)
# define XZALLOC_CONST_PTR(pptr, size) ASSIGN_CONST_PTR(pptr, xzalloc(size))
#endif
#define SET_PTR_TO_GLOBALS(x) ASSIGN_CONST_PTR(&ptr_to_globals, x)
#define FREE_PTR_TO_GLOBALS() do { \
if (ENABLE_FEATURE_CLEAN_UP) { \
free(ptr_to_globals); \
} \
} while (0)
/* You can change LIBBB_DEFAULT_LOGIN_SHELL, but don't use it,
* use bb_default_login_shell and following defines.
* If you change LIBBB_DEFAULT_LOGIN_SHELL,
+3
View File
@@ -239,6 +239,7 @@ typedef uint64_t bb__aliased_uint64_t FIX_ALIASING;
# define move_from_unaligned_long(v, longp) ((v) = *(bb__aliased_long*)(longp))
# define move_from_unaligned16(v, u16p) ((v) = *(bb__aliased_uint16_t*)(u16p))
# define move_from_unaligned32(v, u32p) ((v) = *(bb__aliased_uint32_t*)(u32p))
# define move_from_unaligned64(v, u64p) ((v) = *(bb__aliased_uint64_t*)(u64p))
# define move_to_unaligned16(u16p, v) (*(bb__aliased_uint16_t*)(u16p) = (v))
# define move_to_unaligned32(u32p, v) (*(bb__aliased_uint32_t*)(u32p) = (v))
# define move_to_unaligned64(u64p, v) (*(bb__aliased_uint64_t*)(u64p) = (v))
@@ -250,6 +251,7 @@ typedef uint64_t bb__aliased_uint64_t FIX_ALIASING;
# define move_from_unaligned_long(v, longp) (memcpy(&(v), (longp), sizeof(long)))
# define move_from_unaligned16(v, u16p) (memcpy(&(v), (u16p), 2))
# define move_from_unaligned32(v, u32p) (memcpy(&(v), (u32p), 4))
# define move_from_unaligned64(v, u64p) (memcpy(&(v), (u64p), 8))
# define move_to_unaligned16(u16p, v) do { \
uint16_t __t = (v); \
memcpy((u16p), &__t, 2); \
@@ -344,6 +346,7 @@ typedef unsigned smalluint;
# define ALIGN4
#endif
#define ALIGN8 __attribute__((aligned(8)))
#define ALIGN_INT __attribute__((aligned(sizeof(int))))
#define ALIGN_PTR __attribute__((aligned(sizeof(void*))))
/*
+3
View File
@@ -31,6 +31,9 @@
# define ADJTIME_PATH "/etc/adjtime"
#endif
#define STR1(s) #s
#define STR(s) STR1(s)
INSERT
#define busybox_notes_usage \
+8 -4
View File
@@ -744,7 +744,7 @@ static void pause_and_low_level_reboot(unsigned magic)
pid = vfork();
if (pid == 0) { /* child */
reboot(magic);
_exit(EXIT_SUCCESS);
_exit_SUCCESS();
}
/* Used to have "while (1) sleep(1)" here.
* However, in containers reboot() call is ignored, and with that loop
@@ -752,7 +752,7 @@ static void pause_and_low_level_reboot(unsigned magic)
*/
waitpid(pid, NULL, 0);
sleep1(); /* paranoia */
_exit(EXIT_SUCCESS);
_exit_SUCCESS();
}
static void run_shutdown_and_kill_processes(void)
@@ -942,7 +942,7 @@ static void reload_inittab(void)
for (a = G.init_action_list; a; a = a->next)
if (a->action_type == 0 && a->pid != 0)
kill(a->pid, SIGKILL);
_exit(EXIT_SUCCESS);
_exit_SUCCESS();
}
}
#endif
@@ -1105,10 +1105,14 @@ int init_main(int argc UNUSED_PARAM, char **argv)
setsid();
/* Make sure environs is set to something sane */
putenv((char *) "HOME=/");
putenv((char *) bb_PATH_root_path);
putenv((char *) "SHELL=/bin/sh");
putenv((char *) "USER=root"); /* needed? why? */
/* Linux kernel sets HOME="/" when execing init,
* and it can be overridden (but not unset?) on kernel's command line.
* We used to set it to "/" here, but now we do not:
*/
//putenv((char *) "HOME=/");
if (argv[1])
xsetenv("RUNLEVEL", argv[1]);
+110 -114
View File
@@ -42,51 +42,118 @@ config MD5_SMALL
default 1 # all "fast or small" options default to small
range 0 3
help
Trade binary size versus speed for the md5sum algorithm.
Trade binary size versus speed for the md5 algorithm.
Approximate values running uClibc and hashing
linux-2.4.4.tar.bz2 were:
value user times (sec) text size (386)
0 (fastest) 1.1 6144
1 1.4 5392
2 3.0 5088
3 (smallest) 5.1 4912
value user times (sec) text size (386)
0 (fastest) 1.1 6144
1 1.4 5392
2 3.0 5088
3 (smallest) 5.1 4912
config SHA1_SMALL
int "SHA1: Trade bytes for speed (0:fast, 3:slow)"
default 3 # all "fast or small" options default to small
range 0 3
help
Trade binary size versus speed for the sha1 algorithm.
With FEATURE_COPYBUF_KB=64:
throughput MB/s size of sha1_process_block64
value 486 x86-64 486 x86-64
0 440 485 3481 3502
1 265 265 641 696
2,3 220 210 342 364
config SHA1_HWACCEL
bool "SHA1: Use hardware accelerated instructions if possible"
default y
help
On x86, this adds ~590 bytes of code. Throughput
is about twice as fast as fully-unrolled generic code.
config SHA256_HWACCEL
bool "SHA256: Use hardware accelerated instructions if possible"
default y
help
On x86, this adds ~1k bytes of code.
config SHA3_SMALL
int "SHA3: Trade bytes for speed (0:fast, 1:slow)"
default 1 # all "fast or small" options default to small
range 0 1
help
Trade binary size versus speed for the sha3sum algorithm.
Trade binary size versus speed for the sha3 algorithm.
SHA3_SMALL=0 compared to SHA3_SMALL=1 (approximate):
64-bit x86: +270 bytes of code, 45% faster
32-bit x86: +450 bytes of code, 75% faster
config FEATURE_FAST_TOP
bool "Faster /proc scanning code (+100 bytes)"
default n # all "fast or small" options default to small
config FEATURE_NON_POSIX_CP
bool "Non-POSIX, but safer, copying to special nodes"
default y
help
This option makes top and ps ~20% faster (or 20% less CPU hungry),
but code size is slightly bigger.
With this option, "cp file symlink" will delete symlink
and create a regular file. This does not conform to POSIX,
but prevents a symlink attack.
Similarly, "cp file device" will not send file's data
to the device. (To do that, use "cat file >device")
config FEATURE_ETC_NETWORKS
bool "Support /etc/networks"
config FEATURE_VERBOSE_CP_MESSAGE
bool "Give more precise messages when copy fails (cp, mv etc)"
default n
help
Enable support for network names in /etc/networks. This is
a rarely used feature which allows you to use names
instead of IP/mask pairs in route command.
Error messages with this feature enabled:
config FEATURE_ETC_SERVICES
bool "Consult /etc/services even for well-known ports"
default n
$ cp file /does_not_exist/file
cp: cannot create '/does_not_exist/file': Path does not exist
$ cp file /vmlinuz/file
cp: cannot stat '/vmlinuz/file': Path has non-directory component
If this feature is not enabled, they will be, respectively:
cp: cannot create '/does_not_exist/file': No such file or directory
cp: cannot stat '/vmlinuz/file': Not a directory
This will cost you ~60 bytes.
config FEATURE_USE_SENDFILE
bool "Use sendfile system call"
default y
help
Look up e.g. "telnet" and "http" in /etc/services file
instead of assuming ports 23 and 80.
This is almost never necessary (everybody uses standard ports),
and it makes sense to avoid reading this file.
If you disable this option, in the cases where port is explicitly
specified as a service name (e.g. "telnet HOST PORTNAME"),
it will still be looked up in /etc/services.
When enabled, busybox will use the kernel sendfile() function
instead of read/write loops to copy data between file descriptors
(for example, cp command does this a lot).
If sendfile() doesn't work, copying code falls back to read/write
loop. sendfile() was originally implemented for faster I/O
from files to sockets, but since Linux 2.6.33 it was extended
to work for many more file types.
config FEATURE_COPYBUF_KB
int "Copy buffer size, in kilobytes"
range 1 1024
default 4
help
Size of buffer used by cp, mv, install, wget etc.
Buffers which are 4 kb or less will be allocated on stack.
Bigger buffers will be allocated with mmap, with fallback to 4 kb
stack buffer if mmap fails.
config MONOTONIC_SYSCALL
bool "Use clock_gettime(CLOCK_MONOTONIC) syscall"
default y
help
Use clock_gettime(CLOCK_MONOTONIC) syscall for measuring
time intervals (time, ping, traceroute etc need this).
Probably requires Linux 2.6+. If not selected, gettimeofday
will be used instead (which gives wrong results if date/time
is reset).
config IOCTL_HEX2STR_ERROR
bool "Use ioctl names rather than hex values in error messages"
default y
help
Use ioctl names rather than hex values in error messages
(e.g. VT_DISALLOCATE rather than 0x5608). If disabled this
saves about 1400 bytes.
config FEATURE_EDITING
bool "Command line editing"
@@ -303,95 +370,24 @@ config UNICODE_PRESERVE_BROKEN
at shell prompt will list file named 0xff (single char name
with char value 255), not file named '?'.
config FEATURE_NON_POSIX_CP
bool "Non-POSIX, but safer, copying to special nodes"
default y
choice
prompt "Use LOOP_CONFIGURE for losetup and loop mounts"
default TRY_LOOP_CONFIGURE
help
With this option, "cp file symlink" will delete symlink
and create a regular file. This does not conform to POSIX,
but prevents a symlink attack.
Similarly, "cp file device" will not send file's data
to the device. (To do that, use "cat file >device")
LOOP_CONFIGURE is added to Linux 5.8
https://lwn.net/Articles/820408/
This allows userspace to completely setup a loop device with a single
ioctl, removing the in-between state where the device can be partially
configured - eg the loop device has a backing file associated with it,
but is reading from the wrong offset.
config FEATURE_VERBOSE_CP_MESSAGE
bool "Give more precise messages when copy fails (cp, mv etc)"
default n
help
Error messages with this feature enabled:
config LOOP_CONFIGURE
bool "use LOOP_CONFIGURE, needs kernel >= 5.8"
$ cp file /does_not_exist/file
cp: cannot create '/does_not_exist/file': Path does not exist
$ cp file /vmlinuz/file
cp: cannot stat '/vmlinuz/file': Path has non-directory component
config NO_LOOP_CONFIGURE
bool "use LOOP_SET_FD + LOOP_SET_STATUS"
If this feature is not enabled, they will be, respectively:
config TRY_LOOP_CONFIGURE
bool "try LOOP_CONFIGURE, fall back to LOOP_SET_FD + LOOP_SET_STATUS"
cp: cannot create '/does_not_exist/file': No such file or directory
cp: cannot stat '/vmlinuz/file': Not a directory
This will cost you ~60 bytes.
config FEATURE_USE_SENDFILE
bool "Use sendfile system call"
default y
help
When enabled, busybox will use the kernel sendfile() function
instead of read/write loops to copy data between file descriptors
(for example, cp command does this a lot).
If sendfile() doesn't work, copying code falls back to read/write
loop. sendfile() was originally implemented for faster I/O
from files to sockets, but since Linux 2.6.33 it was extended
to work for many more file types.
config FEATURE_COPYBUF_KB
int "Copy buffer size, in kilobytes"
range 1 1024
default 4
help
Size of buffer used by cp, mv, install, wget etc.
Buffers which are 4 kb or less will be allocated on stack.
Bigger buffers will be allocated with mmap, with fallback to 4 kb
stack buffer if mmap fails.
config FEATURE_SKIP_ROOTFS
bool "Skip rootfs in mount table"
default y
help
Ignore rootfs entry in mount table.
In Linux, kernel has a special filesystem, rootfs, which is initially
mounted on /. It contains initramfs data, if kernel is configured
to have one. Usually, another file system is mounted over / early
in boot process, and therefore most tools which manipulate
mount table, such as df, will skip rootfs entry.
However, some systems do not mount anything on /.
If you need to configure busybox for one of these systems,
you may find it useful to turn this option off to make df show
initramfs statistics.
Otherwise, choose Y.
config MONOTONIC_SYSCALL
bool "Use clock_gettime(CLOCK_MONOTONIC) syscall"
default y
help
Use clock_gettime(CLOCK_MONOTONIC) syscall for measuring
time intervals (time, ping, traceroute etc need this).
Probably requires Linux 2.6+. If not selected, gettimeofday
will be used instead (which gives wrong results if date/time
is reset).
config IOCTL_HEX2STR_ERROR
bool "Use ioctl names rather than hex values in error messages"
default y
help
Use ioctl names rather than hex values in error messages
(e.g. VT_DISALLOCATE rather than 0x5608). If disabled this
saves about 1400 bytes.
config FEATURE_HWIB
bool "Support infiniband HW"
default y
help
Support for printing infiniband addresses in network applets.
endchoice
+7
View File
@@ -24,6 +24,7 @@ lib-y += chomp.o
lib-y += compare_string_array.o
lib-y += concat_path_file.o
lib-y += concat_subpath_file.o
lib-y += const_hack.o
lib-y += copy_file.o
lib-y += copyfd.o
lib-y += crc32.o
@@ -55,6 +56,11 @@ lib-y += login.o
lib-y += make_directory.o
lib-y += makedev.o
lib-y += hash_md5_sha.o
lib-y += hash_md5_sha_x86-64.o
lib-y += hash_md5_sha_x86-64_shaNI.o
lib-y += hash_md5_sha_x86-32_shaNI.o
lib-y += hash_md5_sha256_x86-64_shaNI.o
lib-y += hash_md5_sha256_x86-32_shaNI.o
# Alternative (disabled) MD5 implementation
#lib-y += hash_md5prime.o
lib-y += messages.o
@@ -196,6 +202,7 @@ lib-$(CONFIG_PGREP) += xregcomp.o
lib-$(CONFIG_PKILL) += xregcomp.o
lib-$(CONFIG_DEVFSD) += xregcomp.o
lib-$(CONFIG_FEATURE_FIND_REGEX) += xregcomp.o
lib-$(CONFIG_FEATURE_CUT_REGEX) += xregcomp.o
# Add the experimental logging functionality, only used by zcip
lib-$(CONFIG_ZCIP) += logenv.o
+21 -14
View File
@@ -247,8 +247,7 @@ void lbb_prepare(const char *applet
IF_FEATURE_INDIVIDUAL(, char **argv))
{
#ifdef bb_cached_errno_ptr
(*(int **)not_const_pp(&bb_errno)) = get_perrno();
barrier();
ASSIGN_CONST_PTR(&bb_errno, get_perrno());
#endif
applet_name = applet;
@@ -259,7 +258,6 @@ void lbb_prepare(const char *applet
/* Redundant for busybox (run_applet_and_exit covers that case)
* but needed for "individual applet" mode */
if (argv[1]
&& !argv[2]
&& strcmp(argv[1], "--help") == 0
&& !is_prefixed_with(applet, "busybox")
) {
@@ -652,7 +650,7 @@ static void check_suid(int applet_no)
# if ENABLE_FEATURE_INSTALLER
static const char usr_bin [] ALIGN1 = "/usr/bin/";
static const char usr_sbin[] ALIGN1 = "/usr/sbin/";
static const char *const install_dir[] = {
static const char *const install_dir[] ALIGN_PTR = {
&usr_bin [8], /* "/" */
&usr_bin [4], /* "/bin/" */
&usr_sbin[4] /* "/sbin/" */
@@ -726,9 +724,9 @@ int scripted_main(int argc UNUSED_PARAM, char **argv)
int script = find_script_by_name(applet_name);
if (script >= 0)
# if ENABLE_SHELL_ASH
exit(ash_main(-script - 1, argv));
return ash_main(-script - 1, argv);
# elif ENABLE_SHELL_HUSH
exit(hush_main(-script - 1, argv));
return hush_main(-script - 1, argv);
# else
return 1;
# endif
@@ -763,7 +761,7 @@ get_script_content(unsigned n)
//usage:#define busybox_trivial_usage NOUSAGE_STR
//usage:#define busybox_full_usage ""
//applet:IF_BUSYBOX(IF_FEATURE_SH_STANDALONE(IF_FEATURE_TAB_COMPLETION(APPLET(busybox, BB_DIR_BIN, BB_SUID_MAYBE))))
int busybox_main(int argc, char *argv[]) MAIN_EXTERNALLY_VISIBLE;
int busybox_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
# else
# define busybox_main(argc,argv) busybox_main(argv)
static
@@ -939,10 +937,13 @@ void FAST_FUNC show_usage_if_dash_dash_help(int applet_no, char **argv)
# endif
# if defined APPLET_NO_echo
&& applet_no != APPLET_NO_echo
# endif
# if ENABLE_TEST1 || ENABLE_TEST2
&& argv[0][0] != '[' /* exclude [ --help ] and [[ --help ]] too */
# endif
) {
if (argv[1] && !argv[2] && strcmp(argv[1], "--help") == 0) {
/* Make "foo --help" exit with 0: */
if (argv[1] && strcmp(argv[1], "--help") == 0) {
/* Make "foo --help [...]" exit with 0: */
xfunc_error_retval = 0;
bb_show_usage();
}
@@ -1005,10 +1006,10 @@ int scripted_main(int argc UNUSED_PARAM, char **argv)
{
# if ENABLE_SHELL_ASH
int script = 0;
exit(ash_main(-script - 1, argv));
return ash_main(-script - 1, argv);
# elif ENABLE_SHELL_HUSH
int script = 0;
exit(hush_main(-script - 1, argv));
return hush_main(-script - 1, argv);
# else
return 1;
# endif
@@ -1094,7 +1095,7 @@ int main(int argc UNUSED_PARAM, char **argv)
full_write2_str(bb_basename(argv[0]));
full_write2_str(": no applets enabled\n");
exit(127);
return 127;
#else
@@ -1113,8 +1114,14 @@ int main(int argc UNUSED_PARAM, char **argv)
|| ENABLE_FEATURE_PREFER_APPLETS
|| !BB_MMU
) {
if (NUM_APPLETS > 1)
set_task_comm(applet_name);
if (NUM_APPLETS > 1) {
/* Careful, do not trash comm of "SCRIPT.sh" -
* the case when started from e.g. #!/bin/ash script.
* (not limited to shells - #!/bin/awk scripts also exist)
*/
if (re_execed_comm())
set_task_comm(applet_name);
}
}
parse_config_file(); /* ...maybe, if FEATURE_SUID_CONFIG */
+16
View File
@@ -0,0 +1,16 @@
/* vi: set sw=4 ts=4: */
/*
* Trick to assign a const ptr with barrier for clang
*
* Copyright (C) 2021 by YU Jincheng <shana@zju.edu.cn>
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
#include "libbb.h"
#if defined(__clang_major__) && __clang_major__ >= 9
void FAST_FUNC XZALLOC_CONST_PTR(const void *pptr, size_t size)
{
ASSIGN_CONST_PTR(pptr, xzalloc(size));
}
#endif
+1 -1
View File
@@ -532,7 +532,7 @@ static void conv_u(PR *pr, unsigned char *p)
}
}
static void display(priv_dumper_t* dumper)
static NOINLINE void display(priv_dumper_t* dumper)
{
unsigned char *bp;
unsigned char savech = '\0';
+8 -4
View File
@@ -76,10 +76,14 @@ void FAST_FUNC sleep_for_duration(duration_t duration)
ts.tv_sec = duration;
ts.tv_nsec = (duration - ts.tv_sec) * 1000000000;
}
do {
errno = 0;
nanosleep(&ts, &ts);
} while (errno == EINTR);
/* NB: ENABLE_ASH_SLEEP requires that we do NOT loop on EINTR here:
* otherwise, traps won't execute until we finish looping.
*/
//do {
// errno = 0;
// nanosleep(&ts, &ts);
//} while (errno == EINTR);
nanosleep(&ts, &ts);
}
#else
duration_t FAST_FUNC parse_duration_str(char *str)
+6 -1
View File
@@ -13,10 +13,15 @@
*/
void FAST_FUNC fflush_stdout_and_exit(int retval)
{
xfunc_error_retval = retval;
if (fflush(stdout))
bb_simple_perror_msg_and_die(bb_msg_standard_output);
xfunc_error_retval = retval;
/* In case we are in NOFORK applet. Do not exit() directly,
* but use xfunc_die() */
xfunc_die();
}
void FAST_FUNC fflush_stdout_and_exit_SUCCESS(void)
{
fflush_stdout_and_exit(EXIT_SUCCESS);
}
+1 -1
View File
@@ -37,7 +37,7 @@ static int open_a_console(const char *fnam)
*/
int FAST_FUNC get_console_fd_or_die(void)
{
static const char *const console_names[] = {
static const char *const console_names[] ALIGN_PTR = {
DEV_CONSOLE, CURRENT_VC, CURRENT_TTY
};
+1 -1
View File
@@ -296,7 +296,7 @@ Special characters:
/* Code here assumes that 'unsigned' is at least 32 bits wide */
const char *const bb_argv_dash[] = { "-", NULL };
const char *const bb_argv_dash[] ALIGN_PTR = { "-", NULL };
enum {
PARAM_STRING,
+451 -11
View File
@@ -8,8 +8,32 @@
*/
#include "libbb.h"
#define STR1(s) #s
#define STR(s) STR1(s)
#define NEED_SHA512 (ENABLE_SHA512SUM || ENABLE_USE_BB_CRYPT_SHA)
#if ENABLE_SHA1_HWACCEL || ENABLE_SHA256_HWACCEL
# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
static void cpuid(unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx)
{
asm ("cpuid"
: "=a"(*eax), "=b"(*ebx), "=c"(*ecx), "=d"(*edx)
: "0"(*eax), "1"(*ebx), "2"(*ecx), "3"(*edx)
);
}
static smallint shaNI;
void FAST_FUNC sha1_process_block64_shaNI(sha1_ctx_t *ctx);
void FAST_FUNC sha256_process_block64_shaNI(sha256_ctx_t *ctx);
# if defined(__i386__)
struct ASM_expects_76_shaNI { char t[1 - 2*(offsetof(sha256_ctx_t, hash) != 76)]; };
# endif
# if defined(__x86_64__)
struct ASM_expects_80_shaNI { char t[1 - 2*(offsetof(sha256_ctx_t, hash) != 80)]; };
# endif
# endif
#endif
/* gcc 4.2.1 optimizes rotr64 better with inline than with macro
* (for rotX32, there is no difference). Why? My guess is that
* macro requires clever common subexpression elimination heuristics
@@ -390,7 +414,6 @@ static void FAST_FUNC md5_process_block64(md5_ctx_t *ctx)
OP(FI, D, A, B, C, 11, 10, 0xbd3af235);
OP(FI, C, D, A, B, 2, 15, 0x2ad7d2bb);
OP(FI, B, C, D, A, 9, 21, 0xeb86d391);
# undef OP
# endif
/* Add checksum to the starting values */
ctx->hash[0] += A;
@@ -399,6 +422,7 @@ static void FAST_FUNC md5_process_block64(md5_ctx_t *ctx)
ctx->hash[3] += D;
#endif
}
#undef OP
#undef FF
#undef FG
#undef FH
@@ -490,18 +514,410 @@ unsigned FAST_FUNC md5_end(md5_ctx_t *ctx, void *resbuf)
* then rebuild and compare "shaNNNsum bigfile" results.
*/
#if CONFIG_SHA1_SMALL == 0
# if defined(__GNUC__) && defined(__i386__)
static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx UNUSED_PARAM)
{
BUILD_BUG_ON(offsetof(sha1_ctx_t, hash) != 76);
asm(
"\n\
pushl %ebp # \n\
pushl %edi # \n\
pushl %esi # \n\
pushl %ebx # \n\
pushl %eax \n\
movl $15, %edi \n\
1: \n\
movl (%eax,%edi,4), %esi \n\
bswap %esi \n\
pushl %esi \n\
decl %edi \n\
jns 1b \n\
movl 80(%eax), %ebx # b = ctx->hash[1] \n\
movl 84(%eax), %ecx # c = ctx->hash[2] \n\
movl 88(%eax), %edx # d = ctx->hash[3] \n\
movl 92(%eax), %ebp # e = ctx->hash[4] \n\
movl 76(%eax), %eax # a = ctx->hash[0] \n\
#Register and stack use: \n\
# eax..edx: a..d \n\
# ebp: e \n\
# esi,edi: temps \n\
# 4*n(%esp): W[n] \n\
"
#define RD1As(a,b,c,d,e, n, RCONST) \
"\n\
##movl 4*"n"(%esp), %esi # n=0, W[0] already in %esi \n\
movl "c", %edi # c \n\
xorl "d", %edi # ^d \n\
andl "b", %edi # &b \n\
xorl "d", %edi # (((c ^ d) & b) ^ d) \n\
leal "RCONST"("e",%esi), "e" # e += RCONST + W[n] \n\
addl %edi, "e" # e += (((c ^ d) & b) ^ d) \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD1Bs(a,b,c,d,e, n, RCONST) \
"\n\
movl 4*"n"(%esp), %esi # W[n] \n\
movl "c", %edi # c \n\
xorl "d", %edi # ^d \n\
andl "b", %edi # &b \n\
xorl "d", %edi # (((c ^ d) & b) ^ d) \n\
leal "RCONST"("e",%esi), "e" # e += RCONST + W[n] \n\
addl %edi, "e" # e += (((c ^ d) & b) ^ d) \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD1Cs(a,b,c,d,e, n13,n8,n2,n, RCONST) \
"\n\
movl 4*"n13"(%esp), %esi # W[(n+13) & 15] \n\
xorl 4*"n8"(%esp), %esi # ^W[(n+8) & 15] \n\
xorl 4*"n2"(%esp), %esi # ^W[(n+2) & 15] \n\
xorl 4*"n"(%esp), %esi # ^W[n & 15] \n\
roll %esi # \n\
movl %esi, 4*"n"(%esp) # store to W[n & 15] \n\
movl "c", %edi # c \n\
xorl "d", %edi # ^d \n\
andl "b", %edi # &b \n\
xorl "d", %edi # (((c ^ d) & b) ^ d) \n\
leal "RCONST"("e",%esi), "e" # e += RCONST + mixed_W \n\
addl %edi, "e" # e += (((c ^ d) & b) ^ d) \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD1A(a,b,c,d,e, n) RD1As("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR((n)), STR(RCONST))
#define RD1B(a,b,c,d,e, n) RD1Bs("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR((n)), STR(RCONST))
#define RD1C(a,b,c,d,e, n) RD1Cs("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR(((n+13)&15)), STR(((n+8)&15)), STR(((n+2)&15)), STR(((n)&15)), STR(RCONST))
#undef RCONST
#define RCONST 0x5A827999
RD1A(ax,bx,cx,dx,bp, 0) RD1B(bp,ax,bx,cx,dx, 1) RD1B(dx,bp,ax,bx,cx, 2) RD1B(cx,dx,bp,ax,bx, 3) RD1B(bx,cx,dx,bp,ax, 4)
RD1B(ax,bx,cx,dx,bp, 5) RD1B(bp,ax,bx,cx,dx, 6) RD1B(dx,bp,ax,bx,cx, 7) RD1B(cx,dx,bp,ax,bx, 8) RD1B(bx,cx,dx,bp,ax, 9)
RD1B(ax,bx,cx,dx,bp,10) RD1B(bp,ax,bx,cx,dx,11) RD1B(dx,bp,ax,bx,cx,12) RD1B(cx,dx,bp,ax,bx,13) RD1B(bx,cx,dx,bp,ax,14)
RD1B(ax,bx,cx,dx,bp,15) RD1C(bp,ax,bx,cx,dx,16) RD1C(dx,bp,ax,bx,cx,17) RD1C(cx,dx,bp,ax,bx,18) RD1C(bx,cx,dx,bp,ax,19)
#define RD2s(a,b,c,d,e, n13,n8,n2,n, RCONST) \
"\n\
movl 4*"n13"(%esp), %esi # W[(n+13) & 15] \n\
xorl 4*"n8"(%esp), %esi # ^W[(n+8) & 15] \n\
xorl 4*"n2"(%esp), %esi # ^W[(n+2) & 15] \n\
xorl 4*"n"(%esp), %esi # ^W[n & 15] \n\
roll %esi # \n\
movl %esi, 4*"n"(%esp) # store to W[n & 15] \n\
movl "c", %edi # c \n\
xorl "d", %edi # ^d \n\
xorl "b", %edi # ^b \n\
leal "RCONST"("e",%esi), "e" # e += RCONST + mixed_W \n\
addl %edi, "e" # e += (c ^ d ^ b) \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD2(a,b,c,d,e, n) RD2s("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR(((20+n+13)&15)), STR(((20+n+8)&15)), STR(((20+n+2)&15)), STR(((20+n)&15)), STR(RCONST))
#undef RCONST
#define RCONST 0x6ED9EBA1
RD2(ax,bx,cx,dx,bp, 0) RD2(bp,ax,bx,cx,dx, 1) RD2(dx,bp,ax,bx,cx, 2) RD2(cx,dx,bp,ax,bx, 3) RD2(bx,cx,dx,bp,ax, 4)
RD2(ax,bx,cx,dx,bp, 5) RD2(bp,ax,bx,cx,dx, 6) RD2(dx,bp,ax,bx,cx, 7) RD2(cx,dx,bp,ax,bx, 8) RD2(bx,cx,dx,bp,ax, 9)
RD2(ax,bx,cx,dx,bp,10) RD2(bp,ax,bx,cx,dx,11) RD2(dx,bp,ax,bx,cx,12) RD2(cx,dx,bp,ax,bx,13) RD2(bx,cx,dx,bp,ax,14)
RD2(ax,bx,cx,dx,bp,15) RD2(bp,ax,bx,cx,dx,16) RD2(dx,bp,ax,bx,cx,17) RD2(cx,dx,bp,ax,bx,18) RD2(bx,cx,dx,bp,ax,19)
#define RD3s(a,b,c,d,e, n13,n8,n2,n, RCONST) \
"\n\
movl "b", %edi # di: b \n\
movl "b", %esi # si: b \n\
orl "c", %edi # di: b | c \n\
andl "c", %esi # si: b & c \n\
andl "d", %edi # di: (b | c) & d \n\
orl %esi, %edi # ((b | c) & d) | (b & c) \n\
movl 4*"n13"(%esp), %esi # W[(n+13) & 15] \n\
xorl 4*"n8"(%esp), %esi # ^W[(n+8) & 15] \n\
xorl 4*"n2"(%esp), %esi # ^W[(n+2) & 15] \n\
xorl 4*"n"(%esp), %esi # ^W[n & 15] \n\
roll %esi # \n\
movl %esi, 4*"n"(%esp) # store to W[n & 15] \n\
addl %edi, "e" # += ((b | c) & d) | (b & c)\n\
leal "RCONST"("e",%esi), "e" # e += RCONST + mixed_W \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD3(a,b,c,d,e, n) RD3s("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR(((40+n+13)&15)), STR(((40+n+8)&15)), STR(((40+n+2)&15)), STR(((40+n)&15)), STR(RCONST))
#undef RCONST
#define RCONST 0x8F1BBCDC
RD3(ax,bx,cx,dx,bp, 0) RD3(bp,ax,bx,cx,dx, 1) RD3(dx,bp,ax,bx,cx, 2) RD3(cx,dx,bp,ax,bx, 3) RD3(bx,cx,dx,bp,ax, 4)
RD3(ax,bx,cx,dx,bp, 5) RD3(bp,ax,bx,cx,dx, 6) RD3(dx,bp,ax,bx,cx, 7) RD3(cx,dx,bp,ax,bx, 8) RD3(bx,cx,dx,bp,ax, 9)
RD3(ax,bx,cx,dx,bp,10) RD3(bp,ax,bx,cx,dx,11) RD3(dx,bp,ax,bx,cx,12) RD3(cx,dx,bp,ax,bx,13) RD3(bx,cx,dx,bp,ax,14)
RD3(ax,bx,cx,dx,bp,15) RD3(bp,ax,bx,cx,dx,16) RD3(dx,bp,ax,bx,cx,17) RD3(cx,dx,bp,ax,bx,18) RD3(bx,cx,dx,bp,ax,19)
#define RD4As(a,b,c,d,e, n13,n8,n2,n, RCONST) \
"\n\
movl 4*"n13"(%esp), %esi # W[(n+13) & 15] \n\
xorl 4*"n8"(%esp), %esi # ^W[(n+8) & 15] \n\
xorl 4*"n2"(%esp), %esi # ^W[(n+2) & 15] \n\
xorl 4*"n"(%esp), %esi # ^W[n & 15] \n\
roll %esi # \n\
movl %esi, 4*"n"(%esp) # store to W[n & 15] \n\
movl "c", %edi # c \n\
xorl "d", %edi # ^d \n\
xorl "b", %edi # ^b \n\
leal "RCONST"("e",%esi), "e" # e += RCONST + mixed_W \n\
addl %edi, "e" # e += (c ^ d ^ b) \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD4Bs(a,b,c,d,e, n13,n8,n2,n, RCONST) \
"\n\
movl 4*"n13"(%esp), %esi # W[(n+13) & 15] \n\
xorl 4*"n8"(%esp), %esi # ^W[(n+8) & 15] \n\
xorl 4*"n2"(%esp), %esi # ^W[(n+2) & 15] \n\
xorl 4*"n"(%esp), %esi # ^W[n & 15] \n\
roll %esi # \n\
##movl %esi, 4*"n"(%esp) # store to W[n & 15] elided \n\
movl "c", %edi # c \n\
xorl "d", %edi # ^d \n\
xorl "b", %edi # ^b \n\
leal "RCONST"("e",%esi), "e" # e += RCONST + mixed_W \n\
addl %edi, "e" # e += (c ^ d ^ b) \n\
movl "a", %esi # \n\
roll $5, %esi # rotl32(a,5) \n\
addl %esi, "e" # e += rotl32(a,5) \n\
rorl $2, "b" # b = rotl32(b,30) \n\
"
#define RD4A(a,b,c,d,e, n) RD4As("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR(((60+n+13)&15)), STR(((60+n+8)&15)), STR(((60+n+2)&15)), STR(((60+n)&15)), STR(RCONST))
#define RD4B(a,b,c,d,e, n) RD4Bs("%e"STR(a),"%e"STR(b),"%e"STR(c),"%e"STR(d),"%e"STR(e), STR(((60+n+13)&15)), STR(((60+n+8)&15)), STR(((60+n+2)&15)), STR(((60+n)&15)), STR(RCONST))
#undef RCONST
#define RCONST 0xCA62C1D6
RD4A(ax,bx,cx,dx,bp, 0) RD4A(bp,ax,bx,cx,dx, 1) RD4A(dx,bp,ax,bx,cx, 2) RD4A(cx,dx,bp,ax,bx, 3) RD4A(bx,cx,dx,bp,ax, 4)
RD4A(ax,bx,cx,dx,bp, 5) RD4A(bp,ax,bx,cx,dx, 6) RD4A(dx,bp,ax,bx,cx, 7) RD4A(cx,dx,bp,ax,bx, 8) RD4A(bx,cx,dx,bp,ax, 9)
RD4A(ax,bx,cx,dx,bp,10) RD4A(bp,ax,bx,cx,dx,11) RD4A(dx,bp,ax,bx,cx,12) RD4A(cx,dx,bp,ax,bx,13) RD4A(bx,cx,dx,bp,ax,14)
RD4A(ax,bx,cx,dx,bp,15) RD4A(bp,ax,bx,cx,dx,16) RD4B(dx,bp,ax,bx,cx,17) RD4B(cx,dx,bp,ax,bx,18) RD4B(bx,cx,dx,bp,ax,19)
"\n\
movl 4*16(%esp), %esi # \n\
addl $4*(16+1), %esp # \n\
addl %eax, 76(%esi) # ctx->hash[0] += a \n\
addl %ebx, 80(%esi) # ctx->hash[1] += b \n\
addl %ecx, 84(%esi) # ctx->hash[2] += c \n\
addl %edx, 88(%esi) # ctx->hash[3] += d \n\
addl %ebp, 92(%esi) # ctx->hash[4] += e \n\
popl %ebx # \n\
popl %esi # \n\
popl %edi # \n\
popl %ebp # \n\
"
); /* asm */
#undef RCONST
}
# elif defined(__GNUC__) && defined(__x86_64__)
/* in hash_md5_sha_x86-64.S */
struct ASM_expects_80 { char t[1 - 2*(offsetof(sha1_ctx_t, hash) != 80)]; };
void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx);
# else
/* Fast, fully-unrolled SHA1. +3800 bytes of code on x86.
* It seems further speedup can be achieved by handling more than
* 64 bytes per one function call (coreutils does that).
*/
static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx)
{
static const uint32_t rconsts[] ALIGN4 = {
0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6
};
uint32_t W[16];
uint32_t a, b, c, d, e;
a = ctx->hash[0];
b = ctx->hash[1];
c = ctx->hash[2];
d = ctx->hash[3];
e = ctx->hash[4];
/* From kernel source comments:
* """
* If you have 32 registers or more, the compiler can (and should)
* try to change the array[] accesses into registers. However, on
* machines with less than ~25 registers, that won't really work,
* and at least gcc will make an unholy mess of it.
*
* So to avoid that mess which just slows things down, we force
* the stores to memory to actually happen (we might be better off
* with a 'W(t)=(val);asm("":"+m" (W(t))' there instead, as
* suggested by Artur Skawina - that will also make gcc unable to
* try to do the silly "optimize away loads" part because it won't
* see what the value will be).
* """
*/
#if defined(__GNUC__) && defined(__i386__)
# define DO_NOT_TRY_PROPAGATING(m) asm("":"+m"(m))
#else
# define DO_NOT_TRY_PROPAGATING(m) ((void)0)
#endif
#undef OP
#define OP(A,B,C,D,E, n) \
do { \
uint32_t work = EXPR(B, C, D); \
if (n <= 15) \
work += W[n & 15] = SWAP_BE32(((uint32_t*)ctx->wbuffer)[n]); \
if (n >= 16) \
work += W[n & 15] = rotl32(W[(n+13) & 15] ^ W[(n+8) & 15] ^ W[(n+2) & 15] ^ W[n & 15], 1); \
DO_NOT_TRY_PROPAGATING(W[n & 15]); \
E += work + rotl32(A, 5) + rconsts[n / 20]; \
B = rotl32(B, 30); \
} while (0)
#define OP20(n) \
OP(a,b,c,d,e, (n+ 0)); OP(e,a,b,c,d, (n+ 1)); OP(d,e,a,b,c, (n+ 2)); OP(c,d,e,a,b, (n+ 3)); OP(b,c,d,e,a, (n+ 4)); \
OP(a,b,c,d,e, (n+ 5)); OP(e,a,b,c,d, (n+ 6)); OP(d,e,a,b,c, (n+ 7)); OP(c,d,e,a,b, (n+ 8)); OP(b,c,d,e,a, (n+ 9)); \
OP(a,b,c,d,e, (n+10)); OP(e,a,b,c,d, (n+11)); OP(d,e,a,b,c, (n+12)); OP(c,d,e,a,b, (n+13)); OP(b,c,d,e,a, (n+14)); \
OP(a,b,c,d,e, (n+15)); OP(e,a,b,c,d, (n+16)); OP(d,e,a,b,c, (n+17)); OP(c,d,e,a,b, (n+18)); OP(b,c,d,e,a, (n+19))
/* 4 rounds of 20 operations each */
#define EXPR(b,c,d) (((c ^ d) & b) ^ d)
OP20(0);
#undef EXPR
#define EXPR(b,c,d) (c ^ d ^ b)
OP20(20);
#undef EXPR
#define EXPR(b,c,d) (((b | c) & d) | (b & c))
OP20(40);
#undef EXPR
#define EXPR(b,c,d) (c ^ d ^ b)
OP20(60);
#undef EXPR
#undef OP
#undef OP20
ctx->hash[0] += a;
ctx->hash[1] += b;
ctx->hash[2] += c;
ctx->hash[3] += d;
ctx->hash[4] += e;
}
# endif
#elif CONFIG_SHA1_SMALL == 1
/* Middle-sized version, +300 bytes of code on x86. */
static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx)
{
static const uint32_t rconsts[] ALIGN4 = {
0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6
};
int j;
int n;
uint32_t W[16+16];
uint32_t a, b, c, d, e;
a = ctx->hash[0];
b = ctx->hash[1];
c = ctx->hash[2];
d = ctx->hash[3];
e = ctx->hash[4];
/* 1st round of 20 operations */
n = 0;
do {
uint32_t work = ((c ^ d) & b) ^ d;
W[n] = W[n+16] = SWAP_BE32(((uint32_t*)ctx->wbuffer)[n]);
work += W[n];
work += e + rotl32(a, 5) + rconsts[0];
/* Rotate by one for next time */
e = d;
d = c;
c = rotl32(b, 30);
b = a;
a = work;
n = (n + 1) & 15;
} while (n != 0);
do {
uint32_t work = ((c ^ d) & b) ^ d;
W[n] = W[n+16] = rotl32(W[n+13] ^ W[n+8] ^ W[n+2] ^ W[n], 1);
work += W[n];
work += e + rotl32(a, 5) + rconsts[0];
e = d;
d = c;
c = rotl32(b, 30);
b = a;
a = work;
n = (n + 1) /* & 15*/;
} while (n != 4);
/* 2nd round of 20 operations */
j = 19;
do {
uint32_t work = c ^ d ^ b;
W[n] = W[n+16] = rotl32(W[n+13] ^ W[n+8] ^ W[n+2] ^ W[n], 1);
work += W[n];
work += e + rotl32(a, 5) + rconsts[1];
e = d;
d = c;
c = rotl32(b, 30);
b = a;
a = work;
n = (n + 1) & 15;
} while (--j >= 0);
/* 3rd round */
j = 19;
do {
uint32_t work = ((b | c) & d) | (b & c);
W[n] = W[n+16] = rotl32(W[n+13] ^ W[n+8] ^ W[n+2] ^ W[n], 1);
work += W[n];
work += e + rotl32(a, 5) + rconsts[2];
e = d;
d = c;
c = rotl32(b, 30);
b = a;
a = work;
n = (n + 1) & 15;
} while (--j >= 0);
/* 4th round */
j = 19;
do {
uint32_t work = c ^ d ^ b;
W[n] = W[n+16] = rotl32(W[n+13] ^ W[n+8] ^ W[n+2] ^ W[n], 1);
work += W[n];
work += e + rotl32(a, 5) + rconsts[3];
e = d;
d = c;
c = rotl32(b, 30);
b = a;
a = work;
n = (n + 1) & 15;
} while (--j >= 0);
ctx->hash[0] += a;
ctx->hash[1] += b;
ctx->hash[2] += c;
ctx->hash[3] += d;
ctx->hash[4] += e;
}
#else
/* Compact version, almost twice as slow as fully unrolled */
static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx)
{
static const uint32_t rconsts[] ALIGN4 = {
0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xCA62C1D6
};
int i, j;
int cnt;
int n;
uint32_t W[16+16];
uint32_t a, b, c, d, e;
/* On-stack work buffer frees up one register in the main loop
* which otherwise will be needed to hold ctx pointer */
* which otherwise will be needed to hold ctx pointer.
*
* The compiler is not smart enough to realize it, though. :(
* If __attribute__((optimize("2"))) is added to the function,
* only then gcc-9.3.1 spills "ctx" to stack and uses the freed
* register (making code 6 bytes smaller, not just faster).
*/
for (i = 0; i < 16; i++)
W[i] = W[i+16] = SWAP_BE32(((uint32_t*)ctx->wbuffer)[i]);
@@ -512,7 +928,7 @@ static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx)
e = ctx->hash[4];
/* 4 rounds of 20 operations each */
cnt = 0;
n = 0;
for (i = 0; i < 4; i++) {
j = 19;
do {
@@ -523,27 +939,24 @@ static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx)
work = (work & b) ^ d;
if (j <= 3)
goto ge16;
/* Used to do SWAP_BE32 here, but this
* requires ctx (see comment above) */
work += W[cnt];
} else {
if (i == 2)
work = ((b | c) & d) | (b & c);
else /* i = 1 or 3 */
work ^= b;
ge16:
W[cnt] = W[cnt+16] = rotl32(W[cnt+13] ^ W[cnt+8] ^ W[cnt+2] ^ W[cnt], 1);
work += W[cnt];
W[n] = W[n+16] = rotl32(W[n+13] ^ W[n+8] ^ W[n+2] ^ W[n], 1);
}
work += W[n];
work += e + rotl32(a, 5) + rconsts[i];
/* Rotate by one for next time */
e = d;
d = c;
c = /* b = */ rotl32(b, 30);
c = rotl32(b, 30);
b = a;
a = work;
cnt = (cnt + 1) & 15;
n = (n + 1) & 15;
} while (--j >= 0);
}
@@ -553,6 +966,7 @@ static void FAST_FUNC sha1_process_block64(sha1_ctx_t *ctx)
ctx->hash[3] += d;
ctx->hash[4] += e;
}
#endif
/* Constants for SHA512 from FIPS 180-2:4.2.3.
* SHA256 constants from FIPS 180-2:4.2.2
@@ -758,6 +1172,19 @@ void FAST_FUNC sha1_begin(sha1_ctx_t *ctx)
ctx->hash[4] = 0xc3d2e1f0;
ctx->total64 = 0;
ctx->process_block = sha1_process_block64;
#if ENABLE_SHA1_HWACCEL
# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
{
if (!shaNI) {
unsigned eax = 7, ebx = ebx, ecx = 0, edx = edx;
cpuid(&eax, &ebx, &ecx, &edx);
shaNI = ((ebx >> 28) & 2) - 1; /* bit 29 -> 1 or -1 */
}
if (shaNI > 0)
ctx->process_block = sha1_process_block64_shaNI;
}
# endif
#endif
}
static const uint32_t init256[] ALIGN4 = {
@@ -799,6 +1226,19 @@ void FAST_FUNC sha256_begin(sha256_ctx_t *ctx)
memcpy(&ctx->total64, init256, sizeof(init256));
/*ctx->total64 = 0; - done by prepending two 32-bit zeros to init256 */
ctx->process_block = sha256_process_block64;
#if ENABLE_SHA256_HWACCEL
# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
{
if (!shaNI) {
unsigned eax = 7, ebx = ebx, ecx = 0, edx = edx;
cpuid(&eax, &ebx, &ecx, &edx);
shaNI = ((ebx >> 28) & 2) - 1; /* bit 29 -> 1 or -1 */
}
if (shaNI > 0)
ctx->process_block = sha256_process_block64_shaNI;
}
# endif
#endif
}
#if NEED_SHA512
+284
View File
@@ -0,0 +1,284 @@
#if ENABLE_SHA256_HWACCEL && defined(__GNUC__) && defined(__i386__)
/* The code is adapted from Linux kernel's source */
// We use shorter insns, even though they are for "wrong"
// data type (fp, not int).
// For Intel, there is no penalty for doing it at all
// (CPUs which do have such penalty do not support SHA insns).
// For AMD, the penalty is one extra cycle
// (allegedly: I failed to find measurable difference).
//#define mova128 movdqa
#define mova128 movaps
//#define movu128 movdqu
#define movu128 movups
//#define shuf128_32 pshufd
#define shuf128_32 shufps
// pshufb and palignr are SSSE3 insns.
// We do not check SSSE3 in cpuid,
// all SHA-capable CPUs support it as well.
#ifdef __linux__
.section .note.GNU-stack, "", @progbits
#endif
.section .text.sha256_process_block64_shaNI, "ax", @progbits
.globl sha256_process_block64_shaNI
.hidden sha256_process_block64_shaNI
.type sha256_process_block64_shaNI, @function
#define DATA_PTR %eax
#define SHA256CONSTANTS %ecx
#define MSG %xmm0
#define STATE0 %xmm1
#define STATE1 %xmm2
#define MSGTMP0 %xmm3
#define MSGTMP1 %xmm4
#define MSGTMP2 %xmm5
#define MSGTMP3 %xmm6
#define XMMTMP %xmm7
#define SHUF(a,b,c,d) $(a+(b<<2)+(c<<4)+(d<<6))
.balign 8 # allow decoders to fetch at least 2 first insns
sha256_process_block64_shaNI:
movu128 76+0*16(%eax), XMMTMP /* ABCD (little-endian dword order) */
movu128 76+1*16(%eax), STATE1 /* EFGH */
/* shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one */
mova128 STATE1, STATE0
/* --- -------------- ABCD -- EFGH */
shufps SHUF(1,0,1,0), XMMTMP, STATE0 /* FEBA */
shufps SHUF(3,2,3,2), XMMTMP, STATE1 /* HGDC */
/* XMMTMP holds flip mask from here... */
mova128 PSHUFFLE_BSWAP32_FLIP_MASK, XMMTMP
movl $K256+8*16, SHA256CONSTANTS
/* Rounds 0-3 */
movu128 0*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP0
paddd 0*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 4-7 */
movu128 1*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP1
paddd 1*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
/* Rounds 8-11 */
movu128 2*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP2
paddd 2*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
/* Rounds 12-15 */
movu128 3*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
/* ...to here */
mova128 MSG, MSGTMP3
paddd 3*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP3, XMMTMP
palignr $4, MSGTMP2, XMMTMP
paddd XMMTMP, MSGTMP0
sha256msg2 MSGTMP3, MSGTMP0
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
/* Rounds 16-19 */
mova128 MSGTMP0, MSG
paddd 4*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP0, XMMTMP
palignr $4, MSGTMP3, XMMTMP
paddd XMMTMP, MSGTMP1
sha256msg2 MSGTMP0, MSGTMP1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
/* Rounds 20-23 */
mova128 MSGTMP1, MSG
paddd 5*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP1, XMMTMP
palignr $4, MSGTMP0, XMMTMP
paddd XMMTMP, MSGTMP2
sha256msg2 MSGTMP1, MSGTMP2
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
/* Rounds 24-27 */
mova128 MSGTMP2, MSG
paddd 6*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP2, XMMTMP
palignr $4, MSGTMP1, XMMTMP
paddd XMMTMP, MSGTMP3
sha256msg2 MSGTMP2, MSGTMP3
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
/* Rounds 28-31 */
mova128 MSGTMP3, MSG
paddd 7*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP3, XMMTMP
palignr $4, MSGTMP2, XMMTMP
paddd XMMTMP, MSGTMP0
sha256msg2 MSGTMP3, MSGTMP0
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
/* Rounds 32-35 */
mova128 MSGTMP0, MSG
paddd 8*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP0, XMMTMP
palignr $4, MSGTMP3, XMMTMP
paddd XMMTMP, MSGTMP1
sha256msg2 MSGTMP0, MSGTMP1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
/* Rounds 36-39 */
mova128 MSGTMP1, MSG
paddd 9*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP1, XMMTMP
palignr $4, MSGTMP0, XMMTMP
paddd XMMTMP, MSGTMP2
sha256msg2 MSGTMP1, MSGTMP2
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
/* Rounds 40-43 */
mova128 MSGTMP2, MSG
paddd 10*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP2, XMMTMP
palignr $4, MSGTMP1, XMMTMP
paddd XMMTMP, MSGTMP3
sha256msg2 MSGTMP2, MSGTMP3
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
/* Rounds 44-47 */
mova128 MSGTMP3, MSG
paddd 11*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP3, XMMTMP
palignr $4, MSGTMP2, XMMTMP
paddd XMMTMP, MSGTMP0
sha256msg2 MSGTMP3, MSGTMP0
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
/* Rounds 48-51 */
mova128 MSGTMP0, MSG
paddd 12*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP0, XMMTMP
palignr $4, MSGTMP3, XMMTMP
paddd XMMTMP, MSGTMP1
sha256msg2 MSGTMP0, MSGTMP1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
/* Rounds 52-55 */
mova128 MSGTMP1, MSG
paddd 13*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP1, XMMTMP
palignr $4, MSGTMP0, XMMTMP
paddd XMMTMP, MSGTMP2
sha256msg2 MSGTMP1, MSGTMP2
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 56-59 */
mova128 MSGTMP2, MSG
paddd 14*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP2, XMMTMP
palignr $4, MSGTMP1, XMMTMP
paddd XMMTMP, MSGTMP3
sha256msg2 MSGTMP2, MSGTMP3
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 60-63 */
mova128 MSGTMP3, MSG
paddd 15*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Write hash values back in the correct order */
mova128 STATE0, XMMTMP
/* shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one */
/* --- -------------- HGDC -- FEBA */
shufps SHUF(3,2,3,2), STATE1, STATE0 /* ABCD */
shufps SHUF(1,0,1,0), STATE1, XMMTMP /* EFGH */
/* add current hash values to previous ones */
movu128 76+1*16(%eax), STATE1
paddd XMMTMP, STATE1
movu128 STATE1, 76+1*16(%eax)
movu128 76+0*16(%eax), XMMTMP
paddd XMMTMP, STATE0
movu128 STATE0, 76+0*16(%eax)
ret
.size sha256_process_block64_shaNI, .-sha256_process_block64_shaNI
.section .rodata.cst256.K256, "aM", @progbits, 256
.balign 16
K256:
.long 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
.long 0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
.long 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
.long 0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
.long 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
.long 0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
.long 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
.long 0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
.long 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
.long 0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
.long 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
.long 0xd192e819,0xd6990624,0xf40e3585,0x106aa070
.long 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
.long 0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
.long 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
.long 0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
.section .rodata.cst16.PSHUFFLE_BSWAP32_FLIP_MASK, "aM", @progbits, 16
.balign 16
PSHUFFLE_BSWAP32_FLIP_MASK:
.octa 0x0c0d0e0f08090a0b0405060700010203
#endif
+290
View File
@@ -0,0 +1,290 @@
#if ENABLE_SHA256_HWACCEL && defined(__GNUC__) && defined(__x86_64__)
/* The code is adapted from Linux kernel's source */
// We use shorter insns, even though they are for "wrong"
// data type (fp, not int).
// For Intel, there is no penalty for doing it at all
// (CPUs which do have such penalty do not support SHA insns).
// For AMD, the penalty is one extra cycle
// (allegedly: I failed to find measurable difference).
//#define mova128 movdqa
#define mova128 movaps
//#define movu128 movdqu
#define movu128 movups
//#define shuf128_32 pshufd
#define shuf128_32 shufps
// pshufb and palignr are SSSE3 insns.
// We do not check SSSE3 in cpuid,
// all SHA-capable CPUs support it as well.
#ifdef __linux__
.section .note.GNU-stack, "", @progbits
#endif
.section .text.sha256_process_block64_shaNI, "ax", @progbits
.globl sha256_process_block64_shaNI
.hidden sha256_process_block64_shaNI
.type sha256_process_block64_shaNI, @function
#define DATA_PTR %rdi
#define SHA256CONSTANTS %rax
#define MSG %xmm0
#define STATE0 %xmm1
#define STATE1 %xmm2
#define MSGTMP0 %xmm3
#define MSGTMP1 %xmm4
#define MSGTMP2 %xmm5
#define MSGTMP3 %xmm6
#define XMMTMP %xmm7
#define SAVE0 %xmm8
#define SAVE1 %xmm9
#define SHUF(a,b,c,d) $(a+(b<<2)+(c<<4)+(d<<6))
.balign 8 # allow decoders to fetch at least 2 first insns
sha256_process_block64_shaNI:
movu128 80+0*16(%rdi), XMMTMP /* ABCD (little-endian dword order) */
movu128 80+1*16(%rdi), STATE1 /* EFGH */
/* shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one */
mova128 STATE1, STATE0
/* --- -------------- ABCD -- EFGH */
shufps SHUF(1,0,1,0), XMMTMP, STATE0 /* FEBA */
shufps SHUF(3,2,3,2), XMMTMP, STATE1 /* HGDC */
/* XMMTMP holds flip mask from here... */
mova128 PSHUFFLE_BSWAP32_FLIP_MASK(%rip), XMMTMP
leaq K256+8*16(%rip), SHA256CONSTANTS
/* Save hash values for addition after rounds */
mova128 STATE0, SAVE0
mova128 STATE1, SAVE1
/* Rounds 0-3 */
movu128 0*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP0
paddd 0*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 4-7 */
movu128 1*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP1
paddd 1*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
/* Rounds 8-11 */
movu128 2*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP2
paddd 2*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
/* Rounds 12-15 */
movu128 3*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
/* ...to here */
mova128 MSG, MSGTMP3
paddd 3*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP3, XMMTMP
palignr $4, MSGTMP2, XMMTMP
paddd XMMTMP, MSGTMP0
sha256msg2 MSGTMP3, MSGTMP0
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
/* Rounds 16-19 */
mova128 MSGTMP0, MSG
paddd 4*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP0, XMMTMP
palignr $4, MSGTMP3, XMMTMP
paddd XMMTMP, MSGTMP1
sha256msg2 MSGTMP0, MSGTMP1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
/* Rounds 20-23 */
mova128 MSGTMP1, MSG
paddd 5*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP1, XMMTMP
palignr $4, MSGTMP0, XMMTMP
paddd XMMTMP, MSGTMP2
sha256msg2 MSGTMP1, MSGTMP2
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
/* Rounds 24-27 */
mova128 MSGTMP2, MSG
paddd 6*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP2, XMMTMP
palignr $4, MSGTMP1, XMMTMP
paddd XMMTMP, MSGTMP3
sha256msg2 MSGTMP2, MSGTMP3
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
/* Rounds 28-31 */
mova128 MSGTMP3, MSG
paddd 7*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP3, XMMTMP
palignr $4, MSGTMP2, XMMTMP
paddd XMMTMP, MSGTMP0
sha256msg2 MSGTMP3, MSGTMP0
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
/* Rounds 32-35 */
mova128 MSGTMP0, MSG
paddd 8*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP0, XMMTMP
palignr $4, MSGTMP3, XMMTMP
paddd XMMTMP, MSGTMP1
sha256msg2 MSGTMP0, MSGTMP1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
/* Rounds 36-39 */
mova128 MSGTMP1, MSG
paddd 9*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP1, XMMTMP
palignr $4, MSGTMP0, XMMTMP
paddd XMMTMP, MSGTMP2
sha256msg2 MSGTMP1, MSGTMP2
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
/* Rounds 40-43 */
mova128 MSGTMP2, MSG
paddd 10*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP2, XMMTMP
palignr $4, MSGTMP1, XMMTMP
paddd XMMTMP, MSGTMP3
sha256msg2 MSGTMP2, MSGTMP3
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
/* Rounds 44-47 */
mova128 MSGTMP3, MSG
paddd 11*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP3, XMMTMP
palignr $4, MSGTMP2, XMMTMP
paddd XMMTMP, MSGTMP0
sha256msg2 MSGTMP3, MSGTMP0
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
/* Rounds 48-51 */
mova128 MSGTMP0, MSG
paddd 12*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP0, XMMTMP
palignr $4, MSGTMP3, XMMTMP
paddd XMMTMP, MSGTMP1
sha256msg2 MSGTMP0, MSGTMP1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
/* Rounds 52-55 */
mova128 MSGTMP1, MSG
paddd 13*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP1, XMMTMP
palignr $4, MSGTMP0, XMMTMP
paddd XMMTMP, MSGTMP2
sha256msg2 MSGTMP1, MSGTMP2
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 56-59 */
mova128 MSGTMP2, MSG
paddd 14*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
mova128 MSGTMP2, XMMTMP
palignr $4, MSGTMP1, XMMTMP
paddd XMMTMP, MSGTMP3
sha256msg2 MSGTMP2, MSGTMP3
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 60-63 */
mova128 MSGTMP3, MSG
paddd 15*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
sha256rnds2 MSG, STATE1, STATE0
/* Add current hash values with previously saved */
paddd SAVE0, STATE0
paddd SAVE1, STATE1
/* Write hash values back in the correct order */
mova128 STATE0, XMMTMP
/* shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one */
/* --- -------------- HGDC -- FEBA */
shufps SHUF(3,2,3,2), STATE1, STATE0 /* ABCD */
shufps SHUF(1,0,1,0), STATE1, XMMTMP /* EFGH */
movu128 STATE0, 80+0*16(%rdi)
movu128 XMMTMP, 80+1*16(%rdi)
ret
.size sha256_process_block64_shaNI, .-sha256_process_block64_shaNI
.section .rodata.cst256.K256, "aM", @progbits, 256
.balign 16
K256:
.long 0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5
.long 0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5
.long 0xd807aa98,0x12835b01,0x243185be,0x550c7dc3
.long 0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174
.long 0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc
.long 0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da
.long 0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7
.long 0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967
.long 0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13
.long 0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85
.long 0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3
.long 0xd192e819,0xd6990624,0xf40e3585,0x106aa070
.long 0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5
.long 0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3
.long 0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208
.long 0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
.section .rodata.cst16.PSHUFFLE_BSWAP32_FLIP_MASK, "aM", @progbits, 16
.balign 16
PSHUFFLE_BSWAP32_FLIP_MASK:
.octa 0x0c0d0e0f08090a0b0405060700010203
#endif
+234
View File
@@ -0,0 +1,234 @@
#if ENABLE_SHA1_HWACCEL && defined(__GNUC__) && defined(__i386__)
/* The code is adapted from Linux kernel's source */
// We use shorter insns, even though they are for "wrong"
// data type (fp, not int).
// For Intel, there is no penalty for doing it at all
// (CPUs which do have such penalty do not support SHA insns).
// For AMD, the penalty is one extra cycle
// (allegedly: I failed to find measurable difference).
//#define mova128 movdqa
#define mova128 movaps
//#define movu128 movdqu
#define movu128 movups
//#define xor128 pxor
#define xor128 xorps
//#define shuf128_32 pshufd
#define shuf128_32 shufps
#define extr128_32 pextrd
//#define extr128_32 extractps # not shorter
// pshufb is a SSSE3 insn.
// pinsrd, pextrd, extractps are SSE4.1 insns.
// We do not check SSSE3/SSE4.1 in cpuid,
// all SHA-capable CPUs support them as well.
#ifdef __linux__
.section .note.GNU-stack, "", @progbits
#endif
.section .text.sha1_process_block64_shaNI, "ax", @progbits
.globl sha1_process_block64_shaNI
.hidden sha1_process_block64_shaNI
.type sha1_process_block64_shaNI, @function
#define ABCD %xmm0
#define E0 %xmm1 /* Need two E's b/c they ping pong */
#define E1 %xmm2
#define MSG0 %xmm3
#define MSG1 %xmm4
#define MSG2 %xmm5
#define MSG3 %xmm6
.balign 8 # allow decoders to fetch at least 2 first insns
sha1_process_block64_shaNI:
/* load initial hash values */
movu128 76(%eax), ABCD
xor128 E0, E0
pinsrd $3, 76+4*4(%eax), E0 # load to uppermost 32-bit word
shuf128_32 $0x1B, ABCD, ABCD # DCBA -> ABCD
mova128 PSHUFFLE_BYTE_FLIP_MASK, %xmm7
movu128 0*16(%eax), MSG0
pshufb %xmm7, MSG0
movu128 1*16(%eax), MSG1
pshufb %xmm7, MSG1
movu128 2*16(%eax), MSG2
pshufb %xmm7, MSG2
movu128 3*16(%eax), MSG3
pshufb %xmm7, MSG3
/* Save hash values for addition after rounds */
mova128 E0, %xmm7
/*mova128 ABCD, %xmm8 - NOPE, 32bit has no xmm8 */
/* Rounds 0-3 */
paddd MSG0, E0
mova128 ABCD, E1
sha1rnds4 $0, E0, ABCD
/* Rounds 4-7 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1rnds4 $0, E1, ABCD
sha1msg1 MSG1, MSG0
/* Rounds 8-11 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1rnds4 $0, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 12-15 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $0, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 16-19 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $0, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 20-23 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $1, E1, ABCD
sha1msg1 MSG1, MSG0
xor128 MSG1, MSG3
/* Rounds 24-27 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $1, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 28-31 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $1, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 32-35 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $1, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 36-39 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $1, E1, ABCD
sha1msg1 MSG1, MSG0
xor128 MSG1, MSG3
/* Rounds 40-43 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $2, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 44-47 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $2, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 48-51 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $2, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 52-55 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $2, E1, ABCD
sha1msg1 MSG1, MSG0
xor128 MSG1, MSG3
/* Rounds 56-59 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $2, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 60-63 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $3, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 64-67 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $3, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 68-71 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $3, E1, ABCD
xor128 MSG1, MSG3
/* Rounds 72-75 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $3, E0, ABCD
/* Rounds 76-79 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1rnds4 $3, E1, ABCD
/* Add current hash values with previously saved */
sha1nexte %xmm7, E0
/*paddd %xmm8, ABCD - 32-bit mode has no xmm8 */
movu128 76(%eax), %xmm7 # get original ABCD (not shuffled)...
/* Write hash values back in the correct order */
shuf128_32 $0x1B, ABCD, ABCD
paddd %xmm7, ABCD # ...add it to final ABCD
movu128 ABCD, 76(%eax)
extr128_32 $3, E0, 76+4*4(%eax)
ret
.size sha1_process_block64_shaNI, .-sha1_process_block64_shaNI
.section .rodata.cst16.PSHUFFLE_BYTE_FLIP_MASK, "aM", @progbits, 16
.balign 16
PSHUFFLE_BYTE_FLIP_MASK:
.octa 0x000102030405060708090a0b0c0d0e0f
#endif
File diff suppressed because it is too large. Load diff
+478
View File
@@ -0,0 +1,478 @@
#!/bin/sh
# We don't regenerate it on every "make" invocation - only by hand.
# The reason is that the changes to generated code are difficult
# to visualize by looking only at this script, it helps when the commit
# also contains the diff of the generated file.
exec >hash_md5_sha_x86-64.S
# Based on http://arctic.org/~dean/crypto/sha1.html.
# ("This SHA1 implementation is public domain.")
#
# x86-64 has at least SSE2 vector insns always available.
# We can use them without any CPUID checks (and without a need
# for a fallback code if needed insns are not available).
# This code uses them to calculate W[] ahead of time.
#
# Unfortunately, results are passed from vector unit to
# integer ALUs on the stack. MOVD/Q insns to move them directly
# from vector to integer registers are slower than store-to-load
# forwarding in LSU (on Skylake at least).
#
# The win against a purely integer code is small on Skylake,
# only about 7-8%. We offload about 1/3 of our operations to the vector unit.
# It can do 4 ops at once in one 128-bit register,
# but we have to use x2 of them because of W[0] complication,
# SSE2 has no "rotate each word by N bits" insns,
# moving data to/from vector unit is clunky, and Skylake
# has four integer ALUs unified with three vector ALUs,
# which makes pure integer code rather fast, and makes
# vector ops compete with integer ones.
#
# Zen3, with its separate vector ALUs, wins more, about 12%.
xmmT1="%xmm4"
xmmT2="%xmm5"
xmmRCONST="%xmm6"
xmmALLRCONST="%xmm7"
T=`printf '\t'`
# SSE instructions are longer than 4 bytes on average.
# Intel CPUs (up to Tiger Lake at least) can't decode
# more than 16 bytes of code in one cycle.
# By interleaving SSE code and integer code
# we mostly achieve a situation where 16-byte decode fetch window
# contains 4 (or more) insns.
#
# However. On Skylake, there was no observed difference,
# but on Zen3, non-interleaved code is ~3% faster
# (822 Mb/s versus 795 Mb/s hashing speed).
# Off for now:
interleave=false
INTERLEAVE() {
$interleave || \
{
# Generate non-interleaved code
# (it should work correctly too)
echo "$1"
echo "$2"
return
}
(
echo "$1" | grep -v '^$' >"$0.temp1"
echo "$2" | grep -v '^$' >"$0.temp2"
exec 3<"$0.temp1"
exec 4<"$0.temp2"
IFS=''
while :; do
line1=''
line2=''
while :; do
read -r line1 <&3
if test "${line1:0:1}" != "#" && test "${line1:0:2}" != "$T#"; then
break
fi
echo "$line1"
done
while :; do
read -r line2 <&4
if test "${line2:0:4}" = "${T}lea"; then
# We use 7-8 byte long forms of LEA.
# Do not interleave them with SSE insns
# which are also long.
echo "$line2"
read -r line2 <&4
echo "$line2"
continue
fi
if test "${line2:0:1}" != "#" && test "${line2:0:2}" != "$T#"; then
break
fi
echo "$line2"
done
test "$line1$line2" || break
echo "$line1"
echo "$line2"
done
rm "$0.temp1" "$0.temp2"
)
}
# movaps bswap32_mask(%rip), $xmmT1
# Load W[] to xmm0..3, byteswapping on the fly.
# For iterations 0..15, we pass RCONST+W[] in rsi,r8..r14
# for use in RD1As instead of spilling them to stack.
# (We use rsi instead of rN because this makes two
# ADDs in two first RD1As shorter by one byte).
# movups 16*0(%rdi), %xmm0
# pshufb $xmmT1, %xmm0 #SSSE3 insn
# movaps %xmm0, $xmmT2
# paddd $xmmRCONST, $xmmT2
# movq $xmmT2, %rsi
# #pextrq \$1, $xmmT2, %r8 #SSE4.1 insn
# #movhpd $xmmT2, %r8 #can only move to mem, not to reg
# shufps \$0x0e, $xmmT2, $xmmT2 # have to use two-insn sequence
# movq $xmmT2, %r8 # instead
# ...
# <repeat for xmm1,2,3>
# ...
#- leal $RCONST(%r$e,%rsi), %e$e # e += RCONST + W[n]
#+ addl %esi, %e$e # e += RCONST + W[n]
# ^^^^^^^^^^^^^^^^^^^^^^^^
# The above is -97 bytes of code...
# ...but pshufb is a SSSE3 insn. Can't use it.
echo \
"### Generated by hash_md5_sha_x86-64.S.sh ###
#if CONFIG_SHA1_SMALL == 0 && defined(__GNUC__) && defined(__x86_64__)
#ifdef __linux__
.section .note.GNU-stack, \"\", @progbits
#endif
.section .text.sha1_process_block64, \"ax\", @progbits
.globl sha1_process_block64
.hidden sha1_process_block64
.type sha1_process_block64, @function
.balign 8 # allow decoders to fetch at least 5 first insns
sha1_process_block64:
pushq %rbp # 1 byte insn
pushq %rbx # 1 byte insn
# pushq %r15 # 2 byte insn
pushq %r14 # 2 byte insn
pushq %r13 # 2 byte insn
pushq %r12 # 2 byte insn
pushq %rdi # we need ctx at the end
#Register and stack use:
# eax..edx: a..d
# ebp: e
# esi,edi,r8..r14: temps
# r15: unused
# xmm0..xmm3: W[]
# xmm4,xmm5: temps
# xmm6: current round constant
# xmm7: all round constants
# -64(%rsp): area for passing RCONST + W[] from vector to integer units
movl 80(%rdi), %eax # a = ctx->hash[0]
movl 84(%rdi), %ebx # b = ctx->hash[1]
movl 88(%rdi), %ecx # c = ctx->hash[2]
movl 92(%rdi), %edx # d = ctx->hash[3]
movl 96(%rdi), %ebp # e = ctx->hash[4]
movaps sha1const(%rip), $xmmALLRCONST
pshufd \$0x00, $xmmALLRCONST, $xmmRCONST
# Load W[] to xmm0..3, byteswapping on the fly.
#
# For iterations 0..15, we pass W[] in rsi,r8..r14
# for use in RD1As instead of spilling them to stack.
# We lose parallelized addition of RCONST, but LEA
# can do two additions at once, so it is probably a wash.
# (We use rsi instead of rN because this makes two
# LEAs in two first RD1As shorter by one byte).
movq 4*0(%rdi), %rsi
movq 4*2(%rdi), %r8
bswapq %rsi
bswapq %r8
rolq \$32, %rsi # rsi = W[1]:W[0]
rolq \$32, %r8 # r8 = W[3]:W[2]
movq %rsi, %xmm0
movq %r8, $xmmT1
punpcklqdq $xmmT1, %xmm0 # xmm0 = r8:rsi = (W[0],W[1],W[2],W[3])
# movaps %xmm0, $xmmT1 # add RCONST, spill to stack
# paddd $xmmRCONST, $xmmT1
# movups $xmmT1, -64+16*0(%rsp)
movq 4*4(%rdi), %r9
movq 4*6(%rdi), %r10
bswapq %r9
bswapq %r10
rolq \$32, %r9 # r9 = W[5]:W[4]
rolq \$32, %r10 # r10 = W[7]:W[6]
movq %r9, %xmm1
movq %r10, $xmmT1
punpcklqdq $xmmT1, %xmm1 # xmm1 = r10:r9 = (W[4],W[5],W[6],W[7])
movq 4*8(%rdi), %r11
movq 4*10(%rdi), %r12
bswapq %r11
bswapq %r12
rolq \$32, %r11 # r11 = W[9]:W[8]
rolq \$32, %r12 # r12 = W[11]:W[10]
movq %r11, %xmm2
movq %r12, $xmmT1
punpcklqdq $xmmT1, %xmm2 # xmm2 = r12:r11 = (W[8],W[9],W[10],W[11])
movq 4*12(%rdi), %r13
movq 4*14(%rdi), %r14
bswapq %r13
bswapq %r14
rolq \$32, %r13 # r13 = W[13]:W[12]
rolq \$32, %r14 # r14 = W[15]:W[14]
movq %r13, %xmm3
movq %r14, $xmmT1
punpcklqdq $xmmT1, %xmm3 # xmm3 = r14:r13 = (W[12],W[13],W[14],W[15])
"
PREP() {
local xmmW0=$1
local xmmW4=$2
local xmmW8=$3
local xmmW12=$4
# the above must be %xmm0..3 in some permutation
local dstmem=$5
#W[0] = rol(W[13] ^ W[8] ^ W[2] ^ W[0], 1);
#W[1] = rol(W[14] ^ W[9] ^ W[3] ^ W[1], 1);
#W[2] = rol(W[15] ^ W[10] ^ W[4] ^ W[2], 1);
#W[3] = rol( 0 ^ W[11] ^ W[5] ^ W[3], 1);
#W[3] ^= rol(W[0], 1);
echo "# PREP $@
movaps $xmmW12, $xmmT1
psrldq \$4, $xmmT1 # rshift by 4 bytes: T1 = ([13],[14],[15],0)
# pshufd \$0x4e, $xmmW0, $xmmT2 # 01001110=2,3,0,1 shuffle, ([2],[3],x,x)
# punpcklqdq $xmmW4, $xmmT2 # T2 = W4[0..63]:T2[0..63] = ([2],[3],[4],[5])
# same result as above, but shorter and faster:
# pshufd/shufps are subtly different: pshufd takes all dwords from source operand,
# shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one!
movaps $xmmW0, $xmmT2
shufps \$0x4e, $xmmW4, $xmmT2 # 01001110=(T2.dw[2], T2.dw[3], W4.dw[0], W4.dw[1]) = ([2],[3],[4],[5])
xorps $xmmW8, $xmmW0 # ([8],[9],[10],[11]) ^ ([0],[1],[2],[3])
xorps $xmmT1, $xmmT2 # ([13],[14],[15],0) ^ ([2],[3],[4],[5])
xorps $xmmT2, $xmmW0 # ^
# W0 = unrotated (W[0]..W[3]), still needs W[3] fixup
movaps $xmmW0, $xmmT2
xorps $xmmT1, $xmmT1 # rol(W0,1):
pcmpgtd $xmmW0, $xmmT1 # ffffffff for elements <0 (ones with msb bit 1)
paddd $xmmW0, $xmmW0 # shift left by 1
psubd $xmmT1, $xmmW0 # add 1 to those who had msb bit 1
# W0 = rotated (W[0]..W[3]), still needs W[3] fixup
pslldq \$12, $xmmT2 # lshift by 12 bytes: T2 = (0,0,0,unrotW[0])
movaps $xmmT2, $xmmT1
pslld \$2, $xmmT2
psrld \$30, $xmmT1
# xorps $xmmT1, $xmmT2 # rol((0,0,0,unrotW[0]),2)
xorps $xmmT1, $xmmW0 # same result, but does not depend on/does not modify T2
xorps $xmmT2, $xmmW0 # W0 = rol(W[0]..W[3],1) ^ (0,0,0,rol(unrotW[0],2))
"
# movq $xmmW0, %r8 # high latency (~6 cycles)
# movaps $xmmW0, $xmmT1
# psrldq \$8, $xmmT1 # rshift by 8 bytes: move upper 64 bits to lower
# movq $xmmT1, %r10 # high latency
# movq %r8, %r9
# movq %r10, %r11
# shrq \$32, %r9
# shrq \$32, %r11
# ^^^ slower than passing the results on stack (!!!)
echo "
movaps $xmmW0, $xmmT2
paddd $xmmRCONST, $xmmT2
movups $xmmT2, $dstmem
"
}
# It's possible to interleave integer insns in rounds to mostly eliminate
# dependency chains, but this likely to only help old Pentium-based
# CPUs (ones without OOO, which can only simultaneously execute a pair
# of _adjacent_ insns).
# Testing on old-ish Silvermont CPU (which has OOO window of only
# about ~8 insns) shows very small (~1%) speedup.
RD1A() {
local a=$1;local b=$2;local c=$3;local d=$4;local e=$5
local n=$(($6))
local n0=$(((n+0) & 15))
local rN=$((7+n0/2))
echo "
# $n
";test $n0 = 0 && echo "
leal $RCONST(%r$e,%rsi), %e$e # e += RCONST + W[n]
shrq \$32, %rsi
";test $n0 = 1 && echo "
leal $RCONST(%r$e,%rsi), %e$e # e += RCONST + W[n]
";test $n0 -ge 2 && test $((n0 & 1)) = 0 && echo "
leal $RCONST(%r$e,%r$rN), %e$e # e += RCONST + W[n]
shrq \$32, %r$rN
";test $n0 -ge 2 && test $((n0 & 1)) = 1 && echo "
leal $RCONST(%r$e,%r$rN), %e$e # e += RCONST + W[n]
";echo "
movl %e$c, %edi # c
xorl %e$d, %edi # ^d
andl %e$b, %edi # &b
xorl %e$d, %edi # (((c ^ d) & b) ^ d)
addl %edi, %e$e # e += (((c ^ d) & b) ^ d)
movl %e$a, %edi #
roll \$5, %edi # rotl32(a,5)
addl %edi, %e$e # e += rotl32(a,5)
rorl \$2, %e$b # b = rotl32(b,30)
"
}
RD1B() {
local a=$1;local b=$2;local c=$3;local d=$4;local e=$5
local n=$(($6))
local n13=$(((n+13) & 15))
local n8=$(((n+8) & 15))
local n2=$(((n+2) & 15))
local n0=$(((n+0) & 15))
echo "
# $n
movl %e$c, %edi # c
xorl %e$d, %edi # ^d
andl %e$b, %edi # &b
xorl %e$d, %edi # (((c ^ d) & b) ^ d)
addl -64+4*$n0(%rsp), %e$e # e += RCONST + W[n & 15]
addl %edi, %e$e # e += (((c ^ d) & b) ^ d)
movl %e$a, %esi #
roll \$5, %esi # rotl32(a,5)
addl %esi, %e$e # e += rotl32(a,5)
rorl \$2, %e$b # b = rotl32(b,30)
"
}
RD2() {
local a=$1;local b=$2;local c=$3;local d=$4;local e=$5
local n=$(($6))
local n13=$(((n+13) & 15))
local n8=$(((n+8) & 15))
local n2=$(((n+2) & 15))
local n0=$(((n+0) & 15))
echo "
# $n
movl %e$c, %edi # c
xorl %e$d, %edi # ^d
xorl %e$b, %edi # ^b
addl -64+4*$n0(%rsp), %e$e # e += RCONST + W[n & 15]
addl %edi, %e$e # e += (c ^ d ^ b)
movl %e$a, %esi #
roll \$5, %esi # rotl32(a,5)
addl %esi, %e$e # e += rotl32(a,5)
rorl \$2, %e$b # b = rotl32(b,30)
"
}
RD3() {
local a=$1;local b=$2;local c=$3;local d=$4;local e=$5
local n=$(($6))
local n13=$(((n+13) & 15))
local n8=$(((n+8) & 15))
local n2=$(((n+2) & 15))
local n0=$(((n+0) & 15))
echo "
# $n
movl %e$b, %edi # di: b
movl %e$b, %esi # si: b
orl %e$c, %edi # di: b | c
andl %e$c, %esi # si: b & c
andl %e$d, %edi # di: (b | c) & d
orl %esi, %edi # ((b | c) & d) | (b & c)
addl %edi, %e$e # += ((b | c) & d) | (b & c)
addl -64+4*$n0(%rsp), %e$e # e += RCONST + W[n & 15]
movl %e$a, %esi #
roll \$5, %esi # rotl32(a,5)
addl %esi, %e$e # e += rotl32(a,5)
rorl \$2, %e$b # b = rotl32(b,30)
"
}
{
# Round 1
RCONST=0x5A827999
RD1A ax bx cx dx bp 0; RD1A bp ax bx cx dx 1; RD1A dx bp ax bx cx 2; RD1A cx dx bp ax bx 3;
RD1A bx cx dx bp ax 4; RD1A ax bx cx dx bp 5; RD1A bp ax bx cx dx 6; RD1A dx bp ax bx cx 7;
a=`PREP %xmm0 %xmm1 %xmm2 %xmm3 "-64+16*0(%rsp)"`
b=`RD1A cx dx bp ax bx 8; RD1A bx cx dx bp ax 9; RD1A ax bx cx dx bp 10; RD1A bp ax bx cx dx 11;`
INTERLEAVE "$a" "$b"
a=`echo " pshufd \\$0x55, $xmmALLRCONST, $xmmRCONST"
PREP %xmm1 %xmm2 %xmm3 %xmm0 "-64+16*1(%rsp)"`
b=`RD1A dx bp ax bx cx 12; RD1A cx dx bp ax bx 13; RD1A bx cx dx bp ax 14; RD1A ax bx cx dx bp 15;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm2 %xmm3 %xmm0 %xmm1 "-64+16*2(%rsp)"`
b=`RD1B bp ax bx cx dx 16; RD1B dx bp ax bx cx 17; RD1B cx dx bp ax bx 18; RD1B bx cx dx bp ax 19;`
INTERLEAVE "$a" "$b"
# Round 2
RCONST=0x6ED9EBA1
a=`PREP %xmm3 %xmm0 %xmm1 %xmm2 "-64+16*3(%rsp)"`
b=`RD2 ax bx cx dx bp 20; RD2 bp ax bx cx dx 21; RD2 dx bp ax bx cx 22; RD2 cx dx bp ax bx 23;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm0 %xmm1 %xmm2 %xmm3 "-64+16*0(%rsp)"`
b=`RD2 bx cx dx bp ax 24; RD2 ax bx cx dx bp 25; RD2 bp ax bx cx dx 26; RD2 dx bp ax bx cx 27;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm1 %xmm2 %xmm3 %xmm0 "-64+16*1(%rsp)"`
b=`RD2 cx dx bp ax bx 28; RD2 bx cx dx bp ax 29; RD2 ax bx cx dx bp 30; RD2 bp ax bx cx dx 31;`
INTERLEAVE "$a" "$b"
a=`echo " pshufd \\$0xaa, $xmmALLRCONST, $xmmRCONST"
PREP %xmm2 %xmm3 %xmm0 %xmm1 "-64+16*2(%rsp)"`
b=`RD2 dx bp ax bx cx 32; RD2 cx dx bp ax bx 33; RD2 bx cx dx bp ax 34; RD2 ax bx cx dx bp 35;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm3 %xmm0 %xmm1 %xmm2 "-64+16*3(%rsp)"`
b=`RD2 bp ax bx cx dx 36; RD2 dx bp ax bx cx 37; RD2 cx dx bp ax bx 38; RD2 bx cx dx bp ax 39;`
INTERLEAVE "$a" "$b"
# Round 3
RCONST=0x8F1BBCDC
a=`PREP %xmm0 %xmm1 %xmm2 %xmm3 "-64+16*0(%rsp)"`
b=`RD3 ax bx cx dx bp 40; RD3 bp ax bx cx dx 41; RD3 dx bp ax bx cx 42; RD3 cx dx bp ax bx 43;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm1 %xmm2 %xmm3 %xmm0 "-64+16*1(%rsp)"`
b=`RD3 bx cx dx bp ax 44; RD3 ax bx cx dx bp 45; RD3 bp ax bx cx dx 46; RD3 dx bp ax bx cx 47;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm2 %xmm3 %xmm0 %xmm1 "-64+16*2(%rsp)"`
b=`RD3 cx dx bp ax bx 48; RD3 bx cx dx bp ax 49; RD3 ax bx cx dx bp 50; RD3 bp ax bx cx dx 51;`
INTERLEAVE "$a" "$b"
a=`echo " pshufd \\$0xff, $xmmALLRCONST, $xmmRCONST"
PREP %xmm3 %xmm0 %xmm1 %xmm2 "-64+16*3(%rsp)"`
b=`RD3 dx bp ax bx cx 52; RD3 cx dx bp ax bx 53; RD3 bx cx dx bp ax 54; RD3 ax bx cx dx bp 55;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm0 %xmm1 %xmm2 %xmm3 "-64+16*0(%rsp)"`
b=`RD3 bp ax bx cx dx 56; RD3 dx bp ax bx cx 57; RD3 cx dx bp ax bx 58; RD3 bx cx dx bp ax 59;`
INTERLEAVE "$a" "$b"
# Round 4 has the same logic as round 2, only n and RCONST are different
RCONST=0xCA62C1D6
a=`PREP %xmm1 %xmm2 %xmm3 %xmm0 "-64+16*1(%rsp)"`
b=`RD2 ax bx cx dx bp 60; RD2 bp ax bx cx dx 61; RD2 dx bp ax bx cx 62; RD2 cx dx bp ax bx 63;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm2 %xmm3 %xmm0 %xmm1 "-64+16*2(%rsp)"`
b=`RD2 bx cx dx bp ax 64; RD2 ax bx cx dx bp 65; RD2 bp ax bx cx dx 66; RD2 dx bp ax bx cx 67;`
INTERLEAVE "$a" "$b"
a=`PREP %xmm3 %xmm0 %xmm1 %xmm2 "-64+16*3(%rsp)"`
b=`RD2 cx dx bp ax bx 68; RD2 bx cx dx bp ax 69; RD2 ax bx cx dx bp 70; RD2 bp ax bx cx dx 71;`
INTERLEAVE "$a" "$b"
RD2 dx bp ax bx cx 72; RD2 cx dx bp ax bx 73; RD2 bx cx dx bp ax 74; RD2 ax bx cx dx bp 75;
RD2 bp ax bx cx dx 76; RD2 dx bp ax bx cx 77; RD2 cx dx bp ax bx 78; RD2 bx cx dx bp ax 79;
} | grep -v '^$'
echo "
popq %rdi #
popq %r12 #
addl %eax, 80(%rdi) # ctx->hash[0] += a
popq %r13 #
addl %ebx, 84(%rdi) # ctx->hash[1] += b
popq %r14 #
addl %ecx, 88(%rdi) # ctx->hash[2] += c
# popq %r15 #
addl %edx, 92(%rdi) # ctx->hash[3] += d
popq %rbx #
addl %ebp, 96(%rdi) # ctx->hash[4] += e
popq %rbp #
ret
.size sha1_process_block64, .-sha1_process_block64
.section .rodata.cst16.sha1const, \"aM\", @progbits, 16
.balign 16
sha1const:
.long 0x5A827999
.long 0x6ED9EBA1
.long 0x8F1BBCDC
.long 0xCA62C1D6
#endif"
+232
View File
@@ -0,0 +1,232 @@
#if ENABLE_SHA1_HWACCEL && defined(__GNUC__) && defined(__x86_64__)
/* The code is adapted from Linux kernel's source */
// We use shorter insns, even though they are for "wrong"
// data type (fp, not int).
// For Intel, there is no penalty for doing it at all
// (CPUs which do have such penalty do not support SHA insns).
// For AMD, the penalty is one extra cycle
// (allegedly: I failed to find measurable difference).
//#define mova128 movdqa
#define mova128 movaps
//#define movu128 movdqu
#define movu128 movups
//#define xor128 pxor
#define xor128 xorps
//#define shuf128_32 pshufd
#define shuf128_32 shufps
#define extr128_32 pextrd
//#define extr128_32 extractps # not shorter
// pshufb is a SSSE3 insn.
// pinsrd, pextrd, extractps are SSE4.1 insns.
// We do not check SSSE3/SSE4.1 in cpuid,
// all SHA-capable CPUs support them as well.
#ifdef __linux__
.section .note.GNU-stack, "", @progbits
#endif
.section .text.sha1_process_block64_shaNI, "ax", @progbits
.globl sha1_process_block64_shaNI
.hidden sha1_process_block64_shaNI
.type sha1_process_block64_shaNI, @function
#define ABCD %xmm0
#define E0 %xmm1 /* Need two E's b/c they ping pong */
#define E1 %xmm2
#define MSG0 %xmm3
#define MSG1 %xmm4
#define MSG2 %xmm5
#define MSG3 %xmm6
.balign 8 # allow decoders to fetch at least 2 first insns
sha1_process_block64_shaNI:
/* load initial hash values */
movu128 80(%rdi), ABCD
xor128 E0, E0
pinsrd $3, 80+4*4(%rdi), E0 # load to uppermost 32-bit word
shuf128_32 $0x1B, ABCD, ABCD # DCBA -> ABCD
mova128 PSHUFFLE_BYTE_FLIP_MASK(%rip), %xmm7
movu128 0*16(%rdi), MSG0
pshufb %xmm7, MSG0
movu128 1*16(%rdi), MSG1
pshufb %xmm7, MSG1
movu128 2*16(%rdi), MSG2
pshufb %xmm7, MSG2
movu128 3*16(%rdi), MSG3
pshufb %xmm7, MSG3
/* Save hash values for addition after rounds */
mova128 E0, %xmm7
mova128 ABCD, %xmm8
/* Rounds 0-3 */
paddd MSG0, E0
mova128 ABCD, E1
sha1rnds4 $0, E0, ABCD
/* Rounds 4-7 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1rnds4 $0, E1, ABCD
sha1msg1 MSG1, MSG0
/* Rounds 8-11 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1rnds4 $0, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 12-15 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $0, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 16-19 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $0, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 20-23 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $1, E1, ABCD
sha1msg1 MSG1, MSG0
xor128 MSG1, MSG3
/* Rounds 24-27 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $1, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 28-31 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $1, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 32-35 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $1, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 36-39 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $1, E1, ABCD
sha1msg1 MSG1, MSG0
xor128 MSG1, MSG3
/* Rounds 40-43 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $2, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 44-47 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $2, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 48-51 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $2, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 52-55 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $2, E1, ABCD
sha1msg1 MSG1, MSG0
xor128 MSG1, MSG3
/* Rounds 56-59 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $2, E0, ABCD
sha1msg1 MSG2, MSG1
xor128 MSG2, MSG0
/* Rounds 60-63 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1msg2 MSG3, MSG0
sha1rnds4 $3, E1, ABCD
sha1msg1 MSG3, MSG2
xor128 MSG3, MSG1
/* Rounds 64-67 */
sha1nexte MSG0, E0
mova128 ABCD, E1
sha1msg2 MSG0, MSG1
sha1rnds4 $3, E0, ABCD
sha1msg1 MSG0, MSG3
xor128 MSG0, MSG2
/* Rounds 68-71 */
sha1nexte MSG1, E1
mova128 ABCD, E0
sha1msg2 MSG1, MSG2
sha1rnds4 $3, E1, ABCD
xor128 MSG1, MSG3
/* Rounds 72-75 */
sha1nexte MSG2, E0
mova128 ABCD, E1
sha1msg2 MSG2, MSG3
sha1rnds4 $3, E0, ABCD
/* Rounds 76-79 */
sha1nexte MSG3, E1
mova128 ABCD, E0
sha1rnds4 $3, E1, ABCD
/* Add current hash values with previously saved */
sha1nexte %xmm7, E0
paddd %xmm8, ABCD
/* Write hash values back in the correct order */
shuf128_32 $0x1B, ABCD, ABCD
movu128 ABCD, 80(%rdi)
extr128_32 $3, E0, 80+4*4(%rdi)
ret
.size sha1_process_block64_shaNI, .-sha1_process_block64_shaNI
.section .rodata.cst16.PSHUFFLE_BYTE_FLIP_MASK, "aM", @progbits, 16
.balign 16
PSHUFFLE_BYTE_FLIP_MASK:
.octa 0x000102030405060708090a0b0c0d0e0f
#endif
+116 -47
View File
@@ -135,10 +135,6 @@ enum {
: 0x7ff0
};
#if ENABLE_USERNAME_OR_HOMEDIR
static const char null_str[] ALIGN1 = "";
#endif
/* We try to minimize both static and stack usage. */
struct lineedit_statics {
line_input_t *state;
@@ -161,12 +157,13 @@ struct lineedit_statics {
#if ENABLE_USERNAME_OR_HOMEDIR
char *user_buf;
char *home_pwd_buf; /* = (char*)null_str; */
char *home_pwd_buf;
smallint got_user_strings;
#endif
#if ENABLE_FEATURE_TAB_COMPLETION
char **matches;
unsigned num_matches;
char **matches;
#endif
#if ENABLE_FEATURE_EDITING_WINCH
@@ -192,7 +189,7 @@ struct lineedit_statics {
};
/* See lineedit_ptr_hack.c */
extern struct lineedit_statics *const lineedit_ptr_to_statics;
extern struct lineedit_statics *BB_GLOBAL_CONST lineedit_ptr_to_statics;
#define S (*lineedit_ptr_to_statics)
#define state (S.state )
@@ -207,15 +204,15 @@ extern struct lineedit_statics *const lineedit_ptr_to_statics;
#define prompt_last_line (S.prompt_last_line)
#define user_buf (S.user_buf )
#define home_pwd_buf (S.home_pwd_buf )
#define matches (S.matches )
#define got_user_strings (S.got_user_strings)
#define num_matches (S.num_matches )
#define matches (S.matches )
#define delptr (S.delptr )
#define newdelflag (S.newdelflag )
#define delbuf (S.delbuf )
#define INIT_S() do { \
(*(struct lineedit_statics**)not_const_pp(&lineedit_ptr_to_statics)) = xzalloc(sizeof(S)); \
barrier(); \
XZALLOC_CONST_PTR(&lineedit_ptr_to_statics, sizeof(S)); \
} while (0)
static void deinit_S(void)
@@ -227,14 +224,59 @@ static void deinit_S(void)
#endif
#if ENABLE_USERNAME_OR_HOMEDIR
free(user_buf);
if (home_pwd_buf != null_str)
free(home_pwd_buf);
free(home_pwd_buf);
#endif
free(lineedit_ptr_to_statics);
}
#define DEINIT_S() deinit_S()
#if ENABLE_USERNAME_OR_HOMEDIR
/* Call getpwuid() only if necessary.
* E.g. if PS1=':', no user database reading is needed to generate prompt.
* (Unfortunately, default PS1='\w \$' needs it, \w abbreviates homedir
* as ~/... - for that it needs to *know* the homedir...)
*/
static void get_user_strings(void)
{
struct passwd *entry;
got_user_strings = 1;
entry = getpwuid(geteuid());
if (entry) {
user_buf = xstrdup(entry->pw_name);
home_pwd_buf = xstrdup(entry->pw_dir);
}
}
static NOINLINE const char *get_homedir_or_NULL(void)
{
const char *home;
# if ENABLE_SHELL_ASH || ENABLE_SHELL_HUSH
home = state && state->sh_get_var ? state->sh_get_var("HOME") : getenv("HOME");
# else
home = getenv("HOME");
# endif
if (home != NULL && home[0] != '\0')
return home;
if (!got_user_strings)
get_user_strings();
return home_pwd_buf;
}
#endif
#if ENABLE_FEATURE_EDITING_FANCY_PROMPT
static const char *get_username_str(void)
{
if (!got_user_strings)
get_user_strings();
return user_buf ? user_buf : "";
/* btw, bash uses "I have no name!" string if uid has no entry */
}
#endif
#if ENABLE_UNICODE_SUPPORT
static size_t load_string(const char *src)
{
@@ -692,11 +734,11 @@ static char *username_path_completion(char *ud)
{
struct passwd *entry;
char *tilde_name = ud;
char *home = NULL;
const char *home = NULL;
ud++; /* skip ~ */
if (*ud == '/') { /* "~/..." */
home = home_pwd_buf;
home = get_homedir_or_NULL();
} else {
/* "~user/..." */
ud = strchr(ud, '/');
@@ -783,8 +825,8 @@ static unsigned path_parse(char ***p)
res[npth++] = tmp;
}
/* special case: "match subdirectories of the current directory" */
/*res[npth++] = NULL; - filled by xzalloc() */
return npth;
/*res[npth] = NULL; - filled by xzalloc() */
return npth + 1;
}
/* Complete command, directory or file name.
@@ -831,7 +873,7 @@ static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
continue;
}
# endif
# if EDITING_HAS_get_exe_name
# if ENABLE_SHELL_ASH || ENABLE_SHELL_HUSH
if (state->get_exe_name) {
i = 0;
for (;;) {
@@ -1133,7 +1175,16 @@ static void showfiles(void)
static const char *is_special_char(char c)
{
return strchr(" `\"#$%^&*()=+{}[]:;'|\\<>", c);
// {: It's mandatory to escape { only if entire name is "{"
// (otherwise it's not special. Example: file named "{ "
// can be escaped simply as "{\ "; "{a" or "a{" need no escaping),
// or if shell supports brace expansion
// (ash doesn't, hush optionally does).
// (): unlike {, shell treats () specially even in contexts
// where they clearly are not valid (e.g. "echo )" is an error).
// #: needs escaping to not start a shell comment.
return strchr(" `'\"\\#$~?*[{()&;|<>", c);
// Used to also have %^=+}]: but not necessary to escape?
}
static char *quote_special_chars(char *found)
@@ -1753,7 +1804,7 @@ vi_back_motion(void)
input_backward(1);
}
}
#endif
#endif /* ENABLE_FEATURE_EDITING_VI */
/* Modelled after bash 4.0 behavior of Ctrl-<arrow> */
static void ctrl_left(void)
@@ -1854,7 +1905,7 @@ static void ask_terminal(void)
}
}
#else
#define ask_terminal() ((void)0)
# define ask_terminal() ((void)0)
#endif
/* Note about multi-line PS1 (e.g. "\n\w \u@\h\n> ") and prompt redrawing:
@@ -1963,7 +2014,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
switch (c) {
case 'u':
pbuf = user_buf ? user_buf : (char*)"";
pbuf = (char*)get_username_str();
break;
case 'H':
case 'h':
@@ -1985,14 +2036,21 @@ static void parse_and_put_prompt(const char *prmt_ptr)
case 'w': /* current dir */
case 'W': /* basename of cur dir */
if (!cwd_buf) {
const char *home;
# if EDITING_HAS_sh_get_var
cwd_buf = state && state->sh_get_var
? xstrdup(state->sh_get_var("PWD"))
: xrealloc_getcwd_or_warn(NULL);
# else
cwd_buf = xrealloc_getcwd_or_warn(NULL);
# endif
if (!cwd_buf)
cwd_buf = (char *)bb_msg_unknown;
else if (home_pwd_buf[0]) {
else if ((home = get_homedir_or_NULL()) != NULL && home[0]) {
char *after_home_user;
/* /home/user[/something] -> ~[/something] */
after_home_user = is_prefixed_with(cwd_buf, home_pwd_buf);
after_home_user = is_prefixed_with(cwd_buf, home);
if (after_home_user
&& (*after_home_user == '/' || *after_home_user == '\0')
) {
@@ -2048,7 +2106,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
if (c == '\n')
cmdedit_prmt_len = 0;
else if (flg_not_length != ']') {
#if ENABLE_UNICODE_SUPPORT
# if ENABLE_UNICODE_SUPPORT
if (n == 1) {
/* Only count single-byte characters and the first of multi-byte characters */
if ((unsigned char)*pbuf < 0x80 /* single byte character */
@@ -2059,9 +2117,9 @@ static void parse_and_put_prompt(const char *prmt_ptr)
} else {
cmdedit_prmt_len += unicode_strwidth(pbuf);
}
#else
# else
cmdedit_prmt_len += n;
#endif
# endif
}
}
prmt_mem_ptr = strcat(xrealloc(prmt_mem_ptr, prmt_size+1), pbuf);
@@ -2115,17 +2173,41 @@ static int lineedit_read_key(char *read_key_buffer, int timeout)
#endif
fflush_all();
while (1) {
for (;;) {
/* Wait for input. TIMEOUT = -1 makes read_key wait even
* on nonblocking stdin, TIMEOUT = 50 makes sure we won't
* insist on full MB_CUR_MAX buffer to declare input like
* "\xff\n",pause,"ls\n" invalid and thus won't lose "ls".
*
* If LI_INTERRUPTIBLE, return -1 if got EINTR in poll()
* inside read_key, or if bb_got_signal != 0 (IOW: if signal
* arrived before poll() is reached).
*
* Note: read_key sets errno to 0 on success.
*/
IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 1;)
ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 0;)
for (;;) {
if ((state->flags & LI_INTERRUPTIBLE) && bb_got_signal) {
errno = EINTR;
return -1;
}
//FIXME: still races here with signals, but small window to poll() inside read_key
IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 1;)
/* errno = 0; - read_key does this itself */
ic = read_key(STDIN_FILENO, read_key_buffer, timeout);
IF_FEATURE_EDITING_WINCH(S.ok_to_redraw = 0;)
if (errno != EINTR)
break;
if (state->flags & LI_INTERRUPTIBLE) {
/* LI_INTERRUPTIBLE bails out on EINTR,
* but nothing really guarantees that bb_got_signal
* is nonzero. Follow the least surprise principle:
*/
if (bb_got_signal == 0)
bb_got_signal = 255;
goto ret;
}
}
if (errno) {
#if ENABLE_UNICODE_SUPPORT
if (errno == EAGAIN && unicode_idx != 0)
@@ -2193,7 +2275,7 @@ static int lineedit_read_key(char *read_key_buffer, int timeout)
#endif
break;
}
ret:
return ic;
}
@@ -2288,7 +2370,7 @@ static int32_t reverse_i_search(int timeout)
}
/* Append this char */
#if ENABLE_UNICODE_SUPPORT
# if ENABLE_UNICODE_SUPPORT
if (unicode_status == UNICODE_ON) {
mbstate_t mbstate = { 0 };
char buf[MB_CUR_MAX + 1];
@@ -2299,7 +2381,7 @@ static int32_t reverse_i_search(int timeout)
strcpy(match_buf + match_buf_len, buf);
}
} else
#endif
# endif
if (match_buf_len < sizeof(match_buf) - 1) {
match_buf[match_buf_len] = ic;
match_buf[match_buf_len + 1] = '\0';
@@ -2351,7 +2433,7 @@ static int32_t reverse_i_search(int timeout)
return ic;
}
#endif
#endif /* ENABLE_FEATURE_REVERSE_SEARCH */
#if ENABLE_FEATURE_EDITING_WINCH
static void sigaction2(int sig, struct sigaction *act)
@@ -2391,7 +2473,6 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
//command_len = 0; - done by INIT_S()
//cmdedit_y = 0; /* quasireal y, not true if line > xt*yt */
cmdedit_termw = 80;
IF_USERNAME_OR_HOMEDIR(home_pwd_buf = (char*)null_str;)
IF_FEATURE_EDITING_VI(delptr = delbuf;)
n = get_termios_and_make_raw(STDIN_FILENO, &new_settings, &initial_settings, 0
@@ -2451,18 +2532,6 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
tcsetattr_stdin_TCSANOW(&new_settings);
#if ENABLE_USERNAME_OR_HOMEDIR
{
struct passwd *entry;
entry = getpwuid(geteuid());
if (entry) {
user_buf = xstrdup(entry->pw_name);
home_pwd_buf = xstrdup(entry->pw_dir);
}
}
#endif
#if 0
for (i = 0; i <= state->max_history; i++)
bb_error_msg("history[%d]:'%s'", i, state->history[i]);
+113 -62
View File
@@ -71,7 +71,7 @@ int FAST_FUNC del_loop(const char *device)
fd = open(device, O_RDONLY);
if (fd < 0)
return 1;
return fd; /* -1 */
rc = ioctl(fd, LOOP_CLR_FD, 0);
close(fd);
@@ -96,6 +96,97 @@ int FAST_FUNC get_free_loop(void)
return loopdevno; /* can be -1 if error */
}
static int get_next_free_loop(char *dev, int id)
{
int loopdevno;
loopdevno = get_free_loop();
if (loopdevno != -1) {
/* loopdevno is -2 (use id) or >= 0 (use id = loopdevno): */
if (loopdevno >= 0)
id = loopdevno;
sprintf(dev, LOOP_FORMAT, id);
}
return loopdevno;
}
#if ENABLE_TRY_LOOP_CONFIGURE || ENABLE_LOOP_CONFIGURE
# define LOOP_CONFIGURE 0x4C0A
struct bb_loop_config {
uint32_t fd;
uint32_t block_size;
struct loop_info64 info;
uint64_t __reserved[8];
};
#endif
static int set_loopdev_params(int lfd,
int ffd, const char *file,
unsigned long long offset,
unsigned long long sizelimit,
unsigned flags)
{
int rc;
#if ENABLE_TRY_LOOP_CONFIGURE || ENABLE_LOOP_CONFIGURE
struct bb_loop_config lconfig;
# define loopinfo lconfig.info
#else
bb_loop_info loopinfo;
#endif
rc = ioctl(lfd, BB_LOOP_GET_STATUS, &loopinfo);
/* If device is free, try to claim it */
if (rc && errno == ENXIO) {
#if ENABLE_TRY_LOOP_CONFIGURE || ENABLE_LOOP_CONFIGURE
memset(&lconfig, 0, sizeof(lconfig));
#else
memset(&loopinfo, 0, sizeof(loopinfo));
#endif
safe_strncpy((char *)loopinfo.lo_file_name, file, LO_NAME_SIZE);
loopinfo.lo_offset = offset;
loopinfo.lo_sizelimit = sizelimit;
/*
* LO_FLAGS_READ_ONLY is not set because RO is controlled
* by open type of the lfd.
*/
loopinfo.lo_flags = (flags & ~BB_LO_FLAGS_READ_ONLY);
#if ENABLE_TRY_LOOP_CONFIGURE || ENABLE_LOOP_CONFIGURE
lconfig.fd = ffd;
rc = ioctl(lfd, LOOP_CONFIGURE, &lconfig);
if (rc == 0)
return rc; /* SUCCESS! */
# if ENABLE_TRY_LOOP_CONFIGURE
if (errno != EINVAL)
return rc; /* error other than old kernel */
/* Old kernel, fall through into old way to do it: */
# endif
#endif
#if ENABLE_TRY_LOOP_CONFIGURE || ENABLE_NO_LOOP_CONFIGURE
/* Associate free loop device with file */
rc = ioctl(lfd, LOOP_SET_FD, ffd);
if (rc != 0) {
/* Ouch... race: the device already has a fd */
return rc;
}
rc = ioctl(lfd, BB_LOOP_SET_STATUS, &loopinfo);
if (rc != 0 && (loopinfo.lo_flags & BB_LO_FLAGS_AUTOCLEAR)) {
/* Old kernel, does not support LO_FLAGS_AUTOCLEAR? */
/* (this code path is not tested) */
loopinfo.lo_flags -= BB_LO_FLAGS_AUTOCLEAR;
rc = ioctl(lfd, BB_LOOP_SET_STATUS, &loopinfo);
}
if (rc == 0)
return rc; /* SUCCESS! */
/* failure, undo LOOP_SET_FD */
ioctl(lfd, LOOP_CLR_FD, 0); // actually, 0 param is unnecessary
#endif
}
return -1;
#undef loopinfo
}
/* Returns opened fd to the loop device, <0 on error.
* *device is loop device to use, or if *device==NULL finds a loop device to
* mount it on and sets *device to a strdup of that loop device name.
@@ -105,7 +196,6 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
{
char dev[LOOP_NAMESIZE];
char *try;
bb_loop_info loopinfo;
struct stat statbuf;
int i, lfd, ffd, mode, rc;
@@ -123,30 +213,27 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
try = *device;
if (!try) {
get_free_loopN:
i = get_free_loop();
if (i == -1) {
close(ffd);
return -1; /* no free loop devices */
}
if (i >= 0) {
try = xasprintf(LOOP_FORMAT, i);
goto open_lfd;
}
/* i == -2: no /dev/loop-control. Do an old-style search for a free device */
try = dev;
}
/* Find a loop device */
/* 0xfffff is a max possible minor number in Linux circa 2010 */
for (i = 0; i <= 0xfffff; i++) {
sprintf(dev, LOOP_FORMAT, i);
if (!*device) {
rc = get_next_free_loop(dev, i);
if (rc == -1)
break; /* no free loop devices (or other error in LOOP_CTL_GET_FREE) */
if (rc >= 0)
/* /dev/loop-control gave us the next free /dev/loopN */
goto open_lfd;
/* else: sequential /dev/loopN, needs to be tested/maybe_created */
}
IF_FEATURE_MOUNT_LOOP_CREATE(errno = 0;)
if (stat(try, &statbuf) != 0 || !S_ISBLK(statbuf.st_mode)) {
if (ENABLE_FEATURE_MOUNT_LOOP_CREATE
&& errno == ENOENT
&& try == dev
&& (!*device)
) {
/* Node doesn't exist, try to create it */
if (mknod(dev, S_IFBLK|0644, makedev(7, i)) == 0)
@@ -172,55 +259,19 @@ int FAST_FUNC set_loop(char **device, const char *file, unsigned long long offse
goto try_next_loopN;
}
rc = ioctl(lfd, BB_LOOP_GET_STATUS, &loopinfo);
/* If device is free, try to claim it */
if (rc && errno == ENXIO) {
/* Associate free loop device with file */
if (ioctl(lfd, LOOP_SET_FD, ffd)) {
/* Ouch. Are we racing with other mount? */
if (!*device /* yes */
&& try != dev /* tried a _kernel-offered_ loopN? */
) {
free(try);
close(lfd);
//TODO: add "if (--failcount != 0) ..."?
goto get_free_loopN;
}
goto close_and_try_next_loopN;
}
memset(&loopinfo, 0, sizeof(loopinfo));
safe_strncpy((char *)loopinfo.lo_file_name, file, LO_NAME_SIZE);
loopinfo.lo_offset = offset;
loopinfo.lo_sizelimit = sizelimit;
/*
* Used by mount to set LO_FLAGS_AUTOCLEAR.
* LO_FLAGS_READ_ONLY is not set because RO is controlled by open type of the file.
* Note that closing LO_FLAGS_AUTOCLEARed lfd before mount
* is wrong (would free the loop device!)
rc = set_loopdev_params(lfd, ffd, file, offset, sizelimit, flags);
if (rc == 0) {
/* SUCCESS! */
if (!*device)
*device = xstrdup(dev);
/* Note: mount asks for LO_FLAGS_AUTOCLEAR loopdev.
* Closing LO_FLAGS_AUTOCLEARed lfd before mount
* is wrong (would free the loop device!),
* this is why we return without closing it.
*/
loopinfo.lo_flags = (flags & ~BB_LO_FLAGS_READ_ONLY);
rc = ioctl(lfd, BB_LOOP_SET_STATUS, &loopinfo);
if (rc != 0 && (loopinfo.lo_flags & BB_LO_FLAGS_AUTOCLEAR)) {
/* Old kernel, does not support LO_FLAGS_AUTOCLEAR? */
/* (this code path is not tested) */
loopinfo.lo_flags -= BB_LO_FLAGS_AUTOCLEAR;
rc = ioctl(lfd, BB_LOOP_SET_STATUS, &loopinfo);
}
if (rc == 0) {
/* SUCCESS! */
if (try != dev) /* tried a kernel-offered free loopN? */
*device = try; /* malloced */
if (!*device) /* was looping in search of free "/dev/loopN"? */
*device = xstrdup(dev);
rc = lfd; /* return this */
break;
}
/* failure, undo LOOP_SET_FD */
ioctl(lfd, LOOP_CLR_FD, 0); // actually, 0 param is unnecessary
rc = lfd; /* return this */
break;
}
/* else: device is not free (rc == 0) or error other than ENXIO */
close_and_try_next_loopN:
close(lfd);
try_next_loopN:
rc = -1;
+12 -22
View File
@@ -16,16 +16,18 @@
#error permission bitflag value assumption(s) violated!
#endif
/* Generate ls-style "mode string" like "-rwsr-xr-x" or "drwxrwxrwt" */
#if ( S_IFSOCK!= 0140000 ) || ( S_IFLNK != 0120000 ) \
|| ( S_IFREG != 0100000 ) || ( S_IFBLK != 0060000 ) \
|| ( S_IFDIR != 0040000 ) || ( S_IFCHR != 0020000 ) \
|| ( S_IFIFO != 0010000 )
#warning mode type bitflag value assumption(s) violated! falling back to larger version
# warning mode type bitflag value assumption(s) violated! falling back to larger version
#if (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX) == 07777
#undef mode_t
#define mode_t unsigned short
#endif
# if (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX) == 07777
# undef mode_t
# define mode_t unsigned short
# endif
static const mode_t mode_flags[] ALIGN4 = {
S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID,
@@ -33,19 +35,14 @@ static const mode_t mode_flags[] ALIGN4 = {
S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX
};
/* The static const char arrays below are duplicated for the two cases
* because moving them ahead of the mode_flags declaration cause a text
* size increase with the gcc version I'm using. */
/* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C',
* and 'B' types don't appear to be available on linux. So I removed them. */
static const char type_chars[16] ALIGN1 = "?pc?d?b?-?l?s???";
/***************************************** 0123456789abcdef */
static const char mode_chars[7] ALIGN1 = "rwxSTst";
const char* FAST_FUNC bb_mode_string(mode_t mode)
char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
{
static char buf[12];
char *p = buf;
int i, j, k;
@@ -67,10 +64,7 @@ const char* FAST_FUNC bb_mode_string(mode_t mode)
i += 4;
} while (i < 12);
/* Note: We don't bother with nul termination because bss initialization
* should have taken care of that for us. If the user scribbled in buf
* memory, they deserve whatever happens. But we'll at least assert. */
assert(buf[10] == 0);
buf[10] = '\0';
return buf;
}
@@ -80,12 +74,11 @@ const char* FAST_FUNC bb_mode_string(mode_t mode)
/* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C',
* and 'B' types don't appear to be available on linux. So I removed them. */
static const char type_chars[16] ALIGN1 = "?pc?d?b?-?l?s???";
/********************************** 0123456789abcdef */
/***************************************** 0123456789abcdef */
static const char mode_chars[7] ALIGN1 = "rwxSTst";
const char* FAST_FUNC bb_mode_string(mode_t mode)
char* FAST_FUNC bb_mode_string(char buf[11], mode_t mode)
{
static char buf[12];
char *p = buf;
int i, j, k, m;
@@ -109,10 +102,7 @@ const char* FAST_FUNC bb_mode_string(mode_t mode)
}
} while (i < 3);
/* Note: We don't bother with nul termination because bss initialization
* should have taken care of that for us. If the user scribbled in buf
* memory, they deserve whatever happens. But we'll at least assert. */
assert(buf[10] == 0);
buf[10] = '\0';
return buf;
}
+3 -2
View File
@@ -16,13 +16,14 @@
int FAST_FUNC bb_parse_mode(const char *s, unsigned current_mode)
{
static const mode_t who_mask[] = {
/* should be mode_t really, but in all Unixes these constants fit into uint16 */
static const uint16_t who_mask[] ALIGN2 = {
S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO, /* a */
S_ISUID | S_IRWXU, /* u */
S_ISGID | S_IRWXG, /* g */
S_IRWXO /* o */
};
static const mode_t perm_mask[] = {
static const uint16_t perm_mask[] ALIGN2 = {
S_IRUSR | S_IRGRP | S_IROTH, /* r */
S_IWUSR | S_IWGRP | S_IWOTH, /* w */
S_IXUSR | S_IXGRP | S_IXOTH, /* x */
+2 -2
View File
@@ -12,11 +12,11 @@
* instead of including libbb.h */
//#include "libbb.h"
#include "platform.h"
extern void bb_simple_perror_msg(const char *s) FAST_FUNC;
extern void bb_perror_msg(const char *s, ...) FAST_FUNC;
/* suppress gcc "no previous prototype" warning */
void FAST_FUNC bb_perror_nomsg(void);
void FAST_FUNC bb_perror_nomsg(void)
{
bb_simple_perror_msg(0);
bb_perror_msg(0);
}
+2 -2
View File
@@ -12,11 +12,11 @@
* instead of including libbb.h */
//#include "libbb.h"
#include "platform.h"
extern void bb_simple_perror_msg_and_die(const char *s) FAST_FUNC;
extern void bb_perror_msg_and_die(const char *s, ...) FAST_FUNC;
/* suppress gcc "no previous prototype" warning */
void FAST_FUNC bb_perror_nomsg_and_die(void);
void FAST_FUNC bb_perror_nomsg_and_die(void)
{
bb_simple_perror_msg_and_die(0);
bb_perror_msg_and_die(0);
}
+14 -15
View File
@@ -363,7 +363,7 @@ des_init(struct des_ctx *ctx, const struct const_des_ctx *cctx)
old_rawkey0 = old_rawkey1 = 0;
old_salt = 0;
#endif
saltbits = 0;
//saltbits = 0; /* not needed: we call setup_salt() before do_des() */
bits28 = bits32 + 4;
bits24 = bits28 + 4;
@@ -481,12 +481,11 @@ des_init(struct des_ctx *ctx, const struct const_des_ctx *cctx)
return ctx;
}
/* Accepts 24-bit salt at max */
static void
setup_salt(struct des_ctx *ctx, uint32_t salt)
{
uint32_t obit, saltbit;
int i;
uint32_t invbits;
#if USE_REPETITIVE_SPEEDUP
if (salt == old_salt)
@@ -494,15 +493,15 @@ setup_salt(struct des_ctx *ctx, uint32_t salt)
old_salt = salt;
#endif
saltbits = 0;
saltbit = 1;
obit = 0x800000;
for (i = 0; i < 24; i++) {
if (salt & saltbit)
saltbits |= obit;
saltbit <<= 1;
obit >>= 1;
}
invbits = 0;
salt |= (1 << 24);
do {
invbits = (invbits << 1) + (salt & 1);
salt >>= 1;
} while (salt != 1);
saltbits = invbits;
}
static void
@@ -736,14 +735,14 @@ des_crypt(struct des_ctx *ctx, char output[DES_OUT_BUFSIZE],
des_setkey(ctx, (char *)keybuf);
/*
* salt_str - 2 bytes of salt
* salt_str - 2 chars of salt (converted to 12 bits)
* key - up to 8 characters
*/
output[0] = salt_str[0];
output[1] = salt_str[1];
salt = (ascii_to_bin(salt_str[1]) << 6)
| ascii_to_bin(salt_str[0]);
setup_salt(ctx, salt);
setup_salt(ctx, salt); /* set ctx->saltbits for do_des() */
/* Do it. */
do_des(ctx, /*0, 0,*/ &r0, &r1, 25 /* count */);
+15 -2
View File
@@ -126,7 +126,10 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
* if fd can be in non-blocking mode.
*/
if (timeout >= -1) {
if (safe_poll(&pfd, 1, timeout) == 0) {
n = poll(&pfd, 1, timeout);
if (n < 0 && errno == EINTR)
return n;
if (n == 0) {
/* Timed out */
errno = EAGAIN;
return -1;
@@ -138,7 +141,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
* When we were reading 3 bytes here, we were eating
* "li" too, and cat was getting wrong input.
*/
n = safe_read(fd, buffer, 1);
n = read(fd, buffer, 1);
if (n <= 0)
return -1;
}
@@ -284,6 +287,16 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
goto start_over;
}
int64_t FAST_FUNC safe_read_key(int fd, char *buffer, int timeout)
{
int64_t r;
do {
/* errno = 0; - read_key does this itself */
r = read_key(fd, buffer, timeout);
} while (errno == EINTR);
return r;
}
void FAST_FUNC read_key_ungets(char *buffer, const char *str, unsigned len)
{
unsigned cur_len = (unsigned char)buffer[0];
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff. Show more