Compare commits

..
420 Commits
Author SHA1 Message Date
Denys Vlasenko fc71374dfc Bump version to 1.38.0
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-13 04:20:15 +02:00
Denys Vlasenko ead17e7808 Optimize !ENABLE_SHOW_USAGE config
function                                             old     new   delta
bb_show_usage                                          6       -      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-02 12:05:32 +02:00
Denys Vlasenko 25b756f789 cpio.tests: fix false positive
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-30 10:04:47 +02:00
Denys Vlasenko 3b3d0fc535 cpio.tests: do not use "ls" to detect that file does not exist
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-30 08:05:42 +02:00
Denys Vlasenko 48c7b48f95 tar: unicode fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-30 07:29:37 +02:00
Denys Vlasenko 4f11a4b25d cpio.tests: fix false positive when -o support is not enabled
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-30 06:46:44 +02:00
Denys Vlasenko 6908229d4f cpio: fix a bug (wrong free() address) in !FEATURE_TAR_LONG_OPTIONS config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-30 05:56:58 +02:00
Denys Vlasenko fb10ad3b5c start-stop-daemon.tests: fix false positive if longopts are not enabled
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 15:55:44 +02:00
Denys Vlasenko c8eb861406 Fix "undefined reference to 'skip_unsafe_prefix' build failure
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 08:46:56 +02:00
Denys Vlasenko fdca28aaf4 fdisk: fix build failure on glibc
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 07:32:26 +02:00
Denys Vlasenko a0a98f0700 Fix randomtest to not select TC on glibc
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 07:30:13 +02:00
Denys Vlasenko 7e2b9a4d9c httpd: fix build for !FEATURE_HTTPD_CGI config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 07:09:30 +02:00
Denys Vlasenko a588fb9703 Fix randomtest to never select a debug config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 07:04:30 +02:00
Denys Vlasenko a9e7466e5c telnet: fix build for !TELNETD config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 06:49:48 +02:00
Denys Vlasenko de26b74b1d httpd: fix build for !FEATURE_HTTPD_CONFIG_WITH_SCRIPT_INTERPR config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 06:36:39 +02:00
Denys Vlasenko 0519429ea1 hush: fix build for !HUSH_CASE config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-29 06:31:55 +02:00
Denys Vlasenko 2f3b16fc1b libbb: rename two fields in ioloop_state, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-04-12 16:20:09 +02:00
Denys Vlasenko bee252057c trylink: remove "local" bashism
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-16 14:49:42 +01:00
Christian Stewart 764df2555d trylink: detect linker flag support for non-GNU linkers
wasm-ld does not support --start-group/--end-group, --warn-common,
--verbose, or -Map flags. Add check_cc tests so these are only used
when the linker supports them, following the existing --sort-section
and --sort-common patterns.

Signed-off-by: Christian Stewart <christian@aperture.us>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-15 16:35:32 +01:00
Denys Vlasenko 60221ded38 less: fix ":d" command
function                                             old     new   delta
less_main                                           2105    2062     -43

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-15 16:12:23 +01:00
Denys Vlasenko ca0eb211b0 runsv: fix open error check (fd < -1 should be fd < 0)
From: Weixie Cui <cuiweixie@gmail.com>

function                                             old     new   delta
update_status                                        608     607      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-13 00:46:19 +01:00
Denys Vlasenko d368f3f783 udhcpc6: check the size of D6_OPT_IAPREFIX option
function                                             old     new   delta
option_to_env                                        694     711     +17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-12 13:23:48 +01:00
Denys Vlasenko 42202bfb1e udhcpc6: fix buffer overflow
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-12 07:25:38 +01:00
Ron Yorston e527bd22db ash: fix here strings causing segfault in function invocation
The size of the NFROMSTR struct wasn't initialised in the nodesize
array, so we got:

   $ ./busybox sh
   $ f() { cat <<< hello; }
   $ f
   Segmentation fault         (core dumped) ./busybox sh

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-09 15:23:59 +01:00
Ron Yorston ea01f254b4 paste: fix output when file lengths differ
If the files being pasted had different numbers of lines the
output was incorrect.

Rewrite the loop over all lines to allow for this.  Add tests for
such conditions.

function                                             old     new   delta
paste_main                                           458     526     +68

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-03-05 21:46:04 +01:00
Ron Yorston via busybox b59b003231 ash: fix help builtin and tab completion of builtins
Commit 56143ea63 (ash: code shrink: eliminate pstrcmp1()) changed
the layout of struct builtincmd so the name member points to the
start of the name, not the flag in the first element of the string.
This broke the help builtin and tab completion of builtins.

Remove the unnecessary '+ 1' in ash_command_name() and helpcmd().

ash_command_name                                      92      91      -1
helpcmd                                              106     102      -4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-5)               Total: -5 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-28 11:25:05 +01:00
Radoslav Kolev 599f5dd8fa tar: only strip unsafe components from hardlinks, not symlinks
commit 3fb6b31c7 introduced a check for unsafe components in
tar archive hardlinks, but it was being applied to symlinks too
which broke "Symlinks and hardlinks coexist" tar test.

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-28 05:59:18 +01:00
Denys Vlasenko 138ec0e0d8 less: unbreak EAGAIN propagation
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-27 12:25:28 +01:00
Denys Vlasenko 1068aa8220 less: make read error reporting actually visible
function                                             old     new   delta
m_status_print                                       252     275     +23
status_print                                         111     122     +11
read_lines                                           783     775      -8
.rodata                                           107141  107131     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/2 up/down: 34/-18)             Total: 16 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-27 11:57:50 +01:00
Denys Vlasenko ca3f4c6639 less: improve O_NONBLOCK manipulations on stdin
"less FILE" case needs it to be set just once. In other cases,
manipulate it less often.

function                                             old     new   delta
read_lines                                           702     783     +81
reinitialize                                         198     199      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 82/0)               Total: 82 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-27 11:01:04 +01:00
Denys Vlasenko f51819afa5 less: do not retry reads of stdin if got EAGAIN
Also: fewer syscalls to set/clear O_NONBLOCK, skip trying to read keyboard
if poll() told us it's not ready.

function                                             old     new   delta
reinitialize                                         184     198     +14
getch_nowait                                         251     258      +7
sched_yield                                           25       -     -25
read_lines                                           815     702    -113
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 2/1 up/down: 21/-138)          Total: -117 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-27 08:09:30 +01:00
Denys Vlasenko ad88be9e7e *: don't use getservbyname, it links in a static buffer
function                                             old     new   delta
bb_get_servport_by_name                                -     348    +348
bb_lookup_port                                        83     111     +28
reread_config_file                                   886     907     +21
static.se                                             16       -     -16
getservbyname                                         53       -     -53
getservbyname_r                                      284       -    -284
------------------------------------------------------------------------------
(add/remove: 2/5 grow/shrink: 2/0 up/down: 397/-353)           Total: 44 bytes
   text	   data	    bss	    dec	    hex	filename
1080084	    555	   5024	1085663	 1090df	busybox_old
1080144	    555	   4992	1085691	 1090fb	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-25 02:35:32 +01:00
Denys Vlasenko c920ecd73d telnet: fix false positive "Error writing to foreign host"
function                                             old     new   delta
write_to_net                                         620     625      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-24 23:47:52 +01:00
Denys Vlasenko 1ecee61787 netstat: fix breakage due to last commit
function                                             old     new   delta
bb_get_servname_by_port                              182     195     +13
ip_port_str                                          121     120      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 13/-1)              Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-24 23:11:21 +01:00
Denys Vlasenko c0037a9974 netstat,pscan: don't use getservbyport(), it links in a static buffer
function                                             old     new   delta
bb_get_servname_by_port                                -     182    +182
ip_port_str                                          112     121      +9
pscan_main                                           594     591      -3
getservbyport                                         53       -     -53
getservbyport_r                                      430       -    -430
------------------------------------------------------------------------------
(add/remove: 2/4 grow/shrink: 1/1 up/down: 191/-486)         Total: -295 bytes
   text	   data	    bss	    dec	    hex	filename
1080362	    555	   5056	1085973	 109215	busybox_old
1080067	    555	   5024	1085646	 1090ce	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-24 22:42:30 +01:00
Denys Vlasenko b86f0198d6 telnet: fixes after testing against some MUD servers
A few size tests were not tight enough. More importantly,
the logic "is this a telnet server?" made more robust.

TTYPE seems to be understood by the MUD server I tried,
for some reason NAWS is not?

function                                             old     new   delta
packed_usage                                       36040   36078     +38
write_to_net                                         598     620     +22
telnet_main                                          455     462      +7
handle_SIGWINCH                                       15      21      +6
read_from_net                                        534     539      +5
show_menu                                            212     203      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/1 up/down: 78/-9)              Total: 69 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-24 07:16:16 +01:00
Denys Vlasenko 4bdbb7cc0a telnetd: if vfork in make_new_session() fails, do close socket.
function                                             old     new   delta
telnetd_main                                         372     385     +13
make_new_session                                     550     552      +2
xgetpty                                               81      78      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 15/-3)              Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-24 00:03:20 +01:00
Denys Vlasenko 0ac0492b37 telnet: code shrink
function                                             old     new   delta
write_to_stdout                                      105     113      +8
put_iac                                               28      35      +7
write_to_net                                         596     598      +2
read_from_stdin                                      227     229      +2
read_from_net                                        543     534      -9
telnet_main                                          476     455     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/2 up/down: 19/-30)            Total: -11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-23 15:42:43 +01:00
Denys Vlasenko 87fcfe7dfe telnet: rewrite to use ioloop()
Now should never block on network I/O. Also, window resizing is dynamic now.

function                                             old     new   delta
write_to_net                                           -     596    +596
read_from_net                                          -     543    +543
read_from_stdin                                        -     227    +227
show_menu                                              -     212    +212
write_to_stdout                                        -     105    +105
have_data_to_write_to_net                              -      72     +72
have_data_to_write_to_stdout                           -      38     +38
put_iac_byte_escaped                                   -      32     +32
ioloop_run                                           411     438     +27
have_buffer_to_read_from_stdin                         -      25     +25
have_buffer_to_read_from_net                           -      25     +25
.rodata                                           107125  107141     +16
handle_SIGWINCH                                        -      15     +15
put_iac                                               36      28      -8
put_iac4_msb_lsb                                      19       -     -19
iac_flush                                             36       -     -36
setConMode                                            87       -     -87
handle_net_output                                    110       -    -110
con_escape                                           271       -    -271
telnet_main                                         1232     476    -756
------------------------------------------------------------------------------
(add/remove: 11/5 grow/shrink: 2/2 up/down: 1933/-1287)       Total: 646 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-23 14:47:17 +01:00
Denys Vlasenko 3017f2becf telnetd: do not send stray \r\n before /etc/issue.net
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-23 00:09:10 +01:00
Denys Vlasenko da09ae3451 telnetd: do not wait for more input after 10-byte NAWS is received
If the the screen is resized to 255 columns without any
subsequent data received, the server won't parse and react
to the NAWS (until eventually at least one more byte arrives).

function                                             old     new   delta
read_byte_unescaping_IAC                              28      31      +3
net_to_pty__have_data_to_write                       551     552      +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>
2026-02-22 21:20:59 +01:00
Denys Vlasenko 8738c3102f telnetd: fix handshake: had one wrong, but harmless element
function                                             old     new   delta
static.iacs_to_send                                   12       9      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-22 20:04:41 +01:00
Denys Vlasenko 44e86427f4 telnetd: correct handling of screen sizes with any dimension equal to 255
IOW: teach NAWS parser how to IAC-unescape.

function                                             old     new   delta
net_to_pty__have_data_to_write                       429     551    +122
read_byte_unescaping_IAC                               -      28     +28
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 150/0)             Total: 150 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-22 09:45:03 +01:00
Denys Vlasenko 20387b703b telnetd: do close pty when network read returns EOF; try to cause EOF-on-read
function                                             old     new   delta
fabricate_ctrl_D_on_pty                                -      65     +65
net_to_pty__have_data_to_write                       368     429     +61
.rodata                                           107096  107125     +29
telnetd_main                                         367     372      +5
net_to_pty__have_buffer_to_read_into                 164     162      -2
packed_usage                                       36066   36040     -26
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 3/2 up/down: 160/-28)           Total: 132 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-22 07:11:16 +01:00
Denys Vlasenko dc6e92c990 libbb: add generic "fd polling and I/O" loop, use it in telnetd
We do it, badly, in many places. Better to use one robust implementation.
Can be buggy yet.
Initial use is in a rather old, rarely used tech: telnet.

The I/O in telnetd should be fully non-blocking now,
including pty delays handling.

Several bugs in telnetd handling of IACs are fixed.

function                                             old     new   delta
ioloop_run                                             -     411    +411
net_to_pty__have_data_to_write                         -     368    +368
pty_to_net__write                                      -     318    +318
net_to_pty__write                                      -     180    +180
pty_to_net__read                                       -     171    +171
net_to_pty__have_buffer_to_read_into                   -     164    +164
pty_to_net__have_buffer_to_read_into                   -      90     +90
net_to_pty__read                                       -      87     +87
pty_to_net__have_data_to_write                         -      59     +59
make_new_session                                     491     550     +59
conn_close_fds                                         -      52     +52
accept_conn__accept                                    -      49     +49
conn_close_fds_remove_and_free                         -      27     +27
ioloop_remove_conn                                     -      22     +22
remove_and_free_to_pty                                 -      19     +19
ioloop_insert_conn                                     -      10     +10
accept_conn__can_accept                                -       6      +6
accept_conn__return_zero                               -       3      +3
static.ayt_response                                    -       2      +2
handle_sigchld                                        59      61      +2
free_session                                         130       -    -130
telnetd_main                                        1797     367   -1430
------------------------------------------------------------------------------
(add/remove: 19/1 grow/shrink: 2/1 up/down: 2099/-1560)       Total: 539 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-21 16:54:35 +01:00
Denys Vlasenko ef892681f9 tls: code shrink
function                                             old     new   delta
tls_handshake_as_server                             2408    2400      -8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-21 01:36:01 +01:00
Denys Vlasenko 22b66febbd tls: server: fix incorrect key_block assignments - now works against openssl s_client
function                                             old     new   delta
privRsaEncryptSignedElement                            -     236    +236
tls_handshake_as_server                             2033    2264    +231
.rodata                                           108079  108301    +222
initialize_aes_keys                                    -      77     +77
xwrite_encrypted                                     507     506      -1
tls_handshake                                       1519    1500     -19
derive_master_secret_and_keys                        154     123     -31
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 2/3 up/down: 766/-51)           Total: 715 bytes

Totoal growth compared to code before TLS server code:

function                                             old     new   delta
tls_handshake_as_server                                -    2264   +2264
.rodata                                           107074  108301   +1227
psRsaCrypt                                             -     577    +577
load_rsa_priv_key                                      -     282    +282
ssl_server_main                                        -     279    +279
privRsaEncryptSignedElement                            -     236    +236
ssl_client_main                                      137     363    +226
psRsaDecryptPriv                                       -     171    +171
set_cipher_parameters                                  -     161    +161
derive_master_secret_and_keys                          -     123    +123
packed_usage                                       36034   36146    +112
sp_ecc_make_key_256                                    -     103    +103
send_finished                                          -      94     +94
get_change_cipher_spec                                 -      88     +88
initialize_aes_keys                                    -      77     +77
static.BLOCK_NAMES                                     -      70     +70
curve_P256_compute_premaster                           -      65     +65
der_binary_to_pstm                                     -      50     +50
curve_x25519_generate_keypair                          -      44     +44
get_finished                                           -      42     +42
get_outbuf_fill_handshake_record                       -      37     +37
client_hello_ciphers                                   -      32     +32
curve_P256_generate_keypair                            -      27     +27
sp_256_from_bin_8                                      -      26     +26
tls_xread_record                                     681     704     +23
curve_x25519_compute_premaster                         -      15     +15
applet_names                                        2870    2881     +11
applet_main                                         1652    1656      +4
xwrite_encrypted                                     507     506      -1
xwrite_and_update_handshake_hash                      76      59     -17
sp_256_point_from_bin2x32                             70      43     -27
curve_x25519_compute_pubkey_and_premaster             71      39     -32
curve_P256_compute_pubkey_and_premaster              167      65    -102
psRsaEncryptPub                                      395     199    -196
tls_handshake                                       2069    1500    -569
------------------------------------------------------------------------------
(add/remove: 23/0 grow/shrink: 6/7 up/down: 6466/-944)       Total: 5522 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:26:31 +01:00
Denys Vlasenko 7773faa878 tls: make ECDHE_RSA work against our client (openssl s_client not yet)
function                                             old     new   delta
tls_handshake_as_server                             1601    2033    +432
sp_ecc_make_key_256                                    -     103    +103
curve_P256_compute_premaster                           -      65     +65
.rodata                                           108023  108079     +56
curve_x25519_generate_keypair                          -      44     +44
tls_get_zeroed_outbuf                                  -      28     +28
curve_P256_generate_keypair                            -      27     +27
sp_256_from_bin_8                                      -      26     +26
curve_x25519_compute_premaster                         -      15     +15
tls_xread_record                                     708     704      -4
tls_handshake                                       1530    1519     -11
get_outbuf_fill_handshake_record                      51      37     -14
sp_256_point_from_bin2x32                             70      43     -27
curve_x25519_compute_pubkey_and_premaster             71      39     -32
curve_P256_compute_pubkey_and_premaster              167      65    -102
------------------------------------------------------------------------------
(add/remove: 7/0 grow/shrink: 2/6 up/down: 796/-190)          Total: 606 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko 2ab2c25847 tls: remove unnecessary malloc/free in psRsaDecryptPriv()
function                                             old     new   delta
.rodata                                           108007  108023     +16
psRsaDecryptPriv                                     200     171     -29
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 16/-29)            Total: -13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko 5a1bcdf036 tls: fix cipher-id selection in server mode
ECDSA keys still don't work, and currently will be ignored

function                                             old     new   delta
tls_handshake_as_server                              824    1601    +777
.rodata                                           107764  108007    +243
set_cipher_parameters                                  -     161    +161
packed_usage                                       36072   36146     +74
static.BLOCK_NAMES                                     -      70     +70
client_hello_ciphers                                   -      32     +32
ssl_server_main                                      288     279      -9
load_rsa_priv_key                                    329     282     -47
tls_handshake                                       1676    1530    -146
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 3/3 up/down: 1357/-202)        Total: 1155 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko 456abad825 tls: eliminate unnecessary ENCRYPT_ON_WRITE, merge tls_get_zeroed_outbuf() with fill_handshake_record_hdr()
function                                             old     new   delta
get_outbuf_fill_handshake_record                       -      51     +51
send_finished                                         95      94      -1
tls_handshake                                       1690    1676     -14
xwrite_and_update_handshake_hash                      76      59     -17
tls_handshake_as_server                              852     824     -28
tls_get_zeroed_outbuf                                 28       -     -28
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/4 up/down: 51/-88)            Total: -37 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko e17bc84d4c tls: fix up debug printouts wrt newlines
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko 657fbcd62c tls: implement server code
function                                             old     new   delta
tls_handshake_as_server                                7     852    +845
.rodata                                           107103  107764    +661
psRsaCrypt                                             -     577    +577
load_rsa_priv_key                                      -     329    +329
psRsaDecryptPriv                                       -     200    +200
derive_master_secret_and_keys                          -     154    +154
send_finished                                          -      95     +95
get_change_cipher_spec                                 -      88     +88
der_binary_to_pstm                                     -      50     +50
get_finished                                           -      42     +42
tls_xread_record                                     681     708     +27
ssl_server_main                                      285     288      +3
psRsaEncryptPub                                      395     199    -196
tls_handshake                                       2069    1690    -379
------------------------------------------------------------------------------
(add/remove: 8/0 grow/shrink: 4/2 up/down: 3071/-575)        Total: 2496 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko 61055ef909 ssl_server: new applet, not functional yet
function                                             old     new   delta
ssl_server_main                                        -     285    +285
ssl_client_main                                      137     363    +226
packed_usage                                       36034   36072     +38
.rodata                                           107074  107103     +29
applet_names                                        2870    2881     +11
tls_handshake_as_server                                -       7      +7
applet_main                                         1652    1656      +4
------------------------------------------------------------------------------
(add/remove: 3/0 grow/shrink: 5/0 up/down: 600/0)             Total: 600 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko d972f56837 libbb: better comments in read_key()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:16:26 +01:00
Denys Vlasenko b668e52c90 *: placate warnings where strchr/strstr returns constant pointer
Newer glibc is now smarter and can propagate const-ness from those!

function                                             old     new   delta
readtoken1                                          3111    3108      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:15:30 +01:00
Denys Vlasenko 9e8f8a1968 fdisk: implement -t PARTTYPE
This allows to operate on MBR even if disk also has GPT.

function                                             old     new   delta
.rodata                                           107019  107074     +55
packed_usage                                       36009   36034     +25
get_boot                                            1513    1532     +19
fdisk_main                                          4618    4622      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 103/0)             Total: 103 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-15 15:15:30 +01:00
Denys Vlasenko 8424dc436a main: !CONFIG_BUSYBOX: "busybox --OPT" is not a call to applet "-OPT"
This was confusing:

$ busybox --help
-help: applet not found

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-08 11:45:57 +01:00
Denys Vlasenko 391fdea73b *: whitespace cleanup
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-08 08:31:13 +01:00
Denys Vlasenko 8289b34626 tls: document PSTM_64BIT + PSTM_X86_64 optimizations better
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-08 08:30:03 +01:00
Denys Vlasenko 91075de0a7 vi: code shrink
function                                             old     new   delta
.rodata                                           107007  107019     +12
run_cmds                                              62      50     -12
indicate_error                                        78      55     -23
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 12/-35)            Total: -23 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-07 12:53:27 +01:00
Denys Vlasenko 1380df7a5a vi: fix last commit - do terminate the :CMD on the first whitespace
function                                             old     new   delta
colon                                               3942    3952     +10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-07 03:20:26 +01:00
Denys Vlasenko 9693daaaef *: use is_prefixed_with() where appropriate
function                                             old     new   delta
resume_main                                          560     556      -4
uuidcache_check_device                               107     101      -6
ntp_init                                            1005     997      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-18)             Total: -18 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-07 01:10:55 +01:00
Denys Vlasenko 79d35b5a0e vi: fix ":list" command
function                                             old     new   delta
.rodata                                           107010  107007      -3
show_status_line                                     372     362     -10
colon                                               3989    3942     -47
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-60)             Total: -60 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-07 00:52:49 +01:00
Denys Vlasenko 5de7222395 vi: code shrink
function                                             old     new   delta
colon                                               4005    3989     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-06 23:22:49 +01:00
Denys Vlasenko 3620c4ee67 vi: fix "s /find/repl" with whitespace before /
function                                             old     new   delta
colon                                               3977    4005     +28

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-06 22:56:16 +01:00
Denys Vlasenko 80ce9e3998 vi: code shrink, optimize: do not call count_lines() unless needed
function                                             old     new   delta
colon                                               4010    3980     -30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-06 20:50:47 +01:00
Denys Vlasenko c8cbd3516d *: use xasprintf_inplace() and concat_path_file() where appropriate
function                                             old     new   delta
acpid_main                                          1059    1063      +4
resume_main                                          561     560      -1
unpack_package                                       642     640      -2
adduser_main                                         861     859      -2
getty_main                                          1517    1512      -5
ftpd_main                                           2149    2142      -7
.rodata                                           107018  107010      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/6 up/down: 4/-25)             Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-06 13:16:36 +01:00
Denys Vlasenko 9b2a50efe2 *: use xasprintf_inplace() in more places
function                                             old     new   delta
.rodata                                           107009  107018      +9
parse_stream                                        3075    3069      -6
buffer_print                                         612     603      -9
expand_args                                          159     144     -15
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 9/-30)             Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-06 11:19:11 +01:00
Denys Vlasenko 89f37ebe8c man: fix following links if run inside manpage dir
function                                             old     new   delta
run_man_pipe                                         369     420     +51

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-05 14:28:20 +01:00
Denys Vlasenko fddd93edbd libbb: introduce and use xasprintf_inplace()
function                                             old     new   delta
xasprintf_and_free                                     -      49     +49
watch_main                                           269     282     +13
singlemount                                         1313    1315      +2
append_mount_options                                 157     149      -8
ip_port_str                                          122     112     -10
lsblk_main                                           869     858     -11
add_cmd                                             1178    1167     -11
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/4 up/down: 64/-40)             Total: 24 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-05 13:36:27 +01:00
Denys Vlasenko 3d572a8cc3 watch: implement -x
function                                             old     new   delta
packed_usage                                       35949   36009     +60
watch_main                                           229     269     +40
.rodata                                           107008  107009      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 101/0)             Total: 101 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-05 12:23:32 +01:00
Denys Vlasenko e33bd4aaa2 libbb: use narrow isqrt() when 64-bit one is not needed (only "factor" uses it)
function                                             old     new   delta
isqrt_ull                                              -      84     +84
create_J                                            1809    1808      -1
isqrt                                                106      38     -68
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/2 up/down: 84/-69)             Total: 15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-04 19:47:11 +01:00
Denys Vlasenko cdcb4ce314 volume_id: improve handling of too-small (usually zero-byte or erroring) blockdevs
function                                             old     new   delta
volume_id_get_buffer                                 327     372     +45
volume_id_open_node                                   17      24      +7
volume_id_probe_all                                  133     123     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 52/-10)             Total: 42 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-04 15:59:33 +01:00
Alyssa Ross via busybox 7310339e73 volume_id: volume_id_get_buffer with small FSes
I was working with some very small ext4 filesystems, used for
overlaying on immutable VM/container images.  If it's only desired to
overlay a single config file, these filesystems can be very small
indeed, and so ran afoul of this length check.

Since 4fc5ec56f ("device matching against UUIDs: do not try
floppies") (from 2009), floppy drives are skipped before this function
is even called.  Reading from an unused loop device returns 0, so it
should be fine to reduce  the minimum length.

Signed-off-by: Alyssa Ross via busybox <busybox@busybox.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-04 13:30:24 +01:00
Denys Vlasenko 72fbc81224 fdisk: code shrink
function                                             old     new   delta
new_partition                                       1054    1066     +12
list_table                                          1366    1370      +4
update_units                                          32      35      +3
list_disk_geometry                                    68      71      +3
get_geometry                                         535     538      +3
fdisk_fatal                                           38      41      +3
warn_cylinders                                        42      44      +2
xbsd_print_disklabel                                 836     834      -2
create_doslabel                                      110     108      -2
change_units                                          49      45      -4
xbsd_new_part                                        477     456     -21
add_partition                                       1278    1246     -32
.rodata                                           107059  107008     -51
fdisk_main                                          4775    4618    -157
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 7/7 up/down: 30/-269)          Total: -239 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-04 12:03:33 +01:00
Denys Vlasenko 8aba5f6347 fdisk: comment out "not a multiple of 512 bytes" warning
function                                             old     new   delta
bb_getsize_in_512sect                                187     163     -24
.rodata                                           107088  107059     -29
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-53)             Total: -53 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-04 10:30:45 +01:00
Denys Vlasenko 36eed984b8 fdisk: several fixes for 4K sector size
function                                             old     new   delta
bb_getsize_in_512sect                                  -     187    +187
list_disk_name_and_sizes                               -      80     +80
get_geometry                                         511     535     +24
.rodata                                           107066  107088     +22
msg_building_new_label                               143     142      -1
fdisk_main                                          4781    4775      -6
list_table                                          1423    1366     -57
list_disk_geometry                                   143      68     -75
bb_BLKGETSIZE_sectors                                191       -    -191
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 2/4 up/down: 313/-330)          Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-04 09:46:54 +01:00
Denys Vlasenko 93b684fe9f findfs: tweak --help
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-03 11:40:41 +01:00
Denys Vlasenko 3e80101963 uuidgen: move UUID formatting to libbb
function                                             old     new   delta
format_uuid_DCE_37_chars                               -      94     +94
uuidgen_main                                          71      53     -18
.rodata                                           107089  107066     -23
mkswap_main                                          278     253     -25
volume_id_set_uuid                                   258     178     -80
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 94/-146)           Total: -52 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-03 09:10:25 +01:00
Denys Vlasenko 4855fbe6a8 fdisk: uncomment -s support
function                                             old     new   delta
bb_BLKGETSIZE_sectors                                  -     191    +191
fdisk_main                                          4674    4774    +100
packed_usage                                       35941   35997     +56
.rodata                                           107069  107089     +20
get_geometry                                         665     511    -154
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 3/1 up/down: 367/-154)          Total: 213 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-02 15:26:03 +01:00
Denys Vlasenko 705c9b3487 devfsd: constify, code shrink
function                                             old     new   delta
static.copy_inode                                    613     608      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-5)               Total: -5 bytes
   text	   data	    bss	    dec	    hex	filename
1087619	    827	   5088	1093534	 10af9e	busybox_old
1087654	    787	   5088	1093529	 10af99	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-02 08:49:11 +01:00
Denys Vlasenko 4e815cd7b3 fdisk_sgi: formatting fixes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-02 05:19:26 +01:00
Denys Vlasenko 3b19867d97 fdisk: fix spurious warning about zero unused sectors
while at it, deindent nested for()

function                                             old     new   delta
verify_sun                                           429     447     +18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-01 14:36:06 +01:00
Denys Vlasenko 47775e8e6a fdisk: simplify start/len calcualtions for Sun labels
function                                             old     new   delta
new_partition                                       1060    1054      -6
fetch_sun                                            219     207     -12
verify_sun_cmp                                        54      39     -15
verify_sun                                           508     429     -79
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/4 up/down: 0/-112)           Total: -112 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-01 14:23:00 +01:00
Denys Vlasenko 7ac2bd6917 fdisk: eliminate static variables, fix GPT disk size (32x32->32 overflow)
function                                             old     new   delta
verify_sun                                           481     508     +27
.rodata                                           107016  107022      +6
verify_sun_cmp                                        51      54      +3
sun_other_endian                                       1       -      -1
scsi_disk                                              1       -      -1
floppy                                                 1       -      -1
xbsd_print_disklabel                                 838     836      -2
xbsd_new_part                                        479     477      -2
xbsd_write_bootstrap                                 397     394      -3
set_sun_partition                                    103     100      -3
delete_partition                                     435     432      -3
xbsd_part_index                                        4       -      -4
xbsd_part                                              4       -      -4
verify_sun_starts                                      4       -      -4
part_entry_len                                         4       -      -4
part_array                                             4       -      -4
n_parts                                                4       -      -4
gpt_hdr                                                4       -      -4
check_sun_label                                      214     208      -6
list_table                                          1433    1423     -10
fetch_sun                                            233     219     -14
bsd_select                                          1564    1546     -18
get_geometry                                         691     665     -26
get_boot                                            1539    1513     -26
fdisk_main                                          4737    4674     -63
------------------------------------------------------------------------------
(add/remove: 0/10 grow/shrink: 3/12 up/down: 36/-207)        Total: -171 bytes
   text	   data	    bss	    dec	    hex	filename
1078472	    555	   5088	1084115	 108ad3	busybox_old
1078332	    555	   5056	1083943	 108a27	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-01 13:44:54 +01:00
Osama Abdelkader via busybox 405afbd551 util-linux: add minimal uuidgen implementation
Add a simple uuidgen utility that generates RFC 4122 compliant
UUIDs (version 4, random). Uses the existing generate_uuid()
function from libbb and volume_id_set_uuid() for formatting.

Implementation suggested by Ulli.

Features:
- Generates standard format UUIDs: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
- RFC 4122 version 4 compliant
- Minimal implementation (~1.1 kb)
- NOFORK applet for efficiency
- Uses existing volume_id infrastructure for UUID formatting

function                                             old     new   delta
uuidgen_main                                           -      71     +71
applet_names                                        2862    2870      +8
.rodata                                           107010  107016      +6
applet_main                                         1648    1652      +4
applet_suid                                          103     104      +1
applet_install_loc                                   206     207      +1
applet_flags                                         103     104      +1
packed_usage                                       35952   35941     -11
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 6/1 up/down: 92/-11)             Total: 81 bytes

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-02-01 11:41:08 +01:00
Denys Vlasenko 2bfe3753d9 lkblk: list multiple MOUNTPOINTS
function                                             old     new   delta
lsblk_main                                           550     869    +319
.rodata                                           106977  107010     +33
process__sys_block_NAME                              461     356    -105
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 352/-105)          Total: 247 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-30 21:16:30 +01:00
Denys Vlasenko 8463ce06ca lsblk: add error messages and exit code when non-blockdevs are given
function                                             old     new   delta
process__sys_block_NAME                                -     461    +461
lsblk_main                                           511     550     +39
.rodata                                           106960  106977     +17
process_SYS_BLOCK_entry                              460       -    -460
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 2/0 up/down: 517/-460)           Total: 57 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-30 20:16:59 +01:00
Osama Abdelkader 8a347fd31a lsblk: new applet
Add a simple lsblk utility that lists information about block devices.
Reads from /sys/block to enumerate devices and displays their size,
type, and mount point.

Features:
- Lists all block devices or specific devices
- Shows device size in human-readable format (B, K, M, G, T, P)
- Shows device type (disk, loop, partition)
- Shows mount point if device is mounted
- Sorts devices alphabetically
- Minimal implementation (~2.5 kb)

Mostly rewritten by vda.linux

function                                             old     new   delta
lsblk_main                                             -     511    +511
process_SYS_BLOCK_entry                                -     460    +460
.rodata                                           106856  106960    +104
read_ull                                               -      81     +81
packed_usage                                       35924   35952     +28
compare_devices                                        -      25     +25
applet_names                                        2856    2862      +6
applet_main                                         1644    1648      +4
------------------------------------------------------------------------------
(add/remove: 5/0 grow/shrink: 4/0 up/down: 1219/0)           Total: 1219 bytes

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-30 12:23:42 +01:00
Denys Vlasenko 3fb6b31c71 tar: strip unsafe hardlink components - GNU tar does the same
Defends against files like these (python reproducer):

import tarfile
ti = tarfile.TarInfo("leak_hosts")
ti.type = tarfile.LNKTYPE
ti.linkname = "/etc/hosts"  # or "../etc/hosts" or ".."
ti.size = 0
with tarfile.open("/tmp/hardlink.tar", "w") as t:
	t.addfile(ti)

function                                             old     new   delta
skip_unsafe_prefix                                     -     127    +127
get_header_tar                                      1752    1754      +2
.rodata                                           106861  106856      -5
unzip_main                                          2715    2706      -9
strip_unsafe_prefix                                  102      18     -84
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/3 up/down: 129/-98)            Total: 31 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-29 12:01:56 +01:00
Denys Vlasenko 768ab5384c httpd: do not use a global variable in index.cgi
text	   data	    bss	    dec	    hex	filename
   3255	      0	      0	   3255	    cb7	httpd_indexcgi.o
   3253	      0	      4	   3257	    cb9	httpd_indexcgi.o.old

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-29 02:39:31 +01:00
Denys Vlasenko df1ef312a0 httpd: handle bare "Location: URL" redirects from CGIs
Many sites on the Web give those as valid CGI examples -
no "Status:", just "Location:".

function                                             old     new   delta
cgi_io_loop_and_exit                                 620     684     +64
log_cgi_status                                         -      49     +49
.rodata                                           106846  106861     +15
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/0 up/down: 128/0)             Total: 128 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-28 17:45:37 +01:00
Denys Vlasenko 03d6d1014a ash: fix \ooo octal printout in DEBUG code
function                                             old     new   delta
ash_main                                            1624    1645     +21

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-28 15:12:43 +01:00
Denys Vlasenko 56143ea63f ash: code shrink: eliminate pstrcmp1()
function                                             old     new   delta
find_command                                         961     963      +2
evalcommand                                         1631    1633      +2
hashcmd                                              299     300      +1
describe_command                                     320     321      +1
clearcmdentry                                         93      94      +1
cdcmd                                                695     696      +1
pstrcmp1                                              16       -     -16
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 6/0 up/down: 8/-16)              Total: -8 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-28 09:23:54 +01:00
Denys Vlasenko 758c948a63 ash: remove non-standard chdir builtin
function                                             old     new   delta
.rodata                                           106853  106846      -7
builtintab                                           352     344      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-15)             Total: -15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-28 01:34:13 +01:00
Denys Vlasenko 77d242d7ac ash: get rid of a static in cmdlookup()/delete_cmd_entry()
function                                             old     new   delta
cmdlookup_pp                                           -     120    +120
find_command                                         953     961      +8
unsetcmd                                              74      76      +2
hashcmd                                              297     299      +2
lastcmdentry                                           4       -      -4
delete_cmd_entry                                      47      43      -4
cmdlookup                                            132       -    -132
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 3/1 up/down: 132/-140)           Total: -8 bytes
   text	   data	    bss	    dec	    hex	filename
  47470	      8	    149	  47627	   ba0b	shell/ash.o.orig
  47466	      8	    145	  47619	   ba03	shell/ash.o

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-28 01:01:15 +01:00
Denys Vlasenko 2051c69358 ash: group command hashing/searching code together, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-28 00:34:22 +01:00
Denys Vlasenko e05b922c89 ash: move casematch() directly to its only caller, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 23:44:06 +01:00
Denys Vlasenko c9af9073b8 ash: reorder functions to reduce forward declarations, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 17:08:12 +01:00
Denys Vlasenko b715e82e1f ash: JOBSTOPPED can only be set if job control is compiled in - conditionalize code which depends on it
With !ASH_JOB_CONTROL:

function                                             old     new   delta
cmdloop                                              363     351     -12
exitcmd                                               47      31     -16
.rodata                                           106422  106398     -24
stoppedjobs                                           58       -     -58
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 0/3 up/down: 0/-110)           Total: -110 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 13:15:14 +01:00
Denys Vlasenko dee0168219 ash: reorder functions to reduce forward declarations, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 13:15:13 +01:00
Denys Vlasenko 97a7813971 ash: move applet handling out of tryexec() - making it similar to dash
function                                             old     new   delta
tryexec                                                -      60     +60
shellexec                                            476     349    -127
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 60/-127)           Total: -67 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 11:17:38 +01:00
Denys Vlasenko e4f4bf95ac doc: update docs/nofork_noexec.txt
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 08:13:42 +01:00
Denys Vlasenko 22b96c0ddf ash: unset traps before entering NOEXEC programs after [v]fork
If we don't do that, if INT trap was set, ^C will set a flag
"run trap later" and _return_, which is not expected by the NOFORK!

function                                             old     new   delta
clear_traps                                            -     107    +107
evalcommand                                         1617    1631     +14
shellexec                                            471     476      +5
setsignal                                            333     327      -6
forkchild                                            620     480    -140
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/2 up/down: 126/-146)          Total: -20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-27 08:03:15 +01:00
Denys Vlasenko 28e4d2b854 httpd: optimize example CGIs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-26 07:21:11 +01:00
Wouter Franken 4e82d99460 libbb/loop: fix existence check for LOOP_CONFIGURE ioctl
The LOOP_CONFIGURE ioctl is supported in 5.8 kernels and up. To have
backwards compatibility there is a config option CONFIG_TRY_LOOP_CONFIGURE
that will check if the ioctl exists and if not fall back to old way of
configuring loop devices.

Normally errno will be set to EINVAL when this ioctl does not exist.
However, when kernel config CONFIG_COMPAT is enabled, then compat_ioctl
is called. In that case -ENOIOCTLCMD is returned by loop device driver
and generic ioctl wrapper will set errno to ENOTTY. Because busybox
does not expect this it will fail to mount loop devices in this case.

This patch fixes the check for the existence of the ioctl LOOP_CONFIGURE
by checking if errno is one of both: EINVAL or ENOTTY.

function                                             old     new   delta
set_loop                                             809     821     +12

Signed-off-by: Wouter Franken <wouter.franken_ext@softathome.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-26 05:43:17 +01:00
Denys Vlasenko 4da1badf13 networking/httpd_indexcgi.c: non-mallocing version
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-26 04:48:28 +01:00
Denys Vlasenko 052b253696 httpd: add a TODO, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-25 08:17:23 +01:00
Denys Vlasenko 1db8aa2b59 ash: code shrink
function                                             old     new   delta
fg_bgcmd                                             294     296      +2
killpg                                                43       -     -43
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 1/0 up/down: 2/-43)             Total: -41 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 23:14:33 +01:00
Denys Vlasenko ea7d310ad6 httpd: allow static files in /cgi-bin/, do not search for interpreter twice
function                                             old     new   delta
handle_incoming_and_exit                            2270    2334     +64
send_cgi_and_exit                                    790     754     -36
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 64/-36)             Total: 28 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 17:11:39 +01:00
Denys Vlasenko 898cffe5f9 ash,hush: allow 0x in arith (bash supports it for 0x$v case when v='')
function                                             old     new   delta
parse_with_base                                      174     196     +22

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 14:37:22 +01:00
Denys Vlasenko a2f8c89aec httpd: code shrink
function                                             old     new   delta
send_file_and_exit                                   931     933      +2
get_line                                             126     120      -6
httpd_main                                           968     959      -9
send_headers                                         708     694     -14
handle_incoming_and_exit                            2285    2270     -15
cgi_io_loop_and_exit                                 635     620     -15
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/5 up/down: 2/-59)             Total: -57 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 13:29:50 +01:00
Denys Vlasenko 5cba59e9ce awk: use more understandable form of "split-globals" trick
function                                             old     new   delta
parse_expr                                           986     998     +12
chain_group                                          633     640      +7
next_token                                           930     934      +4
getvar_s                                             102     101      -1
awk_main                                             891     888      -3
evaluate                                            3379    3355     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/3 up/down: 23/-28)             Total: -5 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 05:43:45 +01:00
Denys Vlasenko 43982ed499 httpd: code shrink via "split-globals" trick
function                                             old     new   delta
httpd_main                                           957     968     +11
log_and_exit                                          25      26      +1
send_headers                                         712     708      -4
handle_incoming_and_exit                            2292    2285      -7
sigalrm_handler                                      102      93      -9
parse_conf                                          1332    1323      -9
send_cgi_and_exit                                    803     790     -13
cgi_io_loop_and_exit                                 656     635     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/6 up/down: 12/-63)            Total: -51 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 05:22:33 +01:00
Denys Vlasenko 1a64fe3594 httpd: implement POSTDATA read timeout, and -K KILLSECS CGI lifetime control
function                                             old     new   delta
cgi_io_loop_and_exit                                 496     656    +160
sigalrm_handler                                        1     102    +101
.rodata                                           106814  106853     +39
send_cgi_and_exit                                    770     803     +33
packed_usage                                       35894   35924     +30
httpd_main                                           950     957      +7
handle_incoming_and_exit                            2297    2292      -5
send_REQUEST_TIMEOUT_and_exit                         10       -     -10
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 6/1 up/down: 370/-15)           Total: 355 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-24 02:01:42 +01:00
Denys Vlasenko 927ff335c5 httpd: fix incorrect == comparison in last commit, must be !=
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-23 11:32:32 +01:00
Denys Vlasenko 5d33dbb67c httpd: smarter handling of CGI's "Status: " header
Do one less write()

function                                             old     new   delta
handle_incoming_and_exit                            2290    2297      +7
cgi_io_loop_and_exit                                 498     500      +2
.rodata                                           106821  106814      -7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 9/-7)                Total: 2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-23 11:04:28 +01:00
Denys Vlasenko a5f120b620 httpd: simplify CGI headers handling, check "HTTP/1.1" prefix, not just "HTTP"
function                                             old     new   delta
cgi_io_loop_and_exit                                 477     498     +21
.rodata                                           106830  106821      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 21/-9)              Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-23 10:14:04 +01:00
Denys Vlasenko 01ea35e81d httpd: simplify CGI code a bit, add a bunch of TODOs and FIXMEs
function                                             old     new   delta
log_and_exit                                          33      25      -8
handle_incoming_and_exit                            2298    2290      -8
send_cgi_and_exit                                    784     770     -14
cgi_io_loop_and_exit                                 538     477     -61
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/4 up/down: 0/-91)             Total: -91 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-23 02:18:30 +01:00
Denys Vlasenko 2d78809b74 httpd: do not force clean connection termination on write errors and timeouts
function                                             old     new   delta
send_file_and_exit                                   891     931     +40
send_EOF_and_exit                                      -      14     +14
cgi_io_loop_and_exit                                 535     538      +3
log_and_exit                                          44      33     -11
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 2/1 up/down: 57/-11)             Total: 46 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 22:35:58 +01:00
Denys Vlasenko 04d8729adb httpd: make timeout messages less confusing
function                                             old     new   delta
send_file_and_exit                                   891     930     +39

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 21:21:16 +01:00
Denys Vlasenko d8059bd827 httpd: time out data writes after 60 seconds of no progress
function                                             old     new   delta
prepare_write_timeout                                  -      29     +29
static.tv                                              -      16     +16
httpd_main                                           939     950     +11
send_file_and_exit                                   887     891      +4
handle_incoming_and_exit                            2306    2298      -8
cgi_io_loop_and_exit                                 552     535     -17
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 2/2 up/down: 60/-25)             Total: 35 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 17:22:06 +01:00
Denys Vlasenko c1ed0c4049 httpd: optimize header reading timeout code
Set up the signal handler once, outside of main loop.
Do not reset the timer if headers are big - they still are expected
to arrive quickly.

function                                             old     new   delta
httpd_main                                           913     939     +26
handle_incoming_and_exit                            2312    2306      -6
get_line                                             134     126      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 26/-14)             Total: 12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 15:49:58 +01:00
Denys Vlasenko 52a88341d6 httpd: when reading headers, abort if they are too long
function                                             old     new   delta
get_line                                             130     134      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 15:33:42 +01:00
Denys Vlasenko f0a63eefae httpd: reject request line and headers with control chars
This removes the need to check various corner cases later.

function                                             old     new   delta
get_line                                             108     130     +22

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 14:33:22 +01:00
Denys Vlasenko 851992f070 httpd: allow http2 requests if proxying, tighten METHOD checks
function                                             old     new   delta
handle_incoming_and_exit                            2264    2312     +48
httpd_main                                           915     913      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 48/-2)              Total: 46 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 13:58:28 +01:00
Denys Vlasenko 649da41ca4 httpd: fix compilation script of httpd_ratelimit_cgi.c
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 10:42:20 +01:00
Denys Vlasenko 3f36fe9c2f httpd: add -M MAXCONN - do not accept unlimited number of connections
We were lacking even basic rate-limiting.

function                                             old     new   delta
httpd_main                                           648     915    +267
handle_incoming_and_exit                            2235    2264     +29
packed_usage                                       35868   35894     +26
cgi_io_loop_and_exit                                 537     552     +15
send_headers                                         704     712      +8
get_line                                             106     108      +2
.rodata                                           106829  106830      +1
send_file_and_exit                                   890     887      -3
mini_httpd                                           161       -    -161
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 7/1 up/down: 348/-164)          Total: 184 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-22 01:58:46 +01:00
Denys Vlasenko 5ac9d0a865 httpd: stop disabling/enabling SIGHUP in every child
function                                             old     new   delta
sighup_handler                                        30      47     +17
httpd_main                                           710     695     -15
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 17/-15)              Total: 2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-21 19:16:29 +01:00
Denys Vlasenko 71c703c26b httpd: remove one close() from main loop
function                                             old     new   delta
httpd_main                                           701     710      +9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-21 19:01:42 +01:00
Denys Vlasenko 58b46b7d67 networking/httpd_ratelimit_cgi.c: new example CGI handler
text	   data	    bss	    dec	    hex	filename
   4003	     40	    352	   4395	   112b	httpd_ratelimit_cgi

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-21 18:47:56 +01:00
Denys Vlasenko 38721685af httpd: expand logging: now can see what CGIs are started
function                                             old     new   delta
send_cgi_and_exit                                    711     784     +73
vmstat_main                                          657     708     +51
.rodata                                           106746  106778     +32
send_file_and_exit                                   877     887     +10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 166/0)             Total: 166 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-21 17:49:40 +01:00
Denys Vlasenko b96342799f vmstat: fix I/O, int and ctxt rates: need to be divided by seconds
function                                             old     new   delta
vmstat_main                                          657     708     +51

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-20 01:34:08 +01:00
Denys Vlasenko 3a8d2db1ce vmstat: fixes for >4TB memory and long sampling intervals
function                                             old     new   delta
load_row                                             661    1061    +400
vmstat_main                                          561     657     +96
.rodata                                           106716  106746     +30
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 526/0)             Total: 526 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-20 00:41:47 +01:00
Denys Vlasenko 1ef0c69db4 vmstat: fix "vmstat N 0" to act compatibly (do not print infinitely)
function                                             old     new   delta
vmstat_main                                          559     561      +2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-19 02:52:06 +01:00
Denys Vlasenko afb92adf47 vmstat: smarter handling of header re-printing
function                                             old     new   delta
vmstat_main                                          230     559    +329
print_row                                            340       -    -340
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 329/-340)          Total: -11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-19 02:16:10 +01:00
Denys Vlasenko fd2ce3fa27 vmstat: show shorter, human-readable accumulating counts if they grow large
function                                             old     new   delta
print_row                                            247     340     +93
.rodata                                           106717  106716      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 93/-1)              Total: 92 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 18:57:37 +01:00
Denys Vlasenko 6ba6f5f6ab vmstat: reduce the chances of misaligned columns
function                                             old     new   delta
print_row                                            215     247     +32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 18:09:12 +01:00
Denys Vlasenko c21d8ff8c5 vmstat: code shrink
function                                             old     new   delta
load_row                                             667     661      -6
next_col                                             105      59     -46
coldescs                                             239     146     -93
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-145)           Total: -145 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 16:51:35 +01:00
David Leonard c385dac31c procps: new applet: vmstat
Adds a compact vmstat applet that matches the default behaviour
of procps's vmstat.

function                                             old     new   delta
load_row                                               -     667    +667
.rodata                                           106441  106717    +276
coldescs                                               -     239    +239
vmstat_main                                            -     230    +230
print_row                                              -     215    +215
next_col                                               -     105    +105
find_col                                               -      78     +78
packed_usage                                       35828   35868     +40
applet_names                                        2849    2856      +7
applet_main                                         1640    1644      +4
applet_install_loc                                   205     206      +1
------------------------------------------------------------------------------
(add/remove: 7/0 grow/shrink: 5/0 up/down: 1862/0)           Total: 1862 bytes

Signed-off-by: David Leonard <d+busybox@adaptive-enterprises.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 10:58:46 +01:00
Achill Gilgenast 6f43f948bc adduser: remove preconfigured GECOS full name field
Pre-configuring "Linux User" as Full Name is confusing a lot of users
downstream.[1] For example, in geary e-mails were sent out as "Linux
User"[2] and I also saw a couple of git commits with this name. This name
does not bring any more improvements than just leaving this field
empty, and let applications most likely fallback to the username.

Alternative would be to set the field to `&` (Capitalized username,
according to passwd(5)) or that we just set the GECOS field downstream.

[1] https://gitlab.postmarketos.org/postmarketOS/pmbootstrap/-/issues/2214
[2] https://gitlab.gnome.org/GNOME/geary/-/issues/1486

function                                             old     new   delta
.rodata                                           106455  106441     -14

Signed-off-by: Achill Gilgenast <achill@achill.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 03:17:00 +01:00
Martin Storsjö 993d416d02 md5/sha1sum: Honor the -b flag in the output
The output of md5sum/sha1sum contains a character to indicate
what mode was used to read the file - '*' for binary, and ' '
for text or where binary is insignificant.

This flag character makes a difference for the ffmpeg testsuite.
This testsuite contains a number of reference files (e.g. [1]),
containing the expected md5sum output for those files, which is
checked verbatim.

By making busybox's md5sum honor this flag in the output,
ffmpeg's testsuite can run successfully on top of busybox.

The flag is only partially implemented; in coreutils md5sum,
a later "-t" option overrides an earlier "-b" option. Here,
just check if a "-b" option was specified or not. Neither
flag affects how the files actually are read.

[1] https://code.ffmpeg.org/FFmpeg/FFmpeg/src/commit/894da5ca7d742e4429ffb2af534fcda0103ef593/tests/ref/acodec/flac

Signed-off-by: Martin Storsjö <martin@martin.st>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 03:09:52 +01:00
Denys Vlasenko fc9d352b4c cmp: fix -n causing all diffs to be output, implement size suffixes for SKIP
function                                             old     new   delta
packed_usage                                       35802   35828     +26
cmp_main                                             616     595     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 26/-21)              Total: 5 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 02:41:20 +01:00
Giorgi Tchankvetadze 3bfbce8312 cmp: stop skipping bytes if EOF is reached
Currently, if a skip value is larger than the file size, cmp will continue
to loop and call getc() until the skip count is satisfied, even though
EOF has been reached.

For large skip values (e.g., 1 billion), this results in significant
CPU waste and execution time (e.g., 11 seconds on a modern CPU).

This patch checks for EOF inside the skip loop and breaks early.

Test case:
$ touch empty.txt
$ time ./busybox cmp empty.txt empty.txt 1000000000 1000000000

Before:
real    0m10.937s

After:
real    0m0.002s

function                                             old     new   delta
cmp_main                                             594     616     +22

Signed-off-by: Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 01:41:19 +01:00
Denys Vlasenko 26e9afe22d coreutils: fixes for coreutils/id_test.sh script
Patch from Tito

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-18 01:37:53 +01:00
Giorgi Tchankvetadze 3b785b18d2 networking/udhcp: fix typo in comment
Signed-off-by: Giorgi Tchankvetadze <giorgitchankvetadze1997@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-01-14 08:08:26 +01:00
Denys Vlasenko d755846906 xxd: fix -pANYTHING handling (-pc50 does not mean -p -c50)
function                                             old     new   delta
packed_usage                                       35768   35802     +34
xxd_main                                            1447    1449      +2
.rodata                                           106438  106439      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 37/0)               Total: 37 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-30 06:13:15 +01:00
Denys Vlasenko b143b3f1d4 tls: better error message when TLS record is truncated
function                                             old     new   delta
.rodata                                           106388  106438     +50
tls_xread_record                                     650     681     +31
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 81/0)               Total: 81 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-25 02:47:10 +01:00
Denys Vlasenko 8d7ae80eda eject: fix missing -s option in trivial usage
Fixes missing [-s] option in trivial usage section of `eject --help`

function                                             old     new   delta
packed_usage                                       35125   35127      +2

Signed-off-by: Nir Lichtman <nir@lichtman.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-08 07:42:34 +01:00
Denys Vlasenko b8cf048880 dd: fix overflow for very large count/seek/skip values
function                                             old     new   delta
xatoull_range_sfx                                      -      49     +49
dd_main                                             1607    1640     +33
bb_banner                                             47      46      -1
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/1 up/down: 82/-1)              Total: 81 bytes

Signed-off-by: Sertonix <sertonix@posteo.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-08 07:42:34 +01:00
Denys Vlasenko 4ee218a2d2 pgrep/pkill: fix -x to also match comm field
When running `pgrep -x example` against a process `/bin/example --arg`,
BusyBox fails to match, while GNU pgrep succeeds. The reason is that the
comparison is done only against the full argv[0] rather than comm. This
patch changes pgrep -x to also try /proc/[pid]/comm for exact matching.

function                                             old     new   delta
pgrep_main                                           681     670     -11

Signed-off-by: Paulius Zaleckas <paulius.zaleckas@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-08 07:42:34 +01:00
Denys Vlasenko d549c8be86 ls: restore functionality of --color
Since commit 551bfdb97 (ls: implement -q, fix -w0, reduce startup
time) the '--color' option behaves as though the default argument
'always' had been specified.

This is due to an explicit short option for '--color' being given,
but without specifying that an argument is expected.

function                                             old     new   delta
.rodata                                           106027  106029      +2

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-08 07:42:34 +01:00
Denys Vlasenko 8cafd7a908 lineedit: fix PS1='\W' for root directory
'\W' in PS1 returned an empty string for the root directory.  bash
displays '/' in similar circumstances.

Avoid returning an empty string for the directory.

function                                             old     new   delta
parse_and_put_prompt                                 873     883     +10

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-08 07:42:34 +01:00
Denys Vlasenko 782e3fc2b4 last: fix ignoring the first login entry
The first login entry is ignored if a log file contains more than one
entry. To fix it, do not break the while loop if the offset is zero.

Signed-off-by: Dmitry Klochkov <dmitry.klochkov@bell-sw.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-11-08 07:42:34 +01:00
Denys Vlasenko b99a529177 busybox: optional --version support
function                                             old     new   delta
busybox_main                                         695     734     +39

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-13 21:56:47 +02:00
Denys Vlasenko 3ff3cb483d ntpd: set tmx.maxerror properly - avoid STA_UNSYNC
function                                             old     new   delta
update_local_clock                                   872     951     +79

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-11 23:48:04 +02:00
Denys Vlasenko 3621595939 nsenter,unshare: don't use xvfork_parent_waits_and_exits(), it SEGVs on ppc64le
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-08 14:49:26 +02:00
Denys Vlasenko a0017a5b50 cp: fix cp -aT overwriting symlink to directories
busybox cp refuses to overwrite another symlink to a directory due to
an incorrect stat() call that should be lstat(). When using -T, we want
to consider the target argument directly without resolving symlinks.

function                                             old     new   delta
cp_main                                              496     514     +18

Signed-off-by: Dominique Martinet <dominique.martinet@atmark-techno.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-07 10:05:08 +02:00
Denys Vlasenko 3cc2460952 chrt: support passing -p 0 to operate on self
Specifying a PID of 0 for the -p option of chrt would previously result
in a "number 0... not in range" error. Now, it means instead that the
calling process (i.e. chrt itself) should be operated on; this is to be
consistent with the behavior of util-linux's version of chrt.

function                                             old     new   delta
chrt_main                                            462     474     +12

Signed-off-by: Zuo An <zuoan.penguin@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-07 10:05:08 +02:00
Denys Vlasenko 552003dbd6 selinux: fix potential segfault in sestatus
Remove the puts(cterm) call that was likely leftover debugging code.
The controlling terminal name is already properly displayed via the
'Controlling term:' label, so the raw terminal name output was redundant
and could cause issues when cterm is NULL.

Also add proper cleanup for the allocated cterm string.

function                                             old     new   delta
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/0 up/down: 0/0)                 Total: 0 bytes

Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-07 10:05:08 +02:00
Denys Vlasenko 9443b0bc5e vi: warn about range in ':!' command
Currently vi in Busybox doesn't support filtering text through an
external command with ':1,2!cmd'.  Instead it behaves as if no
range had been supplied and displays the output of the command.

Issue a warning and do nothing in such cases.

function                                             old     new   delta
colon                                               3993    4010     +17

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-10-07 10:05:08 +02:00
Denys Vlasenko f5e1bf966b archival/libarchive: sanitize filenames on output (prevent control sequence attacks
This fixes CVE-2025-46394 (terminal escape sequence injection)

Original credit: Ian.Norton at entrust.com

function                                             old     new   delta
header_list                                            9      15      +6
header_verbose_list                                  239     244      +5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-09-24 03:30:12 +02:00
Denys Vlasenko 381a40a049 ash: change procargs() to match recent dash change
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-09-23 04:46:49 +02:00
Denys Vlasenko 3681b5f618 hush: changes to comments and whitespace, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-09-03 13:36:35 +02:00
Denys Vlasenko 106546961d ash: implement <<<here_string syntax
function                                             old     new   delta
write2pipe                                             -     133    +133
.rodata                                           105992  106009     +17
readtoken1                                          3101    3111     +10
cmdtxt                                               631     641     +10
nodesize                                              27      28      +1
redirect                                             961     916     -45
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 4/1 up/down: 171/-45)           Total: 126 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-09-02 11:46:11 +02:00
Denys Vlasenko b4cedd4c9a hush: fix several syntax corner cases with function definitions
function                                             old     new   delta
parse_stream                                        3063    3075     +12
done_word                                            777     784      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 19/0)               Total: 19 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-18 14:52:46 +02:00
Denys Vlasenko 5d66c8a602 hush: shrink "function" code
function                                             old     new   delta
done_word                                            766     777     +11
static.reserved_match                                 16      12      -4
reserved_list                                        240     168     -72
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 11/-76)            Total: -65 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-18 13:55:09 +02:00
Denys Vlasenko 5c2c2916fc hush: do not SEGV on if { echo foo; } then { echo bar; } fi
For some reason, it was only happening in interactive use

function                                             old     new   delta
initialize_context                                    39      54     +15
parse_stream                                        3077    3063     -14
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 15/-14)              Total: 1 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-18 13:37:09 +02:00
Denys Vlasenko 2bdec03def hush: disentangle keyword detection, no logic changes
function                                             old     new   delta
done_word                                            790     766     -24

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-18 13:14:26 +02:00
Denys Vlasenko 2ccb891819 hush: make "function" keyword support optional
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 17:59:30 +02:00
Denys Vlasenko 84d4ac3754 hush: with --login, errors /etc/profile in must not exit shell
function                                             old     new   delta
die_if_script                                         28      34      +6
hush_main                                           1146    1150      +4
run_list                                            1031    1028      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 10/-3)               Total: 7 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 17:39:04 +02:00
Denys Vlasenko 96466951bf hush: recognize "function FUNC { cmd; }" syntax
function                                             old     new   delta
reserved_list                                          -     240    +240
parse_stream                                        2923    3077    +154
done_word                                            771     790     +19
.rodata                                           105975  105992     +17
static.reserved_match                                 12      16      +4
static.reserved_list                                 168       -    -168
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 4/0 up/down: 434/-168)          Total: 266 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 14:33:00 +02:00
Denys Vlasenko a30882dec5 hush: remove always-true conditional
function                                             old     new   delta
parse_stream                                        2940    2923     -17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 13:47:34 +02:00
Denys Vlasenko 36f1b16b05 hush: fix infinite loop expanding alias a="nice&&a"
function                                             old     new   delta
parse_stream                                        2857    2940     +83
i_peek                                                55      69     +14
i_free_alias_buffer                                   33      37      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 101/0)             Total: 101 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 05:03:41 +02:00
Denys Vlasenko 1a947654b5 hush: comment fixes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 04:17:45 +02:00
Denys Vlasenko 94cb769b65 hush: make "alias" print aliases in properly escaped form
function                                             old     new   delta
print_pfx_escaped_nl                                   -      83     +83
builtin_alias                                        216     218      +2
.rodata                                           105985  105975     -10
parse_stream                                        2873    2857     -16
builtin_set                                          301     259     -42
builtin_readonly                                     107      59     -48
builtin_export                                       145      93     -52
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/5 up/down: 85/-168)           Total: -83 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 04:07:42 +02:00
Denys Vlasenko 7423bbbe98 hush: fix nested alias expansion
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 03:24:13 +02:00
Denys Vlasenko 5ba6ad7733 hush: optional alias support
function                                             old     new   delta
parse_stream                                        2540    2873    +333
i_getch                                               85     410    +325
builtin_alias                                          -     216    +216
builtin_unalias                                        -     185    +185
.rodata                                           105806  105985    +179
word_matches_alias                                     -      82     +82
find_alias_slot                                        -      77     +77
end_of_alias_name                                      -      69     +69
builtin_type                                         128     179     +51
i_free_alias_buffer                                    -      33     +33
enable_all_aliases                                     -      29     +29
bltins1                                              396     420     +24
o_reset_to_empty_unquoted                              -      21     +21
run_pipe                                            1554    1566     +12
i_peek                                                57      55      -2
parse_redirect                                       351     346      -5
redirect_opt_num                                      63      53     -10
encode_then_append_var_plusminus                     552     532     -20
done_word                                            796     771     -25
i_getch_interactive                                  308       -    -308
------------------------------------------------------------------------------
(add/remove: 8/1 grow/shrink: 6/5 up/down: 1636/-370)        Total: 1266 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-17 02:51:35 +02:00
Denys Vlasenko 5806d2a3db hush: optimization in set_local_var()
function                                             old     new   delta
set_local_var                                        416     409      -7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-16 01:53:46 +02:00
Denys Vlasenko 3e766dce5f hush: implement <<<here_string syntax
function                                             old     new   delta
setup_heredoc                                        299     351     +52
parse_stream                                        2514    2540     +26
parse_redirect                                       335     351     +16
redir_table                                           40      48      +8
static.setup_redirects                               394     400      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/0 up/down: 108/0)             Total: 108 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-15 00:08:11 +02:00
Denys Vlasenko 0d1f6a54f7 hush: allow faster parsing for "./:@" characters
function                                             old     new   delta
parse_stream                                        2513    2514      +1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 20:08:19 +02:00
Denys Vlasenko a8f20420a5 hush: shrink syntax error handling
Was trying to add code to reject more invalid "case" syntaxes, but it's not that easy

function                                             old     new   delta
done_word                                            795     796      +1
parse_stream                                        2529    2513     -16
.rodata                                           105825  105806     -19
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 1/-35)             Total: -34 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 19:47:20 +02:00
Denys Vlasenko 6cc3380105 hush: undo incorrect change which allows a'b'=c to be assignment
While at it, remove now-unused WORD_IS_KEYWORD

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 16:19:58 +02:00
Denys Vlasenko cad5a79bd4 hush: explain "empty quoted str marker" trick
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 12:03:24 +02:00
Denys Vlasenko 4343ca9aa8 hush: improve code readability, no logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 11:08:08 +02:00
Denys Vlasenko 279371471e hush: move tickquote1.tests to hush-bugs/ - it's a known bug
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 05:02:07 +02:00
Denys Vlasenko d029e80187 hush: remove the is_blank dance
function                                             old     new   delta
parse_stream                                        2566    2524     -42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 04:04:57 +02:00
Denys Vlasenko 2bb8b9b2a4 hush: remove two strchr's from the hottest parsing loop
function                                             old     new   delta
parse_stream                                        2572    2566      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-14 02:30:32 +02:00
Denys Vlasenko 438b92efdd hush: optimize decoding of $'str' - avoid extra function call if we can
function                                             old     new   delta
parse_stream                                        2565    2572      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-13 23:20:10 +02:00
Denys Vlasenko f29ab91763 hush: shrink i_getch, rename two functions
Final link with: <none>
function                                             old     new   delta
i_getch_interactive                                    -     308    +308
i_getch                                              102      85     -17
fgetc_interactive                                    309       -    -309
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 308/-326)          Total: -18 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-13 17:30:48 +02:00
Denys Vlasenko 187f24b490 hush: ~5% faster parsing of typical shell scripts
0-9,A-Z,a-z are never special and just go into the current word.

function                                             old     new   delta
parse_stream                                        2476    2565     +89

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-13 10:01:16 +02:00
Denys Vlasenko a5cf673c9c hush: create a macro IS_NULL_WORD to test for null shell word
No logic changes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-13 02:30:09 +02:00
Denys Vlasenko 1847fee2d4 hush: fix a corner case in "case" stmt, ctx_dsemicolon is in fact unused
function                                             old     new   delta
parse_stream                                        2446    2476     +30
done_word                                            797     800      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 33/0)               Total: 33 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-13 00:51:44 +02:00
Denys Vlasenko f161bc628f hush: allow nested negation "! ! ! CMD" - bash 5.2.15 allows it
Also, deindent "ch == EOF" code branch in parse_stream()

function                                             old     new   delta
done_word                                            799     797      -2
parse_stream                                        2453    2446      -7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-9)               Total: -9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-12 20:29:26 +02:00
Denys Vlasenko 2b0b74e8b4 hush: drop ctx_inverted, use pipe->pi_inverted
function                                             old     new   delta
done_word                                            776     799     +23
parse_stream                                        2456    2453      -3
done_pipe                                            252     242     -10
.rodata                                           105837  105825     -12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 23/-25)             Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-12 20:29:26 +02:00
Denys Vlasenko 5ecbed0e26 hush: do not segfault on "for </dev/null v in..."
This is not accepted by bash, we may also disallow this,
but for now, at least do not crash

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-12 17:56:58 +02:00
Denys Vlasenko ab1de7df99 hush: test for, and disallow several invalid syntaxes
function                                             old     new   delta
parse_stream                                        2292    2456    +164
done_pipe                                            231     252     +21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 185/0)             Total: 185 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-11 23:18:01 +02:00
Denys Vlasenko 1cd53c15a2 ash: parser: Invalid redirections are run-time, not syntax errors
Upstream commit

    Date: Wed, 14 Dec 2022 02:06:05 +0100
    parser: Invalid redirections are run-time, not syntax errors

    This fixes a long-standing bug where
      echo 'echo >&a' | sh
    errors out with
      sh: 2: Syntax error: Bad fd number
    despite the error being on line 1

    This patch makes the error
      sh: 1: Bad fd number: a
    as expected

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-11 18:43:02 +02:00
Denys Vlasenko 0da6c813e1 hush: fix var_backslash1.tests
function                                             old     new   delta
o_addqblock                                            -     131    +131
append_str_maybe_ifs_split                            53     100     +47
expand_one_var                                      1872    1897     +25
encode_then_expand_vararg                            380     399     +19
sig_unblock                                           41      43      +2
sig_block                                             41      40      -1
sigprocmask_allsigs                                   33      31      -2
expand_vars_to_list                                 1080    1077      -3
wait_for_child_or_signal                             202     193      -9
o_addQstr                                            175      42    -133
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 4/5 up/down: 224/-148)           Total: 76 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-11 17:36:02 +02:00
Denys Vlasenko d18c9eadf0 shells: testcase: add another test for EINTR on fifo open
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-11 14:10:17 +02:00
Denys Vlasenko e660eab458 *: code shrink using sigprocmask2() where appropriate
function                                             old     new   delta
sig_unblock                                           41      43      +2
sig_block                                             41      40      -1
sigprocmask_allsigs                                   33      31      -2
wait_for_child_or_signal                             202     193      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 2/-12)             Total: -10 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-11 01:17:02 +02:00
Denys Vlasenko ea2022efb3 ash: converge waiting code to dash in its form, add comments, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-10 23:39:44 +02:00
Denys Vlasenko f6fb3c603a ash: move 100 bytes off global .data / .bss, no logic changes
text	   data	    bss	    dec	    hex	filename
1067871	    559	   5184	1073614	 1061ce	busybox_old
1068067	    555	   5088	1073710	 10622e	busybox_unstripped
            ^^^^^^^^^^^
function                                             old     new   delta
pgetc                                                580     623     +43
parse_command                                       1633    1651     +18
ash_main                                            1226    1239     +13
popstring                                            115     126     +11
redirect                                             951     961     +10
popfile                                              105     115     +10
expandstr                                            252     262     +10
evalbltin                                            306     314      +8
pushstring                                           155     162      +7
pushfile                                              31      38      +7
freestrings                                           90      97      +7
setinputstring                                        68      74      +6
readtoken1                                          3095    3101      +6
pungetc                                                9      15      +6
nlprompt                                              39      45      +6
nlnoprompt                                            33      39      +6
unwindfiles                                           20      25      +5
dotcmd                                               309     314      +5
setinputfile                                         190     194      +4
init                                                 429     432      +3
forkchild                                            617     620      +3
evalcommand                                         1616    1617      +1
ash_vmsg                                             141     142      +1
g_parsefile                                            4       -      -4
commandname                                            4       -      -4
basepf                                                84       -     -84
------------------------------------------------------------------------------
(add/remove: 0/3 grow/shrink: 23/0 up/down: 196/-92)          Total: 104 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-10 20:18:10 +02:00
Denys Vlasenko 9b67dde8cd ash: redir: Retry open on EINTR
Upstream commit:

    Date: Thu, 28 May 2020 21:31:45 +1000
    redir: Retry open64 on EINTR

    It is possible for open64 to block on named pipes, and therefore
    it can be interrupted by signals and return EINTR.  We should only
    let it fail with EINTR if real signals are pending (i.e., it should
    not fail on SIGCHLD if SIGCHLD has not been trapped).

    This patch adds a new helper sh_open to retry the open64 call if
    necessary.  It also calls sh_error when appropriate.

    Fixes: 3800d4934391 ("[JOBS] Fix dowait signal race")

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 20:17:31 +02:00
Denys Vlasenko 81274d8b30 ash: eval: Reset handler when entering a subshell
Upstream commit:

    Date: Sun, 3 Mar 2019 21:57:50 +0800
    eval: Reset handler when entering a subshell

    As it is a subshell can execute code that is only meant for the
    parent shell when it executes a longjmp that is caught by something
    like evalcommand.  This patch fixes it by resetting the handler
    when entering a subshell.

function                                             old     new   delta
evalsubshell                                         169     183     +14
evalpipe                                             342     356     +14
argstr                                              1406    1416     +10
ash_main                                            1236    1226     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/1 up/down: 65/-10)             Total: 28 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 17:52:09 +02:00
Denys Vlasenko 4ce8afe6b2 ahs: jobs: Block signals during tcsetpgrp
Upstream commit:

    Date: Wed, 6 Jan 2021 15:45:12 +1100
    jobs: Block signals during tcsetpgrp

    Harald van Dijk <harald@gigawatt.nl> wrote:
    > On 19/12/2020 22:21, Steffen Nurpmeso wrote:
    >> Steffen Nurpmeso wrote in
    >>   <20201219172838.1B-WB%steffen@sdaoden.eu>:
    >>   |Long story short, after falsely accusing BSD make of not working
    >>
    >> After dinner i shortened it a bit more, and attach it again, ok?
    >> It is terrible, but now less redundant than before.
    >> Sorry for being so terse, that problem crosses my head for about
    >> a week, and i was totally mislead and if you bang your head
    >> against the wall so many hours bugs or misbehaviours in a handful
    >> of other programs is not the expected outcome.
    >
    > I think a minimal test case is simply
    >
    > all:
    >         $(SHELL) -c 'trap "echo TTOU" TTOU; set -m; echo all good'
    >
    > unless I accidentally oversimplified.
    >
    > The SIGTTOU is caused by setjobctl's xtcsetpgrp(fd, pgrp) call to make
    > its newly started process group the foreground process group when job
    > control is enabled, where xtcsetpgrp is a wrapper for tcsetpgrp. (That's
    > in dash, the other variants may have some small differences.) tcsetpgrp
    > has this little bit in its specification:
    >
    >        Attempts to use tcsetpgrp() from a process which is a member of
    >        a background process group on a fildes associated with its con‐
    >        trolling  terminal  shall  cause the process group to be sent a
    >        SIGTTOU signal. If the calling thread is blocking SIGTTOU  sig‐
    >        nals  or  the  process is ignoring SIGTTOU signals, the process
    >        shall be allowed to perform the operation,  and  no  signal  is
    >        sent.
    >
    > Ordinarily, when job control is enabled, SIGTTOU is ignored. However,
    > when a trap action is specified for SIGTTOU, the signal is not ignored,
    > and there is no blocking in place either, so the tcsetpgrp() call is not
    > allowed.
    >
    > The lowest impact change to make here, the one that otherwise preserves
    > the existing shell behaviour, is to block signals before calling
    > tcsetpgrp and unblocking them afterwards. This ensures SIGTTOU does not
    > get raised here, but also ensures that if SIGTTOU is sent to the shell
    > for another reason, there is no window where it gets silently ignored.
    >
    > Another way to fix this is by not trying to make the shell start a new
    > process group, or at least not make it the foreground process group.
    > Most other shells appear to not try to do this.

    This patch implements the blocking of SIGTTOU (and everything else)
    while we call tcsetpgrp.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 17:39:44 +02:00
Denys Vlasenko df154028dc ash: eval: Add vfork support
Upstream commit:

    Date: Sat, 19 May 2018 02:39:56 +0800
    eval: Add vfork support

    This patch adds basic vfork support for the case of a simple command.

Upstream commit:

    Date: Tue, 12 Jan 2021 17:11:19 +1100
    jobs: Always reset SIGINT/SIGQUIT handlers

    On Fri, Jan 08, 2021 at 08:55:41PM +0000, Harald van Dijk wrote:
    > On 18/05/2018 19:39, Herbert Xu wrote:
    > > This patch adds basic vfork support for the case of a simple command.
    > > ...  @@ -879,17 +892,30 @@ forkchild(struct job *jp, union node *n, int
    > > mode)
    > >   		}
    > >   	}
    > >   	if (!oldlvl && iflag) {
    > > -		setsignal(SIGINT);
    > > -		setsignal(SIGQUIT);
    > > +		if (mode != FORK_BG) {
    > > +			setsignal(SIGINT);
    > > +			setsignal(SIGQUIT);
    > > +		}
    > >   		setsignal(SIGTERM);
    > >   	}
    > > +
    > > +	if (lvforked)
    > > +		return;
    > > +
    > >   	for (jp = curjob; jp; jp = jp->prev_job)
    > >   		freejob(jp);
    > >   }
    >
    > This leaves SIGQUIT ignored in background jobs in interactive shells.
    >
    >   ENV= dash -ic 'dash -c "kill -QUIT \$\$; echo huh" & wait'
    >
    > As of dash 0.5.11, this prints "huh". Before, the subprocess process killed
    > itself before it could print anything. Other shells do not leave SIGQUIT
    > ignored.
    >
    > (In a few other shells, this also prints "huh", but in those other shells,
    > that is because the inner shell chooses to ignore SIGQUIT, not because the
    > outer shell leaves it ignored.)

    Thanks for catching this.  I have no idea how that got in there
    and it makes no sense whatsoever.  This patch removes the if
    conditional.

    Fixes: e94a964e7dd0 ("eval: Add vfork support")

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 17:36:18 +02:00
Denys Vlasenko 9f490785e0 ash: rename got_sigchld, doing_jobctl, and INT_ON/OFF to match dash
Comparing code with dash is more difficult with these differences.
(We didn't know back then that dash will be revived...)

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 17:17:48 +02:00
Denys Vlasenko 53b3854e81 ash: fix fallout of no-more-set commandname
Testsuite reports lots of message mismatches, fix that

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 17:04:16 +02:00
Denys Vlasenko c92755133b shells: fix a typo in var_backslash1.tests, expand it while at it
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 13:00:55 +02:00
Denys Vlasenko 4eb4141b22 ash: eval: Always set exitstatus in evaltree
Upstream commit:

    Date: Tue, 6 Dec 2022 16:49:14 +0800
    eval: Always set exitstatus in evaltree

    There is no harm in setting exitstatus unconditionally in evaltree.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 12:23:21 +02:00
Denys Vlasenko 6d44762589 ash: options: Do not set commandname in procargs
Upstream commit:

    Date:   Mon Feb 25 12:49:20 2019 +0800
    options: Do not set commandname in procargs

    We set commandname in procargs when we don't have to.  This results
    in a duplicated output of arg0 when an error occurs.

function                                             old     new   delta
ash_main                                            1256    1236     -20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 02:26:51 +02:00
Denys Vlasenko 98b1a000c9 ash: jobs: drop unused node parameter in makejob()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 02:02:04 +02:00
Denys Vlasenko fa82ef1a2e shells: add testsuite item
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-09 01:48:12 +02:00
Denys Vlasenko 5b3405594a ash: reuse vstype_suffix[] in debug code, shrink it
function                                             old     new   delta
vstype_suffix                                          -      39     +39
static.vstype                                         42       -     -42
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/0 up/down: 39/-42)             Total: -3 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-08 12:40:44 +02:00
Denys Vlasenko 422f4ede6f ash: fix cmdputs - was showing some variable forms incorrectly
function                                             old     new   delta
cmdputs                                              402     418     +16
static.vstype                                         48      42      -6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 16/-6)              Total: 10 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-07 23:42:45 +02:00
Denys Vlasenko 34948f1858 hush: smarter optimization for not-globbing [ and [[
function                                             old     new   delta
o_save_ptr                                           176     167      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-07 02:46:04 +02:00
Denys Vlasenko abab146b82 ash: fix heredoc.tests broken by last commit
function                                             old     new   delta
readtoken1                                          3053    3095     +42
xxreadtoken                                          215     212      -3
expandstr                                            255     252      -3
parseheredoc                                         148     127     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 42/-27)             Total: 15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-07 02:26:25 +02:00
Denys Vlasenko 7648dc721e ash,hush: fix corner cases with backslash-newlines in heredocs
function                                             old     new   delta
fetch_heredocs                                       477     485      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-07 01:30:57 +02:00
Denys Vlasenko 558ef4962d hush: optimization: do not glob words "[" and "[["
function                                             old     new   delta
glob_needed                                           71      86     +15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-07 00:20:56 +02:00
Denys Vlasenko 8f5d890071 showkey: make -a, -k, -s mutually exclusive
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-06 21:52:04 +02:00
Denys Vlasenko 0b05a4e71e top,pmap: speed up /smaps parsing
function                                             old     new   delta
procps_read_smaps                                    515     529     +14
procps_get_maps                                      685     665     -20
.rodata                                           105847  105820     -27
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 14/-47)            Total: -33 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-06 14:42:06 +02:00
Denys Vlasenko 47d27cdaff libbb: fix too-narrow variable in procps_read_smaps() causing incorrect sizes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-06 14:04:49 +02:00
Denys Vlasenko 40c2d01da2 libbb: make read_cmdline() replace chars 1..31 with '?', not space
Space was too inconspicuous on output

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-06 14:02:05 +02:00
Denys Vlasenko 8bde71eb15 top: simplify command line reading
function                                             old     new   delta
cmdline_to_line_buf_and_print                          -      48     +48
read_cmdline                                         326     327      +1
display_topmem_process_list                          523     505     -18
display_process_list                                1186    1161     -25
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/2 up/down: 49/-43)              Total: 6 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-06 00:42:05 +02:00
Denys Vlasenko 1bd8d714ca top: disentangle printing logic
function                                             old     new   delta
print_line_buf                                         -      78     +78
print_line_bold                                        -      50     +50
top_main                                            1043    1091     +48
handle_input                                         708     714      +6
do_stats                                             186     192      +6
.rodata                                           115543  115526     -17
display_topmem_process_list                          748     523    -225
display_process_list                                1432    1186    -246
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 3/3 up/down: 188/-488)         Total: -300 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-06 00:05:44 +02:00
Denys Vlasenko 2363938883 top: consistently NOT use the last column of the display
function                                             old     new   delta
.rodata                                           115537  115543      +6
top_main                                            1047    1043      -4
display_process_list                                1459    1432     -27
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 6/-31)             Total: -25 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 19:37:43 +02:00
Denys Vlasenko 5a8c03039f pmap: increase max handled command line length to 4k
function                                             old     new   delta
procps_get_maps                                      181     779    +598
read_smaps                                           563       -    -563
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 598/-563)           Total: 35 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 14:35:14 +02:00
Denys Vlasenko d16bde623c top,pmap: do not use common code for reading /proc/PID/smaps
The logic is in fact quite far from common.

While at it, stop accounting "---p" mappings as mapped (e.g. VSZ in top).
Nothing is mapped there (why would kernel waste RAM to map pages
which can't be accessed?).

function                                             old     new   delta
read_smaps                                             -     562    +562
read_cmdline                                         315     326     +11
print_smaprec                                         97     101      +4
procps_scan                                         1219    1211      -8
.rodata                                           115541  115533      -8
skip_whitespace_if_prefixed_with                      25       -     -25
procps_read_smaps                                    864     577    -287
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 2/3 up/down: 577/-328)          Total: 249 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 14:21:51 +02:00
Denys Vlasenko 58b2353baa top: improve response time to keyboard input
function                                             old     new   delta
handle_input                                         674     708     +34
top_main                                            1019    1047     +28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 62/0)               Total: 62 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 04:30:59 +02:00
Denys Vlasenko 3aa2bee269 top: reduce flicker: redraw screen with "clear to EOL" commands, not one "clear screen"
function                                             old     new   delta
display_topmem_process_list                          680     748     +68
display_process_list                                1403    1459     +56
.rodata                                           115512  115541     +29
top_main                                            1014    1019      +5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 158/0)             Total: 158 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 03:40:36 +02:00
Denys Vlasenko 1044533ea9 top: make uppercase 'S' walk topmem in opposite direction
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 03:13:01 +02:00
Denys Vlasenko d647d8aaba top: show RSS instead of VSF, virtual mapped size is often meaningless
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 03:07:40 +02:00
Denys Vlasenko c229982b33 top: fix display of very large VSZ
function                                             old     new   delta
display_process_list                                1366    1403     +37
handle_input                                         628     636      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 45/0)               Total: 45 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 02:57:05 +02:00
Denys Vlasenko c1b5c35246 top: do not rescan processes on second 's'
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-05 01:25:01 +02:00
Denys Vlasenko 5f3a986c9e libbb: simplify concat_path_file()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-04 22:27:40 +02:00
Denys Vlasenko a33ce612b5 libbb: much faster concat_path_file()
function                                             old     new   delta
concat_path_file                                      68     127     +59

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-04 19:21:45 +02:00
Denys Vlasenko d7d8ffed87 shell: typo and whitespace fixes, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 23:29:35 +02:00
Denys Vlasenko 02b518db1c hush: fix memory leak caused by compiler optimizing out a store
function                                             old     new   delta
generate_stream_from_string                          222     232     +10
setup_heredoc                                        329     330      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 20:42:52 +02:00
Denys Vlasenko 58a54fbd5a hush: disentangle interactiveness/job_control setup code
...and discover that we can do away with 1-3 initialization syscalls.

function                                             old     new   delta
hush_main                                           1152    1146      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 17:37:32 +02:00
Denys Vlasenko 778fce3e70 hush: fix build failure if !CONFIG_HUSH_JOB
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 16:22:21 +02:00
Denys Vlasenko dba57344b5 hush: make NORETURN declarations lees verbose, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 16:14:19 +02:00
Denys Vlasenko 4539262b6a hush: do not save history on xfunc error, it's unsafe
Also, make second calls to install_special_sighandlers() less haphazard.
It's not a fix for anything, but looking more organized now.

function                                             old     new   delta
fflush_restore_ttypgrp_and__exit                       -      20     +20
restore_ttypgrp_and__exit                             21       -     -21
hush_main                                           1181    1152     -29
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 20/-50)            Total: -30 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 16:12:00 +02:00
Noelle Leigh 26fdc7c6ef docs: Add links to cmd description from cmd list
In the generated `docs/busybox.pod` file, add a link for each command in
the big command list that goes to that command's description, like a
compact table of contents. This seems to only affect the generated HTML
version of the usage page.

To add `id` attributes to each usage section title, each command now
uses `=head2` instead of `=item` for their section heading.

To add links to each command in the list, the list was unindented so
that it could use rich text, and each command was marked as code text
(C<>) so they are styled in monospace. These changes mean that the HTML
and mandoc command list will expand to fit the available width of the
viewport, rather than wrapping at a fixed line-length. The plain text
version retains its existing wrapping behavior.

Because of the new code text formatting, `--quotes=none` was added to
the pod2man and pod2text invocations in Makefile.custom to prevent the
command list from quoting every single command.

Signed-off-by: Noelle Leigh <noelle@noelle.dev>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 10:53:20 +02:00
Denys Vlasenko c2ef7c6dad hush: if !JOBS, skip tests which wouldn't work
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 09:32:36 +02:00
Denys Vlasenko cdbb6957f1 hush: don't save history in subshells; on NOMMU, don't be interactive on reexec
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 01:26:25 +02:00
Denys Vlasenko e591316e02 hush: rename hush_exit to save_history_run_exit_trap_and_exit, sigexit to restore_ttypgrp_and_killsig_or__exit
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 00:44:32 +02:00
Denys Vlasenko 7d782e8813 shell: fix the check of empty HISTFILE
The check for "" history file is done on a wrong state pointer.

Fixes: shell: empty HISTFILE disables history saving, just as unset one did

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-03 00:11:11 +02:00
Denys Vlasenko 91d8b4eb5c ftpd: code shrink, move replace_char() to libbb
function                                             old     new   delta
modprobe_main                                        803     804      +1
escape_text                                          127     122      -5
replace                                               18       -     -18
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/1 up/down: 1/-23)             Total: -22 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-02 07:18:56 +02:00
Denys Vlasenko 2d7ff2c909 ls: don't do unnecessary tty operations when called from ftpd
function                                             old     new   delta
ls_main                                              660     690     +30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-01 18:16:46 +02:00
Denys Vlasenko 4f43bda947 ls: code shrink
Looks like gcc can figure this out by itself, but let's be explicit

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-01 12:10:22 +02:00
Denys Vlasenko 0fea54a983 libbb/dump: much faster formatting of %_u on x86
function                                             old     new   delta
display                                             1485    1481      -4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-01 03:01:38 +02:00
Denys Vlasenko e95086b2fa libbb/yescrypt: code shrink
function                                             old     new   delta
static.PBKDF2_SHA256                                 219     165     -54

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-01 02:21:38 +02:00
Denys Vlasenko 4f3a56dc12 ls: fix -Q to match GNU
function                                             old     new   delta
print_name                                           137     229     +92
display_files                                        375     402     +27
c_escape_conv_str00                                    -      24     +24
display                                             1476    1485      +9
conv_str                                              33       -     -33
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 3/0 up/down: 152/-33)           Total: 119 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-08-01 01:02:43 +02:00
Denys Vlasenko bb18473216 ls: lack of -q should not suppress -Q
function                                             old     new   delta
print_name                                           134     137      +3
display_files                                        374     375      +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>
2025-07-31 19:24:08 +02:00
Denys Vlasenko 551bfdb97f ls: implement -q, fix -w0, reduce startup time
function                                             old     new   delta
ls_main                                              598     660     +62
ls_longopts                                            -      47     +47
G_isatty                                               -      36     +36
print_name                                           102     134     +32
display_files                                        358     374     +16
.rodata                                           105829  105833      +4
vgetopt32                                           1330    1317     -13
static.ls_longopts                                    47       -     -47
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 4/1 up/down: 197/-60)           Total: 137 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-31 18:35:11 +02:00
Denys Vlasenko a98b95b715 *: use safe_waitpid() or wait_any_nohang() where approppriate
function                                             old     new   delta
crond_main                                          1227    1237     +10
init_main                                            804     794     -10
wait_one                                             263     252     -11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 10/-21)            Total: -11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-30 20:02:23 +02:00
Valentin Lab 41f677ec5d crond: reap orphaned grandchildren to prevent zombie buildup
If a cron job launches a background task, e.g. `sh -c "sleep 5 &"`,
the shell exits immediately and the `sleep` process is re-parented to
PID 1.  When BusyBox `crond` itself happens to be PID 1 (common in a
minimal container), those orphans become direct children of `crond`.
Because `crond` only calls waitpid() for the PIDs it explicitly tracks,
these processes remain forever in Z state and the container slowly
fills with zombies.

Add a small `while (waitpid(-1, NULL, WNOHANG) > 0)` sweep at the end
of check_completions() so any stray children are reaped.  When `crond`
is not PID 1 the loop returns -ECHILD immediately, so behaviour and
overhead on a normal system are unchanged.

Size impact: +12 bytes on x86-64 (gcc 13.3.0 -Os, static)

Signed-off-by: Valentin Lab <valentin.lab@kalysto.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-30 19:49:23 +02:00
Ladislav Michl 427f808732 date: return failure exit code on clock_settime error
Signed-off-by: Ladislav Michl <ladis@linux-mips.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-30 19:44:39 +02:00
Denys Vlasenko 65deb9f7dd sha3sum: add -aBITS tests
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-30 19:11:26 +02:00
Andy Knowles dcbb69e0a5 sha384sum: new applet
function                                             old     new   delta
sha512384_end                                          -     198    +198
packed_usage                                       35021   35134    +113
init384                                                -      80     +80
sha384_begin                                           -      19     +19
sha384_end                                             -      10     +10
applet_names                                        2823    2833     +10
md5_sha1_sum_main                                    501     507      +6
sha3_end                                              54      59      +5
applet_main                                         1628    1632      +4
show_usage_if_dash_dash_help                          79      72      -7
hash_file                                            358     344     -14
sha512_end                                           197      10    -187
------------------------------------------------------------------------------
(add/remove: 4/0 grow/shrink: 5/3 up/down: 445/-208)          Total: 237 bytes

Signed-off-by: Andy Knowles <aknowles@galleonec.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-30 18:39:46 +02:00
Denys Vlasenko 628a7b2f47 telnetd: improve --help
function                                             old     new   delta
packed_usage                                       34996   35021     +25

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-27 14:24:23 +02:00
Denys Vlasenko e022ff88d1 libbb: SHA-NI - document that unpckhpd also works, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-22 16:43:22 +02:00
Denys Vlasenko ed22c5bd4a libbb: SHA-NI code shrink
function                                             old     new   delta
sha256_process_block64_shaNI                         673     657     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-22 00:12:54 +02:00
Denys Vlasenko d23ad55904 libbb: change define names in SHA-NI code to match kernel source more closely
No code changes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-21 08:45:02 +02:00
Denys Vlasenko 77a49a61b2 libbb/yescrypt: de-unroll salsa20()
function                                             old     new   delta
salsa20                                              760     296    -464

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-20 08:42:51 +02:00
Denys Vlasenko c6b9e76373 libbb: crypt_make_pw_salt(): fix yescrypt's random salt last char
function                                             old     new   delta
crypt_make_pw_salt                                   128     146     +18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-19 18:42:32 +02:00
Denys Vlasenko 6979467a62 cryptpw: fix detection of crypt algo from salt (was broken if default isn't DES)
The symptom is: "cryptpw ... implicit" testsuite tests were failing
if CONFIG_FEATURE_DEFAULT_PASSWD_ALGO is not "des".

function                                             old     new   delta
cryptpw_main                                         223     283     +60
pw_encrypt                                           974     975      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 61/0)               Total: 61 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-19 18:20:01 +02:00
Denys Vlasenko 51b45ce28a libbb/yescrypt: code shrink
function                                             old     new   delta
blockmix_xor_save                                   1169     708    -461

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-19 17:20:35 +02:00
Denys Vlasenko 94591a1030 bootchartd: check the result of opendir("/proc")
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-19 02:26:20 +02:00
Denys Vlasenko ee2ef17cc7 tftp: use bb_error_msg instead of info_msg for a debug message
This is the only use of bb_info_msg in tftp.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-18 10:42:09 +02:00
Denys Vlasenko 27e1fc679e ntpd: replace two bb_info_msg's with bb_error_msg
All other messages are printed via bb_error_msg in this applet.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-18 10:34:17 +02:00
Denys Vlasenko 504f44436f sulogin: set ^C to SIG_DFL before execing the shell
function                                             old     new   delta
sulogin_main                                         331     340      +9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-18 07:29:24 +02:00
Denys Vlasenko d2ef2c75c5 password applets: update help text
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-18 07:28:32 +02:00
Denys Vlasenko dde90f1d47 libbb.h: increase MAX_PW_SALT_LEN
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-17 17:34:14 +02:00
Denys Vlasenko b823735b7e libbb/yescrypt: actually, largest allowed salt is 86 chars, support that
function                                             old     new   delta
yescrypt_r                                           767     756     -11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-17 17:01:40 +02:00
Denys Vlasenko abe0b45cd7 libbb/yescrypt: code shrink
function                                             old     new   delta
blockmix_xor                                        1177     702    -475

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-15 05:47:18 +02:00
Denys Vlasenko e62bfbcaed libbb/yescrypt: code shrink
function                                             old     new   delta
salsa20                                              684     650     -34
blockmix_salsa8                                      198     144     -54
blockmix                                             762     565    -197
blockmix_xor                                        1322    1028    -294
blockmix_xor_save                                   1499    1103    -396
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/5 up/down: 0/-975)           Total: -975 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-11 08:58:07 +02:00
Denys Vlasenko 95f169f3bb libbb/yescrypt: code shrink
function                                             old     new   delta
static.yescrypt_kdf32_body                           847     823     -24
yescrypt_r                                           805     767     -38
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-62)             Total: -62 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-09 10:38:11 +02:00
Denys Vlasenko 11d4c08d75 libbb/bitops.c: add inlining comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-09 08:21:47 +02:00
Denys Vlasenko c305c81c94 libbb: introduce and use block-XOR functions
On x86_64, they can be done in 16-byte blocks

64-bit:
function                                             old     new   delta
xorbuf_3                                               -      84     +84
xorbuf64_3_aligned64                                   -      58     +58
smix1                                                687     712     +25
xwrite_encrypted                                     520     534     +14
xorbuf16_aligned_long                                  -      13     +13
tls_xread_record                                     733     742      +9
xorbuf                                                21      13      -8
xorbuf_aligned_AES_BLOCK_SIZE                         15       -     -15
blockmix                                             814     762     -52
blockmix_salsa8                                      317     198    -119
blockmix_xor_save                                   1620    1499    -121
blockmix_xor                                        1543    1322    -221
------------------------------------------------------------------------------
(add/remove: 4/1 grow/shrink: 3/5 up/down: 203/-536)         Total: -333 bytes

32-bit:
function                                             old     new   delta
xorbuf_3                                               -      76     +76
xorbuf64_3_aligned64                                   -      36     +36
xorbuf16_aligned_long                                  -      23     +23
xwrite_encrypted                                     499     507      +8
tls_xread_record                                     646     650      +4
xorbuf                                                22      11     -11
xorbuf_aligned_AES_BLOCK_SIZE                         23       -     -23
blockmix                                            1083     938    -145
blockmix_salsa8                                      415     210    -205
blockmix_salsa8_xor                                  601     163    -438
blockmix_xor                                        2103    1533    -570
blockmix_xor_save                                   2614    1859    -755
------------------------------------------------------------------------------
(add/remove: 4/1 grow/shrink: 2/6 up/down: 147/-2147)       Total: -2000 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-09 07:00:59 +02:00
Denys Vlasenko e9c21c5c3a hush: fix SEGV on "echo << >" and such
function                                             old     new   delta
.rodata                                           105787  105823     +36
fetch_heredocs                                       461     477     +16
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 52/0)               Total: 52 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-08 10:36:12 +02:00
Denys Vlasenko 7b313c3465 libbb: code shrink in sha_crypt()
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-08 10:04:47 +02:00
Denys Vlasenko 0930708794 libbb/yescrypt: disable NROM code
function                                             old     new   delta
smix1                                                  -     595    +595
smix2                                                  -     414    +414
static.yescrypt_kdf32_body                           899     847     -52
static.smix2                                         420       -    -420
static.smix1                                         604       -    -604
------------------------------------------------------------------------------
(add/remove: 2/2 grow/shrink: 0/1 up/down: 1009/-1076)        Total: -67 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-08 06:52:27 +02:00
Denys Vlasenko d0f0874d57 libbb/yescrypt: disable code which accepts unusual yescrypt parameters
Almost any reasonable yescrypt hashes in /etc/shadow should only ever use
"jXY" parameters which set N and r. Fancy multi-byte-encoded
wide integers are not needed for that.

function                                             old     new   delta
static.yescrypt_kdf32_body                             -     899    +899
static.PBKDF2_SHA256                                 213     219      +6
decode64_uint32                                      141       -    -141
yescrypt_r                                           990     805    -185
yescrypt_kdf32_body                                 1423       -   -1423
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 1/1 up/down: 905/-1749)        Total: -844 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-08 05:34:41 +02:00
Denys Vlasenko 78bd8a44b7 libbb/yescrypt: explain and shrink decode64_uint32()
function                                             old     new   delta
decode64_uint32                                      177     141     -36

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-08 03:47:48 +02:00
Denys Vlasenko d18ac080e4 libbb/yescrypt: code shrink
Setting EINVAL in errno is not necessary, just error return works.

function                                             old     new   delta
yescrypt_kdf32_body                                 1434    1423     -11
yescrypt_r                                          1029     990     -39
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-50)             Total: -50 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-08 00:16:56 +02:00
Denys Vlasenko 8466c3e78f libbb/yescrypt: madvise(MADV_HUGEPAGE) our usually very large allocation
Nearly ~2 faster run when buffer is gigabytes in size

function                                             old     new   delta
yescrypt_kdf32_body                                 1386    1406     +20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 23:07:58 +02:00
Denys Vlasenko f8e9bd30d7 libbb/yescrypt: disable unrolling in two places
Also, make many define macros safer

function                                             old     new   delta
blockmix                                            2300     814   -1486
blockmix_xor                                        4606    1543   -3063
blockmix_xor_save                                   4737    1620   -3117
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-7666)         Total: -7666 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 22:34:31 +02:00
Denys Vlasenko e5d3a87633 libbb/yescrypt: 64-bit build fixes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 21:52:39 +02:00
Denys Vlasenko 7798f651a4 add libbb/yescrypt/PARAMETERS
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 21:36:31 +02:00
Denys Vlasenko 67b98c7b1b libbb/yescrypt: no need to find salt-terminating "$" twice
function                                             old     new   delta
yescrypt_r                                          1048    1029     -19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 18:28:56 +02:00
Denys Vlasenko e3484095f9 libbb/yescrypt: code shrink
function                                             old     new   delta
yescrypt_r                                          1063    1048     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 18:03:10 +02:00
Denys Vlasenko 5e9b95ff40 cryptpw: -m sha512crypt must also be accepted
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 17:42:35 +02:00
Denys Vlasenko 479d8db99f libbb/yescrypt: fix salts ending in dots (corresponding to binary zeros)
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 17:26:47 +02:00
Denys Vlasenko 75758c7360 libbb/yescrypt: accept longer salts (up to 84 chars)
function                                             old     new   delta
cryptpw_main                                         214     223      +9
chpasswd_main                                        347     356      +9
passwd_main                                          931     934      +3
yescrypt_r                                          1084    1056     -28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 21/-28)             Total: -7 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 17:08:32 +02:00
Denys Vlasenko 63025e8bca libbb/yescrypt: remove forgotten SHA256 HMAC header file
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 10:51:13 +02:00
Denys Vlasenko f464be22bd libbb/yescrypt: make it possible to set constant parameters, and set YESCRYPT_RW
function                                             old     new   delta
yescrypt_kdf32_body                                 1052    1420    +368
yescrypt_r                                          1133    1084     -49
static.smix                                          762       -    -762
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/1 up/down: 368/-811)         Total: -443 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 10:39:14 +02:00
Denys Vlasenko c11730490a libbb/yescrypt: remove redundant SHA256 HMAC implementation
function                                             old     new   delta
hmac_blocks                                            -      88     +88
static.PBKDF2_SHA256                                 176     213     +37
yescrypt_kdf32_body                                 1046    1052      +6
static.smix                                          759     762      +3
hmac_block                                            88      64     -24
HMAC_SHA256_Final                                     53       -     -53
HMAC_SHA256_Buf                                       58       -     -58
HMAC_SHA256_Init                                     159       -    -159
------------------------------------------------------------------------------
(add/remove: 1/3 grow/shrink: 3/1 up/down: 134/-294)         Total: -160 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 08:21:44 +02:00
Denys Vlasenko 1a0913d57c libbb: factor out HMAC code from TLS
function                                             old     new   delta
hmac_block                                             -      88     +88
hmac_peek_hash                                         -      61     +61
hmac_end                                               -      50     +50
hmac_begin                                           140     177     +37
hmac_hash_v                                            -      30     +30
.rodata                                           105799  105787     -12
hmac_sha_precomputed                                  54       -     -54
hmac_sha_precomputed_v                                69       -     -69
hmac                                                  83       -     -83
------------------------------------------------------------------------------
(add/remove: 5/3 grow/shrink: 1/1 up/down: 266/-218)           Total: 48 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 07:44:01 +02:00
Denys Vlasenko e2091c9842 libbb: add two more forgotten source files
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 04:57:16 +02:00
Denys Vlasenko a2a5db41a3 libbb/pw_ascii64.c: add forgotten source file
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-07 00:04:10 +02:00
Denys Vlasenko 53de6e6150 libbb/yescrypt: use common ascii64 encoding routine
function                                             old     new   delta
num2str64_lsb_first                                   33      46     +13
yescrypt_r                                          1235    1133    -102
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 13/-102)           Total: -89 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 22:43:28 +02:00
Denys Vlasenko 5e17e3c6f4 libbb: shuffle ascii64 code around, shrink i2a64()
function                                             old     new   delta
num2str64_4chars_msb_first                             -      55     +55
num2str64_lsb_first                                    -      33     +33
i2a64                                                 42      25     -17
to64                                                  33       -     -33
to64_msb_first                                        55       -     -55
------------------------------------------------------------------------------
(add/remove: 2/2 grow/shrink: 0/1 up/down: 88/-105)           Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 21:59:03 +02:00
Denys Vlasenko f3a1b7be72 libbb/yescrypt: remove one NOINLINE, add copyright headers, merge two source files
function                                             old     new   delta
pw_encrypt                                           945     974     +29
yes_crypt                                             50       -     -50
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 29/-50)            Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 20:59:00 +02:00
Denys Vlasenko 0574928c85 libbb/yescrypt: remove unused prefetching code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 20:08:53 +02:00
Denys Vlasenko aebe6f7132 libbb/yescrypt: remove inlines (whcih gcc detects anyway) and dead ifderfs
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 19:47:29 +02:00
Denys Vlasenko 447eb6bf71 libbb: in DES crypt, error out on invalid salt chars
function                                             old     new   delta
des_crypt                                           1308    1327     +19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 19:30:58 +02:00
Denys Vlasenko 82bbbd2e53 libbb: code shrink in DES crypt
function                                             old     new   delta
pw_encrypt                                           941     945      +4
bits32                                               128       -    -128
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 4/-128)           Total: -124 bytes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 19:14:09 +02:00
Denys Vlasenko 23b5527f5c libbb/yescrypt: use common ACSII char-to-64 conversion code
function                                             old     new   delta
a2i64                                                  -      46     +46
yescrypt_r                                          1215    1235     +20
decode64_uint32                                      167     177     +10
atoi64                                                25       -     -25
ascii_to_bin                                          53       -     -53
static.atoi64_partial                                 77       -     -77
------------------------------------------------------------------------------
(add/remove: 1/3 grow/shrink: 2/0 up/down: 76/-155)           Total: -79 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 19:08:57 +02:00
Denys Vlasenko f5af8aefea libbb/yescrypt: shrink PBKDF2
function                                             old     new   delta
static.PBKDF2_SHA256                                 189     176     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 18:35:37 +02:00
Denys Vlasenko b8f7600166 libbb/yescrypt: more efficient byteswapping
function                                             old     new   delta
static.smix1                                         631     604     -27
static.smix2                                         452     420     -32
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-59)             Total: -59 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 18:27:16 +02:00
Denys Vlasenko 9c4cd75d12 restore mangled comment
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 11:16:43 +02:00
Denys Vlasenko 0893bc3bac libbb/yescrypt: code shrink
static.PBKDF2_SHA256                                   -     189    +189
HMAC_SHA256_Init                                       -     159    +159
HMAC_SHA256_Buf                                        -      58     +58
HMAC_SHA256_Final                                      -      53     +53
i2a64                                                  -      42     +42
yescrypt_r                                          1221    1215      -6
yescrypt_kdf32_body                                 1064    1046     -18
i64c                                                  42       -     -42
libcperciva_HMAC_SHA256_Final                         53       -     -53
libcperciva_HMAC_SHA256_Buf                           58       -     -58
ascii64                                               65       -     -65
libcperciva_HMAC_SHA256_Init                         159       -    -159
PBKDF2_SHA256                                        386       -    -386
------------------------------------------------------------------------------
(add/remove: 5/6 grow/shrink: 0/2 up/down: 501/-787)         Total: -286 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 11:12:13 +02:00
Denys Vlasenko b21cd481db libbb/yescrypt: code shrink
function                                             old     new   delta
libcperciva_HMAC_SHA256_Final                         56      53      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 11:02:03 +02:00
Denys Vlasenko 62abd47815 Move "sha256-hash a memory array and produce the digest" helper to libbb
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 10:50:46 +02:00
Denys Vlasenko 4e5a6b6dbb libbb/yescrypt: remove extra sha256 implementation
function                                             old     new   delta
libcperciva_HMAC_SHA256_Init                           -     159    +159
libcperciva_HMAC_SHA256_Final                          -      56     +56
SHA256_Buf                                             -      40     +40
static.smix                                          753     759      +6
yescrypt_kdf32_body                                 1059    1060      +1
.rodata                                           105803  105799      -4
initial_state                                         32       -     -32
libcperciva_SHA256_Init                               37       -     -37
static.cpu_to_be32_vect                               51       -     -51
_HMAC_SHA256_Final                                    55       -     -55
PAD                                                   64       -     -64
libcperciva_HMAC_SHA256_Buf                          132      58     -74
libcperciva_SHA256_Buf                                86       -     -86
SHA256_Pad_Almost                                    131       -    -131
_SHA256_Final                                        195       -    -195
_SHA256_Update                                       198       -    -198
_HMAC_SHA256_Init                                    213       -    -213
Krnd                                                 256       -    -256
PBKDF2_SHA256                                       1003     386    -617
SHA256_Transform                                    3083       -   -3083
------------------------------------------------------------------------------
(add/remove: 3/12 grow/shrink: 2/3 up/down: 262/-5096)      Total: -4834 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 10:35:22 +02:00
Denys Vlasenko ffac25d056 libbb/yescrypt: comment tweaks
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 07:43:04 +02:00
Denys Vlasenko 8be6dafe94 libbb/yescrypt: use mmap for allocation, it's large - 16Mbytes
This automatically gives it alignment sufficient for any future SIMD
optimizations.

function                                             old     new   delta
yescrypt_r                                          1217    1221      +4
yescrypt_kdf32_body                                 1077    1059     -18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 4/-18)             Total: -14 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 06:50:18 +02:00
Denys Vlasenko 736589f877 libbb/yescrypt: reduce the number of function parameters
function                                             old     new   delta
yescrypt_kdf32_body                                    -    1077   +1077
static.smix                                          739     753     +14
yescrypt_init_local                                   34       -     -34
yes_crypt                                             87      50     -37
yescrypt_free_local                                   49       -     -49
yescrypt_r                                          1288    1217     -71
static.yescrypt_kdf_body                            1166       -   -1166
------------------------------------------------------------------------------
(add/remove: 1/3 grow/shrink: 1/2 up/down: 1091/-1357)       Total: -266 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 06:05:08 +02:00
Denys Vlasenko 85d3c48217 libbb/yescrypt: code shrink in salt decoding
function                                             old     new   delta
yescrypt_r                                          1311    1288     -23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 03:59:59 +02:00
Denys Vlasenko 1c977008e0 libbb/yescrypt: code shrink in parameter decoding
function                                             old     new   delta
decode64_uint32                                      166     167      +1
yescrypt_r                                          1342    1311     -31
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 1/-31)             Total: -30 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 03:40:06 +02:00
Denys Vlasenko 1524540613 libbb/yescrypt: remove unused variable
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 03:22:46 +02:00
Denys Vlasenko 9b6e03fd09 libbb/yescrypt: remove unused yescrypt_region_t tmp
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 03:03:38 +02:00
Denys Vlasenko e189464fa7 libbb/yescrypt: make some functions static
function                                             old     new   delta
static.yescrypt_kdf_body                               -    1166   +1166
yescrypt_r                                           692    1342    +650
atoi64                                                 -      25     +25
decode64_uint32                                      201     166     -35
encode64                                             153       -    -153
decode64                                             174       -    -174
yescrypt_kdf                                         442       -    -442
yescrypt_kdf_body                                   1239       -   -1239
------------------------------------------------------------------------------
(add/remove: 2/4 grow/shrink: 1/1 up/down: 1841/-2043)       Total: -202 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 02:39:07 +02:00
Denys Vlasenko 3d9b965b4a libbb/yescrypt: remove unused yescrypt_binary_t
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 01:35:23 +02:00
Denys Vlasenko bf8231d11d libbb/yescrypt: remove YESCRYPT_INIT_SHARED flag and code using it
It's only used by libxcrypt-4.4.38/lib/alg-yescrypt-opt.c code
(optimized code version?) which wasn't ported to busybox

function                                             old     new   delta
yescrypt_kdf                                         449     442      -7
static.smix                                          755     739     -16
alloc_region                                          72       -     -72
yescrypt_kdf_body                                   1467    1239    -228
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 0/3 up/down: 0/-323)           Total: -323 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 01:29:14 +02:00
Denys Vlasenko 10196929da libbb/yescrypt: remove unreachable support for scrypt hash ("$7$...")
function                                             old     new   delta
decode64                                             136     174     +38
decode64_uint32                                      166     201     +35
atoi64                                                25       -     -25
yescrypt_r                                           879     692    -187
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 2/1 up/down: 73/-212)          Total: -139 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 01:23:37 +02:00
Denys Vlasenko be327bed9d libbb/yescrypt: remove unused yescrypt_shared_t
function                                             old     new   delta
static.smix                                            -     755    +755
static.smix1                                           -     631    +631
static.smix2                                           -     452    +452
yescrypt_free_local                                    9      49     +40
yes_crypt                                             90      87      -3
yescrypt_r                                           890     879     -11
yescrypt_kdf                                         479     449     -30
free_region                                           47       -     -47
yescrypt_kdf_body                                   1724    1467    -257
smix2                                                659       -    -659
smix                                                 790       -    -790
smix1                                                960       -    -960
------------------------------------------------------------------------------
(add/remove: 3/4 grow/shrink: 1/4 up/down: 1878/-2757)       Total: -879 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 01:03:49 +02:00
Denys Vlasenko 444a91abc9 libbb/yescrypt: remove obviously unused, commented-out parts
No code changes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 00:55:08 +02:00
Denys Vlasenko 80e676664e libbb: add yescrypt password hashing support
It seems to work, but not at all optimized for size.
The extra copy of sha256 code need to be removed.

The yescrypt code in libbb/yescrypt/* is adapted from libxcrypt-4.4.38
with minimal edits, hopefully making it easier to track
backports by resetting the tree to this commit,
then comparing changes in upstream libxcrypt to the tree.

function                                             old     new   delta
blockmix_xor_save                                      -    7050   +7050
static.blockmix_xor                                    -    6475   +6475
blockmix                                               -    3390   +3390
SHA256_Transform                                       -    3083   +3083
yescrypt_kdf_body                                      -    1724   +1724
PBKDF2_SHA256                                          -    1003   +1003
smix1                                                  -     960    +960
yescrypt_r                                             -     890    +890
salsa20                                                -     804    +804
smix                                                   -     790    +790
smix2                                                  -     659    +659
blockmix_salsa8_xor                                    -     601    +601
yescrypt_kdf                                           -     479    +479
blockmix_salsa8                                        -     415    +415
Krnd                                                   -     256    +256
_HMAC_SHA256_Init                                      -     213    +213
_SHA256_Update                                         -     198    +198
_SHA256_Final                                          -     195    +195
decode64_uint32                                        -     166    +166
encode64                                               -     153    +153
decode64                                               -     136    +136
libcperciva_HMAC_SHA256_Buf                            -     132    +132
SHA256_Pad_Almost                                      -     131    +131
salsa20_simd_unshuffle                                 -     101    +101
salsa20_simd_shuffle                                   -     101    +101
yes_crypt                                              -      90     +90
libcperciva_SHA256_Buf                                 -      86     +86
crypt_make_rand64encoded                               -      85     +85
static.atoi64_partial                                  -      77     +77
alloc_region                                           -      72     +72
ascii64                                                -      65     +65
PAD                                                    -      64     +64
_HMAC_SHA256_Final                                     -      55     +55
static.cpu_to_be32_vect                                -      51     +51
free_region                                            -      47     +47
libcperciva_SHA256_Init                                -      37     +37
yescrypt_init_local                                    -      34     +34
crypt_make_pw_salt                                    92     125     +33
initial_state                                          -      32     +32
.rodata                                           105771  105803     +32
atoi64                                                 -      25     +25
explicit_bzero                                         -      22     +22
pw_encrypt                                           920     941     +21
yescrypt_free_local                                    -       9      +9
crypt_make_salt                                       85       -     -85
------------------------------------------------------------------------------
(add/remove: 43/1 grow/shrink: 3/0 up/down: 31042/-85)      Total: 30957 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-06 00:49:22 +02:00
Denys Vlasenko 84766710f4 whitespace fix
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-05 12:59:42 +02:00
Denys Vlasenko 142ac2d796 diff: code shrink
function                                             old     new   delta
diffreg                                             1317    1307     -10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-04 21:40:51 +02:00
Denys Vlasenko 8d3d078917 shell: empty HISTFILE disables history saving, just as unset one did
The rationale here is that unsetting HISTFILE in /etc/profile
does not "stick": if it's unset, the default one is set later
(after /etc/profile is executed) by the shell.
But setting (and exporting, so it is inherited by all
(grand)child shells) an empty one works.

function                                             old     new   delta
save_history                                         296     316     +20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-04 12:51:38 +02:00
Denys Vlasenko 9c46a06885 shell: update HISTFILESIZE code to be actually useful
"HISTFILESIZE=0" in profile wasn't working as intended,
"unset HISTFILE" wasn't preventing creation of history files
Now:
HISTSIZE=n      allows to reduce in-memory history buffer
HISTFILESIZE=n  allows to reduce history file size (0: truncate it)
unset HISTFILE  allows to not save history file at all

function                                             old     new   delta
exitshell                                            138     194     +56
hush_exit                                             97     143     +46
save_history                                         266     296     +30
hush_main                                           1170    1186     +16
.rodata                                           105762  105771      +9
load_history                                         246     254      +8
size_from_HISTFILESIZE                                44      41      -3
read_line_input                                     2746    2712     -34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 6/2 up/down: 165/-37)           Total: 128 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-03 19:10:42 +02:00
Denys Vlasenko 36ac283682 shell: fix race between signal handlers setting bb_got_signal and poll()
function                                             old     new   delta
__ppoll_time64                                         -     211    +211
check_got_signal_and_poll                              -     164    +164
read_key                                             607     601      -6
shell_builtin_read                                  1328    1318     -10
------------------------------------------------------------------------------
(add/remove: 4/0 grow/shrink: 0/2 up/down: 375/-16)           Total: 359 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-02 22:42:47 +02:00
Denys Vlasenko bbaa56f737 use pollfd[1] array for poll() argument
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-02 21:55:42 +02:00
Sertonix 8c835540ef cpio: map -F to --file long option
function                                             old     new   delta
.rodata                                           100437  100444      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 7/0)                 Total: 7 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-02 00:07:18 +02:00
Bin Meng 244f5c4795 libbb: Prevent clang from reading the G pointer before it is assigned
It was observed that getty crashes on RISC-V 64-bit target, with the
busybox binary compiled by clang/LLVM 17 with -O2. Not only getty,
but also some other applets like syslogd/vi are broken too.

Commit 5156b245 ("Make const ptr assign as function call in clang")
introduced XZALLOC_CONST_PTR() to defeat the compiler optimization,
however it only fixed a small number of broken places when compiling
busybox with clang/LLVM. A large number of places remain broken.

This commit treats ASSIGN_CONST_PTR() the same way as XZALLOC_CONST_PTR().

Signed-off-by: Bin Meng <bmeng.cn@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 21:21:16 +02:00
Ron Yorston dcd8df258a shell: improve bash compatibility of read built-in
Make the read built-in more compatible with bash:

- Return an exit code of 142 on timeout.

- When the timeout expires before a newline is detected in the
  input bash captures the partial input.  This behaviour is new
  since bash version 4.4.  BusyBox shells had the pre-4.4 behaviour
  where the input was lost.

Update the tests to suit and fix a couple of compiler errors in
the testsuite.

function                                             old     new   delta
builtin_read                                         154     174     +20
readcmd                                              213     228     +15
shell_builtin_read                                  1364    1370      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 41/0)               Total: 41 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 20:21:37 +02:00
Denys Vlasenko 4b1f1da358 df: -k overrides block size to 1k even if $POSIXLY_CORRECT
function                                             old     new   delta
df_main                                             1060    1070     +10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 19:26:50 +02:00
Radoslav Kolev e6317e72dd hexdump: add tests for %x, handle little/big endian properly
Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 13:35:06 +02:00
Radoslav Kolev b8ce2084cd od: make -B test little endian only, add variant for big endian
Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 13:34:12 +02:00
Radoslav Kolev f5c7cae55f hexdump: fix regression for uint16 on big endian systems
Commit 34751d8bf introduced a bug in the handling of uint16
values on big endian systems not considered safe for unaligned
access when falling back to memcpy.

Signed-off-by: Radoslav Kolev <radoslav.kolev@suse.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 13:31:45 +02:00
Michael Glembotzki 73c67d75ef ntpd: Raise MAXDIST to 3s for better tolerance and consistency with chrony
function                                             old     new   delta
select_and_cluster                                  1088    1093      +5

Signed-off-by: Michael Glembotzki <m.glembo@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 13:30:40 +02:00
Denys Vlasenko 58adc7b527 ip route: make cache printing a bit more similar to upstream
function                                             old     new   delta
print_route                                         1573    1565      -8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 12:54:00 +02:00
Ahmad Fatoum 952a7b9cec lineedit: fix left-over print to stdout
There's code printing to stderr both before and after the single call to
puts inside put_cur_glyph_and_inc_cursor().

This is likely an oversight as we want everything to go through the
same file descriptor, so switch it over to fputs.

Fixes: fd47f05676 ("lineedit: print prompt and editing operations to stderr")
Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 12:25:29 +02:00
Ahmad Fatoum 37abfb919d lineedit: fix printing lines during tab completion
Indentation and escape characters are all output to stderr now, but the
matches themself remained on stdout leading to garbled output on Tab
completion.

Print the results to stderr as well to fix this.

Fixes: fd47f05676 ("lineedit: print prompt and editing operations to stderr")
Signed-off-by: Ahmad Fatoum <a.fatoum@pengutronix.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-07-01 12:25:29 +02:00
Denys Vlasenko 5f07327251 cpio: error out if the file to be achived is >=4GB
function                                             old     new   delta
.rodata                                           105715  105751     +36
cpio_o                                              1145    1167     +22
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 58/0)               Total: 58 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-21 04:42:33 +02:00
Denys Vlasenko f13f68288f rpm2cpio: extract cpio even if compression is not known
This is more useful than failing outright.

function                                             old     new   delta
rpm2cpio_main                                        110     144     +34
.rodata                                           105681  105715     +34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 68/0)               Total: 68 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-20 23:59:38 +02:00
Denys Vlasenko c61fdadf97 libbb/archival: make setup_unzip_on_fd() return bytes read if not compressed
setup_unzip_on_fd() does not return the transformer structure, so the user
does not know how much to seek back (or alternatively what the signature was)
when compressor signature is not detected.

Currently not needed (the only user is tar which dies anyway).
However, rpm2cpio may need this if we extend it to extract the internal .cpio
even if cpio's compressions algo is not known.

function                                             old     new   delta
setup_unzip_on_fd                                     53      59      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-20 23:49:33 +02:00
J. Neuschäfer 636315ccb9 runit: fix setuidgid help text
Signed-off-by: J. Neuschäfer <j.neuschaefer@gmx.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-17 07:06:21 +02:00
Denys Vlasenko 9a8796436b archival: disallow path traversals (CVE-2023-39810)
Create new configure option for archival/libarchive based extractions to
disallow path traversals.
As this is a paranoid option and might introduce backward
incompatibility, default it to no.

Fixes: CVE-2023-39810

Based on the patch by Peter Kaestle <peter.kaestle@nokia.com>

function                                             old     new   delta
data_extract_all                                     921     945     +24
strip_unsafe_prefix                                  101     102      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 25/0)               Total: 25 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-16 03:03:17 +02:00
Grant Erickson fc466720b5 syslogd: Fix 'OPT_locallog' check regression in 'syslogd_main'
In the recent refactoring of 'syslogd_main', a regression was
introduced in handling the manual bitwise OR of 'OPT_locallog' as
follows:

   if (ENABLE_FEATURE_REMOTE_LOG && !(opts & OPT_remotelog)) // -R
       option_mask32 |= OPT_locallog;

'opts' represents the locally-scoped output of 'getopt32' and
'option_mask32' represents the globally-scoped state of the
same. Consequently, the above performs a bitwise OR to include
'OPT_locallog' of the globally-scoped option state, which 'opts' will
not reflect locally.

Manipulating the global, rather than local, state is correct as
'timestamp_and_log_internal' will later need to check 'OPT_locallog'.

However, when the aforementioned refactor occurred, the following
regressing change was made:

    -       if (!ENABLE_FEATURE_REMOTE_LOG || (option_mask32 & OPT_locallog)) {
    +       if (!ENABLE_FEATURE_REMOTE_LOG || (opts & OPT_locallog)) {

breaking the spatially- and temporally-removed check in
'timestamp_and_log_internal'.

Fixes: 02378ce20c ("syslogd: decrease stack usage, ~50 bytes")

function                                             old     new   delta
syslogd_init                                        1140    1137      -3

Signed-off-by: Grant Erickson <gerickson@nuovations.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-08 16:14:34 +02:00
Denys Vlasenko d2d23c848a udhcpd: send DHCPOFFERs as unicast (unless clients specifically asks for bcast)
RFC 2131 says we should do that.
Evidently, since for so many years no one complained, sending them broadcast
works too, but finally we've got someone who wants RFC-compliand behavior.

function                                             old     new   delta
send_packet                                          141     179     +38
.rodata                                           105680  105681      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 39/0)               Total: 39 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-07 02:46:39 +02:00
Denys Vlasenko a8349b115d Makefile: fix passing of EXTRA_LDLIBS
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-06 12:13:16 +02:00
Sébastien Parisot f9274e8d6e init: improve log message when a process exits: show exit code
function                                             old     new   delta
.rodata                                           105649  105680     +31
init_main                                            776     804     +28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 59/0)               Total: 59 bytes

Signed-off-by: Sébastien Parisot <sparisot@free-mobile.fr>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-04-06 10:44:04 +02:00
Denys Vlasenko 887295686d udhcpc6: fix copy-paste error in "generate a consistent IAID" commit
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-02-09 15:09:15 +01:00
Zhou Siqi 4115439496 udhcpc6: generate a consistent IAID
Currently, udhcpc6 does not meet the requirements for
Identity Association in RFC 3315.
This is a specific explanation in RFC 3315 protocol:
https://datatracker.ietf.org/doc/html/rfc3315#section-10
"The IAID uniquely identifies the IA and must be chosen to be unique
   among the IAIDs on the client.  The IAID is chosen by the client.
   For any given use of an IA by the client, the IAID for that IA MUST
   be consistent across restarts of the DHCP client."
This patch makes the client generate a consistent IAID based on the MAC address.

function                                             old     new   delta
send_d6_discover                                     285     270     -15

Signed-off-by: Zhou Siqi <zhousiqi5@huawei.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-02-09 13:51:33 +01:00
Denys Vlasenko 779cca899f udhcpc6: move block comment, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-02-09 12:54:50 +01:00
Laurent Bercot ef21820dc9 udhcpc6: improvements
Several small improvements to udhcpc6.

- Remove usage text for the nonexistent -B option.
- Fix a segfault when renewing an IA_PD lease without IA_NA (which means
the client hasn't been assigned an ip, so we cannot locally bind to it).
- Fix NAK management: check the option length, and print the status code
and status message
- Add a -m option to always send renew requests as multicast.

 These last two changes are useful to deal with hopelessly broken DHCPv6
servers such as the one from the Orange Livebox (one of the main French
ISPs) which I'm currently having the displeasure to have to talk to,
hence the patch.

function                                             old     new   delta
static.send_d6_renew                                   -     126    +126
.rodata                                           105598  105649     +51
udhcpc6_main                                        2607    2650     +43
packed_usage                                       34933   34953     +20
d6_send_kernel_packet_from_client_data_ifindex       266     282     +16
send_d6_renew                                        174       -    -174
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 4/0 up/down: 256/-174)           Total: 82 bytes

Signed-off-by: Laurent Bercot <ska-dietlibc@skarnet.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2025-02-09 12:52:02 +01:00
Denys Vlasenko 14f57f5357 cut: code shrink
move "linenum" manipulations to the one place where it is used.

function                                             old     new   delta
cut_main                                            1373    1360     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-21 00:43:45 +01:00
Denys Vlasenko 1ea89fa98a cut: code shrink
This change eliminates one temporary:

-       if (dcount++ < cut_list[cl_pos].startpos)
+       dcount++;
+       if (dcount <= cut_list[cl_pos].startpos)

function                                             old     new   delta
cut_main                                            1402    1373     -29

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-21 00:24:30 +01:00
Denys Vlasenko b03f5162ac cut: fix up -D/-s behavior with -F
function                                             old     new   delta
cut_main                                            1388    1402     +14
packed_usage                                       34934   34933      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 14/-1)              Total: 13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-20 22:12:33 +01:00
Denys Vlasenko dd40b40ee5 cut: remove unnecessary initialization of regmatch_t
function                                             old     new   delta
cut_main                                            1404    1388     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-20 21:46:32 +01:00
Denys Vlasenko e2304d47a9 cut: shorten error messages on bad syntax even more
$ cut -s -b3
cut: -s requires -f or -F
$ cut -d@ -b3
cut: -d DELIM requires -f or -F

function                                             old     new   delta
static.requires_f                                      -      19     +19
static._op_on_field                                   32       -     -32
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/0 up/down: 19/-32)            Total: -13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-16 01:12:17 +01:00
Denys Vlasenko ee8b94acbf cut: shorten error messages on bad syntax
We don't need to mimic GNU cut error messages.

$ cut -d@ -b3
cut: -d DELIM makes sense only with -f or -F
$ cut -s -b3
cut: -s makes sense only with -f or -F

function                                             old     new   delta
static._op_on_field                                   31      32      +1
.rodata                                           105659  105598     -61
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 1/-61)             Total: -60 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-16 00:53:51 +01:00
Denys Vlasenko 0bd84c9472 cut: terminate cut_list[] so that we don't need "size of the array" variable
function                                             old     new   delta
cut_main                                            1410    1404      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-16 00:32:57 +01:00
Denys Vlasenko ba9651b803 cut: we can't get empty cut_list[], remove the check for that
function                                             old     new   delta
.rodata                                           105685  105659     -26

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-16 00:19:43 +01:00
Denys Vlasenko e8622f0d85 cut: disallow -f '' and -f '-'
function                                             old     new   delta
cut_main                                            1391    1410     +19

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-15 12:27:33 +01:00
Denys Vlasenko b25ea3f156 cut: fix -F n-m to match toybox
function                                             old     new   delta
cut_main                                            1339    1391     +52

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-14 13:58:49 +01:00
Denys Vlasenko d48400d8fb cut: simplify getopt32 code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-13 20:35:28 +01:00
Denys Vlasenko 7624077772 cut: "it's legal to pass an empty list" seems to be untrue
function                                             old     new   delta
cut_main                                            1344    1339      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-13 20:22:05 +01:00
Denys Vlasenko f4f8dc6864 cut: whitespace fixes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-13 19:43:53 +01:00
Denys Vlasenko ed6561685c cut: tweak comments
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-13 19:39:34 +01:00
Denys Vlasenko 96a230f17b cut: fix handling of -d ''
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-13 19:31:41 +01:00
Denys Vlasenko 9adafbc118 cut: prevent infinite loop if -F REGEX matches empty delimiter
function                                             old     new   delta
cut_main                                            1339    1348      +9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-13 19:13:20 +01:00
Denys Vlasenko a4894eaf71 cut: tweak --help
function                                             old     new   delta
packed_usage                                       34901   34934     +33
cut_main                                            1353    1339     -14
.rodata                                           105724  105685     -39
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 33/-53)            Total: -20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-11 01:10:05 +01:00
Denys Vlasenko 9e364b16d1 cut: fix -d$'\n' --output-delimiter=@@ behavior
function                                             old     new   delta
cut_main                                            1261    1353     +92
packed_usage                                       34925   34901     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 92/-24)             Total: 68 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 21:01:52 +01:00
Denys Vlasenko a208fa03de cut: implement --output-delimiter
function                                             old     new   delta
cut_main                                            1204    1261     +57
static.cut_longopts                                    -      20     +20
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 77/0)               Total: 77 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 18:49:10 +01:00
Denys Vlasenko b402b13fab cut: with -F disabled in .config, don't show it in --help
function                                             old     new   delta
packed_usage                                       34897   34849     -48

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 18:09:07 +01:00
Denys Vlasenko 38a3c0ad32 cut: comment out code which seems to be not needed
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 17:50:29 +01:00
Denys Vlasenko 103139d0e6 cut: fix "echo 1.2 | cut -d. -f1,3" (print "1", not "1.")
function                                             old     new   delta
cut_main                                            1228    1201     -27

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 17:21:30 +01:00
Denys Vlasenko 470f009552 cut: with -F, do not regcomp() pattern for every file
function                                             old     new   delta
cut_main                                            1218    1228     +10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 02:55:58 +01:00
Denys Vlasenko 55fc6a18da cut: rename "cut_lists" to "cut_list"
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 02:29:48 +01:00
Denys Vlasenko 1220b1519d cut: rename some variables to hopefully better names
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 02:15:25 +01:00
Denys Vlasenko 808155ebf3 cut: "orig_line" is redundant, remove it
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 01:55:25 +01:00
Denys Vlasenko 478ac90f2c cut: allocate "printed" only if OPT_CHAR or OPT_BYTE
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 01:50:58 +01:00
Denys Vlasenko ad12ab439b cut: localize 'spos' variable, convert !NUMVAR to NUMVAR == 0
This imporves readability

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 01:44:13 +01:00
Denys Vlasenko 73e9d25d75 cut: simplify OPT_ names, eliminate one variable
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 01:38:31 +01:00
Ron Yorston f020414413 cut: improve detection of invalid ranges
Commit 0068ce2fa (cut: add toybox-compatible options -O OUTSEP,
-D, -F LIST) added detection of reversed ranges.  Further
improvements are possible.

- The test for reversed ranges compared the start after it had been
  decremented with the end before decrement.  It thus missed ranges
  of the form 2-1.

- Zero isn't a valid start value for a range.  (Nor is it a valid
  end value, but that's caught by the test for a reversed range.)

- The code

        if (!*ltok)
            e = INT_MAX;

  duplicates a check that's already been made.

- Display the actual range in the error message to make it easier
  to find which range was at fault.

function                                             old     new   delta
.rodata                                           100273  100287     +14
cut_main                                            1239    1237      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 14/-2)              Total: 12 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 01:29:44 +01:00
Colin McAllister 50e2b59370 cut: fix "-s" flag to omit blank lines
Using cut with the delimiter flag ("-d") with the "-s" flag to only
output lines containing the delimiter will print blank lines. This is
deviant behavior from cut provided by GNU Coreutils. Blank lines should
be omitted if "-s" is used with "-d".

This change introduces a somewhat naiive, yet efficient solution, where
line length is checked before looping though bytes. If line length is
zero and the "-s" flag is used, the code will jump to parsing the next
line to avoid printing a newline character.

function                                             old     new   delta
cut_main                                            1196    1185     -11

Signed-off-by: Colin McAllister <colinmca242@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-10 01:27:04 +01:00
Natanael Copa 87e60dcf0f hexdump: fix regression with -n4 -e '"%u"'
Fix bug introduced in busybox 1.37.0 that broke kernel builds.

Fixes commit e2287f99fe (od: for !DESKTOP, match output more closely
to GNU coreutils 9.1, implement -s)

function                                             old     new   delta
rewrite                                              967     976      +9

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-09 11:17:14 +01:00
Ron Yorston 175b8dda19 libbb: tidy argument checks in getopt32()
When getopt32() has complementary options it's possible to specify
the minimum and maximum number of arguments allowed.  Checking
these values was inconsistent:

- '?' correctly checked that it was followed by a digit but set
  the otherwise unused spec_flgs variable on error.

- '=' failed to check that it was followed by a digit.

function                                             old     new   delta
vgetopt32                                           1307    1319     +12

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-09 02:16:44 +01:00
Christian Franke e6f3a3b381 chpst: fix error check of nice(2) call
Check errno instead of return value because -1 is a valid return
value also on success.

Signed-off-by: Christian Franke <christian.franke@t-online.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-09 02:08:52 +01:00
Hajime Tazaki 23db689683 hush: fix G.argv0_for_re_execing to avoid endless loop
When the busybox is used as /sbin/init and the inittab file contains
below:

::respawn:-/bin/sh

/sbin/init spawns hush for the first time with the argv[0] contains '-',
and hush treats it as login shell.  Then it reads /etc/profile and if
the file contains the command execution like below, it invokes hush as
login shell because the argv[0] argument is still '-/bin/sh' and reads
/etc/profile again.  This will last until some failure (e.g., memory
failure) happens.

  [ "$(id -u)" -eq 0 ] && PS1="${PS1}# " || PS1="${PS1}\$ "

This commit fixes this issues by adding an offset (+1) to the
G.argv0_for_re_execing variable.

This issue happens on our out-of-tree UML (use mode linux) with nommu
configuration.

Link: https://lore.kernel.org/all/cover.1731290567.git.thehajime@gmail.com/
Signed-off-by: Hajime Tazaki <thehajime@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-12-09 01:58:45 +01:00
Denys Vlasenko 75ca8d074b hexdump: accept hex numbers in -n, closes 16195
function                                             old     new   delta
hexdump_main                                         366     383     +17

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-08 04:23:29 +02:00
Denys Vlasenko 49d9e06fba libbb: modify find_executable() to not temporarily write to PATH
This allows to simplify "which" applet code

function                                             old     new   delta
find_executable                                       93     111     +18
which_main                                           191     177     -14
builtin_source                                       316     294     -22
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/2 up/down: 18/-36)            Total: -18 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-08 04:03:17 +02:00
Denys Vlasenko 8c4bccb83e hush: fix "type ./cat" and "command -v ./cat" to not scan PATH
function                                             old     new   delta
find_executable_in_PATH                                -      67     +67
if_command_vV_print_and_exit                         114     116      +2
.rodata                                           105712  105710      -2
builtin_type                                         137     128      -9
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/2 up/down: 69/-11)             Total: 58 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 22:00:16 +02:00
Denys Vlasenko baa49bdc1b hush: make "test -x" use cached groupinfo
While at it, correct "type" to skip non-executable files in PATH

function                                             old     new   delta
builtin_source                                       211     316    +105
builtin_test                                          10      32     +22
hush_main                                           1150    1170     +20
builtin_type                                         122     137     +15
if_command_vV_print_and_exit                         120     114      -6
find_in_path                                         131       -    -131
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 4/1 up/down: 162/-137)           Total: 25 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 15:18:45 +02:00
Denys Vlasenko 0929a129fc test: -x can return 0/1 early if all X bits are the same
function                                             old     new   delta
nexpr                                                702     725     +23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 07:33:58 +02:00
Denys Vlasenko 96b0607302 ash: cache more of uid/gid syscalls
Testcase:
setuidgid 1:1 strace ash -c 'test -x TODO; test -x TODO; echo $?'
should show that second "test -x" does not query ids again.

function                                             old     new   delta
ash_main                                            1236    1256     +20
get_cached_euid                                        -      19     +19
get_cached_egid                                        -      19     +19
test_main                                             56      72     +16
test_exec                                            119     135     +16
is_in_supplementary_groups                            52      57      +5
nexpr                                                718     702     -16
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 4/1 up/down: 95/-16)             Total: 79 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 07:28:44 +02:00
Denys Vlasenko d26e958725 ash: make "test -x" use cached groupinfo
function                                             old     new   delta
test_main2                                             -     407    +407
testcmd                                               10      23     +13
test_main                                            418      56    -362
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/1 up/down: 420/-362)           Total: 58 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 07:14:27 +02:00
Denys Vlasenko 4c1d645c86 libbb: simplify parameter passing in is_in_supplementary_groups()
function                                             old     new   delta
is_in_supplementary_groups                            54      52      -2
nexpr                                                721     718      -3
test_exec                                            125     119      -6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-11)             Total: -11 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 06:36:00 +02:00
Denys Vlasenko 860b3d066f ash: command -v CMD must skip (go to next path) when CMD exists, but is not executable
Upstream commit:

    Date: Fri, 5 Apr 2024 17:55:46 +0800
    exec: Check executable bit when searching path

    Andrej Shadura <andrew.shadura@collabora.co.uk> wrote:
    ...
    > https://bugs.debian.org/874264
    > -------- Forwarded Message --------
    > Subject: dash: 'command -v' mistakenly returns a shell script whose
    > executable is not set
    > Date: Mon, 04 Sep 2017 10:45:48 -0400
    > From: Norman Ramsey <nr@cs.tufts.edu>
    > To: Debian Bug Tracking System <submit@bugs.debian.org>
    ...
    > I tracked a build bug in s-nail to a problem with dash.  Symptom:
    > building s-nail tries to run /home/nr/bin/clang, a script whose
    > executable bit is not set.  We tracked the problem to the result of
    > running `command -v clang` with /bin/sh:
    ...
    This is inherited from NetBSD.  There is even a commented-out
    block of code that tried to fix this.

    Anyway, we now have faccessat so we can simply use it.

function                                             old     new   delta
test_exec                                              -     125    +125
find_command                                         911     918      +7
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 132/0)             Total: 132 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 05:46:31 +02:00
Denys Vlasenko 748b168154 libbb: move is_in_supplementary_groups() from test to libbb
function                                             old     new   delta
is_in_supplementary_groups                             -      54     +54
nexpr                                                766     721     -45
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 54/-45)              Total: 9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-07 01:20:43 +02:00
Denys Vlasenko bb5525613e test: Invert return value of test_eaccess and rename it to test_st_mode
From dash:

    From: herbert <herbert@gondor.apana.org.au>
    Date: Wed, 2 Mar 2005 22:14:54 +1100
    Invert return value of test_eaccess and rename it to test_st_mode.

function                                             old     new   delta
nexpr                                                800     766     -34

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-06 19:25:07 +02:00
Denys Vlasenko 222802e833 test: code shrink
function                                             old     new   delta
nexpr                                                813     800     -13

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-06 19:08:10 +02:00
Thomas Devoogdt 8953429a82 networking/libiproute/iplink.c: fix support for older kernels
- The CAN netlink interface has been added in Linux v2.6.31 with only 3 options [1]:

  CAN_CTRLMODE_LOOPBACK    0x1  /* Loopback mode */
  CAN_CTRLMODE_LISTENONLY  0x2  /* Listen-only mode */
  CAN_CTRLMODE_3_SAMPLES   0x4  /* Triple sampling mode */

  So define the other options.

- IFLA_CAN_TERMINATION has been added in Linux 4.11 [2],
  define it for older kernels.

[1] https://github.com/torvalds/linux/blob/v2.6.31/include/linux/can/netlink.h#L80-L82
[2] https://github.com/torvalds/linux/commit/12a6075cabc0d9ffbc0366b44daa22f278606312

Signed-off-by: Thomas Devoogdt <thomas@devoogdt.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-06 18:25:01 +02:00
Rudi Heitbaum bf57f732a5 libbb: fix sha1 on !x86 if CONFIG_SHA1_HWACCEL=y
fixes non i386 and x86 builds

libbb/hash_md5_sha.c: In function 'sha1_end':
libbb/hash_md5_sha.c:1316:35: error: 'sha1_process_block64_shaNI' undeclared
 1316 |          || ctx->process_block == sha1_process_block64_shaNI

Signed-off-by: Rudi Heitbaum <rudi@heitbaum.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-10-06 17:56:42 +02:00
Denys Vlasenko dff444bc37 hush: whitespace and comment fixes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-28 03:52:44 +02:00
Ron Yorston 24aa93d538 ash: reject unknown long options
Commit 64f70cc755 (Add --login support) added code in options()
to handle the bash-compatible '--login' option.  In doing so it
committed BusyBox ash to silently accepting all other long
options.

Restore compatibility with other ash variants by rejecting unknown
long options.

function                                             old     new   delta
options                                              589     624     +35

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 21:29:05 +02:00
Ron Yorston 39c5c08b28 lineedit: use stdout for shell history builtin
Commit fd47f0567 (lineedit: print prompt and editing operations
to stderr) changed various print statements to output to stderr.
The change in show_history() caused the shell history builtin to
send its output to stderr.

Revert that part of the commit.

function                                             old     new   delta
show_history                                          47      42      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-5)               Total: -5 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 20:16:23 +02:00
Ron Yorston 26895db35d ed: fix line insertion before current line. Closes 15081
When text is inserted by insertLine() the lines following the
insertion are moved down and the insertion point is made the new
current line.  To avoid too much scanning of the linked list of
lines setCurNum() may use the position of the old current line to
determine the location of the new current line.

If the insertion point is before the old current line in the file
the latter will have been moved down, so its line pointer needs to
be adjusted.

function                                             old     new   delta
insertLine                                           162     180     +18
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 18/0)               Total: 18 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 20:14:04 +02:00
Sam James 480a07bd68 fixdep: add fstat error handling
When `fstat` fails, `st` is left uninitialised. In our case, Ben Kohler
noticed our release media builds were failing in Gentoo on x86 when building
busybox with occasional SIGBUS. This turned out to be EOVERFLOW (from 32-bit
ino_t) which wasn't being reported because nothing was checking the return value
from `fstat`.

Fix that to avoid UB (use of uninit var) and to give a more friendly
error to the user.

This actually turns out to be fixed already in the kernel from back in
2010 [0] and 2016 [1].

[0] https://github.com/torvalds/linux/commit/a3ba81131aca243bfecfa78c42edec0cd69f72d6
[1] https://github.com/torvalds/linux/commit/46fe94ad18aa7ce6b3dad8c035fb538942020f2b

Reported-by: Ben Kohler <bkohler@gentoo.org>
Signed-off-by: Sam James <sam@gentoo.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 20:03:30 +02:00
Ron Yorston dbd14c4a42 libbb: send usage messages to correct stream
POSIX generally requires normal output to go to stdout and
diagnostic (i.e. error) output to go to stderr.

When usage messages for BusyBox applets are specifically requested
by the user (e.g. 'find --help') they should go to stdout; when
they're emitted due to an error they should go to stderr.

function                                             old     new   delta
bb_show_usage                                        148     146      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-2)               Total: -2 bytes

Signed-off-by: Avi Halachmi <avihpit@yahoo.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 19:52:25 +02:00
Ron Yorston 2c232f1e60 libbb: use full_write1_str() to shrink busybox_main()
There are two calls to dup2() in busybox_main().  These were
introduced to coerce full_write2_str() into writing to stdout.

The relevant commits were: 21278dff7 (busybox: do not print help
to fd 2, print it to fd 1) and 5a7c72015 (busybox --list option.
+140 bytes. Rob wanted it.)

Later, in commit 729ecb87b (bbconfig: make it independent from
printf functions), the function full_write1_str() was added.

Using this in busybox_main() allows us to drop the dup2() calls.

function                                             old     new   delta
run_applet_and_exit                                  796     760     -36
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-36)             Total: -36 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 19:39:28 +02:00
Denys Vlasenko e5b0547ac8 lineedit: make save_history() FAST_FUNC
function                                             old     new   delta
save_history                                         267     266      -1
hush_exit                                             98      97      -1
exitshell                                            140     138      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-4)               Total: -4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-27 19:35:50 +02:00
Denys Vlasenko a023f39265 Start 1.38.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2024-09-26 23:33:06 +02:00
324 changed files with 19169 additions and 7144 deletions

No files matched your search

+7
View File
@@ -204,6 +204,13 @@ config FEATURE_INSTALLER
busybox at runtime to create hard links or symlinks for all the
applets that are compiled into busybox.
config FEATURE_VERSION
bool "Support --version"
default y
depends on BUSYBOX
help
Enable 'busybox --version' support.
config INSTALL_NO_USR
bool "Don't use /usr"
default n
+7 -2
View File
@@ -1,5 +1,5 @@
VERSION = 1
PATCHLEVEL = 37
PATCHLEVEL = 38
SUBLEVEL = 0
EXTRAVERSION =
NAME = Unnamed
@@ -476,6 +476,7 @@ libs-y := \
findutils/ \
init/ \
libbb/ \
libbb/yescrypt/ \
libpwdgrp/ \
loginutils/ \
mailutils/ \
@@ -612,8 +613,12 @@ quiet_cmd_busybox__ ?= LINK $@
"$(core-y)" \
"$(libs-y)" \
"$(LDLIBS)" \
"$(CONFIG_EXTRA_LDLIBS)" \
$(CONFIG_EXTRA_LDLIBS) \
&& $(srctree)/scripts/generate_BUFSIZ.sh --post include/common_bufsiz.h
# ^^^ note: CONFIG_xyz strings already have double quotes: their value
# is '"LIB LIB2"', therefore $(CONFIG_EXTRA_LDLIBS) above must NOT be written
# as "$(CONFIG_EXTRA_LDLIBS)", it would be passed as ""LIB LIB2"",
# and LIB2 would end up in $9, not $8 (and lost or misinterpreted).
# Generate System.map
quiet_cmd_sysmap = SYSMAP
+2 -2
View File
@@ -156,12 +156,12 @@ docs/busybox.pod: $(srctree)/docs/busybox_header.pod \
docs/BusyBox.txt: docs/busybox.pod
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-pod2text $< > $@
$(Q)-pod2text --quotes=none $< > $@
docs/busybox.1: docs/busybox.pod
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-pod2man --center=busybox --release="version $(KERNELVERSION)" $< > $@
$(Q)-pod2man --quotes=none --center=busybox --release="version $(KERNELVERSION)" $< > $@
docs/BusyBox.html: docs/busybox.net/BusyBox.html
$(disp_doc)
+1
View File
@@ -336,6 +336,7 @@ setuidgid - noexec. spawner
sha1sum - noexec. runner
sha256sum - noexec. runner
sha3sum - noexec. runner
sha384sum - noexec. runner
sha512sum - noexec. runner
showkey - interactive, longterm
shred - runner
+12 -5
View File
@@ -67,30 +67,37 @@ int main(void)
}
if (col == 0) {
col = 6;
printf("\t");
} else {
printf(", ");
}
printf("%s", usage_array[i].aname);
if (usage_array[i].usage[0] != NOUSAGE_STR[0]) {
/*
* If the applet usage string will be included in the final document
* optimistically link to its header (which is just the applet name).
*/
printf("L<C<%1$s>|/\"%1$s\">", usage_array[i].aname);
} else {
/* Without a usage string, just output the applet name with no link. */
printf("C<%s>", usage_array[i].aname);
}
col += len2;
}
printf("\n\n");
printf("=head1 COMMAND DESCRIPTIONS\n\n");
printf("=over 4\n\n");
for (i = 0; i < num_messages; i++) {
if (usage_array[i].aname[0] >= 'a' && usage_array[i].aname[0] <= 'z'
&& usage_array[i].usage[0] != NOUSAGE_STR[0]
) {
printf("=item B<%s>\n\n", usage_array[i].aname);
/* This is the heading that will be linked from the command list. */
printf("=head2 %s\n\n", usage_array[i].aname);
if (usage_array[i].usage[0])
printf("%s %s\n\n", usage_array[i].aname, usage_array[i].usage);
else
printf("%s\n\n", usage_array[i].aname);
}
}
printf("=back\n\n");
return 0;
}
+11
View File
@@ -35,4 +35,15 @@ config FEATURE_LZMA_FAST
This option reduces decompression time by about 25% at the cost of
a 1K bigger binary.
config FEATURE_PATH_TRAVERSAL_PROTECTION
bool "Prevent extraction of filenames with /../ path component"
default n
help
busybox tar and unzip remove "PREFIX/../" (if it exists)
from extracted names.
This option enables this behavior for all other unpacking applets,
such as cpio, ar, rpm.
GNU cpio 2.15 has NO such sanity check.
# try other archivers and document their behavior?
endmenu
+3 -3
View File
@@ -71,8 +71,8 @@ int FAST_FUNC bbunpack(char **argv,
goto err;
} else {
/* "clever zcat" with FILE */
/* fail_if_not_compressed because zcat refuses uncompressed input */
int fd = open_zipped(filename, /*fail_if_not_compressed:*/ 1);
/* die_if_not_compressed because zcat refuses uncompressed input */
int fd = open_zipped(filename, /*die_if_not_compressed:*/ 1);
if (fd < 0)
goto err_name;
xmove_fd(fd, STDIN_FILENO);
@@ -80,7 +80,7 @@ int FAST_FUNC bbunpack(char **argv,
} else
if (option_mask32 & BBUNPK_SEAMLESS_MAGIC) {
/* "clever zcat" on stdin */
if (setup_unzip_on_fd(STDIN_FILENO, /*fail_if_not_compressed*/ 1))
if (setup_unzip_on_fd(STDIN_FILENO, /*die_if_not_compressed*/ 1))
goto err;
}
+7
View File
@@ -350,6 +350,12 @@ static NOINLINE int cpio_o(void)
st.st_dev = st.st_rdev = 0;
#endif
if (sizeof(st.st_size) > 4
&& st.st_size > (off_t)0xffffffff
) {
bb_error_msg_and_die("error: file '%s' is larger than 4GB", name);
}
bytes += printf("070701"
"%08X%08X%08X%08X%08X%08X%08X"
"%08X%08X%08X%08X" /* GNU cpio uses uppercase hex */
@@ -421,6 +427,7 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
#endif
#endif
"owner\0" Required_argument "R"
"file\0" Required_argument "F"
"verbose\0" No_argument "v"
"null\0" No_argument "0"
"quiet\0" No_argument "\xff"
+1 -1
View File
@@ -1689,7 +1689,7 @@ static void unpack_package(deb_file_t *deb_file)
accept_list = NULL;
i = 0;
while (i < ARRAY_SIZE(all_control_files)) {
char *c = xasprintf("./%s", all_control_files[i]);
char *c = concat_path_file(".", all_control_files[i]);
llist_add_to(&accept_list, c);
i++;
}
+3
View File
@@ -2215,6 +2215,9 @@ int gzip_main(int argc UNUSED_PARAM, char **argv)
};
#endif
// TODO: use less ugly "split-globals" trick via SET_OFFSET_PTR_TO_GLOBALS().
// The problem is, the current method strategically places G2.heap[]
// (~24 references) so that it has zero offset.
SET_PTR_TO_GLOBALS((char *)xzalloc(sizeof(struct globals)+sizeof(struct globals2))
+ sizeof(struct globals));
+3 -3
View File
@@ -12,6 +12,7 @@ COMMON_FILES:= \
data_extract_all.o \
data_extract_to_stdout.o \
\
unsafe_prefix.o \
unsafe_symlink_target.o \
\
filter_accept_all.o \
@@ -32,7 +33,6 @@ COMMON_FILES:= \
DPKG_FILES:= \
unpack_ar_archive.o \
filter_accept_list_reassign.o \
unsafe_prefix.o \
get_header_ar.o \
get_header_tar.o \
get_header_tar_gz.o \
@@ -47,7 +47,7 @@ lib-$(CONFIG_DPKG_DEB) += $(DPKG_FILES)
lib-$(CONFIG_AR) += get_header_ar.o unpack_ar_archive.o
lib-$(CONFIG_CPIO) += get_header_cpio.o
lib-$(CONFIG_TAR) += get_header_tar.o unsafe_prefix.o
lib-$(CONFIG_TAR) += get_header_tar.o
lib-$(CONFIG_FEATURE_TAR_TO_COMMAND) += data_extract_to_command.o
lib-$(CONFIG_LZOP) += lzo1x_1.o lzo1x_1o.o lzo1x_d.o
lib-$(CONFIG_UNLZOP) += lzo1x_1.o lzo1x_1o.o lzo1x_d.o
@@ -67,7 +67,7 @@ lib-$(CONFIG_FEATURE_UNZIP_XZ) += open_transformer.o decompress_unxz.o
# 'gzip -d', gunzip or zcat selects FEATURE_GZIP_DECOMPRESS
lib-$(CONFIG_FEATURE_GZIP_DECOMPRESS) += open_transformer.o decompress_gunzip.o
lib-$(CONFIG_UNCOMPRESS) += open_transformer.o decompress_uncompress.o
lib-$(CONFIG_UNZIP) += open_transformer.o decompress_gunzip.o unsafe_prefix.o
lib-$(CONFIG_UNZIP) += open_transformer.o decompress_gunzip.o
lib-$(CONFIG_RPM2CPIO) += open_transformer.o decompress_gunzip.o get_header_cpio.o
lib-$(CONFIG_RPM) += open_transformer.o decompress_gunzip.o get_header_cpio.o
lib-$(CONFIG_GZIP) += open_transformer.o
+13 -2
View File
@@ -65,6 +65,18 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
} while (--n != 0);
}
#endif
#if ENABLE_FEATURE_PATH_TRAVERSAL_PROTECTION
/* Skip leading "/" and past last ".." path component */
# if ENABLE_FEATURE_TAR_LONG_OPTIONS
dst_name = (char *)skip_unsafe_prefix(dst_name);
# else /* dst_name is file_header->name, which is free()d by e.g. cpio - must copy, can't just advance the ptr */
strip_unsafe_prefix(dst_name);
# endif
#endif
// ^^^ This may be a problem if some applets do need to extract absolute names.
// (Probably will need to invent ARCHIVE_ALLOW_UNSAFE_NAME flag).
// You might think that rpm needs it, but in my tests rpm's internal cpio
// archive has names like "./usr/bin/FOO", not "/usr/bin/FOO".
if (archive_handle->ah_flags & ARCHIVE_CREATE_LEADING_DIRS) {
char *slash = strrchr(dst_name, '/');
@@ -177,8 +189,7 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
/* To avoid a directory traversal attack via symlinks,
* do not restore symlinks with ".." components
* or symlinks starting with "/", unless a magic
* envvar is set.
* or symlinks starting with "/"
*
* For example, consider a .tar created via:
* $ tar cvf bug.tar anything.txt
+9 -2
View File
@@ -454,8 +454,15 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
#endif
/* Everything up to and including last ".." component is stripped */
overlapping_strcpy(file_header->name, strip_unsafe_prefix(file_header->name));
//TODO: do the same for file_header->link_target?
strip_unsafe_prefix(file_header->name);
if (file_header->link_target && !S_ISLNK(file_header->mode)) {
/* GNU tar 1.34 examples:
* tar: Removing leading '/' from hard link targets
* tar: Removing leading '../' from hard link targets
* tar: Removing leading 'etc/../' from hard link targets
*/
strip_unsafe_prefix(file_header->link_target);
}
/* Strip trailing '/' in directories */
/* Must be done after mode is set as '/' is used to check if it's a directory */
+1 -1
View File
@@ -8,5 +8,5 @@
void FAST_FUNC header_list(const file_header_t *file_header)
{
//TODO: cpio -vp DIR should output "DIR/NAME", not just "NAME" */
puts(file_header->name);
puts(printable_string(file_header->name));
}
+2 -2
View File
@@ -57,13 +57,13 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec,
file_header->name);
printable_string(file_header->name));
#endif /* FEATURE_TAR_UNAME_GNAME */
/* NB: GNU tar shows "->" for symlinks and "link to" for hardlinks */
if (file_header->link_target) {
printf(" -> %s", file_header->link_target);
printf(" -> %s", printable_string(file_header->link_target));
}
bb_putchar('\n');
}
-2
View File
@@ -797,7 +797,6 @@ static int lzo1x_999_compress_internal(const uint8_t *in, unsigned in_len,
if (swd->use_best_off)
better_match(swd, &m_len, &m_off);
#endif
/* shall we try a lazy match ? */
ahead = 0;
if (m_len >= max_lazy) {
@@ -811,7 +810,6 @@ static int lzo1x_999_compress_internal(const uint8_t *in, unsigned in_len,
max_ahead = LZO_MIN(2, (unsigned)l1 - 1);
}
while (ahead < max_ahead && c->look > m_len) {
int lazy_match_min_gain;
+14 -12
View File
@@ -157,7 +157,7 @@ void FAST_FUNC fork_transformer(int fd, const char *transform_prog)
/* Used by e.g. rpm which gives us a fd without filename,
* thus we can't guess the format from filename's extension.
*/
static transformer_state_t *setup_transformer_on_fd(int fd, int fail_if_not_compressed)
static transformer_state_t *setup_transformer_on_fd(int fd, int die_if_not_compressed)
{
transformer_state_t *xstate;
@@ -204,7 +204,7 @@ static transformer_state_t *setup_transformer_on_fd(int fd, int fail_if_not_comp
}
/* No known magic seen */
if (fail_if_not_compressed)
if (die_if_not_compressed)
bb_simple_error_msg_and_die("no gzip"
IF_FEATURE_SEAMLESS_BZ2("/bzip2")
IF_FEATURE_SEAMLESS_XZ("/xz")
@@ -240,13 +240,15 @@ static void fork_transformer_and_free(transformer_state_t *xstate)
/* Used by e.g. rpm which gives us a fd without filename,
* thus we can't guess the format from filename's extension.
*/
int FAST_FUNC setup_unzip_on_fd(int fd, int fail_if_not_compressed)
int FAST_FUNC setup_unzip_on_fd(int fd, int die_if_not_compressed)
{
transformer_state_t *xstate = setup_transformer_on_fd(fd, fail_if_not_compressed);
transformer_state_t *xstate = setup_transformer_on_fd(fd, die_if_not_compressed);
if (!xstate->xformer) {
/* Not compressed */
int retval = xstate->signature_skipped; /* never zero */
free(xstate);
return 1;
return retval;
}
fork_transformer_and_free(xstate);
@@ -264,7 +266,7 @@ void FAST_FUNC setup_lzma_on_fd(int fd)
}
#endif
static transformer_state_t *open_transformer(const char *fname, int fail_if_not_compressed)
static transformer_state_t *open_transformer(const char *fname, int die_if_not_compressed)
{
transformer_state_t *xstate;
int fd;
@@ -284,18 +286,18 @@ static transformer_state_t *open_transformer(const char *fname, int fail_if_not_
}
}
xstate = setup_transformer_on_fd(fd, fail_if_not_compressed);
xstate = setup_transformer_on_fd(fd, die_if_not_compressed);
return xstate;
}
int FAST_FUNC open_zipped(const char *fname, int fail_if_not_compressed)
int FAST_FUNC open_zipped(const char *fname, int die_if_not_compressed)
{
int fd;
transformer_state_t *xstate;
xstate = open_transformer(fname, fail_if_not_compressed);
if (!xstate)
xstate = open_transformer(fname, die_if_not_compressed);
if (!xstate) /* open error */
return -1;
fd = xstate->src_fd;
@@ -326,7 +328,7 @@ void* FAST_FUNC xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_
transformer_state_t *xstate;
char *image;
xstate = open_transformer(fname, /*fail_if_not_compressed:*/ 0);
xstate = open_transformer(fname, /*die_if_not_compressed:*/ 0);
if (!xstate) /* file open error */
return NULL;
@@ -371,7 +373,7 @@ void* FAST_FUNC xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_
int fd;
char *image;
fd = open_zipped(fname, /*fail_if_not_compressed:*/ 0);
fd = open_zipped(fname, /*die_if_not_compressed:*/ 0);
if (fd < 0)
return NULL;
+30 -6
View File
@@ -5,23 +5,42 @@
#include "libbb.h"
#include "bb_archive.h"
const char* FAST_FUNC strip_unsafe_prefix(const char *str)
const char* FAST_FUNC skip_unsafe_prefix(const char *str)
{
const char *cp = str;
while (1) {
char *cp2;
const char *cp2;
if (*cp == '/') {
cp++;
continue;
}
if (is_prefixed_with(cp, "/../"+1)) {
/* We are called lots of times.
* is_prefixed_with(cp, "../") is slower than open-coding it,
* with minimal code growth (~few bytes).
*/
if (cp[0] == '.' && cp[1] == '.' && cp[2] == '/') {
cp += 3;
continue;
}
cp2 = strstr(cp, "/../");
cp2 = cp;
find_dotdot:
cp2 = strstr(cp2, "/..");
if (!cp2)
break;
cp = cp2 + 4;
break; /* No (more) malicious components */
/* We found "/..something" */
cp2 += 3;
if (*cp2 != '/') {
if (*cp2 == '\0') {
/* Trailing "/..": malicious, return "" */
/* (causes harmless errors trying to create or hardlink a file named "") */
return cp2;
}
/* "/..name" is not malicious, look for next "/.." */
goto find_dotdot;
}
/* Found "/../": malicious, advance past it */
cp = cp2 + 1;
}
if (cp != str) {
static smallint warned = 0;
@@ -33,3 +52,8 @@ const char* FAST_FUNC strip_unsafe_prefix(const char *str)
}
return cp;
}
void FAST_FUNC strip_unsafe_prefix(char *str)
{
overlapping_strcpy(str, skip_unsafe_prefix(str));
}
@@ -36,6 +36,7 @@ void FAST_FUNC create_links_from_list(llist_t *list)
*list->data ? "hard" : "sym",
list->data + 1, target
);
/* Note: GNU tar 1.34 errors out only _after_ all links are (attempted to be) created */
}
list = list->link;
}
-1
View File
@@ -208,7 +208,6 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit = 0;
goto match_done;
/* handle matches */
do {
if (t < 16) { /* a M1 match */
+7 -2
View File
@@ -316,7 +316,7 @@ static void extract_cpio(int fd, const char *source_rpm)
archive_handle->src_fd = fd;
/*archive_handle->offset = 0; - init_handle() did it */
setup_unzip_on_fd(archive_handle->src_fd, /*fail_if_not_compressed:*/ 1);
setup_unzip_on_fd(archive_handle->src_fd, /*die_if_not_compressed:*/ 1);
while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
continue;
}
@@ -533,6 +533,7 @@ int rpm2cpio_main(int argc UNUSED_PARAM, char **argv)
// /* We need to know whether child (gzip/bzip/etc) exits abnormally */
// signal(SIGCHLD, check_errors_in_children);
str = NULL;
if (ENABLE_FEATURE_SEAMLESS_LZMA
&& (str = rpm_getstr0(TAG_PAYLOADCOMPRESSOR)) != NULL
&& strcmp(str, "lzma") == 0
@@ -541,7 +542,11 @@ int rpm2cpio_main(int argc UNUSED_PARAM, char **argv)
// set up decompressor without detection
setup_lzma_on_fd(rpm_fd);
} else {
setup_unzip_on_fd(rpm_fd, /*fail_if_not_compressed:*/ 1);
int signature_bytes = setup_unzip_on_fd(rpm_fd, /*die_if_not_compressed:*/ 0);
if (signature_bytes != 0) {
xlseek(rpm_fd, - signature_bytes, SEEK_CUR);
bb_error_msg("warning, unknown compression '%s'", str);
}
}
if (bb_copyfd_eof(rpm_fd, STDOUT_FILENO) < 0)
+6 -2
View File
@@ -119,6 +119,7 @@
#include "libbb.h"
#include "common_bufsiz.h"
#include "bb_archive.h"
#include "unicode.h"
/* FIXME: Stop using this non-standard feature */
#ifndef FNM_LEADING_DIR
# define FNM_LEADING_DIR 0
@@ -475,7 +476,7 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
DBG("writeFileToTarball('%s')", fileName);
/* Strip leading '/' and such (must be before memorizing hardlink's name) */
header_name = strip_unsafe_prefix(fileName);
header_name = skip_unsafe_prefix(fileName);
if (header_name[0] == '\0')
return TRUE;
@@ -1133,6 +1134,9 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
if (tar_handle->accept || tar_handle->reject)
tar_handle->filter = filter_accept_reject_list;
/* For "tar xvf/tvf" output and Unicode in names */
init_unicode();
/* Open the tar file */
{
int tar_fd = STDIN_FILENO;
@@ -1164,7 +1168,7 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
* on e.g. tarball with 1st file named "BZh5".
*/
) {
tar_handle->src_fd = open_zipped(tar_filename, /*fail_if_not_compressed:*/ 0);
tar_handle->src_fd = open_zipped(tar_filename, /*die_if_not_compressed:*/ 0);
if (tar_handle->src_fd < 0)
bb_perror_msg_and_die("can't open '%s'", tar_filename);
} else {
+1 -1
View File
@@ -860,7 +860,7 @@ int unzip_main(int argc, char **argv)
/* Guard against "/abspath", "/../" and similar attacks */
// NB: UnZip 6.00 has option -: to disable this
overlapping_strcpy(dst_fn, strip_unsafe_prefix(dst_fn));
strip_unsafe_prefix(dst_fn);
/* Filter zip entries */
if (find_list_entry(zreject, dst_fn)
+2 -2
View File
@@ -70,8 +70,8 @@ int showkey_main(int argc UNUSED_PARAM, char **argv)
INIT_G();
// FIXME: aks are all mutually exclusive
getopt32(argv, "aks");
// a,k,s are all mutually exclusive
getopt32(argv, "^" "aks" "\0" "a--ks:k--as:s--ak");
// prepare for raw mode
xget1(&tio, &tio0);
+2 -1
View File
@@ -215,7 +215,8 @@ int cp_main(int argc, char **argv)
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
d_flags = cp_mv_stat2(last, &dest_stat,
(flags & FILEUTILS_NO_TARGET_DIR) ? lstat : stat);
if (d_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
+270 -166
View File
@@ -27,21 +27,34 @@
//kbuild:lib-$(CONFIG_CUT) += cut.o
//usage:#define cut_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage: "{-b|c LIST | -f"IF_FEATURE_CUT_REGEX("|F")" LIST [-d SEP] [-s]} [-D] [-O SEP] [FILE]..."
// --output-delimiter SEP is too long to fit into 80 char-wide help ----------------^^^^^^^^
//usage:#define cut_full_usage "\n\n"
//usage: "Print selected fields from FILEs to stdout\n"
//usage: "\n -b LIST Output only bytes from LIST"
//usage: "\n -c LIST Output only characters from LIST"
//usage: "\n -d SEP Field delimiter for input (default -f TAB, -F run of whitespace)"
//usage: "\n -O SEP Field delimeter for output (default = -d for -f, one space for -F)"
//usage: "\n -D Don't sort/collate sections or match -fF lines without delimeter"
//usage: IF_FEATURE_CUT_REGEX(
//usage: "\n -d SEP Input field delimiter (default -f TAB, -F run of whitespace)"
//usage: ) IF_NOT_FEATURE_CUT_REGEX(
//usage: "\n -d SEP Input field delimiter (default TAB)"
//usage: )
//usage: "\n -f LIST Print only these fields (-d is single char)"
//usage: IF_FEATURE_CUT_REGEX(
//usage: "\n -F LIST Print only these fields (-d is regex)"
//usage: )
//usage: "\n -s Output only lines containing delimiter"
//usage: "\n -s Drop lines with no delimiter (else print them in full)"
//usage: "\n -D Don't sort ranges; line without delimiters has one field"
//usage: IF_LONG_OPTS(
//usage: "\n --output-delimiter SEP Output field delimeter"
//usage: ) IF_NOT_LONG_OPTS(
//usage: IF_FEATURE_CUT_REGEX(
//usage: "\n -O SEP Output field delimeter (default = -d for -f, one space for -F)"
//usage: ) IF_NOT_FEATURE_CUT_REGEX(
//usage: "\n -O SEP Output field delimeter (default = -d)"
//usage: )
//usage: )
//usage: "\n -n Ignored"
//(manpage:-n with -b: don't split multibyte characters)
//(manpage:-n with -b: don't split multibyte characters)
//usage:
//usage:#define cut_example_usage
//usage: "$ echo \"Hello world\" | cut -f 1 -d ' '\n"
@@ -53,11 +66,6 @@
#if ENABLE_FEATURE_CUT_REGEX
#include "xregex.h"
#else
#define regex_t int
typedef struct { int rm_eo, rm_so; } regmatch_t;
#define xregcomp(x, ...) *(x) = 0
#define regexec(...) 0
#endif
/* This is a NOEXEC applet. Be very careful! */
@@ -65,250 +73,346 @@ typedef struct { int rm_eo, rm_so; } regmatch_t;
/* option vars */
#define OPT_STR "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
#define CUT_OPT_BYTE_FLGS (1 << 0)
#define CUT_OPT_CHAR_FLGS (1 << 1)
#define CUT_OPT_FIELDS_FLGS (1 << 2)
#define CUT_OPT_DELIM_FLGS (1 << 3)
#define CUT_OPT_ODELIM_FLGS (1 << 4)
#define CUT_OPT_SUPPRESS_FLGS (1 << 5)
#define CUT_OPT_NOSORT_FLGS (1 << 6)
#define CUT_OPT_REGEX_FLGS ((1 << 7) * ENABLE_FEATURE_CUT_REGEX)
#define OPT_BYTE (1 << 0)
#define OPT_CHAR (1 << 1)
#define OPT_FIELDS (1 << 2)
#define OPT_DELIM (1 << 3)
#define OPT_ODELIM (1 << 4)
#define OPT_SUPPRESS (1 << 5)
#define OPT_NOSORT (1 << 6)
#define OPT_REGEX ((1 << 7) * ENABLE_FEATURE_CUT_REGEX)
struct cut_list {
int startpos;
int endpos;
#define opt_REGEX (option_mask32 & OPT_REGEX)
struct cut_range {
unsigned startpos;
unsigned endpos;
};
static int cmpfunc(const void *a, const void *b)
{
return (((struct cut_list *) a)->startpos -
((struct cut_list *) b)->startpos);
const struct cut_range *aa = a;
const struct cut_range *bb = b;
return aa->startpos - bb->startpos;
}
#define END_OF_LIST(list_elem) ((list_elem).startpos == UINT_MAX)
#define NOT_END_OF_LIST(list_elem) ((list_elem).startpos != UINT_MAX)
static void cut_file(FILE *file, const char *delim, const char *odelim,
const struct cut_list *cut_lists, unsigned nlists)
const struct cut_range *cut_list)
{
char *line;
unsigned linenum = 0; /* keep these zero-based to be consistent */
regex_t reg;
int spos, shoe = option_mask32 & CUT_OPT_REGEX_FLGS;
if (shoe) xregcomp(&reg, delim, REG_EXTENDED);
int first_print = 1;
/* go through every line in the file */
while ((line = xmalloc_fgetline(file)) != NULL) {
/* set up a list so we can keep track of what's been printed */
int linelen = strlen(line);
char *printed = xzalloc(linelen + 1);
char *orig_line = line;
unsigned linelen = strlen(line);
unsigned cl_pos = 0;
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (option_mask32 & (CUT_OPT_CHAR_FLGS | CUT_OPT_BYTE_FLGS)) {
/* Cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (option_mask32 & (OPT_CHAR | OPT_BYTE)) {
char *printed = xzalloc(linelen + 1);
int need_odelim = 0;
/* print the chars specified in each cut list */
for (; cl_pos < nlists; cl_pos++) {
for (spos = cut_lists[cl_pos].startpos; spos < linelen;) {
for (; NOT_END_OF_LIST(cut_list[cl_pos]); cl_pos++) {
unsigned spos = cut_list[cl_pos].startpos;
while (spos < linelen) {
if (!printed[spos]) {
printed[spos] = 'X';
if (need_odelim && spos != 0 && !printed[spos-1]) {
need_odelim = 0;
fputs_stdout(odelim);
}
putchar(line[spos]);
}
if (++spos > cut_lists[cl_pos].endpos) {
spos++;
if (spos > cut_list[cl_pos].endpos) {
/* will print OSEP (if not empty) */
need_odelim = (odelim && odelim[0]);
break;
}
}
}
} else if (*delim == '\n') { /* cut by lines */
spos = cut_lists[cl_pos].startpos;
free(printed);
/* Cut by lines */
} else if (!opt_REGEX && *delim == '\n') {
unsigned spos = cut_list[cl_pos].startpos;
/* get out if we have no more lists to process or if the lines
linenum++;
/* get out if we have no more ranges to process or if the lines
* are lower than what we're interested in */
if (((int)linenum < spos) || (cl_pos >= nlists))
if (linenum <= spos || END_OF_LIST(cut_list[cl_pos]))
goto next_line;
/* if the line we're looking for is lower than the one we were
* passed, it means we displayed it already, so move on */
while (spos < (int)linenum) {
spos++;
while (++spos < linenum) {
/* go to the next list if we're at the end of this one */
if (spos > cut_lists[cl_pos].endpos) {
if (spos > cut_list[cl_pos].endpos) {
cl_pos++;
/* get out if there's no more lists to process */
if (cl_pos >= nlists)
/* get out if there's no more ranges to process */
if (END_OF_LIST(cut_list[cl_pos]))
goto next_line;
spos = cut_lists[cl_pos].startpos;
spos = cut_list[cl_pos].startpos;
/* get out if the current line is lower than the one
* we just became interested in */
if ((int)linenum < spos)
if (linenum <= spos)
goto next_line;
}
}
/* If we made it here, it means we've found the line we're
* looking for, so print it */
puts(line);
if (first_print) {
first_print = 0;
fputs_stdout(line);
} else
printf("%s%s", odelim, line);
goto next_line;
} else { /* cut by fields */
unsigned uu = 0, start = 0, end = 0, out = 0;
int dcount = 0;
/* Cut by fields */
} else {
unsigned next = 0, start = 0, end = 0;
unsigned dcount = 0; /* we saw Nth delimiter (0 - didn't see any yet) */
/* Blank line? Check -s (later check for -s does not catch empty lines) */
if (linelen == 0) {
if (option_mask32 & OPT_SUPPRESS)
goto next_line;
}
if (!odelim)
odelim = "\t";
first_print = 1;
/* Loop through bytes, finding next delimiter */
for (;;) {
/* End of current range? */
if (end == linelen || dcount > cut_lists[cl_pos].endpos) {
if (++cl_pos >= nlists) break;
if (option_mask32 & CUT_OPT_NOSORT_FLGS)
start = dcount = uu = 0;
end = 0;
if (end == linelen || dcount > cut_list[cl_pos].endpos) {
end_of_range:
cl_pos++;
if (END_OF_LIST(cut_list[cl_pos]))
break;
if (option_mask32 & OPT_NOSORT)
start = dcount = next = 0;
end = 0; /* (why?) */
//bb_error_msg("End of current range");
}
/* End of current line? */
if (uu == linelen) {
/* If we've seen no delimiters, check -s */
if (!cl_pos && !dcount && !shoe) {
if (option_mask32 & CUT_OPT_SUPPRESS_FLGS)
if (next == linelen) {
end = linelen; /* print up to end */
/* If we've seen no delimiters, and no -D, check -s */
if (!(option_mask32 & OPT_NOSORT) && cl_pos == 0 && dcount == 0) {
if (option_mask32 & OPT_SUPPRESS)
goto next_line;
} else if (dcount < cut_lists[cl_pos].startpos)
start = linelen;
end = linelen;
/* else: will print entire line */
} else if (dcount < cut_list[cl_pos].startpos) {
/* echo 1.2 | cut -d. -f1,3: prints "1", not "1." */
//break;
/* ^^^ this fails a case with -D:
* echo 1 2 | cut -DF 1,3,2:
* do not end line processing when didn't find field#3
*/
//if (option_mask32 & OPT_NOSORT) - no, just do it always
goto end_of_range;
}
//bb_error_msg("End of current line: s:%d e:%d", start, end);
} else {
/* Find next delimiter */
if (shoe) {
regmatch_t rr = {-1, -1};
#if ENABLE_FEATURE_CUT_REGEX
if (opt_REGEX) {
regmatch_t rr;
regex_t *reg = (void*) delim;
if (!regexec(&reg, line+uu, 1, &rr, REG_NOTBOL|REG_NOTEOL)) {
end = uu + rr.rm_so;
uu += rr.rm_eo;
} else {
uu = linelen;
if (regexec(reg, line + next, 1, &rr, REG_NOTBOL|REG_NOTEOL) != 0) {
/* not found, go to "end of line" logic */
next = linelen;
continue;
}
} else if (line[end = uu++] != *delim)
continue;
/* Got delimiter. Loop if not yet within range. */
if (dcount++ < cut_lists[cl_pos].startpos) {
start = uu;
end = next + rr.rm_so;
next += (rr.rm_eo ? rr.rm_eo : 1);
/* ^^^ advancing by at least 1 prevents infinite loops */
/* testcase: echo "no at sign" | cut -d'@*' -F 1- */
} else
#endif
{
end = next++;
if (line[end] != *delim)
continue;
}
/* Got delimiter */
dcount++;
if (dcount <= cut_list[cl_pos].startpos) {
/* Not yet within range - loop */
start = next;
continue;
}
/* -F N-M preserves intermediate delimiters: */
//printf "1 2 3 4 5 6 7\n" | toybox cut -O: -F2,4-6,7
//2:4 5 6:7
if (opt_REGEX && dcount <= cut_list[cl_pos].endpos)
continue;
// NB: toybox does the above for -f too, but it's a compatibility bug:
//printf "1 2 3 4 5 6 7 8\n" | toybox cut -d' ' -O: -f2,4-6,7
//2:4 5 6:7 // WRONG!
//printf "1 2 3 4 5 6 7 8\n" | cut -d' ' --output-delimiter=: -f2,4-6,7
//2:4:5:6:7 // GNU coreutils 9.1
}
if (end != start || !shoe)
printf("%s%.*s", out++ ? odelim : "", end-start, line + start);
start = uu;
if (!dcount)
break;
}
#if ENABLE_FEATURE_CUT_REGEX
if (end != start || !opt_REGEX)
#endif
{
if (first_print) {
first_print = 0;
printf("%.*s", end - start, line + start);
} else
printf("%s%.*s", odelim, end - start, line + start);
}
start = next;
//if (dcount == 0)
// break; - why?
} /* byte loop */
}
/* if we printed anything, finish with newline */
putchar('\n');
next_line:
linenum++;
free(printed);
free(orig_line);
}
free(line);
} /* while (got line) */
/* For -d$'\n' --output-delimiter=^, the overall output is still terminated with \n, not ^ */
if (!opt_REGEX && *delim == '\n' && !first_print)
putchar('\n');
}
int cut_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cut_main(int argc UNUSED_PARAM, char **argv)
{
/* growable array holding a series of lists */
struct cut_list *cut_lists = NULL;
unsigned nlists = 0; /* number of elements in above list */
char *sopt, *ltok;
/* growable array holding a series of ranges */
struct cut_range *cut_list = NULL;
unsigned nranges = 0; /* number of elements in above list */
char *LIST, *ltok;
const char *delim = NULL;
const char *odelim = NULL;
unsigned opt;
#if ENABLE_FEATURE_CUT_REGEX
regex_t reg;
#endif
#if ENABLE_LONG_OPTS
static const char cut_longopts[] ALIGN1 =
"output-delimiter\0" Required_argument "O"
;
#endif
#define ARG "bcf"IF_FEATURE_CUT_REGEX("F")
opt = getopt32(argv, "^"
#if ENABLE_LONG_OPTS
opt = getopt32long
#else
opt = getopt32
#endif
(argv, "^"
OPT_STR // = "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
"\0" "b--"ARG":c--"ARG":f--"ARG IF_FEATURE_CUT_REGEX("F--"ARG),
&sopt, &sopt, &sopt, &delim, &odelim IF_FEATURE_CUT_REGEX(, &sopt)
);
if (!delim || !*delim)
delim = (opt & CUT_OPT_REGEX_FLGS) ? "[[:space:]]+" : "\t";
if (!odelim) odelim = (opt & CUT_OPT_REGEX_FLGS) ? " " : delim;
"\0" "b:c:f:" IF_FEATURE_CUT_REGEX("F:") /* one of -bcfF is required */
"b--"ARG":c--"ARG":f--"ARG IF_FEATURE_CUT_REGEX(":F--"ARG), /* they are mutually exclusive */
IF_LONG_OPTS(cut_longopts,)
&LIST, &LIST, &LIST, &delim, &odelim IF_FEATURE_CUT_REGEX(, &LIST)
);
if (!odelim)
odelim = (opt & OPT_REGEX) ? " " : delim;
if (!delim)
delim = (opt & OPT_REGEX) ? "[[:space:]]+" : "\t";
// argc -= optind;
argv += optind;
if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS | CUT_OPT_REGEX_FLGS)))
bb_simple_error_msg_and_die("expected a list of bytes, characters, or fields");
//if (!(opt & (OPT_BYTE | OPT_CHAR | OPT_FIELDS | OPT_REGEX)))
// bb_simple_error_msg_and_die("expected a list of bytes, characters, or fields");
//^^^ handled by getopt32
/* non-field (char or byte) cutting has some special handling */
if (!(opt & (CUT_OPT_FIELDS_FLGS|CUT_OPT_REGEX_FLGS))) {
static const char _op_on_field[] ALIGN1 = " only when operating on fields";
if (opt & CUT_OPT_SUPPRESS_FLGS) {
bb_error_msg_and_die
("suppressing non-delimited lines makes sense%s", _op_on_field);
}
if (opt & CUT_OPT_DELIM_FLGS) {
bb_error_msg_and_die
("a delimiter may be specified%s", _op_on_field);
}
/* non-field (char or byte) cutting has some special handling */
if (!(opt & (OPT_FIELDS|OPT_REGEX))) {
static const char requires_f[] ALIGN1 = " requires -f"
IF_FEATURE_CUT_REGEX(" or -F");
if (opt & OPT_SUPPRESS)
bb_error_msg_and_die("-s%s", requires_f);
if (opt & OPT_DELIM)
bb_error_msg_and_die("-d DELIM%s", requires_f);
}
/*
* parse list and put values into startpos and endpos.
* valid list formats: N, N-, N-M, -M
* more than one list can be separated by commas
* valid range formats: N, N-, N-M, -M
* more than one range can be separated by commas
*/
{
/* take apart the ranges, one by one (separated with commas) */
while ((ltok = strsep(&LIST, ",")) != NULL) {
char *ntok;
int s = 0, e = 0;
int s, e;
/* take apart the lists, one by one (they are separated with commas) */
while ((ltok = strsep(&sopt, ",")) != NULL) {
/* it's actually legal to pass an empty list */
//if (!ltok[0])
// continue;
//^^^ testcase?
/* it's actually legal to pass an empty list */
if (!ltok[0])
continue;
/* get the start pos */
ntok = strsep(&ltok, "-");
if (!ntok[0]) {
s = 0;
} else {
s = xatoi_positive(ntok);
/* account for the fact that arrays are zero based, while
* the user expects the first char on the line to be char #1 */
if (s != 0)
s--;
}
/* get the end pos */
if (ltok == NULL) {
e = s;
} else if (!ltok[0]) {
e = INT_MAX;
} else {
e = xatoi_positive(ltok);
/* if the user specified and end position of 0,
* that means "til the end of the line" */
if (!*ltok)
e = INT_MAX;
else if (e < s)
bb_error_msg_and_die("%d<%d", e, s);
e--; /* again, arrays are zero based, lines are 1 based */
}
/* add the new list */
cut_lists = xrealloc_vector(cut_lists, 4, nlists);
/* NB: startpos is always >= 0 */
cut_lists[nlists].startpos = s;
cut_lists[nlists].endpos = e;
nlists++;
/* get the start pos */
ntok = strsep(&ltok, "-");
if (!ntok[0]) {
if (!ltok) /* testcase: -f '' */
bb_show_usage();
if (!ltok[0]) /* testcase: -f - */
bb_show_usage();
s = 0; /* "-M" means "1-M" */
} else {
/* "N" or "N-[M]" */
/* arrays are zero based, while the user expects
* the first field/char on the line to be char #1 */
s = xatoi_positive(ntok) - 1;
}
/* make sure we got some cut positions out of all that */
if (nlists == 0)
bb_simple_error_msg_and_die("missing list of positions");
/* get the end pos */
if (!ltok) {
e = s; /* "N" means "N-N" */
} else if (!ltok[0]) {
/* "N-" means "until the end of the line" */
e = INT_MAX;
} else {
/* again, arrays are zero based, fields are 1 based */
e = xatoi_positive(ltok) - 1;
}
/* now that the lists are parsed, we need to sort them to make life
* easier on us when it comes time to print the chars / fields / lines
*/
if (!(opt & CUT_OPT_NOSORT_FLGS))
qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
if (s < 0 || e < s)
bb_error_msg_and_die("invalid range %s-%s", ntok, ltok ?: ntok);
/* add the new range */
cut_list = xrealloc_vector(cut_list, 4, nranges);
/* NB: s is always >= 0 */
cut_list[nranges].startpos = s;
cut_list[nranges].endpos = e;
nranges++;
}
cut_list[nranges].startpos = UINT_MAX; /* end indicator */
/* make sure we got some cut positions out of all that */
//if (nranges == 0)
// bb_simple_error_msg_and_die("missing list of positions");
//^^^ this is impossible since one of -bcfF is required,
// they populate LIST with non-NULL string and when it is parsed,
// cut_list[] gets at least one element.
/* now that the lists are parsed, we need to sort them to make life
* easier on us when it comes time to print the chars / fields / lines
*/
if (!(opt & OPT_NOSORT))
qsort(cut_list, nranges, sizeof(cut_list[0]), cmpfunc);
#if ENABLE_FEATURE_CUT_REGEX
if (opt & OPT_REGEX) {
xregcomp(&reg, delim, REG_EXTENDED);
delim = (void*) &reg;
}
#endif
{
exitcode_t retval = EXIT_SUCCESS;
@@ -322,12 +426,12 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
retval = EXIT_FAILURE;
continue;
}
cut_file(file, delim, odelim, cut_lists, nlists);
cut_file(file, delim, odelim, cut_list);
fclose_if_not_stdin(file);
} while (*++argv);
if (ENABLE_FEATURE_CLEAN_UP)
free(cut_lists);
free(cut_list);
fflush_stdout_and_exit(retval);
}
}
+1 -1
View File
@@ -289,7 +289,7 @@ int date_main(int argc UNUSED_PARAM, char **argv)
/* if setting time, set it */
if ((opt & OPT_SET) && clock_settime(CLOCK_REALTIME, &ts) < 0) {
bb_simple_perror_msg("can't set date");
bb_simple_perror_msg_and_die("can't set date");
}
}
+3 -9
View File
@@ -272,12 +272,6 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
return 1;
}
#if ENABLE_LFS
# define XATOU_SFX xatoull_sfx
#else
# define XATOU_SFX xatoul_sfx
#endif
#if ENABLE_FEATURE_DD_IBS_OBS
static int parse_comma_flags(char *val, const char *words, const char *error_in)
{
@@ -457,15 +451,15 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
/* These can be large: */
if (what == OP_count) {
G.flags |= FLAG_COUNT;
count = XATOU_SFX(val, cwbkMG_suffixes);
count = XATOOFF_SFX(val, cwbkMG_suffixes);
/*continue;*/
}
if (what == OP_seek) {
seek = XATOU_SFX(val, cwbkMG_suffixes);
seek = XATOOFF_SFX(val, cwbkMG_suffixes);
/*continue;*/
}
if (what == OP_skip) {
skip = XATOU_SFX(val, cwbkMG_suffixes);
skip = XATOOFF_SFX(val, cwbkMG_suffixes);
/*continue;*/
}
if (what == OP_if) {
+5 -2
View File
@@ -155,6 +155,9 @@ int df_main(int argc UNUSED_PARAM, char **argv)
, &opt_t
IF_FEATURE_DF_FANCY(, &chp)
);
/* -k overrides $POSIXLY_CORRECT: */
if (opt & OPT_KILO)
df_disp_hr = 1024;
if (opt & OPT_MEGA)
df_disp_hr = 1024*1024;
@@ -185,8 +188,8 @@ int df_main(int argc UNUSED_PARAM, char **argv)
if (disp_units_hdr == NULL) {
#if ENABLE_FEATURE_HUMAN_READABLE
disp_units_hdr = xasprintf("%s-blocks",
/* print df_disp_hr, show no fractionals,
* use suffixes if OPT_POSIX is set in opt */
/* print df_disp_hr; show no fractionals;
* if -P, unit=1 (print it in full, no KMG suffixes) */
make_human_readable_str(df_disp_hr, 0, !!(opt & OPT_POSIX))
);
#else
+1 -1
View File
@@ -136,7 +136,7 @@ static void factorize(wide_t N);
static half_t isqrt_odd(wide_t N)
{
half_t s = isqrt(N);
half_t s = isqrt_ull(N);
/* s^2 is <= N, (s+1)^2 > N */
/* If s^2 in fact is EQUAL to N, it's very lucky.
+11 -11
View File
@@ -50,11 +50,11 @@ if test $FLAG_USER_EXISTS = "yes"; then
exit 1
fi
adduser -s /bin/true -g "" -H -D "$TEST_USER" || exit 1
$BUSYBOX adduser -s /bin/true -g "" -H -D "$TEST_USER" || exit 1
chown $TEST_USER.$TEST_USER $BUSYBOX
chown $TEST_USER:$TEST_USER $BUSYBOX
chmod u+s $BUSYBOX 2>&1 /dev/null
chown $TEST_USER.$TEST_USER $ID
chown $TEST_USER:$TEST_USER $ID
chmod u+s $ID 2>&1 /dev/null
echo "test 3 setuid, existing user: id [options] no username"
@@ -90,9 +90,9 @@ do
done
done
chown $TEST_USER.$TEST_USER $BUSYBOX
chown $TEST_USER:$TEST_USER $BUSYBOX
chmod g+s $BUSYBOX 2>&1 /dev/null
chown $TEST_USER.$TEST_USER $ID
chown $TEST_USER:$TEST_USER $ID
chmod g+s $ID 2>&1 /dev/null
echo "test 5 setgid, existing user: id [options] no username"
@@ -128,9 +128,9 @@ do
done
done
chown $TEST_USER.$TEST_USER $BUSYBOX
chown $TEST_USER:$TEST_USER $BUSYBOX
chmod u+s,g+s $BUSYBOX 2>&1 /dev/null
chown $TEST_USER.$TEST_USER $ID
chown $TEST_USER:$TEST_USER $ID
chmod u+s,g+s $ID 2>&1 /dev/null
echo "test 7 setuid, setgid, existing user: id [options] no username"
@@ -200,8 +200,8 @@ do
done
done
chown .root $BUSYBOX 2>&1 /dev/null
chown .root $ID 2>&1 /dev/null
chown :root $BUSYBOX 2>&1 /dev/null
chown :root $ID 2>&1 /dev/null
chmod g+s $BUSYBOX 2>&1 /dev/null
chmod g+s $ID 2>&1 /dev/null
@@ -238,7 +238,7 @@ do
done
done
chown root.root $BUSYBOX 2>&1 /dev/null
chown root.root $ID 2>&1 /dev/null
chown root:root $BUSYBOX 2>&1 /dev/null
chown root:root $ID 2>&1 /dev/null
rm -f $ID
rm -f foo bar
+178 -90
View File
@@ -126,6 +126,8 @@
//usage: "\n -F Append indicator (one of */=@|) to names"
//usage: )
//usage: "\n -l Long format"
////usage: "\n -g Long format without group column"
////TODO: support -G too ("suppress owner column", GNUism)
//usage: "\n -i List inode numbers"
//usage: "\n -n List numeric UIDs and GIDs instead of names"
//usage: "\n -s List allocated blocks"
@@ -159,6 +161,8 @@
//usage: IF_FEATURE_LS_WIDTH(
//usage: "\n -w N Format N columns wide"
//usage: )
////usage: "\n -Q Double-quote names"
////usage: "\n -q Replace unprintable chars with '?'"
//usage: IF_FEATURE_LS_COLOR(
//usage: "\n --color[={always,never,auto}]"
//usage: )
@@ -196,27 +200,47 @@ SPLIT_SUBDIR = 2,
/* -Cadi1l Std options, busybox always supports */
/* -gnsxA Std options, busybox always supports */
/* -Q GNU option, busybox always supports */
/* -k Std option, busybox always supports (by ignoring) */
/* It means "for -s, show sizes in kbytes" */
/* Seems to only affect "POSIXLY_CORRECT=1 ls -sk" */
/* since otherwise -s shows kbytes anyway */
/* -Q GNU option, busybox always supports: */
/* -Q, --quote-name */
/* enclose entry names in double quotes */
/* -LHRctur Std options, busybox optionally supports */
/* -Fp Std options, busybox optionally supports */
/* -SXvhTw GNU options, busybox optionally supports */
/* -T WIDTH Ignored (we don't use tabs on output) */
/* -Z SELinux mandated option, busybox optionally supports */
/* -q Std option, busybox always supports: */
/* https://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html: */
/* Force each instance of non-printable filename characters and */
/* <tab> characters to be written as the <question-mark> ('?') */
/* character. Implementations may provide this option by default */
/* if the output is to a terminal device. */
/* -k Std option, busybox always supports (by ignoring) */
/* It means "for -s, show sizes in kbytes" */
/* Seems to only affect "POSIXLY_CORRECT=1 ls -sk" */
/* since otherwise -s shows kbytes anyway */
#define ls_options \
"Cadi1lgnsxAk" /* 12 opts, total 12 */ \
IF_FEATURE_LS_FILETYPES("Fp") /* 2, 14 */ \
IF_FEATURE_LS_RECURSIVE("R") /* 1, 15 */ \
IF_SELINUX("Z") /* 1, 16 */ \
"Q" /* 1, 17 */ \
IF_FEATURE_LS_TIMESTAMPS("ctu") /* 3, 20 */ \
IF_FEATURE_LS_SORTFILES("SXrv") /* 4, 24 */ \
IF_FEATURE_LS_FOLLOWLINKS("LH") /* 2, 26 */ \
IF_FEATURE_HUMAN_READABLE("h") /* 1, 27 */ \
IF_FEATURE_LS_WIDTH("T:w:") /* 2, 29 */
"Cadi1lgnsxA" /* 11 opts, total 11 */ \
IF_FEATURE_LS_FILETYPES("Fp") /* 2, 13 */ \
IF_FEATURE_LS_RECURSIVE("R") /* 1, 14 */ \
IF_SELINUX("Z") /* 1, 15 */ \
"Q" /* 1, 16 */ \
IF_FEATURE_LS_TIMESTAMPS("ctu") /* 3, 19 */ \
IF_FEATURE_LS_SORTFILES("SXrv") /* 4, 23 */ \
IF_FEATURE_LS_FOLLOWLINKS("LH") /* 2, 25 */ \
IF_FEATURE_HUMAN_READABLE("h") /* 1, 26 */ \
IF_FEATURE_LS_WIDTH("T:w:") /* 2, 28 */ \
IF_LONG_OPTS("\xff") /* 1, 29 */ \
IF_LONG_OPTS("\xfe") /* 1, 30 */ \
IF_LONG_OPTS("\xfd::") /* 1, 31 */ \
"qk" /* 2, 33 */
#if ENABLE_LONG_OPTS
static const char ls_longopts[] ALIGN1 =
"full-time\0" No_argument "\xff"
"group-directories-first\0" No_argument "\xfe"
IF_FEATURE_LS_COLOR("color\0" Optional_argument "\xfd")
;
#endif
enum {
OPT_C = (1 << 0),
@@ -230,29 +254,31 @@ enum {
OPT_s = (1 << 8),
OPT_x = (1 << 9),
OPT_A = (1 << 10),
//OPT_k = (1 << 11),
OPTBIT_F = 12,
OPTBIT_p, /* 13 */
OPTBIT_F = 11,
OPTBIT_p, /* 12 */
OPTBIT_R = OPTBIT_F + 2 * ENABLE_FEATURE_LS_FILETYPES,
OPTBIT_Z = OPTBIT_R + 1 * ENABLE_FEATURE_LS_RECURSIVE,
OPTBIT_Q = OPTBIT_Z + 1 * ENABLE_SELINUX,
OPTBIT_c, /* 17 */
OPTBIT_t, /* 18 */
OPTBIT_u, /* 19 */
OPTBIT_c, /* 16 */
OPTBIT_t, /* 17 */
OPTBIT_u, /* 18 */
OPTBIT_S = OPTBIT_c + 3 * ENABLE_FEATURE_LS_TIMESTAMPS,
OPTBIT_X, /* 21 */
OPTBIT_r, /* 22 */
OPTBIT_v, /* 23 */
OPTBIT_X, /* 20 */
OPTBIT_r, /* 21 */
OPTBIT_v, /* 22 */
OPTBIT_L = OPTBIT_S + 4 * ENABLE_FEATURE_LS_SORTFILES,
OPTBIT_H, /* 25 */
OPTBIT_H, /* 24 */
OPTBIT_h = OPTBIT_L + 2 * ENABLE_FEATURE_LS_FOLLOWLINKS,
OPTBIT_T = OPTBIT_h + 1 * ENABLE_FEATURE_HUMAN_READABLE,
OPTBIT_w, /* 28 */
OPTBIT_w, /* 27 */
OPTBIT_full_time = OPTBIT_T + 2 * ENABLE_FEATURE_LS_WIDTH,
OPTBIT_dirs_first,
OPTBIT_color, /* 31 */
/* with long opts, we use all 32 bits */
OPTBIT_color, /* 30 */
OPTBIT_q = OPTBIT_color + 1, /* 31 */
OPTBIT_k = OPTBIT_q + 1, /* 32 */
/* with all options enabled, we use all 32 bits and even one extra bit! */
/* this works because -k is ignored, and getopt32 allows such "ignore" options past 31th bit */
OPT_F = (1 << OPTBIT_F) * ENABLE_FEATURE_LS_FILETYPES,
OPT_p = (1 << OPTBIT_p) * ENABLE_FEATURE_LS_FILETYPES,
@@ -274,6 +300,8 @@ enum {
OPT_full_time = (1 << OPTBIT_full_time ) * ENABLE_LONG_OPTS,
OPT_dirs_first = (1 << OPTBIT_dirs_first) * ENABLE_LONG_OPTS,
OPT_color = (1 << OPTBIT_color ) * ENABLE_FEATURE_LS_COLOR,
OPT_q = (1 << OPTBIT_q),
//-k is ignored: OPT_k = (1 << OPTBIT_k),
};
/*
@@ -327,6 +355,7 @@ struct globals {
#endif
smallint exit_code;
smallint show_dirname;
smallint tty_out;
#if ENABLE_FEATURE_LS_WIDTH
unsigned terminal_width;
# define G_terminal_width (G.terminal_width)
@@ -343,16 +372,21 @@ struct globals {
setup_common_bufsiz(); \
/* we have to zero it out because of NOEXEC */ \
memset(&G, 0, sizeof(G)); \
IF_FEATURE_LS_WIDTH(G_terminal_width = TERMINAL_WIDTH;) \
IF_FEATURE_LS_WIDTH(G_terminal_width = ~0U;) \
IF_FEATURE_LS_TIMESTAMPS(time(&G.current_time_t);) \
} while (0)
#define ESC "\033"
static int G_isatty(void)
{
if (!G.tty_out) /* not known yet? */
G.tty_out = isatty(STDOUT_FILENO) + 1;
return (G.tty_out == 2);
}
/*** Output code ***/
/* FYI type values: 1:fifo 2:char 4:dir 6:blk 8:file 10:link 12:socket
* (various wacky OSes: 13:Sun door 14:BSD whiteout 5:XENIX named file
* 3/7:multiplexed char/block device)
@@ -415,28 +449,6 @@ static char append_char(mode_t mode)
}
#endif
static unsigned calc_name_len(const char *name)
{
unsigned len;
uni_stat_t uni_stat;
// TODO: quote tab as \t, etc, if -Q
name = printable_string2(&uni_stat, name);
if (!(option_mask32 & OPT_Q)) {
return uni_stat.unicode_width;
}
len = 2 + uni_stat.unicode_width;
while (*name) {
if (*name == '"' || *name == '\\') {
len++;
}
name++;
}
return len;
}
/* Return the number of used columns.
* Note that only columnar output uses return value.
* -l and -1 modes don't care.
@@ -444,27 +456,86 @@ static unsigned calc_name_len(const char *name)
* ls -b (--escape) = octal escapes (although it doesn't look like working)
* ls -N (--literal) = not escape at all
*/
static unsigned calc_name_len(const char *name)
{
unsigned len;
uni_stat_t uni_stat;
if (!(option_mask32 & (OPT_q|OPT_Q)))
return strlen(name);
if (!(option_mask32 & OPT_Q)) {
/* the most likely branch: "ls" to tty (it auto-enables -q behavior) */
printable_string2(&uni_stat, name);
return uni_stat.unicode_width;
}
len = 2 + strlen(name);
while (*name) {
unsigned char ch = (unsigned char)*name;
if (ch < ' ' || ch > 0x7e) {
ch -= 7;
if (ch <= 6) {
/* quote chars 7..13 as \a,b,t,n,v,f,r */
goto two;
}
/* other chars <32 or >126 as \ooo octal */
len += 3;
goto next;
}
if (*name == '"' || *name == '\\') {
two:
len++;
}
next:
name++;
}
return len;
}
static unsigned print_name(const char *name)
{
unsigned len;
uni_stat_t uni_stat;
// TODO: quote tab as \t, etc, if -Q
name = printable_string2(&uni_stat, name);
if (!(option_mask32 & (OPT_q|OPT_Q))) {
fputs_stdout(name);
return strlen(name);
}
if (!(option_mask32 & OPT_Q)) {
/* the most likely branch: "ls" to tty (it auto-enables -q behavior) */
name = printable_string2(&uni_stat, name);
fputs_stdout(name);
return uni_stat.unicode_width;
}
len = 2 + uni_stat.unicode_width;
len = 2 + strlen(name);
putchar('"');
while (*name) {
if (*name == '"' || *name == '\\') {
unsigned char ch = (unsigned char)*name;
if (ch < ' ' || ch > 0x7e) {
putchar('\\');
ch -= 7;
if (ch <= 6) {
/* quote chars 7..13 as \a,b,t,n,v,f,r */
ch = c_escape_conv_str07[1 + 3 * ch];
goto two;
}
/* other chars <32 or >126 as \ooo octal */
ch = (unsigned char)*name;
putchar('0' + (ch>>6));
putchar('0' + ((ch>>3) & 7));
ch = '0' + (ch & 7);
len += 3;
goto put_ch;
}
if (ch == '"' || ch == '\\') {
putchar('\\');
two:
len++;
}
putchar(*name);
put_ch:
putchar(ch);
name++;
}
putchar('"');
@@ -646,7 +717,7 @@ static void display_files(struct dnode **dn, unsigned nfiles)
unsigned i, ncols, nrows, row, nc;
unsigned column;
unsigned nexttab;
unsigned column_width = 0; /* used only by coulmnal output */
unsigned column_width = 0; /* used only by columnar output */
if (option_mask32 & (OPT_l|OPT_1)) {
ncols = 1;
@@ -691,6 +762,11 @@ static void display_files(struct dnode **dn, unsigned nfiles)
}
nexttab = column + column_width;
column += display_single(dn[i]);
} else {
/* if -w999999999, ncols can be very large */
//bb_error_msg(" col:%u ncol:%u i:%i", nc, ncols, i); sleep1();
/* without "break", we loop millions of times here */
break;
}
}
putchar('\n');
@@ -1090,25 +1166,11 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
/* need to initialize since --color has _an optional_ argument */
const char *color_opt = color_str; /* "always" */
#endif
#if ENABLE_LONG_OPTS
static const char ls_longopts[] ALIGN1 =
"full-time\0" No_argument "\xff"
"group-directories-first\0" No_argument "\xfe"
IF_FEATURE_LS_COLOR("color\0" Optional_argument "\xfd")
;
#endif
INIT_G();
init_unicode();
#if ENABLE_FEATURE_LS_WIDTH
/* obtain the terminal width */
G_terminal_width = get_terminal_width(STDIN_FILENO);
/* go one less... */
G_terminal_width--;
#endif
/* process options */
opt = getopt32long(argv, "^"
ls_options
@@ -1144,6 +1206,29 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
exit(0);
#endif
/* ftpd secret backdoor? */
if (ENABLE_FTPD && applet_name[0] == 'f') {
/* dirs first are much nicer */
opt = option_mask32 |= OPT_dirs_first;
/* don't show SEcontext */
IF_SELINUX(opt = option_mask32 &= ~OPT_Z;)
/* do not query stdout about size and tty-ness */
IF_FEATURE_LS_WIDTH(G_terminal_width = INT_MAX;)
G.tty_out = 1; /* not a tty */
goto skip_if_ftpd;
}
#if ENABLE_FEATURE_LS_WIDTH
if ((int)G_terminal_width < 0) {
/* obtain the terminal width */
G_terminal_width = get_terminal_width(STDIN_FILENO);
/* go one less... */
G_terminal_width--;
}
if (G_terminal_width == 0) /* -w0 */
G_terminal_width = INT_MAX; /* "infinite" */
#endif
#if ENABLE_SELINUX
if (opt & OPT_Z) {
if (!is_selinux_enabled())
@@ -1157,7 +1242,7 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
char *p = getenv("LS_COLORS");
/* LS_COLORS is unset, or (not empty && not "none") ? */
if (!p || (p[0] && strcmp(p, "none") != 0)) {
if (isatty(STDOUT_FILENO)) {
if (G_isatty()) {
/* check isatty() last because it's expensive (syscall) */
G_show_color = 1;
}
@@ -1166,23 +1251,28 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
if (opt & OPT_color) {
if (color_opt[0] == 'n')
G_show_color = 0;
else switch (index_in_substrings(color_str, color_opt)) {
case 3:
case 4:
case 5:
if (!is_TERM_dumb() && isatty(STDOUT_FILENO)) {
case 0:
case 1:
case 2:
G_show_color = 1;
else if (!G_show_color) {
/* if() is not needed, but avoids extra isatty() if G_show_color is already set */
/* Check --color=COLOR_OPT and maybe set show_color=1 */
switch (index_in_substrings(color_str, color_opt)) {
case 3: // auto
case 4: // tty
case 5: // if-tty
if (!is_TERM_dumb() && G_isatty()) {
case 0: // always
case 1: // yes
case 2: // force
G_show_color = 1;
}
}
}
}
#endif
skip_if_ftpd:
/* sort out which command line options take precedence */
if (ENABLE_FEATURE_LS_RECURSIVE && (opt & OPT_d))
option_mask32 &= ~OPT_R; /* no recurse if listing only dir */
opt = option_mask32 &= ~OPT_R; /* no recurse if listing only dir */
if (!(opt & OPT_l)) { /* not -l? */
if (ENABLE_FEATURE_LS_TIMESTAMPS && ENABLE_FEATURE_LS_SORTFILES) {
/* when to sort by time? -t[cu] sorts by time even with -l */
@@ -1190,19 +1280,17 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
/* without -l, bare -c or -u enable sort too */
/* (with -l, bare -c or -u just select which time to show) */
if (opt & (OPT_c|OPT_u)) {
option_mask32 |= OPT_t;
opt = option_mask32 |= OPT_t;
}
}
}
/* choose a display format if one was not already specified by an option */
if (!(option_mask32 & (OPT_l|OPT_1|OPT_x|OPT_C)))
option_mask32 |= (isatty(STDOUT_FILENO) ? OPT_C : OPT_1);
if (!(opt & (OPT_l|OPT_1|OPT_x|OPT_C)))
opt = option_mask32 |= (G_isatty() ? OPT_C : OPT_1);
if (ENABLE_FTPD && applet_name[0] == 'f') {
/* ftpd secret backdoor. dirs first are much nicer */
option_mask32 |= OPT_dirs_first;
}
if (!(opt & OPT_q) && G_isatty())
opt = option_mask32 |= OPT_q;
argv += optind;
if (!argv[0])
+51 -21
View File
@@ -23,6 +23,12 @@
//config: help
//config: Compute and check SHA256 message digest
//config:
//config:config SHA384SUM
//config: bool "sha384sum (7.3 kb)"
//config: default y
//config: help
//config: Compute and check SHA384 message digest
//config:
//config:config SHA512SUM
//config: bool "sha512sum (7.3 kb)"
//config: default y
@@ -35,13 +41,13 @@
//config: help
//config: Compute and check SHA3 message digest
//config:
//config:comment "Common options for md5sum, sha1sum, sha256sum, sha512sum, sha3sum"
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || SHA512SUM || SHA3SUM
//config:comment "Common options for md5sum, sha1sum, sha256sum, ..., sha3sum"
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || SHA384SUM || SHA512SUM || SHA3SUM
//config:
//config:config FEATURE_MD5_SHA1_SUM_CHECK
//config: bool "Enable -c, -s and -w options"
//config: default y
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || SHA512SUM || SHA3SUM
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || SHA384SUM || SHA512SUM || SHA3SUM
//config: help
//config: Enabling the -c options allows files to be checked
//config: against pre-calculated hash values.
@@ -51,11 +57,13 @@
//applet:IF_SHA1SUM(APPLET_NOEXEC(sha1sum, md5_sha1_sum, BB_DIR_USR_BIN, BB_SUID_DROP, sha1sum))
//applet:IF_SHA3SUM(APPLET_NOEXEC(sha3sum, md5_sha1_sum, BB_DIR_USR_BIN, BB_SUID_DROP, sha3sum))
//applet:IF_SHA256SUM(APPLET_NOEXEC(sha256sum, md5_sha1_sum, BB_DIR_USR_BIN, BB_SUID_DROP, sha256sum))
//applet:IF_SHA384SUM(APPLET_NOEXEC(sha384sum, md5_sha1_sum, BB_DIR_USR_BIN, BB_SUID_DROP, sha384sum))
//applet:IF_SHA512SUM(APPLET_NOEXEC(sha512sum, md5_sha1_sum, BB_DIR_USR_BIN, BB_SUID_DROP, sha512sum))
//kbuild:lib-$(CONFIG_MD5SUM) += md5_sha1_sum.o
//kbuild:lib-$(CONFIG_SHA1SUM) += md5_sha1_sum.o
//kbuild:lib-$(CONFIG_SHA256SUM) += md5_sha1_sum.o
//kbuild:lib-$(CONFIG_SHA384SUM) += md5_sha1_sum.o
//kbuild:lib-$(CONFIG_SHA512SUM) += md5_sha1_sum.o
//kbuild:lib-$(CONFIG_SHA3SUM) += md5_sha1_sum.o
@@ -99,6 +107,16 @@
//usage: "\n -w Warn about improperly formatted checksum lines"
//usage: )
//usage:
//usage:#define sha384sum_trivial_usage
//usage: IF_FEATURE_MD5_SHA1_SUM_CHECK("[-c[sw]] ")"[FILE]..."
//usage:#define sha384sum_full_usage "\n\n"
//usage: "Print" IF_FEATURE_MD5_SHA1_SUM_CHECK(" or check") " SHA384 checksums"
//usage: IF_FEATURE_MD5_SHA1_SUM_CHECK( "\n"
//usage: "\n -c Check sums against list in FILEs"
//usage: "\n -s Don't output anything, status code shows success"
//usage: "\n -w Warn about improperly formatted checksum lines"
//usage: )
//usage:
//usage:#define sha512sum_trivial_usage
//usage: IF_FEATURE_MD5_SHA1_SUM_CHECK("[-c[sw]] ")"[FILE]..."
//usage:#define sha512sum_full_usage "\n\n"
@@ -130,16 +148,18 @@
enum {
/* 4th letter of applet_name is... */
HASH_MD5 = 's', /* "md5>s<um" */
HASH_SHA1 = '1',
HASH_MD5 = 's', /* "md5>s<um" */
HASH_SHA1 = '1',
HASH_SHA256 = '2',
HASH_SHA3 = '3',
HASH_SHA3 = '3',
HASH_SHA512 = '5',
/* unfortunately, sha384sum has the same '3' as sha3 */
};
#define FLAG_SILENT 1
#define FLAG_CHECK 2
#define FLAG_WARN 4
#define FLAG_BINARY 8
/* This might be useful elsewhere */
static unsigned char *hash_bin_to_hex(unsigned char *hash_value,
@@ -158,10 +178,11 @@ static unsigned char *hash_bin_to_hex(unsigned char *hash_value,
#endif
static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned sha3_width)
{
int src_fd, hash_len, count;
int src_fd, count;
union _ctx_ {
sha3_ctx_t sha3;
sha512_ctx_t sha512;
sha384_ctx_t sha384;
sha256_ctx_t sha256;
sha1_ctx_t sha1;
md5_ctx_t md5;
@@ -183,25 +204,31 @@ static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned
md5_begin(&context.md5);
update = (void*)md5_hash;
final = (void*)md5_end;
hash_len = 16;
}
else if (ENABLE_SHA1SUM && hash_algo == HASH_SHA1) {
sha1_begin(&context.sha1);
update = (void*)sha1_hash;
final = (void*)sha1_end;
hash_len = 20;
}
else if (ENABLE_SHA256SUM && hash_algo == HASH_SHA256) {
sha256_begin(&context.sha256);
update = (void*)sha256_hash;
final = (void*)sha256_end;
hash_len = 32;
}
else if (ENABLE_SHA384SUM
&& (ENABLE_SHA3SUM
? (applet_name[4] == '8') /* check for "sha384", but do not match "sha3" */
: (hash_algo == '3') /* applet_name = "sha3sum" is not possible */
)
) {
sha384_begin(&context.sha384);
update = (void*)sha384_hash;
final = (void*)sha384_end;
}
else if (ENABLE_SHA512SUM && hash_algo == HASH_SHA512) {
sha512_begin(&context.sha512);
update = (void*)sha512_hash;
final = (void*)sha512_end;
hash_len = 64;
}
#if ENABLE_SHA3SUM
else if (ENABLE_SHA3SUM && hash_algo == HASH_SHA3) {
@@ -219,9 +246,7 @@ static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned
) {
bb_error_msg_and_die("bad -a%u", sha3_width);
}
sha3_width /= 4;
context.sha3.input_block_bytes = 1600/8 - sha3_width;
hash_len = sha3_width/2;
context.sha3.input_block_bytes = 1600/8 - sha3_width/4;
}
#endif
else {
@@ -236,7 +261,7 @@ static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned
if (count < 0)
bb_perror_msg("can't read '%s'", filename);
else /* count == 0 */ {
final(&context, in_buf);
unsigned hash_len = final(&context, in_buf);
hash_value = hash_bin_to_hex(in_buf, hash_len);
}
}
@@ -257,19 +282,24 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
#if ENABLE_SHA3SUM
unsigned sha3_width = 224;
#endif
const char *fmt = "%s %s\n";
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK) {
/* -b "binary", -t "text" are ignored (shaNNNsum compat) */
/* -t per se is a no-op (it means "text mode").
* -b sets the '*' binary mode indicator in the output.
* -t unsets -b (-bt is the same as -t, which is the same as no option) */
/* -s and -w require -c */
#if ENABLE_SHA3SUM
if (applet_name[3] == HASH_SHA3)
flags = getopt32(argv, "^" "scwbta:+" "\0" "s?c:w?c", &sha3_width);
if (applet_name[3] == HASH_SHA3 && (!ENABLE_SHA384SUM || applet_name[4] != '8'))
flags = getopt32(argv, "^" "scwbta:+" "\0" "t-b:s?c:w?c", &sha3_width);
else
#endif
flags = getopt32(argv, "^" "scwbt" "\0" "s?c:w?c");
flags = getopt32(argv, "^" "scwbt" "\0" "t-b:s?c:w?c");
if (flags & FLAG_BINARY)
fmt = "%s *%s\n";
} else {
#if ENABLE_SHA3SUM
if (applet_name[3] == HASH_SHA3)
if (applet_name[3] == HASH_SHA3 && (!ENABLE_SHA384SUM || applet_name[4] != '8'))
getopt32(argv, "a:+", &sha3_width);
else
#endif
@@ -351,7 +381,7 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
if (hash_value == NULL) {
return_value = EXIT_FAILURE;
} else {
printf("%s %s\n", hash_value, *argv);
printf(fmt, hash_value, *argv);
free(hash_value);
}
}
+4 -3
View File
@@ -1155,7 +1155,7 @@ dump_strings(off_t address, off_t end_offset)
leading '+' return nonzero and set *OFFSET to the offset it denotes. */
static int
parse_old_offset(const char *s, off_t *offset)
parse_old_offset(char *s, off_t *offset)
{
static const struct suffix_mult Bb[] ALIGN_SUFFIX = {
{ "B", 1024 },
@@ -1181,7 +1181,8 @@ parse_old_offset(const char *s, off_t *offset)
radix = 16;
*offset = xstrtooff_sfx(s, radix, Bb);
if (p) p[0] = '.';
if (p)
p[0] = '.'; /* undo cheating */
return (*offset >= 0);
}
@@ -1234,7 +1235,7 @@ int od_main(int argc UNUSED_PARAM, char **argv)
static const uint8_t doxn_address_pad_len_char[] ALIGN1 = {
'7', '7', '6', /* '?' */
};
char *p;
const char *p;
int pos;
p = strchr(doxn, str_A[0]);
if (!p)
+23 -11
View File
@@ -34,27 +34,38 @@
static void paste_files(FILE** files, int file_cnt, char* delims, int del_cnt)
{
char *line;
char **line = xmalloc(file_cnt * sizeof(char *));
char delim;
int active_files = file_cnt;
int i;
while (active_files > 0) {
int del_idx = 0;
int got_line = FALSE;
for (i = 0; i < file_cnt; ++i) {
if (files[i] == NULL)
continue;
if (files[i]) {
line[i] = xmalloc_fgetline(files[i]);
if (!line[i]) {
fclose_if_not_stdin(files[i]);
files[i] = NULL;
--active_files;
} else {
got_line = TRUE;
}
} else {
line[i] = NULL;
}
}
line = xmalloc_fgetline(files[i]);
if (!line) {
fclose_if_not_stdin(files[i]);
files[i] = NULL;
--active_files;
continue;
if (!got_line)
break;
for (i = 0; i < file_cnt; ++i) {
if (line[i]) {
fputs_stdout(line[i]);
free(line[i]);
}
fputs_stdout(line);
free(line);
delim = '\n';
if (i != file_cnt - 1) {
delim = delims[del_idx++];
@@ -65,6 +76,7 @@ static void paste_files(FILE** files, int file_cnt, char* delims, int del_cnt)
fputc(delim, stdout);
}
}
free(line);
}
static void paste_files_separate(FILE** files, char* delims, int del_cnt)
+1 -1
View File
@@ -354,7 +354,7 @@ static char **print_formatted(char *f, char **argv, int *conv_err)
/* Add "ll" if integer modifier, then print */
{
static const char format_chars[] ALIGN1 = "diouxXfeEgGcs";
char *p = strchr(format_chars, *f);
char *p = (char*)strchr(format_chars, *f);
/* needed - try "printf %" without it */
if (p == NULL || *f == '\0') {
bb_error_msg("%s: invalid format", direc_start);
+47 -44
View File
@@ -426,8 +426,7 @@ struct test_statics {
/* set only by check_operator(), either to bogus struct
* or points to matching operator_t struct. Never NULL. */
const struct operator_t *last_operator;
gid_t *group_array;
int ngroups;
struct cached_groupinfo *groupinfo;
#if BASH_TEST2
bool bash_test2;
#endif
@@ -440,8 +439,7 @@ extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
#define S (*test_ptr_to_statics)
#define args (S.args )
#define last_operator (S.last_operator)
#define group_array (S.group_array )
#define ngroups (S.ngroups )
#define groupinfo (S.groupinfo )
#define bash_test2 (S.bash_test2 )
#define leaving (S.leaving )
@@ -449,7 +447,6 @@ extern struct test_statics *BB_GLOBAL_CONST test_ptr_to_statics;
XZALLOC_CONST_PTR(&test_ptr_to_statics, sizeof(S)); \
} while (0)
#define DEINIT_S() do { \
free(group_array); \
free(test_ptr_to_statics); \
} while (0)
@@ -637,62 +634,52 @@ static int binop(void)
/*return 1; - NOTREACHED */
}
static void initialize_group_array(void)
{
group_array = bb_getgroups(&ngroups, NULL);
}
/* Return non-zero if GID is one that we have in our groups list. */
//XXX: FIXME: duplicate of existing libbb function?
// see toplevel TODO file:
// possible code duplication ingroup() and is_a_group_member()
static int is_a_group_member(gid_t gid)
{
int i;
/* Short-circuit if possible, maybe saving a call to getgroups(). */
if (gid == getgid() || gid == getegid())
if (gid == get_cached_egid(&groupinfo->egid))
return 1;
if (ngroups == 0)
initialize_group_array();
/* Search through the list looking for GID. */
for (i = 0; i < ngroups; i++)
if (gid == group_array[i])
return 1;
return 0;
return is_in_supplementary_groups(groupinfo, gid);
}
/* Do the same thing access(2) does, but use the effective uid and gid,
and don't make the mistake of telling root that any file is
executable. */
static int test_eaccess(struct stat *st, int mode)
/*
* Similar to what access(2) does, but uses the effective uid and gid.
* Doesn't make the mistake of telling root that any file is executable.
* Returns non-zero if the file is accessible.
*/
static int test_st_mode(struct stat *st, int mode)
{
unsigned int euid = geteuid();
enum { ANY_IX = S_IXUSR | S_IXGRP | S_IXOTH };
unsigned euid;
if (mode == X_OK) {
/* Do we already know with no extra syscalls? */
//if (!S_ISREG(st->st_mode))
// return 0; /* not a regular file */
// ^^^ bash 5.2.15 "test -x" does not check this!
if ((st->st_mode & ANY_IX) == 0)
return 0; /* no one can execute */
if ((st->st_mode & ANY_IX) == ANY_IX)
return 1; /* anyone can execute */
}
euid = get_cached_euid(&groupinfo->euid);
if (euid == 0) {
/* Root can read or write any file. */
if (mode != X_OK)
return 0;
return 1;
/* Root can execute any file that has any one of the execute
* bits set. */
if (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH))
return 0;
}
if (st->st_uid == euid) /* owner */
mode = S_IXUSR | S_IXGRP | S_IXOTH;
} else if (st->st_uid == euid) /* owner */
mode <<= 6;
else if (is_a_group_member(st->st_gid))
mode <<= 3;
if (st->st_mode & mode)
return 0;
return -1;
return st->st_mode & mode;
}
@@ -722,7 +709,7 @@ static int filstat(char *nm, enum token mode)
i = W_OK;
if (mode == FILEX)
i = X_OK;
return test_eaccess(&s, i) == 0;
return test_st_mode(&s, i);
}
if (is_file_type(mode)) {
if (mode == FILREG)
@@ -760,7 +747,7 @@ static int filstat(char *nm, enum token mode)
return ((s.st_mode & i) != 0);
}
if (mode == FILGZ)
return s.st_size > 0L;
return s.st_size != 0L; /* shorter than "> 0" test */
if (mode == FILUID)
return s.st_uid == geteuid();
if (mode == FILGID)
@@ -891,7 +878,7 @@ static number_t primary(enum token n)
}
int test_main(int argc, char **argv)
int FAST_FUNC test_main2(struct cached_groupinfo *pgroupinfo, int argc, char **argv)
{
int res;
const char *arg0;
@@ -924,6 +911,7 @@ int test_main(int argc, char **argv)
/* We must do DEINIT_S() prior to returning */
INIT_S();
groupinfo = pgroupinfo;
#if BASH_TEST2
bash_test2 = bt2;
@@ -1026,3 +1014,18 @@ int test_main(int argc, char **argv)
DEINIT_S();
return res;
}
int test_main(int argc, char **argv)
{
struct cached_groupinfo info;
int r;
info.euid = -1;
info.egid = -1;
info.ngroups = 0;
info.supplementary_array = NULL;
r = test_main2(&info, argc, argv);
free(info.supplementary_array);
return r;
}
+3 -6
View File
@@ -31,15 +31,12 @@
int which_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int which_main(int argc UNUSED_PARAM, char **argv)
{
char *env_path;
const char *env_path;
int status = 0;
/* This sizeof(): bb_default_root_path is shorter than BB_PATH_ROOT_PATH */
char buf[sizeof(BB_PATH_ROOT_PATH)];
env_path = getenv("PATH");
if (!env_path)
/* env_path must be writable, and must not alloc, so... */
env_path = strcpy(buf, bb_default_root_path);
env_path = bb_default_root_path;
getopt32(argv, "^" "a" "\0" "-1"/*at least one arg*/);
argv += optind;
@@ -54,7 +51,7 @@ int which_main(int argc UNUSED_PARAM, char **argv)
puts(*argv);
}
} else {
char *path;
const char *path;
char *p;
path = env_path;
+6 -1
View File
@@ -56,6 +56,11 @@ roughly are:
(although usually xfunc_error_retval's state is not a problem).
* do not expect that stdio wasn't used before. Calling set[v]buf()
can be disastrous.
* the parent program's signal handlers will not be reset to SIG_DFL
(on exec, they are, but we avoid exactly that).
This means that signals will cause a part of _parent's code_
to execute, and may cause EINTR returns from syscalls
in the NOEXEC applet code.
* ...
NOEXEC applets save only one half of fork+exec overhead.
@@ -76,7 +81,7 @@ This poses much more serious limitations on what applet can do:
hush shell only handles signals (like ^C) after you return
from APPLET_main().
* do not ever exit() or exec().
- xfuncs are okay. They are using special trick to return
- xfuncs are okay. They use special trick to return
to the caller applet instead of dying when they detect "x" condition.
- you may "exit" to caller applet by calling xfunc_die(). Return value
is taken from xfunc_error_retval.
+1 -3
View File
@@ -423,13 +423,11 @@ static int wait_one(int flags)
/* if (G.noexecute) { already returned -1; } */
while (1) {
pid = waitpid(-1, &status, flags);
pid = safe_waitpid(-1, &status, flags);
kill_all_if_got_signal();
if (pid == 0) /* flags == WNOHANG and no children exited */
return -1;
if (pid < 0) {
if (errno == EINTR)
continue;
if (errno == ECHILD) { /* paranoia */
bb_simple_error_msg("wait: no more children");
return -1;
+34 -40
View File
@@ -583,14 +583,10 @@ static const char vValues[] ALIGN1 =
static const uint16_t PRIMES[] ALIGN2 = { 251, 1021, 4093, 16381, 65521 };
/* Globals. Split in two parts so that first one is addressed
* with (mostly short) negative offsets.
* NB: it's unsafe to put members of type "double"
* into globals2 (gcc may fail to align them).
*/
struct globals {
double t_double;
chain beginseq, mainseq, endseq;
double t_double;
chain *seq;
node *break_ptr, *continue_ptr;
xhash *ahash; /* argument names, used only while parsing function bodies */
@@ -618,9 +614,8 @@ struct globals {
smallint next_token__concat_inserted;
uint32_t next_token__save_tclass;
uint32_t next_token__save_info;
};
struct globals2 {
uint32_t t_info; /* often used */
uint32_t t_info;
uint32_t t_tclass;
char *t_string;
int t_lineno;
@@ -654,41 +649,40 @@ struct globals2 {
char g_buf[MAXVARFMT + 1];
};
#define G1 (ptr_to_globals[-1])
#define G (*(struct globals2 *)ptr_to_globals)
#define G (*OFFSET_PTR_TO_GLOBALS)
/* For debug. nm --size-sort awk.o | grep -vi ' [tr] ' */
//char G1size[sizeof(G1)]; // 0x70
//char Gsize[sizeof(G)]; // 0x2f8
/* Trying to keep most of members accessible with short offsets: */
//char Gofs_seed[offsetof(struct globals2, evaluate__seed)]; // 0x7c
#define t_double (G1.t_double )
#define beginseq (G1.beginseq )
#define mainseq (G1.mainseq )
#define endseq (G1.endseq )
#define seq (G1.seq )
#define break_ptr (G1.break_ptr )
#define continue_ptr (G1.continue_ptr)
#define ahash (G1.ahash )
#define fnhash (G1.fnhash )
#define vhash (G1.vhash )
#define t_double (G.t_double )
#define beginseq (G.beginseq )
#define mainseq (G.mainseq )
#define endseq (G.endseq )
#define seq (G.seq )
#define break_ptr (G.break_ptr )
#define continue_ptr (G.continue_ptr)
#define ahash (G.ahash )
#define fnhash (G.fnhash )
#define vhash (G.vhash )
#define fdhash ahash
//^^^^^^^^^^^^^^^^^^ ahash is cleared after every function parsing,
// and ends up empty after parsing phase. Thus, we can simply reuse it
// for fdhash in execution stage.
#define g_progname (G1.g_progname )
#define g_lineno (G1.g_lineno )
#define num_fields (G1.num_fields )
#define num_alloc_fields (G1.num_alloc_fields)
#define Fields (G1.Fields )
#define g_pos (G1.g_pos )
#define g_saved_ch (G1.g_saved_ch )
#define got_program (G1.got_program )
#define icase (G1.icase )
#define exiting (G1.exiting )
#define nextrec (G1.nextrec )
#define nextfile (G1.nextfile )
#define is_f0_split (G1.is_f0_split )
#define t_rollback (G1.t_rollback )
#define g_progname (G.g_progname )
#define g_lineno (G.g_lineno )
#define num_fields (G.num_fields )
#define num_alloc_fields (G.num_alloc_fields)
#define Fields (G.Fields )
#define g_pos (G.g_pos )
#define g_saved_ch (G.g_saved_ch )
#define got_program (G.got_program )
#define icase (G.icase )
#define exiting (G.exiting )
#define nextrec (G.nextrec )
#define nextfile (G.nextfile )
#define is_f0_split (G.is_f0_split )
#define t_rollback (G.t_rollback )
#define t_info (G.t_info )
#define t_tclass (G.t_tclass )
#define t_string (G.t_string )
@@ -699,7 +693,7 @@ struct globals2 {
#define rsplitter (G.rsplitter )
#define g_buf (G.g_buf )
#define INIT_G() do { \
SET_PTR_TO_GLOBALS((char*)xzalloc(sizeof(G1)+sizeof(G)) + sizeof(G1)); \
SET_OFFSET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
t_tclass = TC_NEWLINE; \
G.evaluate__seed = 1; \
} while (0)
@@ -1168,9 +1162,9 @@ static int istrue(var *v)
*/
static uint32_t next_token(uint32_t expected)
{
#define concat_inserted (G1.next_token__concat_inserted)
#define save_tclass (G1.next_token__save_tclass)
#define save_info (G1.next_token__save_info)
#define concat_inserted (G.next_token__concat_inserted)
#define save_tclass (G.next_token__save_tclass)
#define save_info (G.next_token__save_info)
char *p;
const char *tl;
@@ -2847,7 +2841,7 @@ static NOINLINE var *exec_builtin(node *op, var *res)
l = strlen(as[0]) - ll;
if (ll > 0 && l >= 0) {
if (!icase) {
char *s = strstr(as[0], as[1]);
const char *s = strstr(as[0], as[1]);
if (s)
n = (s - as[0]) + 1;
} else {
+23 -13
View File
@@ -18,13 +18,21 @@
//kbuild:lib-$(CONFIG_CMP) += cmp.o
//usage:#define cmp_trivial_usage
//usage: "[-ls] [-n NUM] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage: "[-l|s] [-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 -l Show decimal offset and octal byte value for differing bytes,"
//usage: "\n don't stop on first mismatch"
//usage: "\n -s Quiet"
//usage: "\n -n NUM Compare at most NUM bytes"
//TODO?
// -b, --print-bytes print differing bytes
//Prints the first difference:
//FILE1 FILE2 differ: byte 5, line 2 is <OCTAL1> <char1> <OCTAL2> <char2>
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -b adds this
//and exits with exitcode 1.
// -i, --ignore-initial=SKIP1[:SKIP2]
//Same as SKIP1 [SKIP2] in argv, but here SKIP2 defaults to SKIP1, not to zero.
/* BB_AUDIT SUSv3 (virtually) compliant -- uses nicer GNU format for -l. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cmp.html */
@@ -32,9 +40,9 @@
#include "libbb.h"
static const char fmt_eof[] ALIGN1 = "cmp: EOF on %s\n";
static const char fmt_differ[] ALIGN1 = "%s %s differ: char %"OFF_FMT"u, line %u\n";
// 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";
static const char fmt_differ[] ALIGN1 = "%s %s differ: byte %llu, line %u\n";
// This fmt_l_opt is gnu-ism. SUSv3 is "%.0s%.0s%llu %o %o\n"
static const char fmt_l_opt[] ALIGN1 = "%.0s%.0s%llu %3o %3o\n";
#define OPT_STR "sln:+"
#define CMP_OPT_s (1<<0)
@@ -46,7 +54,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
{
FILE *fp1, *fp2, *outfile = stdout;
const char *filename1, *filename2 = "-";
off_t skip1 = 0, skip2 = 0, char_pos = 0;
unsigned long long skip1 = 0, skip2 = 0, char_pos = 0;
int line_pos = 1; /* Hopefully won't overflow... */
const char *fmt;
int c1, c2;
@@ -61,6 +69,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
IF_DESKTOP(":?4")
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
//TODO: -n MAXCOUNT should allow KMG suffixes
&max_count
);
#else
@@ -86,9 +95,9 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
if (*++argv) {
filename2 = *argv;
if (ENABLE_DESKTOP && *++argv) {
skip1 = XATOOFF(*argv);
skip1 = xatoull_sfx(*argv, kmg_i_suffixes);
if (*++argv) {
skip2 = XATOOFF(*argv);
skip2 = xatoull_sfx(*argv, kmg_i_suffixes);
}
}
}
@@ -113,8 +122,8 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
fmt = fmt_differ;
if (ENABLE_DESKTOP) {
while (skip1) { getc(fp1); skip1--; }
while (skip2) { getc(fp2); skip2--; }
while (skip1) { if (getc(fp1) == EOF) break; skip1--; }
while (skip2) { if (getc(fp2) == EOF) break; skip2--; }
}
do {
if (max_count >= 0 && --max_count < 0)
@@ -146,8 +155,9 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
line_pos = c1; /* line_pos is unused in the -l case. */
}
fprintf(outfile, fmt, filename1, filename2, char_pos, line_pos, c2);
if (opt) { /* This must be -l since not -s. */
/* If we encountered an EOF,
if (opt & CMP_OPT_l) {
/* -l: do not stop on first mismatch.
* If we encountered an EOF,
* the while check will catch it. */
continue;
}
+1 -1
View File
@@ -741,7 +741,7 @@ static int diffreg(char *file[2])
fd = fd_tmp;
xlseek(fd, 0, SEEK_SET);
}
fp[i] = fdopen(fd, "r");
fp[i] = xfdopen_for_read(fd);
}
setup_common_bufsiz();
+2
View File
@@ -345,6 +345,8 @@ static int insertLine(int num, const char *data, int len)
lp->prev->next = newLp;
lp->prev = newLp;
if (num <= curNum)
curLine = curLine->prev;
lastNum++;
dirty = TRUE;
return setCurNum(num);
+2 -3
View File
@@ -657,9 +657,8 @@ static void add_cmd(const char *cmdstr)
/* Append this line to any unfinished line from last time. */
if (G.add_cmd_line) {
char *tp = xasprintf("%s\n%s", G.add_cmd_line, cmdstr);
free(G.add_cmd_line);
cmdstr = G.add_cmd_line = tp;
cmdstr = xasprintf_inplace(G.add_cmd_line,
"%s\n%s", G.add_cmd_line, cmdstr);
}
/* If this line ends with unescaped backslash, request next line. */
+127 -129
View File
@@ -555,7 +555,6 @@ static int crashme = 0;
#endif
static void show_status_line(void); // put a message on the bottom line
static void status_line_bold(const char *, ...);
static void show_help(void)
{
@@ -1097,11 +1096,15 @@ static void redraw(int full_screen)
//----- Flash the screen --------------------------------------
static void flash(int h)
{
standout_start();
redraw(TRUE);
//standout_start();
//redraw(TRUE);
write1(ESC"[?5h"); // "reverse screen on"
mysleep(h);
standout_end();
redraw(TRUE);
//standout_end();
//redraw(TRUE);
write1(ESC"[?5l"); // "reverse screen off"
}
static void indicate_error(void)
@@ -1336,11 +1339,10 @@ static void show_status_line(void)
go_bottom_and_clear_to_eol();
write1(status_buffer);
if (have_status_msg) {
if (((int)strlen(status_buffer) - (have_status_msg - 1)) >
(columns - 1) ) {
have_status_msg = 0;
int n = (int)strlen(status_buffer) - (have_status_msg - 1);
// careful with int->unsigned promotion in comparison!
if (n >= 0 && n >= columns)
Hit_Return();
}
have_status_msg = 0;
}
place_cursor(crow, ccol); // put cursor back in correct place
@@ -2601,7 +2603,7 @@ static char *get_one_address(char *p, int *result, int *valid)
// 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, unsigned int *got)
static char *get_address(char *p, int *b, int *e, unsigned *got)
{
int state = GET_ADDRESS;
int valid;
@@ -2682,19 +2684,23 @@ static void setops(char *args, int flg_no)
# if ENABLE_FEATURE_VI_COLON_EXPAND
static char *expand_args(char *args)
{
char *s, *t;
char *s;
const char *replace;
args = xstrdup(args);
for (s = args; *s; s++) {
unsigned n;
if (*s == '%') {
replace = current_filename;
} else if (*s == '#') {
replace = alt_filename;
} else {
if (*s == '\\' && s[1] != '\0') {
for (t = s++; *t; t++)
char *t;
for (t = s; *t; t++)
*t = t[1];
s++;
}
continue;
}
@@ -2705,11 +2711,9 @@ static char *expand_args(char *args)
return NULL;
}
*s = '\0';
t = xasprintf("%s%s%s", args, replace, s+1);
s = t + (s - args) + strlen(replace);
free(args);
args = t;
n = (s - args);
xasprintf_inplace(args, "%.*s%s%s", n, args, replace, s+1);
s = args + n + strlen(replace);
}
return args;
}
@@ -2787,7 +2791,6 @@ static char *regex_search(char *q, regex_t *preg, const char *Rorig,
# define strchr_backslash(s, c) strchr(s, c)
#endif /* ENABLE_FEATURE_VI_REGEX_SEARCH */
// buf must be no longer than MAX_INPUT_LEN!
static void colon(char *buf)
{
#if !ENABLE_FEATURE_VI_COLON
@@ -2847,16 +2850,17 @@ static void colon(char *buf)
}
not_implemented(p);
#else
char cmd[sizeof("features!")]; // longest known command + NUL
char *args;
int cmdlen;
char *useforce;
char *q, *r;
int b, e;
// 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;
# define GOT_RANGE ((got & 3) == 3)
unsigned got;
char *exp = NULL; // may hold expand_args() result: if VI_COLON_EXPAND, needs freeing!
// :3154 // if (-e line 3154) goto it else stay put
// :4,33w! foo // write a portion of buffer to file "foo"
@@ -2871,52 +2875,38 @@ static void colon(char *buf)
// :/xyz/ // goto the "xyz" line
// :s/find/replace/ // substitute pattern "find" with "replace"
// :!<cmd> // run <cmd> then return
//
while (*buf == ':')
buf++; // move past leading colons
while (isblank(*buf))
buf++; // move past leading blanks
if (!buf[0] || buf[0] == '"')
buf = skip_whitespace(buf); // move past leading blanks
if (!*buf || *buf == '"')
goto ret; // ignore empty lines or those starting with '"'
li = i = 0;
// look for optional address(es) ":." ":1" ":1,9" ":'q,'a" ":%"
b = e = -1;
got = 0;
li = count_lines(text, end - 1);
fn = current_filename;
// look for optional address(es) :. :1 :1,9 :'q,'a :%
buf = get_address(buf, &b, &e, &got);
if (buf == NULL) {
if (buf == NULL)
goto ret;
}
// get the COMMAND into cmd[]
strcpy(cmd, buf);
buf1 = cmd;
while (!isspace(*buf1) && *buf1 != '\0') {
buf1++;
}
cmdend = buf1;
// get any ARGuments
while (isblank(*buf1))
buf1++;
args = buf1;
*cmdend = '\0';
useforce = FALSE;
if (cmdend > cmd && cmdend[-1] == '!') {
useforce = TRUE;
cmdend[-1] = '\0'; // get rid of !
}
safe_strncpy(cmd, buf, sizeof(cmd));
skip_non_whitespace(cmd)[0] = '\0';
useforce = last_char_is(cmd, '!');
if (useforce && useforce > cmd)
*useforce = '\0'; // "CMD!" -> "CMD" (unless single "!")
// find ARGuments
args = skip_whitespace(skip_non_whitespace(buf));
// assume the command will want a range, certain commands
// (read, substitute) need to adjust these assumptions
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) {
q = text; // if no addr, use 1,$ for the range
r = end - 1;
if (GOT_ADDRESS) { // at least one addr was given, get its details
int lines;
if (e < 0
|| e > (lines = count_lines(text, end - 1))
) {
status_line_bold("Invalid range");
goto ret;
}
@@ -2926,31 +2916,32 @@ static void colon(char *buf)
// number of the single line the user wants.
// Reset the end pointer to the end of that line.
r = end_line(q);
li = 1;
} else {
// we were given two addrs. change the
// start pointer to the addr given by user.
if (b < 0 || b > li || b > e) {
if (b < 0 || b > lines || 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;
}
}
// ------------ now look for the command ------------
i = strlen(cmd);
if (i == 0) { // :123CR goto line #123
cmdlen = strlen(cmd);
if (cmdlen == 0) { // ":123<enter>" - goto line #123
if (e >= 0) {
dot = find_line(e); // what line is #e
dot_skip_over_ws();
}
}
# if ENABLE_FEATURE_ALLOW_EXEC
else if (cmd[0] == '!') { // run a cmd
else if (cmd[0] == '!') { // ":!CMD" - run shell CMD
int retcode;
// :!ls run the <cmd>
if (GOT_ADDRESS) {
status_line_bold("Range not allowed");
goto ret;
}
exp = expand_args(buf + 1);
if (exp == NULL)
goto ret;
@@ -2968,25 +2959,27 @@ static void colon(char *buf)
e = count_lines(text, dot);
}
status_line("%d", e);
} else if (strncmp(cmd, "delete", i) == 0) { // delete lines
} else if (strncmp(cmd, "delete", cmdlen) == 0) { // delete lines
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
dot = yank_delete(q, r, WHOLE, YANKDEL, ALLOW_UNDO); // save, then delete lines
dot_skip_over_ws();
} else if (strncmp(cmd, "edit", i) == 0) { // Edit a file
} else if (strncmp(cmd, "edit", cmdlen) == 0) { // Edit a file
int size;
char *fn;
// don't edit, if the current file has been modified
if (modified_count && !useforce) {
status_line_bold("No write since last change (:%s! overrides)", cmd);
goto ret;
}
fn = current_filename;
if (args[0]) {
// the user supplied a file name
fn = exp = expand_args(args);
if (exp == NULL)
fn = expand_args(args);
if (fn == NULL)
goto ret;
} else if (current_filename == NULL) {
// no user file name, no current name- punt
@@ -3006,8 +2999,6 @@ static void colon(char *buf)
reg[YDreg] = NULL;
}
# endif
// how many lines in text[]?
li = count_lines(text, end - 1);
status_line("'%s'%s"
IF_FEATURE_VI_READONLY("%s")
" %uL, %uC",
@@ -3016,9 +3007,10 @@ static void colon(char *buf)
IF_FEATURE_VI_READONLY(
((readonly_mode) ? " [Readonly]" : ""),
)
li, (int)(end - text)
count_lines(text, end - 1),
(int)(end - text)
);
} else if (strncmp(cmd, "file", i) == 0) { // what File is this
} else if (strncmp(cmd, "file", cmdlen) == 0) { // what File is this
if (e >= 0) {
status_line_bold("No address allowed on this command");
goto ret;
@@ -3033,46 +3025,52 @@ static void colon(char *buf)
// user wants file status info
last_status_cksum = 0; // force status update
}
} else if (strncmp(cmd, "features", i) == 0) { // what features are available
} else if (strncmp(cmd, "features", cmdlen) == 0) { // what features are available
// print out values of all features
go_bottom_and_clear_to_eol();
cookmode();
show_help();
rawmode();
Hit_Return();
} else if (strncmp(cmd, "list", i) == 0) { // literal print line
} else if (strncmp(cmd, "list", cmdlen) == 0) { // literal print line
char *dst;
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
go_bottom_and_clear_to_eol();
puts("\r");
for (; q <= r; q++) {
have_status_msg = 1;
dst = status_buffer;
#define MAXPRINT (sizeof(ESC_BOLD_TEXT "^?" ESC_NORM_TEXT) + 1)
while (q <= r && dst < status_buffer + STATUS_BUFFER_LEN - MAXPRINT) {
char c;
int c_is_no_print;
c = *q;
c = *q++;
if (c == '\n') {
*dst++ = '$';
break;
}
c_is_no_print = (c & 0x80) && !Isprint(c);
if (c_is_no_print) {
c = '.';
standout_start();
//TODO: print fewer ESC if more than one ctrl char
dst = stpcpy(dst, ESC_BOLD_TEXT);
*dst++ = '.';
dst = stpcpy(dst, ESC_NORM_TEXT);
continue;
}
if (c == '\n') {
write1("$\r");
} else if (c < ' ' || c == 127) {
bb_putchar('^');
if (c < ' ' || c == 127) {
*dst++ = '^';
if (c == 127)
c = '?';
else
c += '@';
}
bb_putchar(c);
if (c_is_no_print)
standout_end();
*dst++ = c;
}
Hit_Return();
} else if (strncmp(cmd, "quit", i) == 0 // quit
|| strncmp(cmd, "next", i) == 0 // edit next file
|| strncmp(cmd, "prev", i) == 0 // edit previous file
*dst = '\0';
} else if (strncmp(cmd, "quit", cmdlen) == 0 // quit
|| strncmp(cmd, "next", cmdlen) == 0 // edit next file
|| strncmp(cmd, "prev", cmdlen) == 0 // edit previous file
) {
int n;
if (useforce) {
@@ -3107,13 +3105,14 @@ static void colon(char *buf)
optind -= 2;
}
editing = 0;
} else if (strncmp(cmd, "read", i) == 0) { // read file into text[]
} else if (strncmp(cmd, "read", cmdlen) == 0) { // read file into text[]
int size, num;
char *fn = current_filename;
if (args[0]) {
// the user supplied a file name
fn = exp = expand_args(args);
if (exp == NULL)
fn = expand_args(args);
if (fn == NULL)
goto ret;
init_filename(fn);
} else if (current_filename == NULL) {
@@ -3139,17 +3138,16 @@ static void colon(char *buf)
}
if (size < 0)
goto ret; // nothing was inserted
// how many lines in text[]?
li = count_lines(q, q + size - 1);
status_line("'%s'"
IF_FEATURE_VI_READONLY("%s")
" %uL, %uC",
fn,
IF_FEATURE_VI_READONLY((readonly_mode ? " [Readonly]" : ""),)
li, size
count_lines(q, q + size - 1),
size
);
dot = find_line(num);
} else if (strncmp(cmd, "rewind", i) == 0) { // rewind cmd line args
} else if (strncmp(cmd, "rewind", cmdlen) == 0) { // rewind cmd line args
if (modified_count && !useforce) {
status_line_bold("No write since last change (:%s! overrides)", cmd);
} else {
@@ -3158,11 +3156,12 @@ static void colon(char *buf)
editing = 0;
}
# if ENABLE_FEATURE_VI_SET
} else if (strncmp(cmd, "set", i) == 0) { // set or clear features
} else if (strncmp(cmd, "set", cmdlen) == 0 // set or clear features
IF_FEATURE_VI_SEARCH(&& cmdlen > 1) // (do not confuse with "s /find/repl/")
) {
# if ENABLE_FEATURE_VI_SETOPTS
char *argp, *argn, oldch;
# endif
// only blank is regarded as args delimiter. What about tab '\t'?
if (!args[0] || strcmp(args, "all") == 0) {
// print out values of all options
# if ENABLE_FEATURE_VI_SETOPTS
@@ -3186,7 +3185,7 @@ static void colon(char *buf)
# if ENABLE_FEATURE_VI_SETOPTS
argp = args;
while (*argp) {
i = 0;
int i = 0;
if (argp[0] == 'n' && argp[1] == 'o') // "noXXX"
i = 2;
argn = skip_non_whitespace(argp);
@@ -3201,8 +3200,10 @@ static void colon(char *buf)
# if ENABLE_FEATURE_VI_SEARCH
} else if (cmd[0] == 's') { // substitute a pattern with a replacement pattern
char c;
char *F, *R, *flags;
size_t len_F, len_R;
int i;
int gflag = 0; // global replace flag
int subs = 0; // number of substitutions
# if ENABLE_FEATURE_VI_VERBOSE_STATUS
@@ -3216,12 +3217,12 @@ static void colon(char *buf)
int undo = 0;
# endif
# endif
buf = skip_whitespace(buf + 1); // spaces allowed: "s /find/repl/"
// F points to the "find" pattern
// R points to the "replace" pattern
// replace the cmd line delimiters "/" with NULs
c = buf[1]; // what is the delimiter
F = buf + 2; // start of "find"
c = buf[0]; // what is the delimiter
F = buf + 1; // start of "find"
R = strchr_backslash(F, c); // middle delimiter
if (!R)
goto colon_s_fail;
@@ -3266,7 +3267,6 @@ static void colon(char *buf)
# else
len_R = strlen(R);
# endif
for (i = b; i <= e; i++) { // so, :20,23 s \0 find \0 replace \0
char *ls = q; // orig line start
char *found;
@@ -3338,15 +3338,16 @@ static void colon(char *buf)
regfree(&preg);
# endif
# endif /* FEATURE_VI_SEARCH */
} else if (strncmp(cmd, "version", i) == 0) { // show software version
} else if (strncmp(cmd, "version", cmdlen) == 0) { // show software version
status_line(BB_VER);
} else if (strncmp(cmd, "write", i) == 0 // write text to file
} else if (strncmp(cmd, "write", cmdlen) == 0 // write text to file
|| strcmp(cmd, "wq") == 0
|| strcmp(cmd, "wn") == 0
|| (cmd[0] == 'x' && !cmd[1])
) {
int size;
int size, l;
//int forced = FALSE;
char *fn = current_filename;
// is there a file name to write to?
if (args[0]) {
@@ -3355,8 +3356,10 @@ static void colon(char *buf)
exp = expand_args(args);
if (exp == NULL)
goto ret;
if (!useforce && (fn == NULL || strcmp(fn, exp) != 0) &&
stat(exp, &statbuf) == 0) {
if (!useforce
&& (fn == NULL || strcmp(fn, exp) != 0)
&& stat(exp, &statbuf) == 0
) {
status_line_bold("File exists (:w! overrides)");
goto ret;
}
@@ -3375,12 +3378,10 @@ static void colon(char *buf)
// system(syscmd);
// forced = TRUE;
//}
size = l = 0;
if (modified_count != 0 || cmd[0] != 'x') {
size = r - q + 1;
l = file_write(fn, q, r);
} else {
size = 0;
l = 0;
}
//if (useforce && forced) {
// chmod u-w
@@ -3393,8 +3394,8 @@ static void colon(char *buf)
status_line_bold_errno(fn);
} else {
// how many lines written
li = count_lines(q, q + l - 1);
status_line("'%s' %uL, %uC", fn, li, l);
int lines = count_lines(q, q + l - 1);
status_line("'%s' %uL, %uC", fn, lines, l);
if (l == size) {
if (q == text && q + l == end) {
modified_count = 0;
@@ -3406,37 +3407,35 @@ static void colon(char *buf)
// are there other files to edit?
int n = cmdline_filecnt - optind - 1;
if (n > 0) {
if (useforce) {
// force end of argv list
optind = cmdline_filecnt;
} else {
if (!useforce) {
status_line_bold("%u more file(s) to edit", n);
goto ret;
}
// force end of argv list
optind = cmdline_filecnt;
}
editing = 0;
}
}
}
# if ENABLE_FEATURE_VI_YANKMARK
} else if (strncmp(cmd, "yank", i) == 0) { // yank lines
} else if (strncmp(cmd, "yank", cmdlen) == 0) { // yank lines
int lines;
if (!GOT_ADDRESS) { // no addr given- use defaults
q = begin_line(dot); // assume .,. for the range
r = end_line(dot);
}
text_yank(q, r, YDreg, WHOLE);
li = count_lines(q, r);
lines = count_lines(q, r);
status_line("Yank %d lines (%d chars) into [%c]",
li, strlen(reg[YDreg]), what_reg());
lines, strlen(reg[YDreg]), what_reg());
# endif
} else {
// cmd unknown
not_implemented(cmd);
}
ret:
# if ENABLE_FEATURE_VI_COLON_EXPAND
free(exp);
# endif
IF_FEATURE_VI_COLON_EXPAND(free(exp);)
dot = bound_dot(dot); // make sure "dot" is valid
return;
# if ENABLE_FEATURE_VI_SEARCH
@@ -4793,8 +4792,7 @@ static void run_cmds(char *p)
if (p)
while (*p == '\n')
*p++ = '\0';
if (strlen(q) < MAX_INPUT_LEN)
colon(q);
colon(q);
}
}
#endif
+2 -1
View File
@@ -202,7 +202,8 @@ char get_header_tar_xz(archive_handle_t *archive_handle) FAST_FUNC;
void seek_by_jump(int fd, off_t amount) FAST_FUNC;
void seek_by_read(int fd, off_t amount) FAST_FUNC;
const char *strip_unsafe_prefix(const char *str) FAST_FUNC;
const char *skip_unsafe_prefix(const char *str) FAST_FUNC;
void strip_unsafe_prefix(char *str) FAST_FUNC;
void create_or_remember_link(llist_t **link_placeholders,
const char *target,
const char *linkname,
+265 -95
View File
@@ -290,6 +290,7 @@ PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN
/* "long" is long enough on this system */
typedef unsigned long uoff_t;
# define XATOOFF(a) xatoul_range((a), 0, LONG_MAX)
# define XATOOFF_SFX(a, s) xatoul_range_sfx((a), 0, LONG_MAX, s)
/* usage: sz = BB_STRTOOFF(s, NULL, 10); if (errno || sz < 0) die(); */
# define BB_STRTOOFF bb_strtoul
# define STRTOOFF strtoul
@@ -299,6 +300,7 @@ typedef unsigned long uoff_t;
/* "long" is too short, need "long long" */
typedef unsigned long long uoff_t;
# define XATOOFF(a) xatoull_range((a), 0, LLONG_MAX)
# define XATOOFF_SFX(a, s) xatoull_range_sfx((a), 0, LLONG_MAX, s)
# define BB_STRTOOFF bb_strtoull
# define STRTOOFF strtoull
# define OFF_FMT "ll"
@@ -314,12 +316,14 @@ typedef unsigned long long uoff_t;
# if UINT_MAX == ULONG_MAX
typedef unsigned long uoff_t;
# define XATOOFF(a) xatoi_positive(a)
# define XATOOFF_SFX(a, s) xatoul_range_sfx((a), 0, INT_MAX, s)
# define BB_STRTOOFF bb_strtou
# define STRTOOFF strtol
# define OFF_FMT "l"
# else
typedef unsigned long uoff_t;
# define XATOOFF(a) xatoul_range((a), 0, LONG_MAX)
# define XATOOFF_SFX(a, s) xatoul_range_sfx((a), 0, LONG_MAX, s)
# define BB_STRTOOFF bb_strtoul
# define STRTOOFF strtol
# define OFF_FMT "l"
@@ -404,7 +408,12 @@ unsigned FAST_FUNC bb_popcnt_long(unsigned long m);
#define bb_popcnt_long(m) bb_popcnt_32(m)
#endif
unsigned long FAST_FUNC isqrt(unsigned long long N);
unsigned FAST_FUNC isqrt(unsigned long N);
#if LLONG_MAX > LONG_MAX
unsigned long FAST_FUNC isqrt_ull(unsigned long long N);
#else
# define isqrt_ull(N) isqrt(N)
#endif
unsigned long long monotonic_ns(void) FAST_FUNC;
unsigned long long monotonic_us(void) FAST_FUNC;
@@ -442,6 +451,11 @@ 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;
#if defined(__x86_64__) || defined(i386)
/* 0x7f would be better, but it causes alignment problems */
# define ARCH_GLOBAL_PTR_OFF 0x80
#endif
#if defined(__x86_64__) || defined(i386)
# define BB_ARCH_FIXED_PAGESIZE 4096
#elif defined(__arm__) /* only 32bit, 64bit ARM has variable page size */
@@ -643,6 +657,8 @@ int sigaction_set(int sig, const struct sigaction *act) FAST_FUNC;
int sigprocmask_allsigs(int how) FAST_FUNC;
/* Return old set in the same set: */
int sigprocmask2(int how, sigset_t *set) FAST_FUNC;
/* SIG_BLOCK all signals, return old set: */
int sigblockall(sigset_t *set) FAST_FUNC;
/* Standard handler which just records signo */
extern smallint bb_got_signal;
void record_signo(int signo); /* not FAST_FUNC! */
@@ -687,6 +703,76 @@ struct fd_pair { int rd; int wr; };
#define piped_pair(pair) pipe(&((pair).rd))
#define xpiped_pair(pair) xpipe(&((pair).rd))
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;
void xgettimeofday(struct timeval *tv) FAST_FUNC;
void xsettimeofday(const struct timeval *tv) FAST_FUNC;
/* Generic I/O loop */
struct connection;
typedef struct ioloop_state {
struct connection *conns;
unsigned flags;
unsigned max_timeout;
unsigned current_iteration_timeout;
unsigned last_timeout;
int (*pre_poll_callback)(struct ioloop_state*);
} ioloop_state_t;
#define STRUCT_CONNECTION \
struct connection *next; \
ioloop_state_t *io; \
int read_fd; \
int write_fd; \
int (*should_poll_read_fd)(void *this); \
int (*should_poll_write_fd)(void *this); \
int (*read)(void *this); \
int (*write)(void *this); \
typedef struct connection {
STRUCT_CONNECTION
} connection_t;
static ALWAYS_INLINE void free_connection(connection_t *conn)
{
free(conn);
}
void FAST_FUNC conn_close_fds(connection_t *conn);
void FAST_FUNC conn_close_fds_remove_and_free(connection_t *conn);
static ALWAYS_INLINE ioloop_state_t *new_ioloop_state(void)
{
ioloop_state_t *io = xzalloc(sizeof(*io));
return io;
}
static ALWAYS_INLINE void free_ioloop_state(ioloop_state_t *io)
{
free(io);
}
static ALWAYS_INLINE void ioloop_decrease_current_timeout(ioloop_state_t *io, unsigned n)
{
if (io->current_iteration_timeout > n)
io->current_iteration_timeout = n;
}
void FAST_FUNC ioloop_insert_conn(ioloop_state_t *io, connection_t *conn);
void FAST_FUNC ioloop_remove_conn(ioloop_state_t *io, connection_t *conn);
enum {
IOLOOP_FLAG_EXIT_IF_TIMEOUT = (1 << 0),
IOLOOP_FLAG_EXIT_IF_EINTR = (1 << 1),
//IOLOOP_FLAG_EXIT_IF_ALL_NOT_READY = (1 << 1),
/* ioloop_run return values */
IOLOOP_NO_CONNS = 0,
IOLOOP_TIMEOUT = 1,
IOLOOP_EINTR = 2,
};
int FAST_FUNC ioloop_run(ioloop_state_t *io);
/* Useful for having small structure members/global variables */
typedef int8_t socktype_t;
typedef int8_t family_t;
@@ -715,14 +801,6 @@ struct BUG_too_small {
};
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;
void xgettimeofday(struct timeval *tv) FAST_FUNC;
void xsettimeofday(const struct timeval *tv) FAST_FUNC;
int xsocket(int domain, int type, int protocol) FAST_FUNC;
void xbind(int sockfd, struct sockaddr *my_addr, socklen_t addrlen) FAST_FUNC;
void xlisten(int s, int backlog) FAST_FUNC;
@@ -833,6 +911,11 @@ char* xmalloc_sockaddr2hostonly_noport(const struct sockaddr *sa) FAST_FUNC RETU
/* inet_[ap]ton on steroids */
char* xmalloc_sockaddr2dotted(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
char* xmalloc_sockaddr2dotted_noport(const struct sockaddr *sa) FAST_FUNC RETURNS_MALLOC;
// NB: unlike getservbyport, port parameter/retval are in host, NOT network order!
#define getservbyport dont_use_getservbyport_uses_global_buffer
char* bb_get_servname_by_port(char **p_etc_services, int port, const char *type) FAST_FUNC RETURNS_MALLOC;
#define getservbyname dont_use_getservbyname_uses_global_buffer
int bb_get_servport_by_name(char **p_etc_services, const char *name, const char *type) FAST_FUNC;
// "old" (ipv4 only) API
// users: traceroute.c hostname.c - use _list_ of all IPs
struct hostent *xgethostbyname(const char *name) FAST_FUNC;
@@ -854,8 +937,11 @@ typedef struct tls_state {
int ofd;
int ifd;
unsigned min_encrypted_len_on_read;
#if ENABLE_SSL_SERVER // || ENABLE_FEATURE_HTTPD_SSL
smallint expecting_first_packet;
#endif
uint16_t cipher_id;
unsigned min_encrypted_len_on_read;
unsigned MAC_size;
unsigned key_size;
unsigned IV_size;
@@ -880,21 +966,27 @@ typedef struct tls_state {
/*uint64_t read_seq64_be;*/
uint64_t write_seq64_be;
/*uint8_t *server_write_MAC_key;*/
uint8_t *client_write_key;
uint8_t *server_write_key;
uint8_t *client_write_IV;
uint8_t *server_write_IV;
uint8_t client_write_MAC_key[TLS_MAX_MAC_SIZE];
uint8_t server_write_MAC_k__[TLS_MAX_MAC_SIZE];
uint8_t client_write_k__[TLS_MAX_KEY_SIZE];
uint8_t server_write_k__[TLS_MAX_KEY_SIZE];
uint8_t client_write_I_[TLS_MAX_IV_SIZE];
uint8_t server_write_I_[TLS_MAX_IV_SIZE];
uint8_t *our_write_MAC_key;
uint8_t *peer_write_MAC_key;
uint8_t *our_write_key;
uint8_t *peer_write_key;
uint8_t *our_write_IV;
uint8_t *peer_write_IV;
uint8_t key_block[TLS_MAX_MAC_SIZE];
uint8_t key_block2[TLS_MAX_MAC_SIZE];
uint8_t key_block3[TLS_MAX_KEY_SIZE];
uint8_t key_block4[TLS_MAX_KEY_SIZE];
uint8_t key_block5[TLS_MAX_IV_SIZE];
uint8_t key_block6[TLS_MAX_IV_SIZE];
struct tls_aes aes_encrypt;
struct tls_aes aes_decrypt;
uint8_t H[16]; //used by AES_GCM
#if ENABLE_SSL_SERVER // || ENABLE_FEATURE_HTTPD_SSL
/* For ECDHE: server's ephemeral EC private key */
//uint8_t ecc_priv_key32[32];
#endif
} tls_state_t;
static inline tls_state_t *new_tls_state(void)
@@ -902,7 +994,9 @@ static inline tls_state_t *new_tls_state(void)
tls_state_t *tls = xzalloc(sizeof(*tls));
return tls;
}
void tls_handshake(tls_state_t *tls, const char *sni) FAST_FUNC;
void FAST_FUNC tls_handshake(tls_state_t *tls, const char *sni);
void FAST_FUNC tls_handshake_as_server(tls_state_t *tls,
const char *pem_filename);
#define TLSLOOP_EXIT_ON_LOCAL_EOF (1 << 0)
void tls_run_copy_loop(tls_state_t *tls, unsigned flags) FAST_FUNC;
@@ -923,6 +1017,8 @@ int parse_pasv_epsv(char *buf) FAST_FUNC;
/* 0 if argv[0] is NULL: */
unsigned string_array_len(char **argv) FAST_FUNC;
void overlapping_strcpy(char *dst, const char *src) FAST_FUNC;
/* Like strncpy but make sure the resulting string is always 0 terminated: */
/* writes SIZE chars, the [SIZE-1] char is always NUL (unless SIZE==0). */
char *safe_strncpy(char *dst, const char *src, size_t size) FAST_FUNC;
char *strncpy_IFNAMSIZ(char *dst, const char *src) FAST_FUNC;
unsigned count_strstr(const char *str, const char *sub) FAST_FUNC;
@@ -934,6 +1030,8 @@ int bb_putchar(int ch) FAST_FUNC;
int bb_putchar_stderr(char ch) FAST_FUNC;
int fputs_stdout(const char *s) FAST_FUNC;
char *xasprintf(const char *format, ...) __attribute__ ((format(printf, 1, 2))) FAST_FUNC RETURNS_MALLOC;
char *xasprintf_and_free(char *allocated, const char *format, ...) __attribute__ ((format(printf, 2, 3))) FAST_FUNC RETURNS_MALLOC;
#define xasprintf_inplace(allocated, ...) ((allocated) = xasprintf_and_free((allocated), __VA_ARGS__))
char *auto_string(char *str) FAST_FUNC;
// gcc-4.1.1 still isn't good enough at optimizing it
// (+200 bytes compared to macro)
@@ -1011,13 +1109,13 @@ unsigned bb_clk_tck(void) FAST_FUNC;
#if SEAMLESS_COMPRESSION
/* Autodetects gzip/bzip2 formats. fd may be in the middle of the file! */
int setup_unzip_on_fd(int fd, int fail_if_not_compressed) FAST_FUNC;
int setup_unzip_on_fd(int fd, int die_if_not_compressed) FAST_FUNC;
/* Autodetects .gz etc */
extern int open_zipped(const char *fname, int fail_if_not_compressed) FAST_FUNC;
extern int open_zipped(const char *fname, int die_if_not_compressed) FAST_FUNC;
extern void *xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_p) FAST_FUNC RETURNS_MALLOC;
#else
# define setup_unzip_on_fd(...) (0)
# define open_zipped(fname, fail_if_not_compressed) open((fname), O_RDONLY);
# define open_zipped(fname, die_if_not_compressed) open((fname), O_RDONLY);
# define xmalloc_open_zipped_read_close(fname, maxsz_p) xmalloc_open_read_close((fname), (maxsz_p))
#endif
/* lzma has no signature, need a little helper. NB: exist only for ENABLE_FEATURE_SEAMLESS_LZMA=y */
@@ -1113,8 +1211,35 @@ char *bin2hex(char *dst, const char *src, int count) FAST_FUNC;
/* Reverse */
char* hex2bin(char *dst, const char *src, int count) FAST_FUNC;
/* Returns strlen as a bonus */
//size_t replace_char(char *s, char what, char with) FAST_FUNC;
static inline size_t replace_char(char *str, char from, char to)
{
char *p = str;
while (*p) {
if (*p == from)
*p = to;
p++;
}
return p - str;
}
extern const char c_escape_conv_str00[];
#define c_escape_conv_str07 (c_escape_conv_str00+3)
void FAST_FUNC xorbuf_3(void *dst, const void *src1, const void *src2, unsigned count);
void FAST_FUNC xorbuf(void* buf, const void* mask, unsigned count);
void FAST_FUNC xorbuf16_aligned_long(void* buf, const void* mask);
void FAST_FUNC xorbuf64_3_aligned64(void *dst, const void *src1, const void *src2);
#if BB_UNALIGNED_MEMACCESS_OK
# define xorbuf16(buf,mask) xorbuf16_aligned_long(buf,mask)
#else
void FAST_FUNC xorbuf16(void* buf, const void* mask);
#endif
/* Generate a UUID */
void generate_uuid(uint8_t *buf) FAST_FUNC;
void FAST_FUNC format_uuid_DCE_37_chars(char *dst37, const uint8_t *buf16);
/* Last element is marked by mult == 0 */
struct suffix_mult {
@@ -1201,6 +1326,19 @@ void die_if_bad_username(const char* name) FAST_FUNC;
* Dies on errors (on Linux, only xrealloc can cause this, not internal getgroups call).
*/
gid_t *bb_getgroups(int *ngroups, gid_t *group_array) FAST_FUNC;
/*
* True if GID is in our getgroups() result.
* getgroups() is cached in supplementary_array[], to make successive calls faster.
*/
struct cached_groupinfo {
uid_t euid;
gid_t egid;
int ngroups;
gid_t *supplementary_array;
};
uid_t FAST_FUNC get_cached_euid(uid_t *euid);
gid_t FAST_FUNC get_cached_egid(gid_t *egid);
int FAST_FUNC is_in_supplementary_groups(struct cached_groupinfo *groupinfo, gid_t gid);
#if ENABLE_FEATURE_UTMP
void FAST_FUNC write_new_utmp(pid_t pid, int new_type, const char *tty_name, const char *username, const char *hostname);
@@ -1214,7 +1352,7 @@ void FAST_FUNC update_utmp_DEAD_PROCESS(pid_t pid);
int file_is_executable(const char *name) FAST_FUNC;
char *find_executable(const char *filename, char **PATHp) FAST_FUNC;
char *find_executable(const char *filename, const char **PATHp) FAST_FUNC;
int executable_exists(const char *filename) FAST_FUNC;
/* BB_EXECxx always execs (it's not doing NOFORK/NOEXEC stuff),
@@ -1436,7 +1574,11 @@ extern smallint logmode;
extern uint8_t xfunc_error_retval;
extern void (*die_func)(void);
void xfunc_die(void) NORETURN FAST_FUNC;
#if !ENABLE_SHOW_USAGE
#define bb_show_usage() xfunc_die()
#else
void bb_show_usage(void) NORETURN FAST_FUNC;
#endif
void bb_error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2))) FAST_FUNC;
void bb_simple_error_msg(const char *s) FAST_FUNC;
void bb_error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2))) FAST_FUNC;
@@ -1539,6 +1681,7 @@ int test_main(int argc, char **argv)
MAIN_EXTERNALLY_VISIBLE
#endif
;
int FAST_FUNC test_main2(struct cached_groupinfo *pgroupinfo, int argc, char **argv);
int kill_main(int argc, char **argv)
#if ENABLE_KILL || ENABLE_KILLALL || ENABLE_KILLALL5
MAIN_EXTERNALLY_VISIBLE
@@ -1792,18 +1935,25 @@ extern char *pw_encrypt(const char *clear, const char *salt, int cleanup) FAST_F
extern int obscure(const char *old, const char *newval, const struct passwd *pwdp) FAST_FUNC;
/*
* rnd is additional random input. New one is returned.
* Useful if you call crypt_make_salt many times in a row:
* rnd = crypt_make_salt(buf1, 4, 0);
* rnd = crypt_make_salt(buf2, 4, rnd);
* rnd = crypt_make_salt(buf3, 4, rnd);
* Useful if you call crypt_make_rand64encoded many times in a row:
* rnd = crypt_make_rand64encoded(buf1, 4, 0);
* rnd = crypt_make_rand64encoded(buf2, 4, rnd);
* rnd = crypt_make_rand64encoded(buf3, 4, rnd);
* (otherwise we risk having same salt generated)
*/
extern int crypt_make_salt(char *p, int cnt /*, int rnd*/) FAST_FUNC;
/* "$N$" + sha_salt_16_bytes + NUL */
#define MAX_PW_SALT_LEN (3 + 16 + 1)
extern int crypt_make_rand64encoded(char *p, int cnt /*, int rnd*/) FAST_FUNC;
/* Size of char salt[] to hold randomly-generated salt string
* sha256/512:
* "$5$" ["rounds=999999999$"] "<sha_salt_16_chars><NUL>"
* "$6$" ["rounds=999999999$"] "<sha_salt_16_chars><NUL>"
* #define MAX_PW_SALT_LEN (3 + sizeof("rounds=999999999$")-1 + 16 + 1)
* yescrypt:
* "$y$" <up to 8 params of up to 6 chars each> "$" <up to 86 chars salt><NUL>
* (86 chars are ascii64-encoded 64 binary bytes)
*/
#define MAX_PW_SALT_LEN (3 + 8*6 + 1 + 86 + 1)
extern char* crypt_make_pw_salt(char p[MAX_PW_SALT_LEN], const char *algo) FAST_FUNC;
/* Returns number of lines changed, or -1 on error */
#if !(ENABLE_FEATURE_ADDUSER_TO_GROUP || ENABLE_FEATURE_DEL_USER_FROM_GROUP)
#define update_passwd(filename, username, data, member) \
@@ -1937,6 +2087,7 @@ int64_t read_key(int fd, char *buffer, int timeout) FAST_FUNC;
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;
int check_got_signal_and_poll(struct pollfd pfd[1], int timeout) FAST_FUNC;
#if ENABLE_FEATURE_EDITING
/* It's NOT just ENABLEd or disabled. It's a number: */
@@ -1974,7 +2125,7 @@ typedef struct line_input_t {
# if MAX_HISTORY
int cnt_history;
int cur_history;
int max_history; /* must never be <= 0 */
int max_history; /* must never be < 0 */
# if ENABLE_FEATURE_EDITING_SAVEHISTORY
/* meaning of this field depends on FEATURE_EDITING_SAVE_ON_EXIT:
* if !FEATURE_EDITING_SAVE_ON_EXIT: "how many lines are
@@ -1998,11 +2149,11 @@ enum {
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
# if ENABLE_FEATURE_EDITING_SAVEHISTORY
void free_line_input_t(line_input_t *n) FAST_FUNC;
#else
# define free_line_input_t(n) free(n)
#endif
# else
# define free_line_input_t(n) free(n)
# endif
/*
* maxsize must be >= 2.
* Returns:
@@ -2013,7 +2164,7 @@ void free_line_input_t(line_input_t *n) FAST_FUNC;
int read_line_input(line_input_t *st, const char *prompt, char *command, int maxsize) FAST_FUNC;
void show_history(const line_input_t *st) FAST_FUNC;
# if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
void save_history(line_input_t *st);
void save_history(line_input_t *st) FAST_FUNC;
# endif
#else
#define MAX_HISTORY 0
@@ -2033,33 +2184,6 @@ enum { COMM_LEN = 16 };
# endif
#endif
struct smaprec {
unsigned long mapped_rw;
unsigned long mapped_ro;
unsigned long shared_clean;
unsigned long shared_dirty;
unsigned long private_clean;
unsigned long private_dirty;
unsigned long stack;
unsigned long smap_pss, smap_swap;
unsigned long smap_size;
// For mixed 32/64 userspace, 32-bit pmap still needs
// 64-bit field here to correctly show 64-bit processes:
unsigned long long smap_start;
// (strictly speaking, other fields need to be wider too,
// but they are in kbytes, not bytes, and they hold sizes,
// not start addresses, sizes tend to be less than 4 terabytes)
char smap_mode[5];
char *smap_name;
};
#if !ENABLE_PMAP
#define procps_read_smaps(pid, total, cb, data) \
procps_read_smaps(pid, total)
#endif
int FAST_FUNC procps_read_smaps(pid_t pid, struct smaprec *total,
void (*cb)(struct smaprec *, void *), void *data);
typedef struct procps_status_t {
DIR *dir;
IF_FEATURE_SHOW_THREADS(DIR *task_dir;)
@@ -2089,7 +2213,13 @@ typedef struct procps_status_t {
#endif
unsigned tty_major,tty_minor;
#if ENABLE_FEATURE_TOPMEM
struct smaprec smaps;
unsigned long mapped_rw;
unsigned long mapped_ro;
unsigned long shared_clean;
unsigned long shared_dirty;
unsigned long private_clean;
unsigned long private_dirty;
unsigned long stack;
#endif
char state[4];
/* basename of executable in exec(2), read from /proc/N/stat
@@ -2138,11 +2268,15 @@ void free_procps_scan(procps_status_t* sp) FAST_FUNC;
procps_status_t* procps_scan(procps_status_t* sp, int flags) FAST_FUNC;
/* Format cmdline (up to col chars) into char buf[size] */
/* Puts [comm] if cmdline is empty (-> process is a kernel thread) */
void read_cmdline(char *buf, int size, unsigned pid, const char *comm) FAST_FUNC;
int read_cmdline(char *buf, int size, unsigned pid, const char *comm) FAST_FUNC;
pid_t *find_pid_by_name(const char* procName) FAST_FUNC;
pid_t *pidlist_reverse(pid_t *pidList) FAST_FUNC;
int starts_with_cpu(const char *str) FAST_FUNC;
unsigned get_cpu_count(void) FAST_FUNC;
/* Some internals reused by pmap: */
unsigned long FAST_FUNC fast_strtoul_10(char **endptr);
unsigned long long FAST_FUNC fast_strtoull_16(char **endptr);
char* FAST_FUNC skip_fields(char *str, int count);
/* Use strict=1 if you process input from untrusted source:
@@ -2168,6 +2302,21 @@ char *decode_base64(char *dst, const char **pp_src) FAST_FUNC;
char *decode_base32(char *dst, const char **pp_src) FAST_FUNC;
void read_base64(FILE *src_stream, FILE *dst_stream, int flags) FAST_FUNC;
int FAST_FUNC i2a64(int i);
int FAST_FUNC a2i64(char c);
char* FAST_FUNC num2str64_lsb_first(char *s, unsigned v, int n);
enum {
/* how many bytes XYZ_end() fills */
MD5_OUTSIZE = 16,
SHA1_OUTSIZE = 20,
SHA256_OUTSIZE = 32,
SHA384_OUTSIZE = 48,
SHA512_OUTSIZE = 64,
//SHA3-224_OUTSIZE = 28,
/* size of input block */
SHA2_INSIZE = 64,
};
typedef struct md5_ctx_t {
uint8_t wbuffer[64]; /* always correctly aligned for uint64_t */
void (*process_block)(struct md5_ctx_t*) FAST_FUNC;
@@ -2181,6 +2330,7 @@ typedef struct sha512_ctx_t {
uint64_t hash[8];
uint8_t wbuffer[128]; /* always correctly aligned for uint64_t */
} sha512_ctx_t;
typedef struct sha512_ctx_t sha384_ctx_t;
typedef struct sha3_ctx_t {
uint64_t state[25];
unsigned bytes_queued;
@@ -2198,20 +2348,46 @@ void sha256_begin(sha256_ctx_t *ctx) FAST_FUNC;
void sha512_begin(sha512_ctx_t *ctx) FAST_FUNC;
void sha512_hash(sha512_ctx_t *ctx, const void *buffer, size_t len) FAST_FUNC;
unsigned sha512_end(sha512_ctx_t *ctx, void *resbuf) FAST_FUNC;
void sha384_begin(sha384_ctx_t *ctx) FAST_FUNC;
#define sha384_hash sha512_hash
unsigned sha384_end(sha384_ctx_t *ctx, void *resbuf) FAST_FUNC;
void sha3_begin(sha3_ctx_t *ctx) FAST_FUNC;
void sha3_hash(sha3_ctx_t *ctx, const void *buffer, size_t len) FAST_FUNC;
unsigned sha3_end(sha3_ctx_t *ctx, void *resbuf) FAST_FUNC;
void FAST_FUNC sha256_block(const void *in, size_t len, uint8_t hash[32]);
/* TLS benefits from knowing that sha1 and sha256 share these. Give them "agnostic" names too */
typedef struct md5_ctx_t md5sha_ctx_t;
#define md5sha_hash md5_hash
#define sha_end sha1_end
enum {
MD5_OUTSIZE = 16,
SHA1_OUTSIZE = 20,
SHA256_OUTSIZE = 32,
SHA512_OUTSIZE = 64,
SHA3_OUTSIZE = 28,
};
/* RFC 2104 HMAC (hash-based message authentication code) */
typedef struct hmac_ctx {
md5sha_ctx_t hashed_key_xor_ipad;
md5sha_ctx_t hashed_key_xor_opad;
} hmac_ctx_t;
#define HMAC_ONLY_SHA256 (!ENABLE_FEATURE_TLS_SHA1)
typedef void md5sha_begin_func(md5sha_ctx_t *ctx) FAST_FUNC;
#if HMAC_ONLY_SHA256
#define hmac_begin(ctx,key,key_size,begin) \
hmac_begin(ctx,key,key_size)
#endif
void FAST_FUNC hmac_begin(hmac_ctx_t *ctx, const uint8_t *key, unsigned key_size, md5sha_begin_func *begin);
static ALWAYS_INLINE void hmac_hash(hmac_ctx_t *ctx, const void *in, size_t len)
{
md5sha_hash(&ctx->hashed_key_xor_ipad, in, len);
}
unsigned FAST_FUNC hmac_end(hmac_ctx_t *ctx, uint8_t *out);
#if HMAC_ONLY_SHA256
#define hmac_block(key,key_size,begin,in,sz,out) \
hmac_block(key,key_size,in,sz,out)
#endif
unsigned FAST_FUNC hmac_block(const uint8_t *key, unsigned key_size,
md5sha_begin_func *begin,
const void *in, unsigned sz,
uint8_t *out);
/* HMAC helpers for TLS: */
void FAST_FUNC hmac_hash_v(hmac_ctx_t *ctx, va_list va);
unsigned FAST_FUNC hmac_peek_hash(hmac_ctx_t *ctx, uint8_t *out, ...);
extern uint32_t *global_crc32_table;
uint32_t *crc32_filltable(uint32_t *tbl256, int endian) FAST_FUNC;
@@ -2323,26 +2499,10 @@ 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.
* Needs serious convincing to not eliminate the store.
*/
static ALWAYS_INLINE void* not_const_pp(const void *p)
{
void *pp;
asm volatile (
"# forget that p points to const"
: /*outputs*/ "=r" (pp)
: /*inputs*/ "0" (p)
);
return pp;
}
# 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.
/* {ASSIGN,XZALLOC}_CONST_PTR() are out-of-line functions
* to prevent clang from reading pointer before it is assigned.
*/
void ASSIGN_CONST_PTR(const void *pptr, void *v) FAST_FUNC;
void XZALLOC_CONST_PTR(const void *pptr, size_t size) FAST_FUNC;
#else
# define ASSIGN_CONST_PTR(pptr, v) do { \
@@ -2360,6 +2520,16 @@ void XZALLOC_CONST_PTR(const void *pptr, size_t size) FAST_FUNC;
} \
} while (0)
#if defined(ARCH_GLOBAL_PTR_OFF)
# define SET_OFFSET_PTR_TO_GLOBALS(x) \
ASSIGN_CONST_PTR(&ptr_to_globals, (char*)(x) + ARCH_GLOBAL_PTR_OFF)
# define OFFSET_PTR_TO_GLOBALS \
((struct globals*)((char*)ptr_to_globals - ARCH_GLOBAL_PTR_OFF))
#else
# define SET_OFFSET_PTR_TO_GLOBALS(x) SET_PTR_TO_GLOBALS(x)
# define OFFSET_PTR_TO_GLOBALS ptr_to_globals
#endif
/* You can change LIBBB_DEFAULT_LOGIN_SHELL, but don't use it,
* use bb_default_login_shell and following defines.
+6 -1
View File
@@ -187,7 +187,7 @@
#elif defined(BYTE_ORDER) && BYTE_ORDER == LITTLE_ENDIAN
# define BB_BIG_ENDIAN 0
# define BB_LITTLE_ENDIAN 1
#elif defined(__386__)
#elif defined(__i386__)
# define BB_BIG_ENDIAN 0
# define BB_LITTLE_ENDIAN 1
#else
@@ -209,6 +209,9 @@
# define SWAP_LE64(x) bb_bswap_64(x)
# define IF_BIG_ENDIAN(...) __VA_ARGS__
# define IF_LITTLE_ENDIAN(...)
/* How do bytes a,b,c,d (sequential in memory) look if fetched into uint32_t? */
# define PACK32_BYTES(a,b,c,d) (uint32_t)((d)+((c)<<8)+((b)<<16)+((a)<<24))
# define PACK64_LITERAL_STR(s) (((uint64_t)PACK32_BYTES((s)[0],(s)[1],(s)[2],(s)[3])<<32) + PACK32_BYTES((s)[4],(s)[5],(s)[6],(s)[7]))
#else
# define SWAP_BE16(x) bswap_16(x)
# define SWAP_BE32(x) bswap_32(x)
@@ -218,6 +221,8 @@
# define SWAP_LE64(x) (x)
# define IF_BIG_ENDIAN(...)
# define IF_LITTLE_ENDIAN(...) __VA_ARGS__
# define PACK32_BYTES(a,b,c,d) (uint32_t)((a)+((b)<<8)+((c)<<16)+((d)<<24))
# define PACK64_LITERAL_STR(s) (((uint64_t)PACK32_BYTES((s)[4],(s)[5],(s)[6],(s)[7])<<32) + PACK32_BYTES((s)[0],(s)[1],(s)[2],(s)[3]))
#endif
+3 -3
View File
@@ -17,11 +17,11 @@
#define scripted_trivial_usage NOUSAGE_STR
#define scripted_full_usage ""
#if !ENABLE_USE_BB_CRYPT || ENABLE_USE_BB_CRYPT_SHA
# define CRYPT_METHODS_HELP_STR "des,md5,sha256/512" \
#if !ENABLE_USE_BB_CRYPT
# define CRYPT_METHODS_HELP_STR "des,md5,sha256/512,yescrypt" \
" (default "CONFIG_FEATURE_DEFAULT_PASSWD_ALGO")"
#else
# define CRYPT_METHODS_HELP_STR "des,md5" \
# define CRYPT_METHODS_HELP_STR "des,md5"IF_USE_BB_CRYPT_SHA(",sha256/512")IF_USE_BB_CRYPT_YES(",yescrypt") \
" (default "CONFIG_FEATURE_DEFAULT_PASSWD_ALGO")"
#endif
+1 -1
View File
@@ -133,7 +133,7 @@ static void dump_file(FILE *fp, const char *filename)
static int dump_procs(FILE *fp, int look_for_login_process)
{
struct dirent *entry;
DIR *dir = opendir("/proc");
DIR *dir = xopendir("/proc");
int found_login_process = 0;
fputs(G.jiffy_line, fp);
+15 -3
View File
@@ -1198,17 +1198,29 @@ int init_main(int argc UNUSED_PARAM, char **argv)
/* Wait for any child process(es) to exit */
while (1) {
pid_t wpid;
int status;
struct init_action *a;
wpid = waitpid(-1, NULL, WNOHANG);
wpid = wait_any_nohang(&status);
if (wpid <= 0)
break;
a = mark_terminated(wpid);
if (a) {
message(L_LOG, "process '%s' (pid %u) exited. "
const char *s = "killed, signal";
int ex = WTERMSIG(status);
/* "if (!WIFSIGNALED(status))" generates more code:
* on linux, WIFEXITED(status) is "WTERMSIG(status) == 0"
* and WTERMSIG(status) is known, so compiler optimizes.
*/
if (WIFEXITED(status)) {
s = "exited, exitcode";
ex = WEXITSTATUS(status);
}
message(L_LOG, "process '%s' (pid %u) %s:%d. "
"Scheduling for restart.",
a->command, (unsigned)wpid);
a->command, (unsigned)wpid,
s, ex);
}
}
+3 -3
View File
@@ -31,7 +31,7 @@
* - /dev/ram (alias to /dev/ram0)
* - /dev/mtd
*/
static dev_t name_to_dev_t(const char *devname)
static dev_t name_to_dev_t(char *devname)
{
char devfile[sizeof(int)*3 * 2 + 4];
char *sysname;
@@ -39,7 +39,7 @@ static dev_t name_to_dev_t(const char *devname)
struct stat st;
int r;
if (strncmp(devname, "/dev/", 5) != 0) {
if (!is_prefixed_with(devname, "/dev/")) {
char *cptr;
cptr = strchr(devname, ':');
@@ -59,7 +59,7 @@ static dev_t name_to_dev_t(const char *devname)
return res;
}
devname = xasprintf("/dev/%s", devname);
devname = concat_path_file("/dev", devname);
}
/* Now devname is always "/dev/FOO" */
+2 -2
View File
@@ -182,8 +182,8 @@ config FEATURE_EDITING_VI
config FEATURE_EDITING_HISTORY
int "History size"
# Don't allow way too big values here, code uses fixed "char *history[N]" struct member
range 0 9999
default 255
range 0 2000
default 200
depends on FEATURE_EDITING
help
Specify command history size (0 - disable).
+72 -59
View File
@@ -124,55 +124,57 @@ static const char packed_usage[] ALIGN1 = { PACKED_USAGE };
#endif /* FEATURE_COMPRESS_USAGE */
#if ENABLE_SHOW_USAGE
void FAST_FUNC bb_show_usage(void)
{
if (ENABLE_SHOW_USAGE) {
#ifdef SINGLE_APPLET_STR
/* Imagine that this applet is "true". Dont link in printf! */
const char *usage_string = unpack_usage_messages();
ssize_t FAST_FUNC (*full_write_fn)(const char *) =
xfunc_error_retval ? full_write2_str : full_write1_str;
# ifdef SINGLE_APPLET_STR
/* Imagine that this applet is "true". Dont link in printf! */
const char *usage_string = unpack_usage_messages();
if (usage_string) {
if (*usage_string == '\b') {
full_write2_str("No help available\n");
} else {
full_write2_str("Usage: "SINGLE_APPLET_STR" ");
full_write2_str(usage_string);
full_write2_str("\n");
}
if (ENABLE_FEATURE_CLEAN_UP)
dealloc_usage_messages((char*)usage_string);
}
#else
const char *p;
const char *usage_string = p = unpack_usage_messages();
int ap = find_applet_by_name(applet_name);
if (ap < 0 || usage_string == NULL)
xfunc_die();
while (ap) {
while (*p++) continue;
ap--;
}
full_write2_str(bb_banner);
full_write2_str(" multi-call binary.\n"); /* common string */
if (*p == '\b')
full_write2_str("\nNo help available\n");
else {
full_write2_str("\nUsage: ");
full_write2_str(applet_name);
if (p[0]) {
if (p[0] != '\n')
full_write2_str(" ");
full_write2_str(p);
}
full_write2_str("\n");
if (usage_string) {
if (*usage_string == '\b') {
full_write_fn("No help available\n");
} else {
full_write_fn("Usage: "SINGLE_APPLET_STR" ");
full_write_fn(usage_string);
full_write_fn("\n");
}
if (ENABLE_FEATURE_CLEAN_UP)
dealloc_usage_messages((char*)usage_string);
#endif
}
# else
const char *p;
const char *usage_string = p = unpack_usage_messages();
int ap = find_applet_by_name(applet_name);
if (ap < 0 || usage_string == NULL)
xfunc_die();
while (ap) {
while (*p++) continue;
ap--;
}
full_write_fn(bb_banner);
full_write_fn(" multi-call binary.\n"); /* common string */
if (*p == '\b')
full_write_fn("\nNo help available\n");
else {
full_write_fn("\nUsage: ");
full_write_fn(applet_name);
if (p[0]) {
if (p[0] != '\n')
full_write_fn(" ");
full_write_fn(p);
}
full_write_fn("\n");
}
if (ENABLE_FEATURE_CLEAN_UP)
dealloc_usage_messages((char*)usage_string);
# endif
xfunc_die();
}
#endif
int FAST_FUNC find_applet_by_name(const char *name)
{
@@ -268,8 +270,10 @@ void lbb_prepare(const char *applet
&& !(ENABLE_TRUE && strcmp(applet_name, "true") == 0)
&& !(ENABLE_FALSE && strcmp(applet_name, "false") == 0)
&& !(ENABLE_ECHO && strcmp(applet_name, "echo") == 0)
)
) {
xfunc_error_retval = 0;
bb_show_usage();
}
}
#endif
}
@@ -776,10 +780,9 @@ int busybox_main(int argc UNUSED_PARAM, char **argv)
help:
output_width = get_terminal_width(2);
dup2(1, 2);
full_write2_str(bb_banner); /* reuse const string */
full_write2_str(" multi-call binary.\n"); /* reuse */
full_write2_str(
full_write1_str(bb_banner); /* reuse const string */
full_write1_str(" multi-call binary.\n"); /* reuse */
full_write1_str(
"BusyBox is copyrighted by many authors between 1998-2015.\n"
"Licensed under GPLv2. See source distribution for detailed\n"
"copyright notices.\n"
@@ -817,20 +820,20 @@ int busybox_main(int argc UNUSED_PARAM, char **argv)
while (*a) {
int len2 = strlen(a) + 2;
if (col >= (int)output_width - len2) {
full_write2_str(",\n");
full_write1_str(",\n");
col = 0;
}
if (col == 0) {
col = 6;
full_write2_str("\t");
full_write1_str("\t");
} else {
full_write2_str(", ");
full_write1_str(", ");
}
full_write2_str(a);
full_write1_str(a);
col += len2;
a += len2 - 1;
}
full_write2_str("\n");
full_write1_str("\n");
return 0;
}
@@ -850,14 +853,13 @@ int busybox_main(int argc UNUSED_PARAM, char **argv)
if (is_prefixed_with(argv[1], "--list")) {
unsigned i = 0;
const char *a = applet_names;
dup2(1, 2);
while (*a) {
# if ENABLE_FEATURE_INSTALLER
if (argv[1][6]) /* --list-full? */
full_write2_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
full_write1_str(install_dir[APPLET_INSTALL_LOC(i)] + 1);
# endif
full_write2_str(a);
full_write2_str("\n");
full_write1_str(a);
full_write1_str("\n");
i++;
while (*a++ != '\0')
continue;
@@ -890,14 +892,14 @@ int busybox_main(int argc UNUSED_PARAM, char **argv)
}
if (strcmp(argv[1], "--help") == 0) {
/* "busybox --help [<applet>]" */
/* "busybox --help [APPLET]" */
if (!argv[2]
# if ENABLE_FEATURE_SH_STANDALONE && ENABLE_FEATURE_TAB_COMPLETION
|| strcmp(argv[2], "busybox") == 0 /* prevent getting "No help available" */
# endif
)
goto help;
/* convert to "<applet> --help" */
/* convert to "APPLET --help" */
applet_name = argv[0] = argv[2];
argv[2] = NULL;
if (find_applet_by_name(applet_name) >= 0) {
@@ -905,8 +907,16 @@ int busybox_main(int argc UNUSED_PARAM, char **argv)
xfunc_error_retval = 0;
bb_show_usage();
} /* else: unknown applet, fall through (causes "applet not found" later) */
} else {
/* "busybox <applet> arg1 arg2 ..." */
}
# if ENABLE_FEATURE_VERSION
else if (!argv[2] && strcmp(argv[1], "--version") == 0) {
full_write1_str(bb_banner); /* reuse const string */
full_write1_str("\n");
return 0;
}
# endif
else {
/* "busybox APPLET arg1 arg2 ..." */
argv++;
/* We support "busybox /a/path/to/applet args..." too. Allows for
* "#!/bin/busybox"-style wrappers
@@ -1101,8 +1111,11 @@ int main(int argc UNUSED_PARAM, char **argv)
lbb_prepare("busybox" IF_FEATURE_INDIVIDUAL(, argv));
# if !ENABLE_BUSYBOX
if (argv[1] && is_prefixed_with(bb_basename(argv[0]), "busybox"))
if (argv[1] && argv[1][0] != '-' /* do not match "busybox --OPT" */
&& is_prefixed_with(bb_basename(argv[0]), "busybox")
) {
argv++;
}
# endif
applet_name = argv[0];
if (applet_name[0] == '-')
+56
View File
@@ -0,0 +1,56 @@
/*
* Utility routines.
*
* Copyright (C) 2026 Denys Vlasenko
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_NETSTAT) += bb_get_servname_by_port.o
//kbuild:lib-$(CONFIG_PSCAN) += bb_get_servname_by_port.o
#include "libbb.h"
//Rationale for existing:
//#define getservbyport dont_use_getservbyport_uses_global_buffer
//(for example: -280 bytes on musl, x86-32)
char* FAST_FUNC bb_get_servname_by_port(char **p_etc_services, int port, const char *type)
{
char *sp;
sp = *p_etc_services;
if (!sp) {
//TODO: we need mmap_entire_file() for this use case!
sp = xmalloc_open_read_close("/etc/services", NULL);
if (!sp)
return NULL;
*p_etc_services = sp;
}
while (*sp) {
const char *pnstr, *sp_end;
char *end;
unsigned n;
sp = skip_whitespace(sp);
if (*sp == '#')
goto next;
sp_end = skip_non_whitespace(sp);
pnstr = skip_whitespace(sp_end);
n = bb_strtou(pnstr, &end, 10);
if (n != port || *end != '/')
goto next;
if (type) {
end++;
end = is_prefixed_with(end, type);
if (!end
|| !(isspace(*end) || *end == '\0'
|| *end == '#') // glibc treats "http 80/tcp#COMMENT" (no space!) as valid
) {
goto next;
}
}
return auto_string(xstrndup(sp, sp_end - sp));
next:
sp = strchrnul(sp, '\n');
}
return NULL;
}
+129
View File
@@ -0,0 +1,129 @@
/*
* Utility routines.
*
* Copyright (C) 2026 Denys Vlasenko
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-y += bb_get_servport_by_name.o
//kbuild:lib-y += bb_get_servport_by_name.o
#include "libbb.h"
//Rationale for existing:
//#define getservbyname dont_use_getservbyname_uses_global_buffer
//(for example: -32 BSS bytes on musl, x86-32)
int FAST_FUNC bb_get_servport_by_name(char **p_etc_services, const char *name, const char *proto)
{
unsigned namelen;
char *sp;
if (!name[0]) // This can hang the search (strstr advances by 0 bytes)
return -1; // bad service name form: ""
// Any other bogosity to reject?
// Or just enforce isalnum_or_dash_or_slash(name[i])?
// Yes, service name like "cl/1" is allowed and _exists_.
//
// Protect against finding service "www#c" in "http 10/tcp www#c" line
//if (strchr(name, '#'))
// return -1; // bad service name form
//^^^^ the main code already catches this possibility.
//
// Current code allows e.g. service names like "http 80/tcp"
// to map to port 80. Probably harmless?
//if (skip_non_whitespace(name)[0])
// return -1; // bad service name form (has whitespace)
sp = *p_etc_services;
if (!sp) {
//TODO: we need mmap_entire_file() for this use case!
sp = xmalloc_open_read_close("/etc/services", NULL);
if (!sp)
return -1;
*p_etc_services = sp;
}
namelen = strlen(name);
while (*sp) {
const char *pnstr;
char *start, *end;
unsigned n;
// First, find a possible service name without regard for line separators (!)
start = strstr(sp, name);
if (!start)
return -1;
sp = start + namelen;
if (start != *p_etc_services && !isspace(start[-1])) {
// There is a char before it, and it's not whitespace
continue;
}
if (!(isspace(*sp) || *sp == '\0' || *sp == '#'))
// After it: not whitespace/EOF/comment
continue;
// The found substring _is_ correctly delimited before and after
// Find beginning of the line we are on
while (start != *p_etc_services && start[-1] != '\n')
start--;
start = skip_whitespace(start);
// Is there a comment char between start of line and "service name"?
if (memchr(start, '#', sp - start)) {
// The "service name" we found is actually in comment / has comment in it.
// Also rejects names with #:
// service "www#c" won't be found even on "http 80/tcp www#c" line
continue;
}
// Is the [start...sp) of the form "SERVNAME NUM/PROTO[ ALIAS[ ALIAS...][ ]]"?
pnstr = skip_whitespace(skip_non_whitespace(start)); // go to NUM...
// I've seen this line in /etc/services of a real-world machine:
//914c/g 211/tcp 914c-g
// Now consider just a bit more pathological example:
//914c/tcp 914/tcp 914/tcp
// If we search for service name "914/tcp",
// we'll find it at second word first, yet we must not reject this line
// because the THIRD word also matches, and it's a valid match (tested on glibc!).
// But in this case we must not match:
//914c/tcp 914/tcp something-else
if (sp - namelen == pnstr)
continue; // the match is at NUM..., try matching further
n = bb_strtou(pnstr, &end, 10);
if (n > 0xffff || *end != '/')
continue; // NUM... part is not a valid port#, or has no slash
if (proto) {
end++; // points to PROTO
end = is_prefixed_with(end, proto);
if (!end
|| !(isspace(*end) || *end == '\0'
|| *end == '#') // glibc treats "http 80/tcp#COMMENT" (no space!) as valid
) {
continue; // PROTO does not match
}
}
// By now, either WORD or one of the ALIASes has to be the part
// which was found by strstr()!
return n;
}
return -1;
}
// Return port number for a service.
// If "port" is a number use it as the port.
// If "port" is a name it is looked up in /etc/services.
// if NULL, return default_port
unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned port_nr)
{
if (port) {
port_nr = bb_strtou(port, NULL, 10);
if (errno || port_nr > 65535) {
char *p_etc_services = NULL;
port_nr = bb_get_servport_by_name(&p_etc_services, port, protocol);
if (port_nr > 0xffff) // -1?
bb_error_msg_and_die("bad port '%s'", port);
free(p_etc_services);
}
}
return (uint16_t)port_nr;
}
+34
View File
@@ -45,3 +45,37 @@ gid_t* FAST_FUNC bb_getgroups(int *ngroups, gid_t *group_array)
*ngroups = n;
return group_array;
}
uid_t FAST_FUNC get_cached_euid(uid_t *euid)
{
if (*euid == (uid_t)-1)
*euid = geteuid();
return *euid;
}
gid_t FAST_FUNC get_cached_egid(gid_t *egid)
{
if (*egid == (gid_t)-1)
*egid = getegid();
return *egid;
}
/* Return non-zero if GID is in our supplementary group list. */
int FAST_FUNC is_in_supplementary_groups(struct cached_groupinfo *groupinfo, gid_t gid)
{
int i;
int ngroups;
gid_t *group_array;
if (groupinfo->ngroups == 0)
groupinfo->supplementary_array = bb_getgroups(&groupinfo->ngroups, NULL);
ngroups = groupinfo->ngroups;
group_array = groupinfo->supplementary_array;
/* Search through the list looking for GID. */
for (i = 0; i < ngroups; i++)
if (gid == group_array[i])
return 1;
return 0;
}
+128
View File
@@ -0,0 +1,128 @@
/*
* Utility routines.
*
* Copyright (C) 2025 by Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-y += bitops.o
#include "libbb.h"
void FAST_FUNC xorbuf_3(void *dst, const void *src1, const void *src2, unsigned count)
{
uint8_t *d = dst;
const uint8_t *s1 = src1;
const uint8_t *s2 = src2;
#if BB_UNALIGNED_MEMACCESS_OK
while (count >= sizeof(long)) {
*(long*)d = *(long*)s1 ^ *(long*)s2;
count -= sizeof(long);
d += sizeof(long);
s1 += sizeof(long);
s2 += sizeof(long);
}
#endif
while (count--)
*d++ = *s1++ ^ *s2++;
}
void FAST_FUNC xorbuf(void *dst, const void *src, unsigned count)
{
xorbuf_3(dst, dst, src, count);
}
void FAST_FUNC xorbuf16_aligned_long(void *dst, const void *src)
{
#if defined(__SSE__) /* any x86_64 has it */
asm volatile(
"\n movups (%0),%%xmm0"
"\n movups (%1),%%xmm1" // can't just xorps(%1),%%xmm0:
"\n xorps %%xmm1,%%xmm0" // SSE requires 16-byte alignment
"\n movups %%xmm0,(%0)"
"\n"
: "=r" (dst), "=r" (src)
: "0" (dst), "1" (src)
: "xmm0", "xmm1", "memory"
);
#else
unsigned long *d = dst;
const unsigned long *s = src;
d[0] ^= s[0];
# if LONG_MAX <= 0x7fffffffffffffff
d[1] ^= s[1];
# if LONG_MAX == 0x7fffffff
d[2] ^= s[2];
d[3] ^= s[3];
# endif
# endif
#endif
}
// The above can be inlined in libbb.h, in a way where compiler
// is even free to use better addressing modes than (%reg), and
// to keep the result in a register
// (to not store it to memory after each XOR):
//#if defined(__SSE__)
//#include <xmmintrin.h>
//^^^ or just: typedef float __m128_u attribute((__vector_size__(16),__may_alias__,__aligned__(1)));
//static ALWAYS_INLINE void xorbuf16_aligned_long(void *dst, const void *src)
//{
// __m128_u xmm0, xmm1;
// asm volatile(
//"\n xorps %1,%0"
// : "=x" (xmm0), "=x" (xmm1)
// : "0" (*(__m128_u*)dst), "1" (*(__m128_u*)src)
// );
// *(__m128_u*)dst = xmm0; // this store may be optimized out!
//}
//#endif
// but I don't trust gcc optimizer enough to not generate some monstrosity.
// See GMULT() function in TLS code as an example.
void FAST_FUNC xorbuf64_3_aligned64(void *dst, const void *src1, const void *src2)
{
#if defined(__SSE__) /* any x86_64 has it */
asm volatile(
"\n movups 0*16(%1),%%xmm0"
"\n movups 0*16(%2),%%xmm1" // can't just xorps(%2),%%xmm0:
"\n xorps %%xmm1,%%xmm0" // SSE requires 16-byte alignment, we have only 8-byte
"\n movups %%xmm0,0*16(%0)"
"\n movups 1*16(%1),%%xmm0"
"\n movups 1*16(%2),%%xmm1"
"\n xorps %%xmm1,%%xmm0"
"\n movups %%xmm0,1*16(%0)"
"\n movups 2*16(%1),%%xmm0"
"\n movups 2*16(%2),%%xmm1"
"\n xorps %%xmm1,%%xmm0"
"\n movups %%xmm0,2*16(%0)"
"\n movups 3*16(%1),%%xmm0"
"\n movups 3*16(%2),%%xmm1"
"\n xorps %%xmm1,%%xmm0"
"\n movups %%xmm0,3*16(%0)"
"\n"
: "=r" (dst), "=r" (src1), "=r" (src2)
: "0" (dst), "1" (src1), "2" (src2)
: "xmm0", "xmm1", "memory"
);
#else
long *d = dst;
const long *s1 = src1;
const long *s2 = src2;
unsigned count = 64 / sizeof(long);
do {
*d++ = *s1++ ^ *s2++;
} while (--count != 0);
#endif
}
#if !BB_UNALIGNED_MEMACCESS_OK
void FAST_FUNC xorbuf16(void *dst, const void *src)
{
#define p_aligned(a) (((uintptr_t)(a) & (sizeof(long)-1)) == 0)
if (p_aligned(src) && p_aligned(dst)) {
xorbuf16_aligned_long(dst, src);
return;
}
xorbuf_3(dst, dst, src, 16);
}
#endif
+20
View File
@@ -0,0 +1,20 @@
/* vi: set sw=4 ts=4: */
/*
* Copyright (C) 2025 by Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-y += c_escape.o
#include "libbb.h"
const char c_escape_conv_str00[] ALIGN1 =
"\\""0""\0" // [0]:00
"\\""a""\0" // [1]:07
"\\""b""\0" // [2]:08
"\\""t""\0" // [3]:09
"\\""n""\0" // [4]:0a
"\\""v""\0" // [5]:0b
"\\""f""\0" // [6]:0c
"\\""r" // [7]:0d
;
+75
View File
@@ -17,6 +17,7 @@
char* FAST_FUNC concat_path_file(const char *path, const char *filename)
{
#if 0
char *lc;
if (!path)
@@ -25,4 +26,78 @@ char* FAST_FUNC concat_path_file(const char *path, const char *filename)
while (*filename == '/')
filename++;
return xasprintf("%s%s%s", path, (lc==NULL ? "/" : ""), filename);
#else
/* ^^^^^^^^^^^ timing of xasprintf-based code above:
* real 7.074s
* user 0.156s <<<
* sys 6.394s
* "rm -rf" of a Linux kernel tree from tmpfs (run time still dominated by in-kernel work, though)
* real 6.989s
* user 0.055s <<< 3 times less CPU used
* sys 6.450s
* vvvvvvvvvvv timing of open-coded malloc+memcpy code below (+59 bytes):
*/
char *buf, *p;
size_t n1, n2, n3;
while (*filename == '/')
filename++;
if (!path || !path[0])
return xstrdup(filename);
n1 = strlen(path);
n2 = (path[n1 - 1] != '/'); /* 1: "path has no trailing slash" */
n3 = strlen(filename) + 1;
buf = xmalloc(n1 + n2 + n3);
p = mempcpy(buf, path, n1);
if (n2)
*p++ = '/';
memcpy(p, filename, n3);
return buf;
#endif
}
/* If second component comes from struct dirent,
* it's possible to eliminate one strlen() by using name length
* provided by kernel in struct dirent. See below.
* However, the win seems to be insignificant.
*/
#if 0
/* Extract d_namlen from struct dirent */
static size_t get_d_namlen(const struct dirent *de)
{
#if defined(_DIRENT_HAVE_D_NAMLEN)
return de->d_namlen;
#elif defined(_DIRENT_HAVE_D_RECLEN)
const size_t prefix_sz = offsetof(struct dirent, d_name);
return de->d_reclen - prefix_sz;
#else
return strlen(de->d_name);
#endif
}
char* FAST_FUNC concat_path_dirent(const char *path, const struct dirent *de)
{
char *buf, *p;
size_t n1, n2, n3;
if (!path || !path[0])
return xstrdup(de->d_name);
n1 = strlen(path);
n2 = (path[n1 - 1] != '/');
n3 = get_d_namlen(de) + 1;
buf = xmalloc(n1 + n2 + n3);
p = mempcpy(buf, path, n1);
if (n2)
*p++ = '/';
memcpy(p, de->d_name, n3);
return buf;
}
#endif
+20 -1
View File
@@ -9,8 +9,27 @@
#include "libbb.h"
#if defined(__clang_major__) && __clang_major__ >= 9
/* Clang/llvm drops assignment to "constant" storage. Silently.
* Needs serious convincing to not eliminate the store.
*/
static ALWAYS_INLINE void* not_const_pp(const void *p)
{
void *pp;
asm volatile (
"# forget that p points to const"
: /*outputs*/ "=r" (pp)
: /*inputs*/ "0" (p)
);
return pp;
}
void FAST_FUNC ASSIGN_CONST_PTR(const void *pptr, void *v)
{
*(void**)not_const_pp(pptr) = v;
barrier();
}
void FAST_FUNC XZALLOC_CONST_PTR(const void *pptr, size_t size)
{
ASSIGN_CONST_PTR(pptr, xzalloc(size));
*(void**)not_const_pp(pptr) = xzalloc(size);
barrier();
}
#endif
+46 -23
View File
@@ -198,9 +198,11 @@ static NOINLINE void rewrite(priv_dumper_t *dumper, FS *fs)
if (!e)
goto DO_BAD_CONV_CHAR;
pr->flags = F_INT;
if (e > int_convs + 1) /* not d or i? */
pr->flags = F_UINT;
byte_count_str = "\010\004\002\001";
if (e > int_convs + 1) { /* not d or i? */
pr->flags = F_UINT;
byte_count_str++;
}
goto DO_BYTE_COUNT;
} else
if (strchr(int_convs, *p1)) { /* %d etc */
@@ -476,37 +478,52 @@ static void bpad(PR *pr)
continue;
}
static const char conv_str[] ALIGN1 =
"\0" "\\""0""\0"
"\007""\\""a""\0"
"\b" "\\""b""\0"
"\f" "\\""f""\0"
"\n" "\\""n""\0"
"\r" "\\""r""\0"
"\t" "\\""t""\0"
"\v" "\\""v""\0"
;
static void conv_c(PR *pr, unsigned char *p)
{
const char *str = conv_str;
const char *str;
unsigned char ch;
do {
if (*p == *str) {
++str;
goto strpr; /* map e.g. '\n' to "\\n" */
}
str += 4;
} while (*str);
ch = *p;
if (ch == 0 || (ch -= 6, (signed char)ch > 0 && ch <= 7)) {
/* map chars 0,7..13 to "\0","\{a,b,t,n,v,f,r}" */
str = c_escape_conv_str00 + 3 * ch;
goto strpr;
}
if (isprint_asciionly(*p)) {
*pr->cchar = 'c';
printf(pr->fmt, *p);
} else {
#if defined(__i386__) || defined(__x86_64__)
/* Abuse partial register operations */
uint32_t buf;
unsigned n = *p;
asm ( //00000000 00000000 00000000 aabbbccc
"\n shll $10,%%eax" //00000000 000000aa bbbccc00 00000000
"\n shrw $5,%%ax" //00000000 000000aa 00000bbb ccc00000
"\n shrb $5,%%al" //00000000 000000aa 00000bbb 00000ccc
"\n shll $8,%%eax" //000000aa 00000bbb 00000ccc 00000000
"\n bswapl %%eax" //00000000 00000ccc 00000bbb 000000aa
"\n addl $0x303030,%%eax"
"\n" : "=a" (n)
: "0" (n)
);
buf = n;
str = (void*)&buf;
#elif 1
char buf[4];
/* gcc-8.0.1 needs lots of casts to shut up */
sprintf(buf, "%03o", (unsigned)(uint8_t)*p);
str = buf;
#else // use faster version? +20 bytes of code relative to sprintf() method
char buf[4];
buf[3] = '\0';
ch = *p;
buf[2] = '0' + (ch & 7); ch >>= 3;
buf[1] = '0' + (ch & 7); ch >>= 3;
buf[0] = '0' + ch;
str = buf;
#endif
strpr:
*pr->cchar = 's';
printf(pr->fmt, str);
@@ -665,15 +682,21 @@ static NOINLINE void display(priv_dumper_t* dumper)
conv_u(pr, bp);
break;
case F_UINT: {
union {
uint16_t uval16;
uint32_t uval32;
} u;
unsigned value = (unsigned char)*bp;
switch (pr->bcnt) {
case 1:
break;
case 2:
move_from_unaligned16(value, bp);
move_from_unaligned16(u.uval16, bp);
value = u.uval16;
break;
case 4:
move_from_unaligned32(value, bp);
move_from_unaligned32(u.uval32, bp);
value = u.uval32;
break;
/* case 8: no users yet */
}
+30 -26
View File
@@ -21,14 +21,11 @@ int FAST_FUNC file_is_executable(const char *name)
/* search (*PATHp) for an executable file;
* return allocated string containing full path if found;
* PATHp points to the component after the one where it was found
* (or NULL),
* (or NULL if found in last component),
* you may call find_executable again with this PATHp to continue
* (if it's not NULL).
* return NULL otherwise; (PATHp is undefined)
* in all cases (*PATHp) contents are temporarily modified
* but are restored on return (s/:/NUL/ and back).
* return NULL otherwise (PATHp is undefined)
*/
char* FAST_FUNC find_executable(const char *filename, char **PATHp)
char* FAST_FUNC find_executable(const char *name, const char **PATHp)
{
/* About empty components in $PATH:
* http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap08.html
@@ -38,38 +35,45 @@ char* FAST_FUNC find_executable(const char *filename, char **PATHp)
* initial colon preceding the rest of the list, or as a trailing colon
* following the rest of the list.
*/
char *p, *n;
char *p = (char*) *PATHp;
p = *PATHp;
while (p) {
int ex;
if (!p)
return NULL;
while (1) {
const char *end = strchrnul(p, ':');
int sz = end - p;
n = strchr(p, ':');
if (n) *n = '\0';
p = concat_path_file(
p[0] ? p : ".", /* handle "::" case */
filename
);
ex = file_is_executable(p);
if (n) *n++ = ':';
if (ex) {
*PATHp = n;
if (sz != 0) {
p = xasprintf("%.*s/%s", sz, p, name);
} else {
/* We have xxx::yyy in $PATH,
* it means "use current dir" */
p = xstrdup(name);
// A bit of discrepancy wrt the path used if file is found here.
// bash 5.2.15 "type" returns "./NAME".
// GNU which v2.21 returns "/CUR/DIR/NAME".
// With -a, both skip over all colons: xxx::::yyy is the same as xxx::yyy,
// current dir is not tried the second time.
}
if (file_is_executable(p)) {
*PATHp = (*end ? end+1 : NULL);
return p;
}
free(p);
p = n;
} /* on loop exit p == NULL */
return p;
if (*end == '\0')
return NULL;
p = (char *) end + 1;
}
}
/* search $PATH for an executable file;
* return 1 if found;
* return 0 otherwise;
*/
int FAST_FUNC executable_exists(const char *filename)
int FAST_FUNC executable_exists(const char *name)
{
char *path = getenv("PATH");
char *ret = find_executable(filename, &path);
const char *path = getenv("PATH");
char *ret = find_executable(name, &path);
free(ret);
return ret != NULL;
}
+2 -2
View File
@@ -24,12 +24,12 @@ const char* FAST_FUNC bb_basename(const char *name)
*/
char* FAST_FUNC bb_get_last_path_component_nostrip(const char *path)
{
char *slash = strrchr(path, '/');
const char *slash = strrchr(path, '/');
if (!slash || (slash == path && !slash[1]))
return (char*)path;
return slash + 1;
return (char*)slash + 1;
}
/*
+18 -12
View File
@@ -93,7 +93,7 @@ getopt32(char **argv, const char *applet_opts, ...)
"!" If the first character in the applet_opts string is a '!',
report bad options, missing required options,
inconsistent options with all-ones return value (instead of abort.
inconsistent options with all-ones return value instead of aborting.
"+" If the first character in the applet_opts string is a plus,
then option processing will stop as soon as a non-option is
@@ -265,7 +265,7 @@ Special characters:
for "long options only" cases, such as tar --exclude=PATTERN,
wget --header=HDR cases.
"a?b" A "?" between an option and a group of options means that
"a?bc" A "?" between an option and a group of options means that
at least one of them is required to occur if the first option
occurs in preceding command line arguments.
@@ -348,9 +348,6 @@ vgetopt32(char **argv, const char *applet_opts, const char *applet_long_options,
unsigned trigger;
int min_arg = 0;
int max_arg = -1;
int spec_flgs = 0;
#define SHOW_USAGE_IF_ERROR 1
on_off = complementary;
memset(on_off, 0, sizeof(complementary));
@@ -449,9 +446,7 @@ vgetopt32(char **argv, const char *applet_opts, const char *applet_long_options,
continue;
c = s[1];
if (*s == '?') {
if (c < '0' || c > '9') {
spec_flgs |= SHOW_USAGE_IF_ERROR;
} else {
if (c >= '0' && c <= '9') {
max_arg = c - '0';
s++;
}
@@ -465,8 +460,10 @@ vgetopt32(char **argv, const char *applet_opts, const char *applet_long_options,
continue;
}
if (*s == '=') {
min_arg = max_arg = c - '0';
s++;
if (c >= '0' && c <= '9') {
min_arg = max_arg = c - '0';
s++;
}
continue;
}
for (on_off = complementary; on_off->opt_char; on_off++)
@@ -533,6 +530,7 @@ vgetopt32(char **argv, const char *applet_opts, const char *applet_long_options,
* "fake" short options, like this one:
* wget $'-\203' "Test: test" http://kernel.org/
* (supposed to act as --header, but doesn't) */
next_opt:
#if ENABLE_LONG_OPTS
while ((c = getopt_long(argc, argv, applet_opts,
long_options, NULL)) != -1) {
@@ -547,8 +545,16 @@ vgetopt32(char **argv, const char *applet_opts, const char *applet_long_options,
* but we construct long opts so that flag
* is always NULL (see above) */
if (on_off->opt_char == '\0' /* && c != '\0' */) {
/* c is probably '?' - "bad option" */
goto error;
/* We reached the end of complementary[] and did not find -c */
if (c == '?') /* getopt says: "bad option, or option has no required argument" */
goto error;
/* if there were options beyond 32 bits (example: ls),
* they got no complementary[] slot, and no result bit.
* IOW: they must be "accept but ignore" options.
* For them, we end up here.
*/
//bb_error_msg("ignored option '%c', skipping", c);
goto next_opt;
}
}
if (flags & on_off->incongruously)
+58 -24
View File
@@ -9,35 +9,69 @@
#define DEBUG 0
// On modern systems (old ways were more kludgy with setuid "pt_chown" binary):
// ptyfd = open("/dev/ptmx"):
// Kernel creates slave /dev/pts/N with owner = real UID of opener,
// group and mode as configured by /dev/pts mount options.
// The mode is safe with standard mount options (gid=5,mode=620).
//
// grantpt(ptyfd) is now only a verification step. In glibc:
// Calls ioctl(fd, TIOCGPTN, &minor) to confirm ptyfd is valid master pty.
// If ioctl fails with ENOTTY, remaps to EINVAL (POSIX).
// Otherwise returns 0. (No chown/chmod occurs.)
//
// unlockpt(ptyfd) is ioctl(TIOCSPTLCK, 0): clears optional protection flag
// on slave. If flag was set, open(slave) fails with EIO for everyone (even root)
// until unlocked. [Do modern kernels still set the lock in open("/dev/ptmx")?]
// The lock historically prevented opening slave before grantpt() fixes perms
// in misconfigured/old setups where kernel didn't set 0620 atomically.
// Today it's mostly belt-and-suspenders + POSIX compatibility.
//
// The attack thwarted by the lock (assuming unprivileged adversary):
// you open /dev/ptmx, kernel allocates /dev/pts/N with overly permissive mode.
// Adversary manages to open /dev/pts/N before your grantpt() call
// locks down permissions.
// Typically, /dev/pts mount options are gid=5,mode=620, 5 = "tty" group,
// system is set up with only trusted binaries and no users in "tty" group.
// In this case, the locking mechanism is overkill (would be safe without it).
// To fortify more, you can mount with gid=0,mode=600. Tools like "wall",
// "mesg" would stop working.
// Processes with my own UID can still race against me, but I probably
// trust myself...
//
// ptsname(ptyfd), internally ioctl(TIOCGPTN): get index, build
// "/dev/pts/NN" string which refers to the slave pty.
int FAST_FUNC xgetpty(char *line)
{
int p;
#if ENABLE_FEATURE_DEVPTS
p = open("/dev/ptmx", O_RDWR);
if (p >= 0) {
grantpt(p); /* chmod+chown corresponding slave pty */
unlockpt(p); /* (what does this do?) */
int ptyfd;
ptyfd = open("/dev/ptmx", O_RDWR);
if (ptyfd < 0)
bb_simple_perror_msg_and_die("can't find free pty");
grantpt(ptyfd); /* chmod+chown corresponding slave pty */
unlockpt(ptyfd); /* allow open() on slave /dev node */
# ifndef HAVE_PTSNAME_R
{
const char *name;
name = ptsname(p); /* find out the name of slave pty */
if (!name) {
bb_simple_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
}
safe_strncpy(line, name, GETPTY_BUFSIZE);
}
# else
/* find out the name of slave pty */
if (ptsname_r(p, line, GETPTY_BUFSIZE-1) != 0) {
{
const char *name;
name = ptsname(ptyfd); /* find out the name of slave pty */
if (!name) {
bb_simple_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
}
line[GETPTY_BUFSIZE-1] = '\0';
# endif
return p;
safe_strncpy(line, name, GETPTY_BUFSIZE);
}
# else
/* find out the name of slave pty */
if (ptsname_r(ptyfd, line, GETPTY_BUFSIZE-1) != 0) {
bb_simple_perror_msg_and_die("ptsname error (is /dev/pts mounted?)");
}
line[GETPTY_BUFSIZE-1] = '\0';
# endif
return ptyfd;
#else
struct stat stb;
int ptyfd;
int i;
int j;
@@ -53,13 +87,13 @@ int FAST_FUNC xgetpty(char *line)
line[9] = j < 10 ? j + '0' : j - 10 + 'a';
if (DEBUG)
fprintf(stderr, "Trying to open device: %s\n", line);
p = open(line, O_RDWR | O_NOCTTY);
if (p >= 0) {
ptyfd = open(line, O_RDWR | O_NOCTTY);
if (ptyfd >= 0) {
line[5] = 't';
return p;
return ptyfd;
}
}
}
#endif /* FEATURE_DEVPTS */
bb_simple_error_msg_and_die("can't find free pty");
#endif /* FEATURE_DEVPTS */
}
+107
View File
@@ -0,0 +1,107 @@
/*
* Copyright (C) 2025 Denys Vlasenko
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_TLS) += hash_hmac.o
//kbuild:lib-$(CONFIG_USE_BB_CRYPT_YES) += hash_hmac.o
#include "libbb.h"
// RFC 2104:
// HMAC(key, text) based on a hash H (say, sha256) is:
// ipad = [0x36 x INSIZE]
// opad = [0x5c x INSIZE]
// HMAC(key, text) = H((key XOR opad) + H((key XOR ipad) + text))
//
// H(key XOR opad) and H(key XOR ipad) can be precomputed
// if we often need HMAC hmac with the same key.
//
// text is often given in disjoint pieces.
void FAST_FUNC hmac_begin(hmac_ctx_t *ctx, const uint8_t *key, unsigned key_size, md5sha_begin_func *begin)
{
#if HMAC_ONLY_SHA256
#define begin sha256_begin
#endif
uint8_t key_xor_ipad[SHA2_INSIZE];
uint8_t key_xor_opad[SHA2_INSIZE];
unsigned i;
// "The authentication key can be of any length up to INSIZE, the
// block length of the hash function. Applications that use keys longer
// than INSIZE bytes will first hash the key using H and then use the
// resultant OUTSIZE byte string as the actual key to HMAC."
if (key_size > SHA2_INSIZE) {
uint8_t tempkey[SHA1_OUTSIZE < SHA256_OUTSIZE ? SHA256_OUTSIZE : SHA1_OUTSIZE];
/* use ctx->hashed_key_xor_ipad as scratch ctx */
begin(&ctx->hashed_key_xor_ipad);
md5sha_hash(&ctx->hashed_key_xor_ipad, key, key_size);
key_size = sha_end(&ctx->hashed_key_xor_ipad, tempkey);
key = tempkey;
}
for (i = 0; i < key_size; i++) {
key_xor_ipad[i] = key[i] ^ 0x36;
key_xor_opad[i] = key[i] ^ 0x5c;
}
for (; i < SHA2_INSIZE; i++) {
key_xor_ipad[i] = 0x36;
key_xor_opad[i] = 0x5c;
}
begin(&ctx->hashed_key_xor_ipad);
begin(&ctx->hashed_key_xor_opad);
md5sha_hash(&ctx->hashed_key_xor_ipad, key_xor_ipad, SHA2_INSIZE);
md5sha_hash(&ctx->hashed_key_xor_opad, key_xor_opad, SHA2_INSIZE);
}
#undef begin
unsigned FAST_FUNC hmac_end(hmac_ctx_t *ctx, uint8_t *out)
{
unsigned len = sha_end(&ctx->hashed_key_xor_ipad, out);
/* out = H((key XOR opad) + out) */
md5sha_hash(&ctx->hashed_key_xor_opad, out, len);
return sha_end(&ctx->hashed_key_xor_opad, out);
}
unsigned FAST_FUNC hmac_block(const uint8_t *key, unsigned key_size, md5sha_begin_func *begin, const void *in, unsigned sz, uint8_t *out)
{
hmac_ctx_t ctx;
hmac_begin(&ctx, key, key_size, begin);
hmac_hash(&ctx, in, sz);
return hmac_end(&ctx, out);
}
/* TLS helpers */
void FAST_FUNC hmac_hash_v(
hmac_ctx_t *ctx,
va_list va)
{
uint8_t *in;
/* ctx->hashed_key_xor_ipad contains unclosed "H((key XOR ipad) +" state */
/* ctx->hashed_key_xor_opad contains unclosed "H((key XOR opad) +" state */
/* calculate out = H((key XOR ipad) + text) */
while ((in = va_arg(va, uint8_t*)) != NULL) {
unsigned size = va_arg(va, unsigned);
md5sha_hash(&ctx->hashed_key_xor_ipad, in, size);
}
}
/* Using HMAC state, make a copy of it (IOW: without affecting this state!)
* hash in the list of (ptr,size) blocks, and finish the HMAC to out[] buffer.
* This function is useful for TLS PRF.
*/
unsigned FAST_FUNC hmac_peek_hash(hmac_ctx_t *ctx, uint8_t *out, ...)
{
hmac_ctx_t tmpctx = *ctx; /* struct copy */
va_list va;
va_start(va, out);
hmac_hash_v(&tmpctx, va);
va_end(va);
return hmac_end(&tmpctx, out);
}
+47 -13
View File
@@ -11,7 +11,7 @@
#define STR1(s) #s
#define STR(s) STR1(s)
#define NEED_SHA512 (ENABLE_SHA512SUM || ENABLE_USE_BB_CRYPT_SHA)
#define NEED_SHA512 (ENABLE_SHA512SUM || ENABLE_SHA384SUM || ENABLE_USE_BB_CRYPT_SHA)
#if ENABLE_SHA1_HWACCEL || ENABLE_SHA256_HWACCEL
# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
@@ -1032,7 +1032,7 @@ static const sha_K_int sha_K[] ALIGN8 = {
K(0x84c87814a1f0ab72ULL), K(0x8cc702081a6439ecULL),
K(0x90befffa23631e28ULL), K(0xa4506cebde82bde9ULL),
K(0xbef9a3f7b2c67915ULL), K(0xc67178f2e372532bULL),
#if NEED_SHA512 /* [64]+ are used for sha512 only */
#if NEED_SHA512 /* [64]+ are used for sha384 and sha512 only */
K(0xca273eceea26619cULL), K(0xd186b8c721c0c207ULL),
K(0xeada7dd6cde0eb1eULL), K(0xf57d4f7fee6ed178ULL),
K(0x06f067aa72176fbaULL), K(0x0a637dc5a2c898a6ULL),
@@ -1229,11 +1229,20 @@ static const uint32_t init512_lo[] ALIGN4 = {
0x137e2179,
};
#endif /* NEED_SHA512 */
// Note: SHA-384 is identical to SHA-512, except that initial hash values are
// 0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939,
// 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4,
// and the output is constructed by omitting last two 64-bit words of it.
#if ENABLE_SHA384SUM
static const uint64_t init384[] ALIGN8 = {
0,
0,
0xcbbb9d5dc1059ed8,
0x629a292a367cd507,
0x9159015a3070dd17,
0x152fecd8f70e5939,
0x67332667ffc00b31,
0x8eb44a8768581511,
0xdb0c2e0d64f98fa7,
0x47b5481dbefa4fa4,
};
#endif
/* Initialize structure containing state of computation.
(FIPS 180-2:5.3.2) */
@@ -1255,9 +1264,19 @@ void FAST_FUNC sha256_begin(sha256_ctx_t *ctx)
#endif
}
#if NEED_SHA512
#if ENABLE_SHA384SUM
/* Initialize structure containing state of computation.
(FIPS 180-2:5.3.3) */
void FAST_FUNC sha384_begin(sha512_ctx_t *ctx)
{
memcpy(&ctx->total64, init384, sizeof(init384));
/*ctx->total64[0] = ctx->total64[1] = 0; - already done */
}
#endif
#if NEED_SHA512
/* Initialize structure containing state of computation.
(FIPS 180-2:5.3.4) */
void FAST_FUNC sha512_begin(sha512_ctx_t *ctx)
{
int i;
@@ -1313,7 +1332,9 @@ unsigned FAST_FUNC sha1_end(sha1_ctx_t *ctx, void *resbuf)
hash_size = 8;
if (ctx->process_block == sha1_process_block64
#if ENABLE_SHA1_HWACCEL
# if defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))
|| ctx->process_block == sha1_process_block64_shaNI
# endif
#endif
) {
hash_size = 5;
@@ -1330,7 +1351,7 @@ unsigned FAST_FUNC sha1_end(sha1_ctx_t *ctx, void *resbuf)
}
#if NEED_SHA512
unsigned FAST_FUNC sha512_end(sha512_ctx_t *ctx, void *resbuf)
static unsigned FAST_FUNC sha512384_end(sha512_ctx_t *ctx, void *resbuf, unsigned outsize)
{
unsigned bufpos = ctx->total64[0] & 127;
@@ -1361,11 +1382,21 @@ unsigned FAST_FUNC sha512_end(sha512_ctx_t *ctx, void *resbuf)
for (i = 0; i < ARRAY_SIZE(ctx->hash); ++i)
ctx->hash[i] = SWAP_BE64(ctx->hash[i]);
}
memcpy(resbuf, ctx->hash, sizeof(ctx->hash));
return sizeof(ctx->hash);
memcpy(resbuf, ctx->hash, outsize);
return outsize;
}
unsigned FAST_FUNC sha512_end(sha384_ctx_t *ctx, void *resbuf)
{
return sha512384_end(ctx, resbuf, SHA512_OUTSIZE);
}
#endif /* NEED_SHA512 */
#if ENABLE_SHA384SUM
unsigned FAST_FUNC sha384_end(sha384_ctx_t *ctx, void *resbuf)
{
return sha512384_end(ctx, resbuf, SHA384_OUTSIZE);
}
#endif
/*
* The Keccak sponge function, designed by Guido Bertoni, Joan Daemen,
@@ -1902,6 +1933,8 @@ void FAST_FUNC sha3_hash(sha3_ctx_t *ctx, const void *buffer, size_t len)
unsigned FAST_FUNC sha3_end(sha3_ctx_t *ctx, void *resbuf)
{
unsigned hash_len;
/* Padding */
uint8_t *buf = (uint8_t*)ctx->state;
/*
@@ -1924,6 +1957,7 @@ unsigned FAST_FUNC sha3_end(sha3_ctx_t *ctx, void *resbuf)
sha3_process_block72(ctx->state);
/* Output */
memcpy(resbuf, ctx->state, 64);
return 64;
hash_len = (1600/8 - ctx->input_block_bytes) / 2;
memcpy(resbuf, ctx->state, hash_len);
return hash_len;
}
+19
View File
@@ -0,0 +1,19 @@
/* vi: set sw=4 ts=4: */
/*
* Utility routines.
*
* Copyright (C) 2025 Denys Vlasenko
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//kbuild:lib-y += hash_sha256_block.o
#include "libbb.h"
void FAST_FUNC
sha256_block(const void *in, size_t len, uint8_t hash[32])
{
sha256_ctx_t ctx;
sha256_begin(&ctx);
sha256_hash(&ctx, in, len);
sha256_end(&ctx, hash);
}
+118 -100
View File
@@ -34,21 +34,21 @@
#define MSG %xmm0
#define STATE0 %xmm1
#define STATE1 %xmm2
#define MSGTMP0 %xmm3
#define MSGTMP1 %xmm4
#define MSGTMP2 %xmm5
#define MSGTMP3 %xmm6
#define MSG0 %xmm3
#define MSG1 %xmm4
#define MSG2 %xmm5
#define MSG3 %xmm6
#define XMMTMP %xmm7
#define SHUF(a,b,c,d) $(a+(b<<2)+(c<<4)+(d<<6))
#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+0*16(%eax), XMMTMP /* ABCD (shown least-significant-dword-first) */
movu128 76+1*16(%eax), STATE1 /* EFGH */
/* shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one */
/* shufps: dwords 0,1 of the result are selected from *2nd* operand, and dwords 2,3 from 1st operand */
mova128 STATE1, STATE0
/* --- -------------- ABCD -- EFGH */
shufps SHUF(1,0,1,0), XMMTMP, STATE0 /* FEBA */
@@ -58,190 +58,208 @@ sha256_process_block64_shaNI:
mova128 PSHUFFLE_BSWAP32_FLIP_MASK, XMMTMP
movl $K256+8*16, SHA256CONSTANTS
// sha256rnds2 instruction uses only lower 64 bits of MSG.
// The code below needs to move upper 64 bits to lower 64 bits
// for the second sha256rnds2 invocation
// (what remains in upper bits does not matter).
// There are several ways to do it:
// movhlps MSG, MSG // abcd -> cdcd (3 bytes of code)
// shuf128_32 SHUF(2,3,n,n), MSG, MSG // abcd -> cdXX (4 bytes)
// punpckhqdq MSG, MSG // abcd -> cdcd (4 bytes)
// unpckhpd MSG, MSG // abcd -> cdcd (4 bytes)
// psrldq $8, MSG // abcd -> cd00 (5 bytes)
// palignr $8, MSG, MSG // abcd -> cdab (6 bytes, SSSE3 insn)
#define MOVE_UPPER64_DOWN(reg) movhlps reg, reg
//#define MOVE_UPPER64_DOWN(reg) shuf128_32 SHUF(2,3,0,0), reg, reg
//#define MOVE_UPPER64_DOWN(reg) punpckhqdq reg, reg
//#define MOVE_UPPER64_DOWN(reg) unpckhpd reg, reg
//#define MOVE_UPPER64_DOWN(reg) psrldq $8, reg
//#define MOVE_UPPER64_DOWN(reg) palignr $8, reg, reg
/* Rounds 0-3 */
movu128 0*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP0
mova128 MSG, MSG0
paddd 0*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 4-7 */
movu128 1*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP1
mova128 MSG, MSG1
paddd 1*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
sha256msg1 MSG1, MSG0
/* Rounds 8-11 */
movu128 2*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP2
mova128 MSG, MSG2
paddd 2*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
sha256msg1 MSG2, MSG1
/* Rounds 12-15 */
movu128 3*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
/* ...to here */
mova128 MSG, MSGTMP3
mova128 MSG, MSG3
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
mova128 MSG3, XMMTMP
palignr $4, MSG2, XMMTMP
paddd XMMTMP, MSG0
sha256msg2 MSG3, MSG0
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
sha256msg1 MSG3, MSG2
/* Rounds 16-19 */
mova128 MSGTMP0, MSG
mova128 MSG0, 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
mova128 MSG0, XMMTMP
palignr $4, MSG3, XMMTMP
paddd XMMTMP, MSG1
sha256msg2 MSG0, MSG1
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
sha256msg1 MSG0, MSG3
/* Rounds 20-23 */
mova128 MSGTMP1, MSG
mova128 MSG1, 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
mova128 MSG1, XMMTMP
palignr $4, MSG0, XMMTMP
paddd XMMTMP, MSG2
sha256msg2 MSG1, MSG2
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
sha256msg1 MSG1, MSG0
/* Rounds 24-27 */
mova128 MSGTMP2, MSG
mova128 MSG2, 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
mova128 MSG2, XMMTMP
palignr $4, MSG1, XMMTMP
paddd XMMTMP, MSG3
sha256msg2 MSG2, MSG3
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
sha256msg1 MSG2, MSG1
/* Rounds 28-31 */
mova128 MSGTMP3, MSG
mova128 MSG3, 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
mova128 MSG3, XMMTMP
palignr $4, MSG2, XMMTMP
paddd XMMTMP, MSG0
sha256msg2 MSG3, MSG0
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
sha256msg1 MSG3, MSG2
/* Rounds 32-35 */
mova128 MSGTMP0, MSG
mova128 MSG0, 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
mova128 MSG0, XMMTMP
palignr $4, MSG3, XMMTMP
paddd XMMTMP, MSG1
sha256msg2 MSG0, MSG1
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
sha256msg1 MSG0, MSG3
/* Rounds 36-39 */
mova128 MSGTMP1, MSG
mova128 MSG1, 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
mova128 MSG1, XMMTMP
palignr $4, MSG0, XMMTMP
paddd XMMTMP, MSG2
sha256msg2 MSG1, MSG2
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
sha256msg1 MSG1, MSG0
/* Rounds 40-43 */
mova128 MSGTMP2, MSG
mova128 MSG2, 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
mova128 MSG2, XMMTMP
palignr $4, MSG1, XMMTMP
paddd XMMTMP, MSG3
sha256msg2 MSG2, MSG3
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
sha256msg1 MSG2, MSG1
/* Rounds 44-47 */
mova128 MSGTMP3, MSG
mova128 MSG3, 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
mova128 MSG3, XMMTMP
palignr $4, MSG2, XMMTMP
paddd XMMTMP, MSG0
sha256msg2 MSG3, MSG0
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
sha256msg1 MSG3, MSG2
/* Rounds 48-51 */
mova128 MSGTMP0, MSG
mova128 MSG0, 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
mova128 MSG0, XMMTMP
palignr $4, MSG3, XMMTMP
paddd XMMTMP, MSG1
sha256msg2 MSG0, MSG1
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
sha256msg1 MSG0, MSG3
/* Rounds 52-55 */
mova128 MSGTMP1, MSG
mova128 MSG1, 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
mova128 MSG1, XMMTMP
palignr $4, MSG0, XMMTMP
paddd XMMTMP, MSG2
sha256msg2 MSG1, MSG2
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 56-59 */
mova128 MSGTMP2, MSG
mova128 MSG2, 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
mova128 MSG2, XMMTMP
palignr $4, MSG1, XMMTMP
paddd XMMTMP, MSG3
sha256msg2 MSG2, MSG3
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 60-63 */
mova128 MSGTMP3, MSG
mova128 MSG3, MSG
paddd 15*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(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 */
/* shufps: dwords 0,1 of the result are selected from *2nd* operand, and dwords 2,3 from 1st operand */
/* --- -------------- HGDC -- FEBA */
shufps SHUF(3,2,3,2), STATE1, STATE0 /* ABCD */
shufps SHUF(1,0,1,0), STATE1, XMMTMP /* EFGH */
+118 -100
View File
@@ -34,24 +34,24 @@
#define MSG %xmm0
#define STATE0 %xmm1
#define STATE1 %xmm2
#define MSGTMP0 %xmm3
#define MSGTMP1 %xmm4
#define MSGTMP2 %xmm5
#define MSGTMP3 %xmm6
#define MSG0 %xmm3
#define MSG1 %xmm4
#define MSG2 %xmm5
#define MSG3 %xmm6
#define XMMTMP %xmm7
#define SAVE0 %xmm8
#define SAVE1 %xmm9
#define SHUF(a,b,c,d) $(a+(b<<2)+(c<<4)+(d<<6))
#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+0*16(%rdi), XMMTMP /* ABCD (shown least-significant-dword-first) */
movu128 80+1*16(%rdi), STATE1 /* EFGH */
/* shufps takes dwords 0,1 from *2nd* operand, and dwords 2,3 from 1st one */
/* shufps: dwords 0,1 of the result are selected from *2nd* operand, and dwords 2,3 from 1st operand */
mova128 STATE1, STATE0
/* --- -------------- ABCD -- EFGH */
shufps SHUF(1,0,1,0), XMMTMP, STATE0 /* FEBA */
@@ -65,185 +65,203 @@ sha256_process_block64_shaNI:
mova128 STATE0, SAVE0
mova128 STATE1, SAVE1
// sha256rnds2 instruction uses only lower 64 bits of MSG.
// The code below needs to move upper 64 bits to lower 64 bits
// for the second sha256rnds2 invocation
// (what remains in upper bits does not matter).
// There are several ways to do it:
// movhlps MSG, MSG // abcd -> cdcd (3 bytes of code)
// shuf128_32 SHUF(2,3,n,n), MSG, MSG // abcd -> cdXX (4 bytes)
// punpckhqdq MSG, MSG // abcd -> cdcd (4 bytes)
// unpckhpd MSG, MSG // abcd -> cdcd (4 bytes)
// psrldq $8, MSG // abcd -> cd00 (5 bytes)
// palignr $8, MSG, MSG // abcd -> cdab (6 bytes, SSSE3 insn)
#define MOVE_UPPER64_DOWN(reg) movhlps reg, reg
//#define MOVE_UPPER64_DOWN(reg) shuf128_32 SHUF(2,3,0,0), reg, reg
//#define MOVE_UPPER64_DOWN(reg) punpckhqdq reg, reg
//#define MOVE_UPPER64_DOWN(reg) unpckhpd reg, reg
//#define MOVE_UPPER64_DOWN(reg) psrldq $8, reg
//#define MOVE_UPPER64_DOWN(reg) palignr $8, reg, reg
/* Rounds 0-3 */
movu128 0*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP0
mova128 MSG, MSG0
paddd 0*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 4-7 */
movu128 1*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP1
mova128 MSG, MSG1
paddd 1*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
sha256msg1 MSG1, MSG0
/* Rounds 8-11 */
movu128 2*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
mova128 MSG, MSGTMP2
mova128 MSG, MSG2
paddd 2*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
sha256msg1 MSG2, MSG1
/* Rounds 12-15 */
movu128 3*16(DATA_PTR), MSG
pshufb XMMTMP, MSG
/* ...to here */
mova128 MSG, MSGTMP3
mova128 MSG, MSG3
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
mova128 MSG3, XMMTMP
palignr $4, MSG2, XMMTMP
paddd XMMTMP, MSG0
sha256msg2 MSG3, MSG0
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
sha256msg1 MSG3, MSG2
/* Rounds 16-19 */
mova128 MSGTMP0, MSG
mova128 MSG0, 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
mova128 MSG0, XMMTMP
palignr $4, MSG3, XMMTMP
paddd XMMTMP, MSG1
sha256msg2 MSG0, MSG1
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
sha256msg1 MSG0, MSG3
/* Rounds 20-23 */
mova128 MSGTMP1, MSG
mova128 MSG1, 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
mova128 MSG1, XMMTMP
palignr $4, MSG0, XMMTMP
paddd XMMTMP, MSG2
sha256msg2 MSG1, MSG2
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
sha256msg1 MSG1, MSG0
/* Rounds 24-27 */
mova128 MSGTMP2, MSG
mova128 MSG2, 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
mova128 MSG2, XMMTMP
palignr $4, MSG1, XMMTMP
paddd XMMTMP, MSG3
sha256msg2 MSG2, MSG3
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
sha256msg1 MSG2, MSG1
/* Rounds 28-31 */
mova128 MSGTMP3, MSG
mova128 MSG3, 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
mova128 MSG3, XMMTMP
palignr $4, MSG2, XMMTMP
paddd XMMTMP, MSG0
sha256msg2 MSG3, MSG0
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
sha256msg1 MSG3, MSG2
/* Rounds 32-35 */
mova128 MSGTMP0, MSG
mova128 MSG0, 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
mova128 MSG0, XMMTMP
palignr $4, MSG3, XMMTMP
paddd XMMTMP, MSG1
sha256msg2 MSG0, MSG1
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
sha256msg1 MSG0, MSG3
/* Rounds 36-39 */
mova128 MSGTMP1, MSG
mova128 MSG1, 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
mova128 MSG1, XMMTMP
palignr $4, MSG0, XMMTMP
paddd XMMTMP, MSG2
sha256msg2 MSG1, MSG2
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP1, MSGTMP0
sha256msg1 MSG1, MSG0
/* Rounds 40-43 */
mova128 MSGTMP2, MSG
mova128 MSG2, 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
mova128 MSG2, XMMTMP
palignr $4, MSG1, XMMTMP
paddd XMMTMP, MSG3
sha256msg2 MSG2, MSG3
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP2, MSGTMP1
sha256msg1 MSG2, MSG1
/* Rounds 44-47 */
mova128 MSGTMP3, MSG
mova128 MSG3, 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
mova128 MSG3, XMMTMP
palignr $4, MSG2, XMMTMP
paddd XMMTMP, MSG0
sha256msg2 MSG3, MSG0
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP3, MSGTMP2
sha256msg1 MSG3, MSG2
/* Rounds 48-51 */
mova128 MSGTMP0, MSG
mova128 MSG0, 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
mova128 MSG0, XMMTMP
palignr $4, MSG3, XMMTMP
paddd XMMTMP, MSG1
sha256msg2 MSG0, MSG1
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
sha256msg1 MSGTMP0, MSGTMP3
sha256msg1 MSG0, MSG3
/* Rounds 52-55 */
mova128 MSGTMP1, MSG
mova128 MSG1, 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
mova128 MSG1, XMMTMP
palignr $4, MSG0, XMMTMP
paddd XMMTMP, MSG2
sha256msg2 MSG1, MSG2
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 56-59 */
mova128 MSGTMP2, MSG
mova128 MSG2, 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
mova128 MSG2, XMMTMP
palignr $4, MSG1, XMMTMP
paddd XMMTMP, MSG3
sha256msg2 MSG2, MSG3
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Rounds 60-63 */
mova128 MSGTMP3, MSG
mova128 MSG3, MSG
paddd 15*16-8*16(SHA256CONSTANTS), MSG
sha256rnds2 MSG, STATE0, STATE1
shuf128_32 $0x0E, MSG, MSG
MOVE_UPPER64_DOWN(MSG)
sha256rnds2 MSG, STATE1, STATE0
/* Add current hash values with previously saved */
@@ -252,7 +270,7 @@ sha256_process_block64_shaNI:
/* 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 */
/* shufps: dwords 0,1 of the result are selected from *2nd* operand, and dwords 2,3 from 1st operand */
/* --- -------------- HGDC -- FEBA */
shufps SHUF(3,2,3,2), STATE1, STATE0 /* ABCD */
shufps SHUF(1,0,1,0), STATE1, XMMTMP /* EFGH */
+265
View File
@@ -0,0 +1,265 @@
/* vi: set sw=4 ts=4: */
/*
* Copyright (C) 2026 Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_TELNETD) += ioloop.o
//kbuild:lib-$(CONFIG_TELNET) += ioloop.o
#include "libbb.h"
#define DEBUG 0
#if DEBUG
# define dbg(...) bb_error_msg(__VA_ARGS__)
static char *bin_to_hex(const void *hash_value, unsigned hash_length)
{
/* xzalloc zero-terminates */
char *hex_value = xzalloc((hash_length * 2) + 1);
bin2hex(hex_value, (char*)hash_value, hash_length);
return auto_string(hex_value);
}
#else
# define dbg(...) ((void)0)
#endif
void FAST_FUNC ioloop_insert_conn(ioloop_state_t *io, connection_t *conn)
{
conn->io = io;
conn->next = io->conns;
io->conns = conn;
}
void FAST_FUNC ioloop_remove_conn(ioloop_state_t *io, connection_t *conn)
{
connection_t **pp = &io->conns;
while (*pp) {
if (*pp == conn) {
*pp = conn->next;
return;
}
pp = &(*pp)->next;
}
}
void FAST_FUNC conn_close_fds(connection_t *conn)
{
if (conn->read_fd >= 0)
close(conn->read_fd);
if (conn->write_fd >= 0 && conn->write_fd != conn->read_fd)
close(conn->write_fd);
conn->write_fd = -1;
conn->read_fd = -1;
}
void FAST_FUNC conn_close_fds_remove_and_free(connection_t *conn)
{
conn_close_fds(conn);
ioloop_remove_conn(conn->io, conn);
free_connection(conn);
}
#ifdef UNUSED
void FAST_FUNC ioloop_close_fd_in_all_conns(ioloop_state_t *io, int fd)
{
connection_t *conn;
close(fd);
conn = io->conns;
while (conn) {
if (conn->read_fd == fd)
conn->read_fd = -1;
if (conn->write_fd == fd)
conn->write_fd = -1;
conn = conn->next;
}
}
#endif
// should_poll_write_fd() - Should ioloop poll write_fd for writability?
// May return error if knows that write side is closed, even if it has free buffer space.
// > 0: Yes, poll write_fd (has data to write, or can generate such data)
// In this case, write_fd must be valid! (it's a bug if it is < 0, can crash)
// 0: No, don't poll write_fd currently
// < 0: error, I probably freed myself (do not use my structure in this iteration,
// on next iteration, if I indeed freed myself, you won't find me in the list).
//
// should_poll_read_fd() - Should ioloop poll read_fd for readability?
// May return error if knows that write side is closed, even if it has free buffer space.
// > 0: Yes, poll read_fd (has buffer space, healthy)
// In this case, read_fd must be valid! (it's a bug if it is < 0)
// 0: No, don't poll read_fd. One of:
// Buffer is full (hopefully write() will free some)
// Got error/EOF, want to drain write buffer first
// < 0: Error/EOF, I probably freed myself (do not use my structure)
//
// Essentially: add your "this connection is dead, close+ioloop_remove_conn(this)+free(this)" code
// to either of the above two functions.
// Either would work equally well from ioloop POV.
//
// write() - Perform write
// Even if poll shows that write_fd become ready, the method will not be called if conn->write_fd become < 0.
// However, changing it to another fd >= 0 is a bug.
// >= 0: No error (ioloop() does not handle 0 specially)
// < 0: Error occurred, I probably freed myself (do not use my structure)
//
// Error returns from read() and write() will skip the opposite op.
// (Which one happens first depends on ioloop_run() code, as I write this, write()
// is done first - therefore read() can't skip write()).
// IOW: if you "remove(this)" in either of them you MUST return < 0.
//
// Write function, if it performs some processing, needs to account for the possibility
// that any "incomplete data, can't write, wait for more" logic should also check whether
// "more" is even possible: your other code may know that the read side is at EOF,
// and arrange for it to not be polled. Thus a hang: read not reading, write waits for more date.
//
// read() - Perform read
// Will not be called if read_fd become < 0.
// >= 0: No error (0 is EOF, ioloop() does not handle 0 specially)
// < 0: Error occurred, I probably freed myself (do not use my structure)
//
// Putting "this connection is dead, close+remove+free" code into read function
// is often inconvenient: if you got EOF/error on read, you still want to poll write side
// and try to write out the buffered data to it. Which means read() can't "remove+free".
// Instead, you can remember EOF/error and make future should_poll_read_fd() respond 0.
// One way is to close (if possible) read_fd, set it to -1 and use as a flag.
//
// If need to support one-sided close, such as when HTTP/1.x client sends us
// "GET / HTTP/1.1\r\n\r\n" and closes its writing side with shutdown(SHUT_WR),
// the idiom is that when read() sees EOF, it sets conn->read_fd to -1
// and subsequently should_poll_read_fd() always return 0 (no more attempts to read);
// write() flushes all remaining data to conn->write_fd and then signals EOF
// to write_fd: shutdown(SHUT_WR) for sockets, close() for pipes
// (how to do this for ptys!?).
// After this, should_poll_write_fd() can return 0 if fd has to stay open (socket)
// or can return -1 and free itself if fd is closed.
static ALWAYS_INLINE int should_poll_write_fd(connection_t *conn)
{
return conn->should_poll_write_fd(conn);
}
static ALWAYS_INLINE int should_poll_read_fd(connection_t *conn)
{
return conn->should_poll_read_fd(conn);
}
static ALWAYS_INLINE int write_from_buf(connection_t *conn)
{
return conn->write(conn);
}
static ALWAYS_INLINE int read_to_buf(connection_t *conn)
{
return conn->read(conn);
}
int FAST_FUNC ioloop_run(ioloop_state_t *io)
{
connection_t *conn;
unsigned poll_timeout_us;
int maxfd;
int count;
struct timeval tv;
struct timeval *tv_ptr;
fd_set rdfdset, wrfdset;
io->current_iteration_timeout = io->max_timeout ? io->max_timeout : UINT_MAX;
//bb_error_msg("io->current_iteration_timeout:%d", io->current_iteration_timeout);
again:
FD_ZERO(&rdfdset);
FD_ZERO(&wrfdset);
conn = io->conns;
if (!conn)
return IOLOOP_NO_CONNS;
maxfd = -1;
while (conn) {
connection_t *next;
int rcw, rcr;
next = conn->next; /* in case conn is freed */
rcw = should_poll_write_fd(conn);
if (rcw < 0) {
/* often indicates that conn is gone (freed), do not use it anymore */
goto next;
}
/* Do not add conn->write_fd to waiting set yet,
* the *reader* may decide to abort (return rcr < 0)!
* Check it first:
*/
rcr = should_poll_read_fd(conn);
if (rcr < 0)
goto next;
if (rcw > 0) {
FD_SET(conn->write_fd, &wrfdset);
//FIXME: what if fd > 1023
if (conn->write_fd > maxfd)
maxfd = conn->write_fd;
}
if (rcr > 0) {
FD_SET(conn->read_fd, &rdfdset);
if (conn->read_fd > maxfd)
maxfd = conn->read_fd;
}
next:
conn = next;
}
if (!io->conns)
return IOLOOP_NO_CONNS; /* all conns removed themselves before we reached polling */
poll_timeout_us = io->current_iteration_timeout;
/* May be useful to know after loop exit: */
io->last_timeout = poll_timeout_us;
dbg("poll_timeout_us:%d", poll_timeout_us);
tv_ptr = NULL; /* infinite timeout */
if (poll_timeout_us != UINT_MAX) {
tv.tv_sec = poll_timeout_us / 1000000;
tv.tv_usec = poll_timeout_us % 1000000;
tv_ptr = &tv;
}
maxfd++;
count = select(maxfd, maxfd ? &rdfdset : NULL, maxfd ? &wrfdset : NULL, NULL, tv_ptr);
dbg("select:%d", count);
/* Any function in the loop can change it, modifying next select() timeout */
io->current_iteration_timeout = io->max_timeout ? io->max_timeout : UINT_MAX;
dbg("io->current_iteration_timeout:%d", io->current_iteration_timeout);
if (count <= 0) {
/* 0: timeout */
if (count == 0 && (io->flags & IOLOOP_FLAG_EXIT_IF_TIMEOUT))
return IOLOOP_TIMEOUT;
/* < 0: EINTR or ENOMEM */
if (count < 0 && (io->flags & IOLOOP_FLAG_EXIT_IF_EINTR) && errno == EINTR)
return IOLOOP_EINTR;
goto again;
}
conn = io->conns;
while (conn) {
connection_t *next = conn->next; /* in case conn freed */
int rcw;
/* We do check for valid fd >=0: this means that conns
* may prevent I/O of other conns by setting fds to -1.
*/
dbg("conn->write_fd:%d ?", conn->write_fd);
if (conn->write_fd >= 0 && FD_ISSET(conn->write_fd, &wrfdset)) {
dbg("conn->write_fd:%d ready", conn->write_fd);
rcw = write_from_buf(conn);
if (rcw < 0) {
/* often indicates that conn is gone (freed), do not use it anymore */
goto next1;
}
}
dbg("conn->read_fd:%d ?", conn->read_fd);
if (conn->read_fd >= 0 && FD_ISSET(conn->read_fd, &rdfdset)) {
dbg("conn->read_fd:%d ready", conn->read_fd);
read_to_buf(conn);
}
next1:
conn = next;
}
goto again;
}
+55 -3
View File
@@ -9,15 +9,42 @@
#ifndef ISQRT_TEST
# include "libbb.h"
#else
/* gcc -DISQRT_TEST -Wall -O2 isqrt.c -oisqrt && ./isqrt $((RANDOM*RANDOM)) */
// gcc -DISQRT_TEST -Wall -Os -ffunction-sections isqrt.c -S -fverbose-asm
// gcc -DISQRT_TEST -Wall -Os -ffunction-sections isqrt.c -c
// gcc -DISQRT_TEST -Wall -Os -ffunction-sections isqrt.c -oisqrt && ./isqrt $((RANDOM*RANDOM))
# include <stdlib.h>
# include <stdio.h>
# include <time.h>
# include <limits.h>
# define FAST_FUNC /* nothing */
#endif
/* Returns such x that x+1 > sqrt(N) */
unsigned long FAST_FUNC isqrt(unsigned long long N)
/* Stolen from kernel code */
unsigned FAST_FUNC isqrt(unsigned long x)
{
unsigned long y = 0;
unsigned long m = 1UL << (8*sizeof(x) - 2);
// ^^^^^ should be m = 1UL << ((fls(x) - 1) & ~1UL);
// but calculating fls() would take time and code
do {
unsigned long b = y + m;
y >>= 1;
if (x >= b) {
x -= b;
y += m;
}
m >>= 2;
} while (m);
return y;
}
#if LLONG_MAX > LONG_MAX
# if defined(i386)
/* Smaller code on this register-starved arch */
unsigned long FAST_FUNC isqrt_ull(unsigned long long N)
{
unsigned long x;
unsigned shift;
@@ -33,15 +60,40 @@ unsigned long FAST_FUNC isqrt(unsigned long long N)
} while ((int)shift >= 0);
return x;
}
# else
/* Stolen from kernel code */
unsigned long FAST_FUNC isqrt_ull(unsigned long long x)
{
unsigned long long y = 0;
unsigned long long m = 1ULL << (8*sizeof(x) - 2);
// ^^^^^ should be m = 1ULL << ((fls(x) - 1) & ~1ULL);
// but calculating fls() would take time and code
do {
unsigned long long b = y + m;
y >>= 1;
if (x >= b) {
x -= b;
y += m;
}
m >>= 2;
} while (m);
return y;
}
# endif
#endif /* wide version needed */
#ifdef ISQRT_TEST
# if LLONG_MAX == LONG_MAX
# define isqrt_ull(N) isqrt(N)
# endif
int main(int argc, char **argv)
{
unsigned long long n = argv[1] ? strtoull(argv[1], NULL, 0) : time(NULL);
for (;;) {
unsigned long h;
n--;
h = isqrt(n);
h = isqrt_ull(n);
if (!(n & 0xffff))
printf("isqrt(%llx)=%lx\n", n, h);
if ((unsigned long long)h * h > n) {
+65 -53
View File
@@ -451,7 +451,7 @@ static void put_cur_glyph_and_inc_cursor(void)
* have automargin (IOW: it is moving cursor to next line
* by itself (which is wrong for VT-10x terminals)),
* this will break things: there will be one extra empty line */
puts("\r"); /* + implicit '\n' */
fputs("\r\n", stderr);
#else
/* VT-10x terminals don't wrap cursor to next line when last char
* on the line is printed - cursor stays "over" this char.
@@ -1170,9 +1170,10 @@ static void showfiles(void)
);
}
if (ENABLE_UNICODE_SUPPORT)
puts(printable_string(matches[n]));
fputs(printable_string(matches[n]), stderr);
else
puts(matches[n]);
fputs(matches[n], stderr);
bb_putchar_stderr('\n');
}
}
@@ -1405,8 +1406,8 @@ unsigned FAST_FUNC size_from_HISTFILESIZE(const char *hp)
int size = MAX_HISTORY;
if (hp) {
size = atoi(hp);
if (size <= 0)
return 1;
if (size < 0)
return 0;
if (size > MAX_HISTORY)
return MAX_HISTORY;
}
@@ -1463,7 +1464,7 @@ void FAST_FUNC show_history(const line_input_t *st)
if (!st)
return;
for (i = 0; i < st->cnt_history; i++)
fprintf(stderr, "%4d %s\n", i, st->history[i]);
printf("%4d %s\n", i, st->history[i]);
}
# if ENABLE_FEATURE_EDITING_SAVEHISTORY
@@ -1500,18 +1501,21 @@ static void load_history(line_input_t *st_parm)
/* NB: do not trash old history if file can't be opened */
fp = fopen_for_read(st_parm->hist_file);
if (fp) {
/* clean up old history */
for (idx = st_parm->cnt_history; idx > 0;) {
idx--;
free(st_parm->history[idx]);
st_parm->history[idx] = NULL;
}
if (!fp)
return;
/* fill temp_h[], retaining only last MAX_HISTORY lines */
memset(temp_h, 0, sizeof(temp_h));
idx = 0;
st_parm->cnt_history_in_file = 0;
/* clean up old history */
for (idx = st_parm->cnt_history; idx > 0;) {
idx--;
free(st_parm->history[idx]);
st_parm->history[idx] = NULL;
}
/* fill temp_h[], retaining only last max_history lines */
memset(temp_h, 0, sizeof(temp_h));
idx = 0;
st_parm->cnt_history_in_file = 0;
if (st_parm->max_history != 0) {
while ((line = xmalloc_fgetline(fp)) != NULL) {
if (line[0] == '\0') {
free(line);
@@ -1524,52 +1528,62 @@ static void load_history(line_input_t *st_parm)
if (idx == st_parm->max_history)
idx = 0;
}
fclose(fp);
}
fclose(fp);
/* find first non-NULL temp_h[], if any */
if (st_parm->cnt_history_in_file) {
while (temp_h[idx] == NULL) {
idx++;
if (idx == st_parm->max_history)
idx = 0;
}
}
/* copy temp_h[] to st_parm->history[] */
for (i = 0; i < st_parm->max_history;) {
line = temp_h[idx];
if (!line)
break;
/* find first non-NULL temp_h[], if any */
if (st_parm->cnt_history_in_file != 0) {
while (temp_h[idx] == NULL) {
idx++;
if (idx == st_parm->max_history)
idx = 0;
line_len = strlen(line);
if (line_len >= MAX_LINELEN)
line[MAX_LINELEN-1] = '\0';
st_parm->history[i++] = line;
}
st_parm->cnt_history = i;
if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
st_parm->cnt_history_in_file = i;
}
/* copy temp_h[] to st_parm->history[] */
for (i = 0; i < st_parm->max_history;) {
line = temp_h[idx];
if (!line)
break;
idx++;
if (idx == st_parm->max_history)
idx = 0;
line_len = strlen(line);
if (line_len >= MAX_LINELEN)
line[MAX_LINELEN-1] = '\0';
st_parm->history[i++] = line;
}
st_parm->cnt_history = i;
if (ENABLE_FEATURE_EDITING_SAVE_ON_EXIT)
st_parm->cnt_history_in_file = i;
}
# if ENABLE_FEATURE_EDITING_SAVE_ON_EXIT
void save_history(line_input_t *st)
void FAST_FUNC save_history(line_input_t *st)
{
FILE *fp;
if (!st || !st->hist_file)
/* bash compat: HISTFILE="" disables history saving */
if (!st || !st->hist_file || !st->hist_file[0])
return;
if (st->cnt_history <= st->cnt_history_in_file)
return;
return; /* no new entries were added */
/* note: if st->max_history is 0, we do not abort: we truncate the history to 0 lines */
fp = fopen(st->hist_file, "a");
fp = fopen(st->hist_file, (st->max_history == 0 ? "w" : "a"));
if (fp) {
int i, fd;
char *new_name;
line_input_t *st_temp;
/* max_history==0 needs special-casing in general code,
* just handle it in a simpler way: */
if (st->max_history == 0) {
/* fopen("w") already truncated it */
fclose(fp);
return;
}
for (i = st->cnt_history_in_file; i < st->cnt_history; i++)
fprintf(fp, "%s\n", st->history[i]);
fclose(fp);
@@ -1579,6 +1593,8 @@ void save_history(line_input_t *st)
st_temp = new_line_input_t(st->flags);
st_temp->hist_file = st->hist_file;
st_temp->max_history = st->max_history;
/* load no more than max_history last lines */
/* (in unlikely case that file disappeared, st_temp gets empty history) */
load_history(st_temp);
/* write out temp file and replace hist_file atomically */
@@ -1602,13 +1618,13 @@ static void save_history(char *str)
int fd;
int len, len2;
if (!state->hist_file)
/* bash compat: HISTFILE="" disables history saving */
if (!state->hist_file || !state->hist_file[0])
return;
fd = open(state->hist_file, O_WRONLY | O_CREAT | O_APPEND, 0600);
if (fd < 0)
return;
xlseek(fd, 0, SEEK_END); /* paranoia */
len = strlen(str);
str[len] = '\n'; /* we (try to) do atomic write */
len2 = full_write(fd, str, len + 1);
@@ -1663,13 +1679,10 @@ static void remember_in_history(char *str)
if (str[0] == '\0')
return;
i = state->cnt_history;
/* Don't save dupes */
if (i && strcmp(state->history[i-1], str) == 0)
/* Don't save dups */
if (i != 0 && strcmp(state->history[i-1], str) == 0)
return;
free(state->history[state->max_history]); /* redundant, paranoia */
state->history[state->max_history] = NULL; /* redundant, paranoia */
/* If history[] is full, remove the oldest command */
/* we need to keep history[state->max_history] empty, hence >=, not > */
if (i >= state->max_history) {
@@ -1682,7 +1695,7 @@ static void remember_in_history(char *str)
state->cnt_history_in_file--;
# endif
}
/* i <= state->max_history-1 */
/* i < state->max_history */
state->history[i++] = xstrdup(str);
/* i <= state->max_history */
state->cur_history = i;
@@ -2066,7 +2079,7 @@ static void parse_and_put_prompt(const char *prmt_ptr)
if (c == 'w')
break;
cp = strrchr(pbuf, '/');
if (cp)
if (cp && cp[1])
pbuf = (char*)cp + 1;
break;
// bb_process_escape_sequence does this now:
@@ -2194,7 +2207,6 @@ static int lineedit_read_key(char *read_key_buffer, int timeout)
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);
-2
View File
@@ -28,8 +28,6 @@ void FAST_FUNC print_login_issue(const char *issue_file, const char *tty)
time(&t);
uname(&uts);
puts("\r"); /* start a new line */
fp = fopen_for_read(issue_file);
if (!fp)
return;
+1 -1
View File
@@ -158,7 +158,7 @@ static int set_loopdev_params(int lfd,
if (rc == 0)
return rc; /* SUCCESS! */
# if ENABLE_TRY_LOOP_CONFIGURE
if (errno != EINVAL)
if (errno != EINVAL && errno != ENOTTY)
return rc; /* error other than old kernel */
/* Old kernel, fall through into old way to do it: */
# endif
+48
View File
@@ -0,0 +1,48 @@
/* vi: set sw=4 ts=4: */
/*
* Utility routines.
*
* Copyright (C) 2025 Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-y += poll_with_signals.o
#include "libbb.h"
/* Shells, for example, need their line input and "read" builtin
* to be interruptible, and the naive handling of it a-la:
* if (bb_got_signal) {
* errno = EINTR;
* return -1;
* }
* poll(pfd, 1, -1); // signal here would set EINTR
* is racy.
* This is a bit heavy-handed, but safe wrt races:
*/
int FAST_FUNC check_got_signal_and_poll(struct pollfd pfd[1], int timeout)
{
int n;
struct timespec tv;
sigset_t orig_mask;
if (bb_got_signal) /* optimization */
goto eintr;
if (timeout >= 0) {
tv.tv_sec = timeout / 1000;
tv.tv_nsec = (timeout % 1000) * 1000000;
}
/* test bb_got_signal, then poll(), atomically wrt signals */
sigfillset(&orig_mask);
sigprocmask2(SIG_BLOCK, &orig_mask);
if (bb_got_signal) {
sigprocmask2(SIG_SETMASK, &orig_mask);
eintr:
errno = EINTR; /* inform the caller that we got a signal */
return -1;
}
n = ppoll(pfd, 1, timeout >= 0 ? &tv : NULL, &orig_mask);
sigprocmask2(SIG_SETMASK, &orig_mask);
return n;
}
+91 -92
View File
@@ -109,7 +109,7 @@ void FAST_FUNC free_procps_scan(procps_status_t* sp)
}
#if ENABLE_FEATURE_TOPMEM || ENABLE_PMAP
static unsigned long long fast_strtoull_16(char **endptr)
unsigned long long FAST_FUNC fast_strtoull_16(char **endptr)
{
unsigned char c;
char *str = *endptr;
@@ -130,7 +130,7 @@ static unsigned long long fast_strtoull_16(char **endptr)
#if ENABLE_FEATURE_FAST_TOP || ENABLE_FEATURE_TOPMEM || ENABLE_PMAP
/* We cut a lot of corners here for speed */
static unsigned long fast_strtoul_10(char **endptr)
unsigned long FAST_FUNC fast_strtoul_10(char **endptr)
{
unsigned char c;
char *str = *endptr;
@@ -143,6 +143,24 @@ static unsigned long fast_strtoul_10(char **endptr)
*endptr = str + 1; /* We skip trailing space! */
return n;
}
# if LONG_MAX < LLONG_MAX
/* For VSZ, which can be very large */
static unsigned long long fast_strtoull_10(char **endptr)
{
unsigned char c;
char *str = *endptr;
unsigned long long n = *str - '0';
/* Need to stop on both ' ' and '\n' */
while ((c = *++str) > ' ')
n = n*10 + (c - '0');
*endptr = str + 1; /* We skip trailing space! */
return n;
}
# else
# define fast_strtoull_10(endptr) fast_strtoul_10(endptr)
# endif
# if ENABLE_FEATURE_FAST_TOP
static long fast_strtol_10(char **endptr)
@@ -155,7 +173,7 @@ static long fast_strtol_10(char **endptr)
}
# endif
static char *skip_fields(char *str, int count)
char* FAST_FUNC skip_fields(char *str, int count)
{
do {
while (*str++ != ' ')
@@ -166,35 +184,25 @@ static char *skip_fields(char *str, int count)
}
#endif
#if ENABLE_FEATURE_TOPMEM || ENABLE_PMAP
static char* skip_whitespace_if_prefixed_with(char *buf, const char *prefix)
#if ENABLE_FEATURE_TOPMEM
static NOINLINE void procps_read_smaps(pid_t pid, procps_status_t *sp)
{
char *tp = is_prefixed_with(buf, prefix);
if (tp) {
tp = skip_whitespace(tp);
}
return tp;
}
// There is A LOT of /proc/PID/smaps data on a big system.
// Optimize this for speed, makes "top -m" faster.
//TODO large speedup:
//read /proc/PID/smaps_rollup (cumulative stats of all mappings, much faster)
//and /proc/PID/maps to get mapped_ro and mapped_rw (IOW: VSZ,VSZRW)
int FAST_FUNC procps_read_smaps(pid_t pid, struct smaprec *total,
void (*cb)(struct smaprec *, void *), void *data)
{
FILE *file;
struct smaprec currec;
char filename[sizeof("/proc/%u/smaps") + sizeof(int)*3];
char buf[PROCPS_BUFSIZE];
#if !ENABLE_PMAP
void (*cb)(struct smaprec *, void *) = NULL;
void *data = NULL;
#endif
char buf[PROCPS_BUFSIZE] ALIGN4;
sprintf(filename, "/proc/%u/smaps", (int)pid);
file = fopen_for_read(filename);
if (!file)
return 1;
return;
memset(&currec, 0, sizeof(currec));
while (fgets(buf, PROCPS_BUFSIZE, file)) {
// Each mapping datum has this form:
// f7d29000-f7d39000 rw-s FILEOFS M:m INODE FILENAME
@@ -202,80 +210,60 @@ int FAST_FUNC procps_read_smaps(pid_t pid, struct smaprec *total,
// Rss: nnn kB
// .....
char *tp, *p;
char *tp;
#define bytes4 *(uint32_t*)buf
#define Priv PACK32_BYTES('P','r','i','v')
#define Shar PACK32_BYTES('S','h','a','r')
#define SCAN(S, X) \
if ((tp = skip_whitespace_if_prefixed_with(buf, S)) != NULL) { \
total->X += currec.X = fast_strtoul_10(&tp); \
continue; \
if (memcmp(buf+4, S, sizeof(S)-1) == 0) { \
tp = skip_whitespace(buf+4 + sizeof(S)-1); \
sp->X += fast_strtoul_10(&tp); \
continue; \
}
if (bytes4 == Priv) {
SCAN("ate_Dirty:", private_dirty)
SCAN("ate_Clean:", private_clean)
}
if (cb) {
SCAN("Pss:" , smap_pss );
SCAN("Swap:" , smap_swap );
if (bytes4 == Shar) {
SCAN("ed_Dirty:" , shared_dirty )
SCAN("ed_Clean:" , shared_clean )
}
SCAN("Private_Dirty:", private_dirty);
SCAN("Private_Clean:", private_clean);
SCAN("Shared_Dirty:" , shared_dirty );
SCAN("Shared_Clean:" , shared_clean );
#undef bytes4
#undef Priv
#undef Shar
#undef SCAN
tp = strchr(buf, '-');
if (tp) {
// We reached next mapping - the line of this form:
// f7d29000-f7d39000 rw-s FILEOFS M:m INODE FILENAME
if (cb) {
/* If we have a previous record, there's nothing more
* for it, call the callback and clear currec
*/
if (currec.smap_size)
cb(&currec, data);
free(currec.smap_name);
}
memset(&currec, 0, sizeof(currec));
char *rwx;
unsigned long long sz;
*tp = ' ';
tp = buf;
currec.smap_start = fast_strtoull_16(&tp);
currec.smap_size = (fast_strtoull_16(&tp) - currec.smap_start) >> 10;
strncpy(currec.smap_mode, tp, sizeof(currec.smap_mode)-1);
sz = fast_strtoull_16(&tp); // start
sz = (fast_strtoull_16(&tp) - sz) >> 10; // end - start
// tp -> "rw-s" string
rwx = tp;
// skipping "rw-s FILEOFS M:m INODE "
tp = skip_whitespace(skip_fields(tp, 4));
// filter out /dev/something (something != zero)
if (!is_prefixed_with(tp, "/dev/") || strcmp(tp, "/dev/zero\n") == 0) {
if (currec.smap_mode[1] == 'w') {
currec.mapped_rw = currec.smap_size;
total->mapped_rw += currec.smap_size;
} else if (currec.smap_mode[1] == '-') {
currec.mapped_ro = currec.smap_size;
total->mapped_ro += currec.smap_size;
}
// if not a device memory mapped...
if (memcmp(tp, "/dev/", 5) != 0 // not "/dev/something"
|| strcmp(tp + 5, "zero\n") == 0 // or is "/dev/zero" (which isn't a device)
) {
if (rwx[1] == 'w')
sp->mapped_rw += sz;
else if (rwx[0] == 'r' || rwx[2] == 'x')
sp->mapped_ro += sz;
// else: seen "---p" mappings (mmap guard gaps?),
// do NOT account these as VSZ, they aren't really
}
if (strcmp(tp, "[stack]\n") == 0)
total->stack += currec.smap_size;
if (cb) {
p = skip_non_whitespace(tp);
if (p == tp) {
currec.smap_name = xstrdup(" [ anon ]");
} else {
*p = '\0';
currec.smap_name = xstrdup(tp);
}
}
total->smap_size += currec.smap_size;
sp->stack += sz;
}
}
fclose(file);
if (cb) {
if (currec.smap_size)
cb(&currec, data);
free(currec.smap_name);
}
return 0;
}
#endif
@@ -370,7 +358,8 @@ procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
char *cp, *comm1;
int tty;
#if !ENABLE_FEATURE_FAST_TOP
unsigned long vsz, rss;
unsigned long long vsz;
unsigned long rss;
#endif
/* see proc(5) for some details on this */
strcpy(filename_tail, "stat");
@@ -396,7 +385,7 @@ procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
"%ld " /* nice */
"%*s %*s " /* timeout, it_real_value */
"%lu " /* start_time */
"%lu " /* vsize */
"%llu " /* vsize - can be very large */
"%lu " /* rss */
# if ENABLE_FEATURE_TOP_SMP_PROCESS
"%*s %*s %*s %*s %*s %*s " /*rss_rlim, start_code, end_code, start_stack, kstk_esp, kstk_eip */
@@ -449,7 +438,7 @@ procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
cp = skip_fields(cp, 2); /* timeout, it_real_value */
sp->start_time = fast_strtoul_10(&cp);
/* vsz is in bytes and we want kb */
sp->vsz = fast_strtoul_10(&cp) >> 10;
sp->vsz = fast_strtoull_10(&cp) >> 10;
/* vsz is in bytes but rss is in *PAGES*! Can you believe that? */
sp->rss = fast_strtoul_10(&cp) << sp->shift_pages_to_kb;
# if ENABLE_FEATURE_TOP_SMP_PROCESS
@@ -483,7 +472,7 @@ procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
#if ENABLE_FEATURE_TOPMEM
if (flags & PSSCAN_SMAPS)
procps_read_smaps(pid, &sp->smaps, NULL, NULL);
procps_read_smaps(pid, sp);
#endif /* TOPMEM */
#if ENABLE_FEATURE_PS_ADDITIONAL_COLUMNS
if (flags & PSSCAN_RUIDGID) {
@@ -566,36 +555,45 @@ procps_status_t* FAST_FUNC procps_scan(procps_status_t* sp, int flags)
return sp;
}
void FAST_FUNC read_cmdline(char *buf, int col, unsigned pid, const char *comm)
int FAST_FUNC read_cmdline(char *buf, int col, unsigned pid, const char *comm)
{
int sz;
char filename[sizeof("/proc/%u/cmdline") + sizeof(int)*3];
sprintf(filename, "/proc/%u/cmdline", pid);
sz = open_read_close(filename, buf, col - 1);
if (sz < 0)
return sz;
if (sz > 0) {
const char *base;
const char *program_basename;
int comm_len;
buf[sz] = '\0';
while (--sz >= 0 && buf[sz] == '\0')
continue;
/* Prevent basename("process foo/bar") = "bar" */
strchrnul(buf, ' ')[0] = '\0';
base = bb_basename(buf); /* before we replace argv0's NUL with space */
/* Find "program" in "[-][/PATH/TO/]program" */
strchrnul(buf, ' ')[0] = '\0'; /* prevent basename("program foo/bar") = "bar" */
program_basename = bb_basename(buf[0] == '-' ? buf + 1 : buf);
/* ^^^ note: must do it *before* replacing argv0's NUL with space */
/* Prevent stuff like this:
* echo 'sleep 999; exit' >`printf '\ec'`; sh ?c
* messing up top and ps output (or worse).
* This also replaces NULs with spaces, converting
* list of NUL-strings into one string.
*/
while (sz >= 0) {
if ((unsigned char)(buf[sz]) < ' ')
buf[sz] = ' ';
buf[sz] = (buf[sz] ? /*ctrl*/'?' : /*NUL*/' ');
sz--;
}
if (base[0] == '-') /* "-sh" (login shell)? */
base++;
/* If comm differs from argv0, prepend "{comm} ".
* It allows to see thread names set by prctl(PR_SET_NAME).
*/
if (!comm)
return;
return 0;
comm_len = strlen(comm);
/* Why compare up to comm_len, not COMM_LEN-1?
* Well, some processes rewrite argv, and use _spaces_ there
@@ -603,19 +601,20 @@ void FAST_FUNC read_cmdline(char *buf, int col, unsigned pid, const char *comm)
* I prefer to still treat argv0 "process foo bar"
* as 'equal' to comm "process".
*/
if (strncmp(base, comm, comm_len) != 0) {
if (strncmp(program_basename, comm, comm_len) != 0) {
comm_len += 3;
if (col > comm_len)
memmove(buf + comm_len, buf, col - comm_len);
snprintf(buf, col, "{%s}", comm);
if (col <= comm_len)
return;
return 0;
buf[comm_len - 1] = ' ';
buf[col - 1] = '\0';
}
} else {
snprintf(buf, col, "[%s]", comm ? comm : "?");
}
return 0;
}
/* from kernel:
+91
View File
@@ -0,0 +1,91 @@
/* vi: set sw=4 ts=4: */
/*
* Utility routines.
*
* Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
/* Returns >=64 for invalid chars */
int FAST_FUNC a2i64(char c)
{
unsigned char ch = c;
if (ch >= 'a')
/* "a..z" to 38..63 */
/* anything after "z": positive int >= 64 */
return (ch - 'a' + 38);
if (ch > 'Z')
/* after "Z" but before "a": positive byte >= 64 */
return ch;
if (ch >= 'A')
/* "A..Z" to 12..37 */
return (ch - 'A' + 12);
if (ch > '9')
return 64;
/* "./0123456789" to 0,1,2..11 */
/* anything before "." becomes positive byte >= 64 */
return (unsigned char)(ch - '.');
}
/* 0..63 ->
* "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
*/
int FAST_FUNC i2a64(int i)
{
i &= 0x3f;
i += '.';
/* the above maps 0..11 to "./0123456789":
* ACSII codes of "./" are ('0'-2) and ('0'-1) */
if (i > '9')
i += ('A' - '9' - 1);
if (i > 'Z')
i += ('a' - 'Z' - 1);
return i;
}
char* FAST_FUNC
num2str64_lsb_first(char *s, unsigned v, int n)
{
while (--n >= 0) {
*s++ = i2a64(v);
v >>= 6;
}
return s;
}
static void
num2str64_4chars_msb_first(char *s, unsigned v)
{
*s++ = i2a64(v >> 18); /* bits 23..18 */
*s++ = i2a64(v >> 12); /* bits 17..12 */
*s++ = i2a64(v >> 6); /* bits 11..6 */
*s = i2a64(v); /* bits 5..0 */
}
int FAST_FUNC crypt_make_rand64encoded(char *p, int cnt /*, int x */)
{
/* was: x += ... */
unsigned x = getpid() + monotonic_us();
do {
/* x = (x*1664525 + 1013904223) % 2^32 generator is lame
* (low-order bit is not "random", etc...),
* but for our purposes it is good enough */
x = x*1664525 + 1013904223;
/* BTW, Park and Miller's "minimal standard generator" is
* x = x*16807 % ((2^31)-1)
* It has no problem with visibly alternating lowest bit
* but is also weak in cryptographic sense + needs div,
* which needs more code (and slower) on many CPUs */
*p++ = i2a64(x >> 16);
*p++ = i2a64(x >> 22);
} while (--cnt);
*p = '\0';
return x;
}
+58 -55
View File
@@ -13,48 +13,11 @@
#endif
#include "libbb.h"
/* static const uint8_t ascii64[] ALIGN1 =
* "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
*/
static int i64c(int i)
{
i &= 0x3f;
if (i == 0)
return '.';
if (i == 1)
return '/';
if (i < 12)
return ('0' - 2 + i);
if (i < 38)
return ('A' - 12 + i);
return ('a' - 38 + i);
}
int FAST_FUNC crypt_make_salt(char *p, int cnt /*, int x */)
{
/* was: x += ... */
unsigned x = getpid() + monotonic_us();
do {
/* x = (x*1664525 + 1013904223) % 2^32 generator is lame
* (low-order bit is not "random", etc...),
* but for our purposes it is good enough */
x = x*1664525 + 1013904223;
/* BTW, Park and Miller's "minimal standard generator" is
* x = x*16807 % ((2^31)-1)
* It has no problem with visibly alternating lowest bit
* but is also weak in cryptographic sense + needs div,
* which needs more code (and slower) on many CPUs */
*p++ = i64c(x >> 16);
*p++ = i64c(x >> 22);
} while (--cnt);
*p = '\0';
return x;
}
#include "pw_ascii64.c"
char* FAST_FUNC crypt_make_pw_salt(char salt[MAX_PW_SALT_LEN], const char *algo)
{
int len = 2/2;
int len = 2 / 2;
char *salt_ptr = salt;
/* Standard chpasswd uses uppercase algos ("MD5", not "md5").
@@ -67,28 +30,61 @@ char* FAST_FUNC crypt_make_pw_salt(char salt[MAX_PW_SALT_LEN], const char *algo)
*salt_ptr++ = '$';
#if !ENABLE_USE_BB_CRYPT || ENABLE_USE_BB_CRYPT_SHA
if ((algo[0]|0x20) == 's') { /* sha */
salt[1] = '5' + (strcasecmp(algo, "sha512") == 0);
len = 16/2;
salt[1] = '5' + (strncasecmp(algo, "sha512", 6) == 0);
len = 16 / 2;
}
#endif
#if !ENABLE_USE_BB_CRYPT || ENABLE_USE_BB_CRYPT_YES
if ((algo[0]|0x20) == 'y') { /* yescrypt */
int rnd;
salt[1] = 'y';
// The "j9T$" below is the default "yescrypt parameters" encoded by yescrypt_encode_params_r():
//shadow-4.17.4/src/passwd.c
// salt = crypt_make_salt(NULL, NULL);
//shadow-4.17.4/lib/salt.c
//const char *crypt_make_salt(const char *meth, void *arg)
// if (streq(method, "YESCRYPT")) {
// MAGNUM(result, 'y');
// salt_len = YESCRYPT_SALT_SIZE; // 24
// rounds = YESCRYPT_get_salt_cost(arg); // always Y_COST_DEFAULT == 5 for NULL arg
// YESCRYPT_salt_cost_to_buf(result, rounds); // always "j9T$"
// char *retval = crypt_gensalt(result, rounds, NULL, 0);
//libxcrypt-4.4.38/lib/crypt-yescrypt.c
//void gensalt_yescrypt_rn (unsigned long count,
// const uint8_t *rbytes, size_t nrbytes,
// uint8_t *output, size_t o_size)
// yescrypt_params_t params = {
// .flags = YESCRYPT_DEFAULTS,
// .p = 1,
// };
// if (count < 3) ... else
// params.r = 32; // N in 4KiB
// params.N = 1ULL << (count + 7); // 3 -> 1024, 4 -> 2048, ... 11 -> 262144
// yescrypt_encode_params_r(&params, rbytes, nrbytes, outbuf, o_size) // always "$y$j9T$<random>"
len = 22 / 2;
salt_ptr = stpcpy(salt_ptr, "j9T$");
/* append 2*len random chars */
rnd = crypt_make_rand64encoded(salt_ptr, len);
/* fix up last char: it must be in 0..3 range (encoded as one of "./01").
* IOW: salt_ptr[20..21] encode 16th random byte, must not be > 0xff.
* Without this, we can generate salts which are rejected
* by implementations with more strict salt length check.
*/
salt_ptr[21] = i2a64(rnd & 3);
/* For "mkpasswd -m yescrypt PASS j9T$<salt>" use case,
* "j9T$" is considered part of salt,
* need to return pointer to 'j'. Without -4,
* we'd end up using "j9T$j9T$<salt>" as salt.
*/
return salt_ptr - 4;
}
#endif
}
crypt_make_salt(salt_ptr, len);
crypt_make_rand64encoded(salt_ptr, len); /* appends 2*len random chars */
return salt_ptr;
}
#if ENABLE_USE_BB_CRYPT
static char*
to64(char *s, unsigned v, int n)
{
while (--n >= 0) {
/* *s++ = ascii64[v & 0x3f]; */
*s++ = i64c(v);
v >>= 6;
}
return s;
}
/*
* DES and MD5 crypt implementations are taken from uclibc.
* They were modified to not use static buffers.
@@ -99,6 +95,9 @@ to64(char *s, unsigned v, int n)
#if ENABLE_USE_BB_CRYPT_SHA
#include "pw_encrypt_sha.c"
#endif
#if ENABLE_USE_BB_CRYPT_YES
#include "pw_encrypt_yes.c"
#endif
/* Other advanced crypt ids (TODO?): */
/* $2$ or $2a$: Blowfish */
@@ -109,13 +108,17 @@ static struct des_ctx *des_ctx;
/* my_crypt returns malloc'ed data */
static char *my_crypt(const char *key, const char *salt)
{
/* MD5 or SHA? */
/* "$x$...." string? */
if (salt[0] == '$' && salt[1] && salt[2] == '$') {
if (salt[1] == '1')
return md5_crypt(xzalloc(MD5_OUT_BUFSIZE), (unsigned char*)key, (unsigned char*)salt);
#if ENABLE_USE_BB_CRYPT_SHA
if (salt[1] == '5' || salt[1] == '6')
return sha_crypt((char*)key, (char*)salt);
#endif
#if ENABLE_USE_BB_CRYPT_YES
if (salt[1] == 'y')
return yes_crypt(key, salt);
#endif
}
+17 -71
View File
@@ -186,39 +186,9 @@ static const uint8_t pbox[32] ALIGN1 = {
2, 8, 24, 14, 32, 27, 3, 9, 19, 13, 30, 6, 22, 11, 4, 25
};
static const uint32_t bits32[32] ALIGN4 = {
0x80000000, 0x40000000, 0x20000000, 0x10000000,
0x08000000, 0x04000000, 0x02000000, 0x01000000,
0x00800000, 0x00400000, 0x00200000, 0x00100000,
0x00080000, 0x00040000, 0x00020000, 0x00010000,
0x00008000, 0x00004000, 0x00002000, 0x00001000,
0x00000800, 0x00000400, 0x00000200, 0x00000100,
0x00000080, 0x00000040, 0x00000020, 0x00000010,
0x00000008, 0x00000004, 0x00000002, 0x00000001
};
static const uint8_t bits8[8] ALIGN1 = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
static int
ascii_to_bin(char ch)
{
if (ch > 'z')
return 0;
if (ch >= 'a')
return (ch - 'a' + 38);
if (ch > 'Z')
return 0;
if (ch >= 'A')
return (ch - 'A' + 12);
if (ch > '9')
return 0;
if (ch >= '.')
return (ch - '.');
return 0;
}
/* Static stuff that stays resident and doesn't change after
* being initialized, and therefore doesn't need to be made
* reentrant. */
@@ -354,11 +324,18 @@ des_init(struct des_ctx *ctx, const struct const_des_ctx *cctx)
int i, j, b, k, inbit, obit;
uint32_t p;
const uint32_t *bits28, *bits24;
uint32_t bits32[32];
if (!ctx)
ctx = xmalloc(sizeof(*ctx));
const_ctx = cctx;
p = 0x80000000U;
for (i = 0; p; i++) {
bits32[i] = p;
p >>= 1;
}
#if USE_REPETITIVE_SPEEDUP
old_rawkey0 = old_rawkey1 = 0;
old_salt = 0;
@@ -694,21 +671,6 @@ do_des(struct des_ctx *ctx, /*uint32_t l_in, uint32_t r_in,*/ uint32_t *l_out, u
#define DES_OUT_BUFSIZE 21
static void
to64_msb_first(char *s, unsigned v)
{
#if 0
*s++ = ascii64[(v >> 18) & 0x3f]; /* bits 23..18 */
*s++ = ascii64[(v >> 12) & 0x3f]; /* bits 17..12 */
*s++ = ascii64[(v >> 6) & 0x3f]; /* bits 11..6 */
*s = ascii64[v & 0x3f]; /* bits 5..0 */
#endif
*s++ = i64c(v >> 18); /* bits 23..18 */
*s++ = i64c(v >> 12); /* bits 17..12 */
*s++ = i64c(v >> 6); /* bits 11..6 */
*s = i64c(v); /* bits 5..0 */
}
static char *
NOINLINE
des_crypt(struct des_ctx *ctx, char output[DES_OUT_BUFSIZE],
@@ -740,44 +702,28 @@ des_crypt(struct des_ctx *ctx, char output[DES_OUT_BUFSIZE],
*/
output[0] = salt_str[0];
output[1] = salt_str[1];
salt = (ascii_to_bin(salt_str[1]) << 6)
| ascii_to_bin(salt_str[0]);
salt = a2i64(salt_str[0]);
if (salt >= 64)
return NULL; /* bad salt char */
salt |= (a2i64(salt_str[1]) << 6);
if (salt >= (64 << 6))
return NULL; /* bad salt char */
setup_salt(ctx, salt); /* set ctx->saltbits for do_des() */
/* Do it. */
do_des(ctx, /*0, 0,*/ &r0, &r1, 25 /* count */);
/* Now encode the result. */
#if 0
{
uint32_t l = (r0 >> 8);
q = (uint8_t *)output + 2;
*q++ = ascii64[(l >> 18) & 0x3f]; /* bits 31..26 of r0 */
*q++ = ascii64[(l >> 12) & 0x3f]; /* bits 25..20 of r0 */
*q++ = ascii64[(l >> 6) & 0x3f]; /* bits 19..14 of r0 */
*q++ = ascii64[l & 0x3f]; /* bits 13..8 of r0 */
l = ((r0 << 16) | (r1 >> 16));
*q++ = ascii64[(l >> 18) & 0x3f]; /* bits 7..2 of r0 */
*q++ = ascii64[(l >> 12) & 0x3f]; /* bits 1..2 of r0 and 31..28 of r1 */
*q++ = ascii64[(l >> 6) & 0x3f]; /* bits 27..22 of r1 */
*q++ = ascii64[l & 0x3f]; /* bits 21..16 of r1 */
l = r1 << 2;
*q++ = ascii64[(l >> 12) & 0x3f]; /* bits 15..10 of r1 */
*q++ = ascii64[(l >> 6) & 0x3f]; /* bits 9..4 of r1 */
*q++ = ascii64[l & 0x3f]; /* bits 3..0 of r1 + 00 */
*q = 0;
}
#else
/* Each call takes low-order 24 bits and stores 4 chars */
/* bits 31..8 of r0 */
to64_msb_first(output + 2, (r0 >> 8));
num2str64_4chars_msb_first(output + 2, (r0 >> 8));
/* bits 7..0 of r0 and 31..16 of r1 */
to64_msb_first(output + 6, (r0 << 16) | (r1 >> 16));
num2str64_4chars_msb_first(output + 6, (r0 << 16) | (r1 >> 16));
/* bits 15..0 of r1 and two zero bits (plus extra zero byte) */
to64_msb_first(output + 10, (r1 << 8));
num2str64_4chars_msb_first(output + 10, (r1 << 8));
/* extra zero byte is encoded as '.', fixing it */
output[13] = '\0';
#endif
return output;
}
+2 -2
View File
@@ -149,9 +149,9 @@ md5_crypt(char result[MD5_OUT_BUFSIZE], const unsigned char *pw, const unsigned
final[16] = final[5];
for (i = 0; i < 5; i++) {
unsigned l = (final[i] << 16) | (final[i+6] << 8) | final[i+12];
p = to64(p, l, 4);
p = num2str64_lsb_first(p, l, 4);
}
p = to64(p, final[11], 2);
p = num2str64_lsb_first(p, final[11], 2);
*p = '\0';
/* Don't leave anything around in vm they could use. */
+2 -3
View File
@@ -84,8 +84,7 @@ sha_crypt(/*const*/ char *key_data, /*const*/ char *salt_data)
as a scratch space later. */
salt_data = xstrndup(salt_data, salt_len);
/* add "salt$" to result */
strcpy(resptr, salt_data);
resptr += salt_len;
resptr = stpcpy(resptr, salt_data);
*resptr++ = '$';
/* key data doesn't need much processing */
key_len = strlen(key_data);
@@ -198,7 +197,7 @@ sha_crypt(/*const*/ char *key_data, /*const*/ char *salt_data)
#define b64_from_24bit(B2, B1, B0, N) \
do { \
unsigned w = ((B2) << 16) | ((B1) << 8) | (B0); \
resptr = to64(resptr, w, N); \
resptr = num2str64_lsb_first(resptr, w, N); \
} while (0)
if (_32or64 == 32) { /* sha256 */
unsigned i = 0;
+24
View File
@@ -0,0 +1,24 @@
/*
* Utility routines.
*
* Copyright (C) 2025 by Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
#include "yescrypt/alg-yescrypt.h"
static char *
yes_crypt(const char *passwd, const char *salt_data)
{
/* prefix, '$', hash, NUL */
char buf[YESCRYPT_PREFIX_LEN + 1 + YESCRYPT_HASH_LEN + 1];
char *retval;
retval = yescrypt_r(
(const uint8_t *)passwd, strlen(passwd),
(const uint8_t *)salt_data,
buf, sizeof(buf));
/* The returned value is either buf[], or NULL on error */
return xstrdup(retval);
}
+53 -47
View File
@@ -11,7 +11,7 @@
int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
{
struct pollfd pfd;
struct pollfd pfd[1];
const char *seq;
int n;
@@ -26,7 +26,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
'd' |0x80,KEYCODE_ALT_D ,
/* lineedit mimics bash: Alt-f and Alt-b are forward/backward
* word jumps. We cheat here and make them return ALT_LEFT/RIGHT
* keycodes. This way, lineedit need no special code to handle them.
* keycodes. This way, lineedit needs no special code to handle them.
* If we'll need to distinguish them, introduce new ALT_F/B keycodes,
* and update lineedit to react to them.
*/
@@ -40,12 +40,12 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
'O','F' |0x80,KEYCODE_END ,
#if 0
'O','P' |0x80,KEYCODE_FUN1 ,
/* [ESC] ESC O [2] P - [Alt-][Shift-]F1 */
/* ESC [ O 1 ; 2 P - Shift-F1 */
/* ESC [ O 1 ; 3 P - Alt-F1 */
/* ESC [ O 1 ; 4 P - Alt-Shift-F1 */
/* ESC [ O 1 ; 5 P - Ctrl-F1 */
/* ESC [ O 1 ; 6 P - Ctrl-Shift-F1 */
// [ESC] ESC O [2] P - [Alt-][Shift-]F1
// ESC [ O 1 ; 2 P - Shift-F1
// ESC [ O 1 ; 3 P - Alt-F1
// ESC [ O 1 ; 4 P - Alt-Shift-F1
// ESC [ O 1 ; 5 P - Ctrl-F1
// ESC [ O 1 ; 6 P - Ctrl-Shift-F1
'O','Q' |0x80,KEYCODE_FUN2 ,
'O','R' |0x80,KEYCODE_FUN3 ,
'O','S' |0x80,KEYCODE_FUN4 ,
@@ -54,29 +54,29 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
'[','B' |0x80,KEYCODE_DOWN ,
'[','C' |0x80,KEYCODE_RIGHT ,
'[','D' |0x80,KEYCODE_LEFT ,
/* ESC [ 1 ; 2 x, where x = A/B/C/D: Shift-<arrow> */
/* ESC [ 1 ; 3 x, where x = A/B/C/D: Alt-<arrow> - implemented below */
/* ESC [ 1 ; 4 x, where x = A/B/C/D: Alt-Shift-<arrow> */
/* ESC [ 1 ; 5 x, where x = A/B/C/D: Ctrl-<arrow> - implemented below */
/* ESC [ 1 ; 6 x, where x = A/B/C/D: Ctrl-Shift-<arrow> */
/* ESC [ 1 ; 7 x, where x = A/B/C/D: Ctrl-Alt-<arrow> */
/* ESC [ 1 ; 8 x, where x = A/B/C/D: Ctrl-Alt-Shift-<arrow> */
// ESC [ 1 ; 2 x, where x = A/B/C/D: Shift-<arrow>
// ESC [ 1 ; 3 x, where x = A/B/C/D: Alt-<arrow> - implemented below
// ESC [ 1 ; 4 x, where x = A/B/C/D: Alt-Shift-<arrow>
// ESC [ 1 ; 5 x, where x = A/B/C/D: Ctrl-<arrow> - implemented below
// ESC [ 1 ; 6 x, where x = A/B/C/D: Ctrl-Shift-<arrow>
// ESC [ 1 ; 7 x, where x = A/B/C/D: Ctrl-Alt-<arrow>
// ESC [ 1 ; 8 x, where x = A/B/C/D: Ctrl-Alt-Shift-<arrow>
'[','H' |0x80,KEYCODE_HOME , /* xterm */
'[','F' |0x80,KEYCODE_END , /* xterm */
/* [ESC] ESC [ [2] H - [Alt-][Shift-]Home (End similarly?) */
/* '[','Z' |0x80,KEYCODE_SHIFT_TAB, */
// [ESC] ESC [ [2] H - [Alt-][Shift-]Home (End similarly?)
// '[','Z' |0x80,KEYCODE_SHIFT_TAB,
'[','1','~' |0x80,KEYCODE_HOME , /* vt100? linux vt? or what? */
'[','2','~' |0x80,KEYCODE_INSERT ,
/* ESC [ 2 ; 3 ~ - Alt-Insert */
// ESC [ 2 ; 3 ~ - Alt-Insert
'[','3','~' |0x80,KEYCODE_DELETE ,
/* [ESC] ESC [ 3 [;2] ~ - [Alt-][Shift-]Delete */
/* ESC [ 3 ; 3 ~ - Alt-Delete */
/* ESC [ 3 ; 5 ~ - Ctrl-Delete */
// [ESC] ESC [ 3 [;2] ~ - [Alt-][Shift-]Delete
// ESC [ 3 ; 3 ~ - Alt-Delete
// ESC [ 3 ; 5 ~ - Ctrl-Delete
'[','4','~' |0x80,KEYCODE_END , /* vt100? linux vt? or what? */
'[','5','~' |0x80,KEYCODE_PAGEUP ,
/* ESC [ 5 ; 3 ~ - Alt-PgUp */
/* ESC [ 5 ; 5 ~ - Ctrl-PgUp */
/* ESC [ 5 ; 7 ~ - Ctrl-Alt-PgUp */
// ESC [ 5 ; 3 ~ - Alt-PgUp
// ESC [ 5 ; 5 ~ - Ctrl-PgUp
// ESC [ 5 ; 7 ~ - Ctrl-Alt-PgUp
'[','6','~' |0x80,KEYCODE_PAGEDOWN,
'[','7','~' |0x80,KEYCODE_HOME , /* vt100? linux vt? or what? */
'[','8','~' |0x80,KEYCODE_END , /* vt100? linux vt? or what? */
@@ -86,7 +86,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
'[','1','3','~'|0x80,KEYCODE_FUN3 , /* old xterm... */
'[','1','4','~'|0x80,KEYCODE_FUN4 , /* old xterm... */
'[','1','5','~'|0x80,KEYCODE_FUN5 ,
/* [ESC] ESC [ 1 5 [;2] ~ - [Alt-][Shift-]F5 */
// [ESC] ESC [ 1 5 [;2] ~ - [Alt-][Shift-]F5
'[','1','7','~'|0x80,KEYCODE_FUN6 ,
'[','1','8','~'|0x80,KEYCODE_FUN7 ,
'[','1','9','~'|0x80,KEYCODE_FUN8 ,
@@ -94,26 +94,26 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
'[','2','1','~'|0x80,KEYCODE_FUN10 ,
'[','2','3','~'|0x80,KEYCODE_FUN11 ,
'[','2','4','~'|0x80,KEYCODE_FUN12 ,
/* ESC [ 2 4 ; 2 ~ - Shift-F12 */
/* ESC [ 2 4 ; 3 ~ - Alt-F12 */
/* ESC [ 2 4 ; 4 ~ - Alt-Shift-F12 */
/* ESC [ 2 4 ; 5 ~ - Ctrl-F12 */
/* ESC [ 2 4 ; 6 ~ - Ctrl-Shift-F12 */
// ESC [ 2 4 ; 2 ~ - Shift-F12
// ESC [ 2 4 ; 3 ~ - Alt-F12
// ESC [ 2 4 ; 4 ~ - Alt-Shift-F12
// ESC [ 2 4 ; 5 ~ - Ctrl-F12
// ESC [ 2 4 ; 6 ~ - Ctrl-Shift-F12
#endif
/* '[','1',';','5','A' |0x80,KEYCODE_CTRL_UP , - unused */
/* '[','1',';','5','B' |0x80,KEYCODE_CTRL_DOWN , - unused */
'[','1',';','5','C' |0x80,KEYCODE_CTRL_RIGHT,
'[','1',';','5','D' |0x80,KEYCODE_CTRL_LEFT ,
/* '[','1',';','3','A' |0x80,KEYCODE_ALT_UP , - unused */
/* '[','1',';','3','B' |0x80,KEYCODE_ALT_DOWN , - unused */
// '[','1',';','3','A' |0x80,KEYCODE_ALT_UP , - unused
// '[','1',';','3','B' |0x80,KEYCODE_ALT_DOWN , - unused
'[','1',';','3','C' |0x80,KEYCODE_ALT_RIGHT,
'[','1',';','3','D' |0x80,KEYCODE_ALT_LEFT ,
/* '[','3',';','3','~' |0x80,KEYCODE_ALT_DELETE, - unused */
// '[','1',';','5','A' |0x80,KEYCODE_CTRL_UP , - unused
// '[','1',';','5','B' |0x80,KEYCODE_CTRL_DOWN , - unused
'[','1',';','5','C' |0x80,KEYCODE_CTRL_RIGHT,
'[','1',';','5','D' |0x80,KEYCODE_CTRL_LEFT ,
// '[','3',';','3','~' |0x80,KEYCODE_ALT_DELETE, - unused
0
};
pfd.fd = fd;
pfd.events = POLLIN;
pfd->fd = fd;
pfd->events = POLLIN;
buffer++; /* saved chars counter is in buffer[-1] now */
@@ -121,12 +121,16 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
errno = 0;
n = (unsigned char)buffer[-1];
if (n == 0) {
/* If no data, wait for input.
* If requested, wait TIMEOUT ms. TIMEOUT = -1 is useful
* if fd can be in non-blocking mode.
*/
/* No data. Wait for input. */
/* timeout == -2 means "do not poll". Else: */
if (timeout >= -1) {
n = poll(&pfd, 1, timeout);
/* We must poll even if timeout == -1:
* we want to be interrupted if signal arrives,
* regardless of SA_RESTART-ness of that signal!
*/
/* test bb_got_signal, then poll(), atomically wrt signals */
n = check_got_signal_and_poll(pfd, timeout);
if (n < 0 && errno == EINTR)
return n;
if (n == 0) {
@@ -135,6 +139,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
return -1;
}
}
/* It is tempting to read more than one byte here,
* but it breaks pasting. Example: at shell prompt,
* user presses "c","a","t" and then pastes "\nline\n".
@@ -173,7 +178,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
* so if we block for long it's not really an escape sequence.
* Timeout is needed to reconnect escape sequences
* split up by transmission over a serial console. */
if (safe_poll(&pfd, 1, 50) == 0) {
if (safe_poll(pfd, 1, 50) == 0) {
/* No more data!
* Array is sorted from shortest to longest,
* we can't match anything later in array -
@@ -200,7 +205,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
/* Forward to last char */
while (!(*seq & 0x80))
seq++;
/* Skip it and the keycode which follows */
/* Skip seq terminating byte, and KEYCODE_xyz byte that follows */
seq += 2;
break;
}
@@ -212,6 +217,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
* but we never read ahead that much,
* and n == i here. */
buffer[-1] = 0;
/* Return KEYCODE_xyz (always negative) */
return (signed char)seq[i+1];
}
i++;
@@ -222,7 +228,7 @@ int64_t FAST_FUNC read_key(int fd, char *buffer, int timeout)
* n = bytes read. Try to read more until we time out.
*/
while (n < KEYCODE_BUFFER_SIZE-1) { /* 1 for count byte at buffer[-1] */
if (safe_poll(&pfd, 1, 50) == 0) {
if (safe_poll(pfd, 1, 50) == 0) {
/* No more data! */
break;
}
+16 -1
View File
@@ -28,7 +28,8 @@ unsigned FAST_FUNC count_strstr(const char *str, const char *sub)
char* FAST_FUNC xmalloc_substitute_string(const char *src, int count, const char *sub, const char *repl)
{
char *buf, *dst, *end;
char *buf, *dst;
const char *end;
size_t sub_len = strlen(sub);
size_t repl_len = strlen(repl);
@@ -46,3 +47,17 @@ char* FAST_FUNC xmalloc_substitute_string(const char *src, int count, const char
//dbg_msg("subst9:'%s'", buf);
return buf;
}
#if 0 /* inlined in libbb.h */
/* Returns strlen as a bonus */
size_t FAST_FUNC replace_char(char *str, char from, char to)
{
char *p = str;
while (*p) {
if (*p == from)
*p = to;
p++;
}
return p - str;
}
#endif
+21 -9
View File
@@ -24,13 +24,6 @@ int FAST_FUNC sigaction_set(int signum, const struct sigaction *act)
return sigaction(signum, act, NULL);
}
int FAST_FUNC sigprocmask_allsigs(int how)
{
sigset_t set;
sigfillset(&set);
return sigprocmask(how, &set, NULL);
}
int FAST_FUNC sigprocmask2(int how, sigset_t *set)
{
// Grr... gcc 8.1.1:
@@ -41,6 +34,25 @@ int FAST_FUNC sigprocmask2(int how, sigset_t *set)
return sigprocmask(how, set, oset);
}
int FAST_FUNC sigprocmask_allsigs(int how)
{
sigset_t set;
sigfillset(&set);
return sigprocmask2(how, &set);
}
int FAST_FUNC sigblockall(sigset_t *set)
{
#if 0 /* nope. set can be NULL */
sigfillset(set);
return sigprocmask2(SIG_SETMASK, set);
#else
sigset_t mask;
sigfillset(&mask);
return sigprocmask(SIG_SETMASK, &mask, set);
#endif
}
void FAST_FUNC bb_signals(int sigs, void (*f)(int))
{
int sig_no = 0;
@@ -82,7 +94,7 @@ void FAST_FUNC sig_block(int sig)
sigset_t ss;
sigemptyset(&ss);
sigaddset(&ss, sig);
sigprocmask(SIG_BLOCK, &ss, NULL);
sigprocmask2(SIG_BLOCK, &ss);
}
void FAST_FUNC sig_unblock(int sig)
@@ -90,7 +102,7 @@ void FAST_FUNC sig_unblock(int sig)
sigset_t ss;
sigemptyset(&ss);
sigaddset(&ss, sig);
sigprocmask(SIG_UNBLOCK, &ss, NULL);
sigprocmask2(SIG_UNBLOCK, &ss);
}
void FAST_FUNC wait_for_any_sig(void)
+2 -2
View File
@@ -19,10 +19,10 @@ char* FAST_FUNC strrstr(const char *haystack, const char *needle)
if (!needle[0])
return (char*)haystack + strlen(haystack);
while (1) {
char *p = strstr(haystack, needle);
const char *p = strstr(haystack, needle);
if (!p)
return r;
r = p;
r = (char *)p;
haystack = p + 1;
}
}
-21
View File
@@ -113,29 +113,8 @@ void FAST_FUNC xconnect(int s, const struct sockaddr *s_addr, socklen_t addrlen)
}
}
/* Return port number for a service.
* If "port" is a number use it as the port.
* If "port" is a name it is looked up in /etc/services.
* if NULL, return default_port
*/
unsigned FAST_FUNC bb_lookup_port(const char *port, const char *protocol, unsigned port_nr)
{
if (port) {
port_nr = bb_strtou(port, NULL, 10);
if (errno || port_nr > 65535) {
struct servent *tserv = getservbyname(port, protocol);
if (!tserv)
bb_error_msg_and_die("bad port '%s'", port);
port_nr = ntohs(tserv->s_port);
}
}
return (uint16_t)port_nr;
}
/* "New" networking API */
int FAST_FUNC get_nport(const struct sockaddr *sa)
{
#if ENABLE_FEATURE_IPV6
-41
View File
@@ -176,47 +176,6 @@ char* FAST_FUNC hex2bin(char *dst, const char *str, int count)
return dst;
}
/* Return how long the file at fd is, if there's any way to determine it. */
#ifdef UNUSED
off_t FAST_FUNC fdlength(int fd)
{
off_t bottom = 0, top = 0, pos;
long size;
// If the ioctl works for this, return it.
if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512;
// FIXME: explain why lseek(SEEK_END) is not used here!
// If not, do a binary search for the last location we can read. (Some
// block devices don't do BLKGETSIZE right.)
do {
char temp;
pos = bottom + (top - bottom) / 2;
// If we can read from the current location, it's bigger.
if (lseek(fd, pos, SEEK_SET)>=0 && safe_read(fd, &temp, 1)==1) {
if (bottom == top) bottom = top = (top+1) * 2;
else bottom = pos;
// If we can't, it's smaller.
} else {
if (bottom == top) {
if (!top) return 0;
bottom = top/2;
}
else top = pos;
}
} while (bottom + 1 != top);
return pos + 1;
}
#endif
int FAST_FUNC bb_putchar_stderr(char ch)
{
return write(STDERR_FILENO, &ch, 1);
+42 -4
View File
@@ -349,6 +349,22 @@ char* FAST_FUNC xasprintf(const char *format, ...)
return string_ptr;
}
char* FAST_FUNC xasprintf_and_free(char *allocated, const char *format, ...)
{
va_list p;
int r;
char *string_ptr;
va_start(p, format);
r = vasprintf(&string_ptr, format, p);
va_end(p);
if (r < 0)
bb_die_memory_exhausted();
free(allocated);
return string_ptr;
}
void FAST_FUNC xsetenv(const char *key, const char *value)
{
if (setenv(key, value, 1))
@@ -363,7 +379,7 @@ void FAST_FUNC bb_unsetenv(const char *var)
char onstack[128 - 16]; /* smaller stack setup code on x86 */
char *tp;
tp = strchr(var, '=');
tp = (char*)strchr(var, '=');
if (tp) {
/* In case var was putenv'ed, we can't replace '='
* with NUL and unsetenv(var) - it won't work,
@@ -642,14 +658,14 @@ void FAST_FUNC generate_uuid(uint8_t *buf)
* uint32_t time_low (big endian)
* uint16_t time_mid (big endian)
* uint16_t time_hi_and_version (big endian)
* version is a 4-bit field:
* version is a 4-bit field (most significant 4 bits):
* 1 Time-based
* 2 DCE Security, with embedded POSIX UIDs
* 3 Name-based (MD5)
* 4 Randomly generated
* 5 Name-based (SHA-1)
* uint16_t clk_seq_and_variant (big endian)
* variant is a 3-bit field:
* variant is a 3-bit field (most significant 3 bits):
* 0xx Reserved, NCS backward compatibility
* 10x The variant specified in rfc4122
* 110 Reserved, Microsoft backward compatibility
@@ -681,10 +697,23 @@ void FAST_FUNC generate_uuid(uint8_t *buf)
/* version = 4 */
buf[4 + 2 ] = (buf[4 + 2 ] & 0x0f) | 0x40;
/* variant = 10x */
/* variant = 10x binary (uppermost 3 bits) */
buf[4 + 2 + 2] = (buf[4 + 2 + 2] & 0x3f) | 0x80;
}
void FAST_FUNC format_uuid_DCE_37_chars(char *dst37, const uint8_t *buf)
{
/* 37 = 16*2 hexdigits + 4 dashes + 1 NUL */
sprintf(dst37,
"%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5],
buf[6], buf[7],
buf[8], buf[9],
buf[10], buf[11], buf[12], buf[13], buf[14], buf[15]
);
}
#if BB_MMU
pid_t FAST_FUNC xfork(void)
{
@@ -696,6 +725,14 @@ pid_t FAST_FUNC xfork(void)
}
#endif
#if 0
/* DO NOT DO THIS. This can't be a function.
* It works on some arches (x86) but fails on others (ppc64le: SEGV).
* The reason is: the child returns from this function
* and likely pops up the stack in an arch-dependent way.
* When child eventually exits or execs, parent "reappear"
* in the now-unwound stack (!) and the behavior is undefined.
*/
void FAST_FUNC xvfork_parent_waits_and_exits(void)
{
pid_t pid;
@@ -711,6 +748,7 @@ void FAST_FUNC xvfork_parent_waits_and_exits(void)
}
/* Child continues */
}
#endif
// Useful when we do know that pid is valid, and we just want to wait
// for it to exit. Not existing pid is fatal. waitpid() status is not returned.
+9
View File
@@ -0,0 +1,9 @@
# Makefile for busybox
#
# Copyright (C) 2025 by Denys Vlasenko <vda.linux@googlemail.com>
#
# Licensed under GPLv2, see file LICENSE in this source tree.
lib-y:=
INSERT
+196
View File
@@ -0,0 +1,196 @@
Optimal yescrypt configuration.
yescrypt is very flexible, but configuring it optimally is complicated.
Here are some guidelines to simplify near-optimal configuration. We
start by listing the parameters and their typical values, and then give
currently recommended parameter sets by use case.
Parameters and their typical values.
Set flags (yescrypt flavor) to YESCRYPT_DEFAULTS to use the currently
recommended flavor. (Other flags values exist for compatibility and for
specialized cases where you think you know what you're doing.)
Set N (block count) based on target memory usage and running time, as
well as on the value of r (block size in 128 byte units). N must be a
power of two.
Set r (block size) to 8 (so that N is in KiB, which is convenient) or to
another small value (if more optimal or for fine-tuning of the total
size and/or running time). Reasonable values for r are from 8 to 96.
Set p (parallelism) to 1 meaning no thread-level parallelism within one
computation of yescrypt. (Use of thread-level parallelism within
yescrypt makes sense for ROM initialization and for key derivation at
high memory usage, but usually not for password hashing where
parallelism is available through concurrent authentication attempts.
Don't use p > 1 unnecessarily.)
Set t (time) to 0 to use the optimal running time for a given memory
usage. This will allow you to maximize the memory usage (the value of
N*r) while staying within your running time constraints. (Non-zero t
makes sense in specialized cases where you can't afford higher memory
usage but can afford more time.)
Set g (upgrades) to 0 because there have been no hash upgrades yet.
Set NROM (block count of ROM) to 0 unless you use a ROM (see below).
NROM must be a power of two.
Password hashing for user authentication, no ROM.
Small and fast (memory usage 2 MiB, performance like bcrypt cost 2^5 -
latency 2-3 ms and throughput 10,000+ per second on a 16-core server):
flags = YESCRYPT_DEFAULTS, N = 2048, r = 8, p = 1, t = 0, g = 0, NROM = 0
Large and slow (memory usage 16 MiB, performance like bcrypt cost 2^8 -
latency 10-30 ms and throughput 1000+ per second on a 16-core server):
flags = YESCRYPT_DEFAULTS, N = 4096, r = 32, p = 1, t = 0, g = 0, NROM = 0
Of course, even heavier and slower settings are possible, if affordable.
Simply double the value of N as many times as needed. Since N must be a
power of two, you may use r (in the range of 8 to 32) or/and t (in the
range of 0 to 2) for fine-tuning the running time, but first bring N to
the maximum you can afford. If this feels too complicated, just use one
of the two parameter sets given above (preferably the second) as-is.
Password hashing for user authentication, with ROM.
It's similar to the above, except that you need to adjust r, set NROM,
and initialize the ROM.
First decide on a ROM size, such as making it a large portion of your
dedicated authentication servers' RAM sizes. Since NROM (block count)
must be a power of two, you might need to choose r (block size) based on
how your desired ROM size corresponds to a power of two. Also tuning
for performance on current hardware, you'll likely end up with r in the
range from slightly below 16 to 32. For example, to use 15/16 of a
server's 256 GiB RAM as ROM (thus, making it 240 GiB), you could use
r=15 or r=30. To use 23/24 of a server's 384 GiB RAM as ROM (thus,
making it 368 GiB), you'd use r=23. Then set NROM to your desired ROM
size in KiB divided by 128*r. Note that these examples might (or might
not) be too extreme, leaving little memory for the rest of the system.
You could as well opt for 7/8 with r=14 or 11/12 with r=11 or r=22.
Note that higher r may make placing of ROM in e.g. NVMe flash memory
instead of in RAM more reasonable (or less unreasonable) than it would
have been with a lower r. If this is a concern as it relates to
possible attacks and you do not intend to ever do it defensively, you
might want to keep r lower (e.g., prefer r=15 over r=30 in the example
above, even if 30 performs slightly faster).
Your adjustments to r, if you deviate from powers of two, will also
result in weirder memory usage per hash. Like 1.75 MiB at r=14 instead
of 2 MiB at r=8 that you would have used without a ROM. That's OK.
For ROM initialization, which you do with yescrypt_init_shared(), use
the same r and NROM that you'd later use for password hashing, choose p
based on your servers' physical and/or logical CPU count (maybe
considering eventual upgrades as you won't be able to change this later,
but without going unnecessarily high - e.g., p=28, p=56, or p=112 make
sense on servers that currently have 28 physical / 56 logical CPUs), and
set the rest of the parameters to:
flags = YESCRYPT_DEFAULTS, N = 0, t = 0, g = 0
N is set to 0 because it isn't relevant during ROM initialization (you
can use different values of N for hashing passwords with the same ROM).
To keep the ROM in e.g. SysV shared memory and reuse it across your
authentication service restarts, you'd need to allocate the memory and
set the flags to "YESCRYPT_DEFAULTS | YESCRYPT_SHARED_PREALLOCATED".
For actual password hashing, you'd use your chosen values for N, r,
NROM, and set the rest of the parameters to:
flags = YESCRYPT_DEFAULTS, p = 1, t = 0, g = 0
Note that although you'd use a large p for ROM initialization, you
should use p=1 for actual password hashing like you would without a ROM.
Do not forget to pass the ROM into the actual password hashing (and keep
r and NROM set accordingly).
Since N must be a power of two and r is dependent on ROM size, you may
use t (in the range of 0 to 2) for fine-tuning the running time, but
first bring N to the maximum you can afford.
If this feels too complicated, or even if it doesn't, please consider
engaging Openwall for your yescrypt deployment. We'd be happy to help.
Password-based key derivation.
(Or rather passphrase-based.)
Use settings similar to those for password hashing without a ROM, but
adjusted for higher memory usage and running time, and optionally with
thread-level parallelism.
Small and fast (memory usage 128 MiB, running time under 100 ms on a
fast desktop):
flags = YESCRYPT_DEFAULTS, N = 32768, r = 32, p = 1, t = 0, g = 0, NROM = 0
Large and fast (memory usage 1 GiB, running time under 200 ms on a fast
quad-core desktop not including memory allocation overhead, under 250 ms
with the overhead included), but requires build with OpenMP support (or
otherwise will run as slow as yet be weaker than its p=1 alternative):
flags = YESCRYPT_DEFAULTS, N = 262144, r = 32, p = 4, t = 0, g = 0, NROM = 0
Large and slower (memory usage 1 GiB, running time under 300 ms on a
fast quad-core desktop not including memory allocation overhead, under
350 ms with the overhead included), also requires build with OpenMP
support (or otherwise will run slower than the p=1 alternative below):
flags = YESCRYPT_DEFAULTS, N = 262144, r = 32, p = 4, t = 2, g = 0, NROM = 0
Large and slow (memory usage 1 GiB, running time under 600 ms on a fast
desktop not including memory allocation overhead, under 650 ms with the
overhead included):
flags = YESCRYPT_DEFAULTS, N = 262144, r = 32, p = 1, t = 0, g = 0, NROM = 0
Just like with password hashing, even heavier and slower settings are
possible, if affordable, and you achieve them by adjusting N, r, t in
the same way and in the same preferred ranges (please see the section on
password hashing without a ROM, above). Unlike with password hashing,
it makes some sense to go above t=2 if you expect that your users might
not be able to afford more memory but can afford more time. However,
increasing the memory usage provides better protection, and we don't
recommend forcing your users to wait for more than 1 second as they
could as well type more characters in that time. If this feels too
complicated, just use one of the above parameter sets as-is.
Amortization of memory allocation overhead.
It takes a significant fraction of yescrypt's total running time to
allocate memory from the operating system, especially considering that
the kernel zeroizes the memory before handing it over to your program.
Unless you naturally need to compute yescrypt just once per process, you
may achieve greater efficiency by fully using advanced yescrypt APIs
that let you preserve and reuse the memory allocation across yescrypt
invocations. This is done by reusing the structure pointed to by the
"yescrypt_local_t *local" argument of yescrypt_r() or yescrypt_kdf()
without calling yescrypt_free_local() inbetween the repeated invocations
of yescrypt.
YESCRYPT_DEFAULTS macro.
Please note that the value of the YESCRYPT_DEFAULTS macro might change
later, so if you use the macro like it's recommended here then for
results reproducible across versions you might need to store its value
somewhere along with the hashes or the encrypted data.
If you use yescrypt's standard hash string encoding, then yescrypt
already encodes and decodes this value for you, so you don't need to
worry about this.
+4
View File
@@ -0,0 +1,4 @@
The yescrypt code in this directory is adapted from libxcrypt-4.4.38
with minimal edits, hopefully making it easier to track
backports by resetting the tree to the commit which created this file,
then comparing changes in upstream libxcrypt to the tree.
+91
View File
@@ -0,0 +1,91 @@
/*-
* Copyright 2005-2016 Colin Percival
* Copyright 2016-2018,2021 Alexander Peslyak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/**
* PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen):
* Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and
* write the output to buf. The value dkLen must be at most 32 * (2^32 - 1).
*/
static void
PBKDF2_SHA256(const uint8_t *passwd, size_t passwdlen,
const uint8_t *salt, size_t saltlen,
uint64_t c, uint8_t *buf, size_t dkLen)
{
hmac_ctx_t Phctx, PShctx;
uint32_t i;
/* Compute HMAC state after processing P. */
hmac_begin(&Phctx, passwd, passwdlen, sha256_begin);
/* Compute HMAC state after processing P and S. */
PShctx = Phctx;
hmac_hash(&PShctx, salt, saltlen);
/* Iterate through the blocks. */
for (i = 0; dkLen != 0; ) {
long U[32 / sizeof(long)];
long T[32 / sizeof(long)];
// Do not make these ^^ uint64_t[]. Keep them long[].
// Even though the XORing loop below is optimized out,
// gcc is not smart enough to realize that 64-bit alignment of the stack
// is no longer useful, and generates ~50 more bytes of code on i386...
uint32_t ivec;
size_t clen;
int k;
/* Generate INT(i). */
i++;
ivec = SWAP_BE32(i);
/* Compute U_1 = PRF(P, S || INT(i)). */
hmac_peek_hash(&PShctx, (void*)T, &ivec, 4, NULL);
//TODO: the above is a vararg function, might incur some ABI pain
//does libbb need a non-vararg version with just one (buf,len)?
if (c > 1) {
//in yescrypt, c is always 1, so this if() branch is optimized out
uint64_t j;
/* T_i = U_1 ... */
memcpy(U, T, 32);
for (j = 2; j <= c; j++) {
/* Compute U_j. */
hmac_peek_hash(&Phctx, (void*)U, U, 32, NULL);
/* ... xor U_j ... */
for (k = 0; k < 32 / sizeof(long); k++)
T[k] ^= U[k];
//TODO: xorbuf32_aligned_long(T, U);
}
}
/* Copy as many bytes as necessary into buf. */
clen = dkLen;
if (clen > 32)
clen = 32;
buf = mempcpy(buf, T, clen);
dkLen -= clen;
}
}
+408
View File
@@ -0,0 +1,408 @@
/*-
* Copyright 2013-2018 Alexander Peslyak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if RESTRICTED_PARAMS
#define decode64_uint32(dst, src, min) \
({ \
uint32_t d32 = a2i64(*(src)); \
if (d32 > 47) \
goto fail; \
*(dst) = d32 + (min); \
++src; \
})
#define test_decode64_uint32() ((void)0)
#define FULL_PARAMS(...)
#else
#define FULL_PARAMS(...) __VA_ARGS__
/* Not inlining:
* de/encode64 functions are only used to read
* yescrypt_params_t field, and convert salt to binary -
* both of these are negligible compared to main hashing operation
*/
static NOINLINE const uint8_t *decode64_uint32(
uint32_t *dst,
const uint8_t *src, uint32_t val)
{
uint32_t start = 0, end = 47, bits = 0;
uint32_t c;
if (!src) /* previous decode failed already? */
goto fail;
c = a2i64(*src++);
if (c > 63)
goto fail;
// The encoding of number N:
// start = 0 end = 47
// If N < 48, it is encoded verbatim, else
// N -= 48
// start = end+1 = 48
// end += (64-end)/2 = 55
// If N < (end+1-start)<<6 = 8<<6, it is encoded as 48+(N>>6)|low6bits (that is, 48...55|<6bit>), else
// N -= 8<<6
// start = end+1 = 56
// end += (64-end)/2 = 59
// If N < (end+1-start)<<2*6 = 4<<12, it is encoded as 56+(N>>2*6)|low12bits (that is, 56...59|<6bit>|<6bit>), else
// ...same for 60..61|<6bit>|<6bit>|<6bit>
// .......same for 62|<6bit>|<6bit>|<6bit>|<6bit>
// .......same for 63|<6bit>|<6bit>|<6bit>|<6bit>|<6bit>
dbg_dec64("c:%d val:0x%08x", (int)c, (unsigned)val);
while (c > end) {
dbg_dec64("c:%d > end:%d", (int)c, (int)end);
val += (end + 1 - start) << bits;
dbg_dec64("val+=0x%08x", (int)((end + 1 - start) << bits));
dbg_dec64(" val:0x%08x", (unsigned)val);
start = end + 1;
end += (64 - end) / 2;
bits += 6;
dbg_dec64("start=%d", (int)start);
dbg_dec64("end=%d", (int)end);
dbg_dec64("bits=%d", (int)bits);
}
val += (c - start) << bits;
dbg_dec64("final val+=0x%08x", (int)((c - start) << bits));
dbg_dec64(" val:0x%08x", (unsigned)val);
while (bits != 0) {
c = a2i64(*src++);
if (c > 63)
goto fail;
bits -= 6;
val += c << bits;
dbg_dec64("low bits val+=0x%08x", (int)(c << bits));
dbg_dec64(" val:0x%08x", (unsigned)val);
}
ret:
*dst = val;
return src;
fail:
val = 0;
src = NULL;
goto ret;
}
#if TEST_DECODE64
static void test_decode64_uint32(void)
{
const uint8_t *src, *end;
uint32_t u32;
int a = 48;
int b = 8<<6; // 0x0200
int c = 4<<12; // 0x04000
int d = 2<<18; // 0x080000
int e = 1<<24; // 0x1000000
src = (void*)"wzzz";
end = decode64_uint32(&u32, src, 0);
if (u32 != 0x0003ffff+c+b+a) bb_error_msg_and_die("Incorrect decode '%s':0x%08x", src, (unsigned)u32);
if (end != src + 4) bb_error_msg_and_die("Incorrect decode '%s': %p end:%p", src, src, end);
src = (void*)"xzzz";
end = decode64_uint32(&u32, src, 0);
if (u32 != 0x0007ffff+c+b+a) bb_error_msg_and_die("Incorrect decode '%s':0x%08x", src, (unsigned)u32);
if (end != src + 4) bb_error_msg_and_die("Incorrect decode '%s': %p end:%p", src, src, end);
// Note how the last representable "x---" encoding, 0x7ffff, is exactly d-1!
// And if we now increment it, we get:
src = (void*)"y....";
end = decode64_uint32(&u32, src, 0);
if (u32 != 0x00000000+d+c+b+a) bb_error_msg_and_die("Incorrect decode '%s':0x%08x", src, (unsigned)u32);
if (end != src + 5) bb_error_msg_and_die("Incorrect decode '%s': %p end:%p", src, src, end);
src = (void*)"yzzzz";
end = decode64_uint32(&u32, src, 0);
if (u32 != 0x00ffffff+d+c+b+a) bb_error_msg_and_die("Incorrect decode '%s':0x%08x", src, (unsigned)u32);
if (end != src + 5) bb_error_msg_and_die("Incorrect decode '%s': %p end:%p", src, src, end);
src = (void*)"zzzzzz";
end = decode64_uint32(&u32, src, 0);
if (u32 != 0x3fffffff+e+d+c+b+a) bb_error_msg_and_die("Incorrect decode '%s':0x%08x", src, (unsigned)u32);
if (end != src + 6) bb_error_msg_and_die("Incorrect decode '%s': %p end:%p", src, src, end);
bb_error_msg("test_decode64_uint32() OK");
}
#else
# define test_decode64_uint32() ((void)0)
#endif
#endif /* !RESTRICTED_PARAMS */
#if 1
static const uint8_t *decode64(
uint8_t *dst, size_t *dstlen,
const uint8_t *src)
{
unsigned dstpos = 0;
dbg_dec64("src:'%s'", src);
for (;;) {
uint32_t c, value = 0;
int bits = 0;
while (*src != '\0' && *src != '$') {
c = a2i64(*src);
if (c > 63) { /* bad ascii64 char, stop decoding at it */
break;
}
src++;
value |= c << bits;
bits += 6;
if (bits == 24) /* got 4 chars */
goto store;
}
/* we read entire src, or met a non-ascii64 char (such as "$") */
if (bits == 0)
break;
/* else: we got last, partial bit block - store it */
store:
dbg_dec64(" storing bits:%d dstpos:%u v:%08x", bits, dstpos, (int)SWAP_BE32(value)); //BE to see lsb first
for (;;) {
if ((*src == '\0' || *src == '$')
&& value == 0 && bits < 8
) {
/* Example: mkpasswd PWD '$y$j9T$123':
* the "123" is bits:18 value:03,51,00
* is considered to be 2 bytes, not 3!
*
* '$y$j9T$zzz' in upstream fails outright (3rd byte isn't zero).
* IOW: for upstream, validity of salt depends on VALUE,
* not just size of salt. Which is a bug.
* The '$y$j9T$zzz.' salt is the same
* (it adds 6 zero msbits) but upstream works with it,
* thus '$y$j9T$zzz' should work too and give the same result.
*/
goto end;
}
if (dstpos >= *dstlen) {
dbg_dec64(" ERR: bits:%d dstpos:%u dst[] is too small", bits, dstpos);
goto fail;
}
*dst++ = value;
dstpos++;
value >>= 8;
bits -= 8;
if (bits <= 0) /* can get negative, if we e.g. had 6 bits */
break;
}
if (*src == '\0' || *src == '$')
break;
}
end:
*dstlen = dstpos;
dbg_dec64("dec64: OK, dst[%d]", (int)dstpos);
return src;
fail:
/* *dstlen = 0; - not needed, caller detects error by seeing NULL */
return NULL;
}
#else
/* Buggy (and larger) original code */
static const uint8_t *decode64(
uint8_t *dst, size_t *dstlen,
const uint8_t *src, size_t srclen)
{
size_t dstpos = 0;
while (dstpos <= *dstlen && srclen) {
uint32_t value = 0, bits = 0;
while (srclen--) {
uint32_t c = a2i64(*src);
if (c > 63) {
srclen = 0;
break;
}
src++;
value |= c << bits;
bits += 6;
if (bits >= 24)
break;
}
if (!bits)
break;
if (bits < 12) /* must have at least one full byte */
goto fail;
dbg_dec64(" storing bits:%d v:%08x", (int)bits, (int)SWAP_BE32(value)); //BE to see lsb first
while (dstpos++ < *dstlen) {
*dst++ = value;
value >>= 8;
bits -= 8;
if (bits < 8) { /* 2 or 4 */
if (value) /* must be 0 */
goto fail;
bits = 0;
break;
}
}
if (bits)
goto fail;
}
if (!srclen && dstpos <= *dstlen) {
*dstlen = dstpos;
dbg_dec64("dec64: OK, dst[%d]", (int)dstpos);
return src;
}
fail:
/* *dstlen = 0; - not needed, caller detects error by seeing NULL */
return NULL;
}
#endif
static char *encode64(
char *dst, size_t dstlen,
const uint8_t *src, size_t srclen)
{
while (srclen) {
uint32_t value = 0, b = 0;
do {
value |= (uint32_t)(*src++ << b);
b += 8;
srclen--;
} while (srclen && b < 24);
b >>= 3; /* number of bits to number of bytes */
b++; /* 1, 2 or 3 bytes will become 2, 3 or 4 ascii64 chars */
dstlen -= b;
if ((ssize_t)dstlen <= 0)
return NULL;
dst = num2str64_lsb_first(dst, value, b);
}
*dst = '\0';
return dst;
}
char *yescrypt_r(
const uint8_t *passwd, size_t passwdlen,
const uint8_t *setting,
char *buf, size_t buflen)
{
struct {
yescrypt_ctx_t yctx[1];
unsigned char hashbin32[32];
} u;
#define yctx u.yctx
#define hashbin32 u.hashbin32
char *dst;
const uint8_t *src, *saltend;
size_t need, prefixlen;
uint32_t u32;
test_decode64_uint32();
memset(yctx, 0, sizeof(yctx));
FULL_PARAMS(yctx->param.p = 1;)
/* we assume setting starts with "$y$" (caller must ensure this) */
src = setting + 3;
src = decode64_uint32(&yctx->param.flags, src, 0);
/* "j9T" returns: 0x2f */
//if (!src)
// goto fail;
if (yctx->param.flags < YESCRYPT_RW) {
dbg("yctx->param.flags=0x%x", (unsigned)yctx->param.flags);
goto fail; // bbox: we don't support scrypt - only yescrypt
} else if (yctx->param.flags <= YESCRYPT_RW + (YESCRYPT_RW_FLAVOR_MASK >> 2)) {
/* "j9T" sets flags to 0xb6 */
yctx->param.flags = YESCRYPT_RW + ((yctx->param.flags - YESCRYPT_RW) << 2);
dbg("yctx->param.flags=0x%x", (unsigned)yctx->param.flags);
dbg(" YESCRYPT_RW:%u", !!(yctx->param.flags & YESCRYPT_RW));
dbg((yctx->param.flags & YESCRYPT_RW_FLAVOR_MASK) ==
(YESCRYPT_ROUNDS_6 | YESCRYPT_GATHER_4 | YESCRYPT_SIMPLE_2 | YESCRYPT_SBOX_12K)
? " YESCRYPT_ROUNDS_6 | YESCRYPT_GATHER_4 | YESCRYPT_SIMPLE_2 | YESCRYPT_SBOX_12K"
: " flags are not standard"
);
} else {
goto fail;
}
src = decode64_uint32(&u32, src, 1);
if (/*!src ||*/ u32 > 63)
goto fail;
yctx->param.N = (uint64_t)1 << u32;
/* "j9T" sets to 4096 (1<<12) */
dbg("yctx->param.N=%llu (1<<%u)", (unsigned long long)yctx->param.N, (unsigned)u32);
src = decode64_uint32(&yctx->param.r, src, 1);
/* "j9T" sets to 32 */
dbg("yctx->param.r=%u", yctx->param.r);
if (!src)
goto fail;
if (*src != '$') {
#if RESTRICTED_PARAMS
goto fail;
#else
src = decode64_uint32(&u32, src, 1);
dbg("yescrypt has extended params:0x%x", (unsigned)u32);
if (u32 & 1)
src = decode64_uint32(&yctx->param.p, src, 2);
if (u32 & 2)
src = decode64_uint32(&yctx->param.t, src, 1);
if (u32 & 4)
src = decode64_uint32(&yctx->param.g, src, 1);
if (u32 & 8) {
src = decode64_uint32(&u32, src, 1);
if (/*!src ||*/ u32 > 63)
goto fail;
yctx->param.NROM = (uint64_t)1 << u32;
}
if (!src)
goto fail;
if (*src != '$')
goto fail;
#endif
}
yctx->saltlen = sizeof(yctx->salt);
src++; /* now points to salt */
saltend = decode64(yctx->salt, &yctx->saltlen, src);
if (!saltend || (*saltend != '\0' && *saltend != '$'))
goto fail; /* salt[] is too small, or bad char during decode */
dbg_dec64("salt is %d ascii64 chars -> %d bytes (in binary)", (int)(saltend - src), (int)yctx->saltlen);
prefixlen = saltend - setting;
need = prefixlen + 1 + YESCRYPT_HASH_LEN + 1;
if (need > buflen /*overflow is quite unlikely: || need < prefixlen*/)
goto fail;
if (yescrypt_kdf32(yctx, passwd, passwdlen, hashbin32)) {
dbg("error in yescrypt_kdf32");
goto fail;
}
dst = mempcpy(buf, setting, prefixlen);
*dst++ = '$';
dst = encode64(dst, buflen - (dst - buf), hashbin32, sizeof(hashbin32));
if (!dst)
goto fail;
ret:
free_region(yctx->local);
explicit_bzero(&u, sizeof(u));
return buf;
fail:
buf = NULL;
goto ret;
#undef yctx
#undef hashbin32
}
File diff suppressed because it is too large. Load diff
+247
View File
@@ -0,0 +1,247 @@
/*-
* Copyright 2009 Colin Percival
* Copyright 2013-2018 Alexander Peslyak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file was originally written by Colin Percival as part of the Tarsnap
* online backup system.
*/
// busybox debug and size-reduction configuration
#ifdef YESCRYPT_INTERNAL
# if 1
# define dbg(...) ((void)0)
# else
# define dbg(...) bb_error_msg(__VA_ARGS__)
# endif
# if 1
# define dbg_dec64(...) ((void)0)
# else
# define dbg_dec64(...) bb_error_msg(__VA_ARGS__)
# endif
# define TEST_DECODE64 0
#endif
// Only accept one-char parameters in salt, and only first three?
// Almost any reasonable yescrypt hashes in /etc/shadow should
// only ever use "jXY" parameters which set N and r.
// Fancy multi-byte-encoded wide integers are not needed for that.
#define RESTRICTED_PARAMS 1
// Note: if you enable the above, please also enable
// YCTX_param_p, YCTX_param_t, YCTX_param_g, YCTX_param_NROM
// optimizations, and DISABLE_NROM_CODE.
#define DISABLE_NROM_CODE 1
// How much we save by forcing "standard" value by commenting the next line:
// 160 bytes
//#define YCTX_param_flags yctx->param.flags
// 260 bytes
//#define flags___YESCRYPT_RW (flags & YESCRYPT_RW)
// 140 bytes
//#define flags___YESCRYPT_MODE_MASK (flags & YESCRYPT_MODE_MASK)
// ^^^^ forcing the above since the code already requires (checks for) this
// 50 bytes
#define YCTX_param_N yctx->param.N
// -100 bytes (negative!!!)
#define YCTX_param_r yctx->param.r
// 400 bytes
//#define YCTX_param_p yctx->param.p
// 130 bytes
//#define YCTX_param_t yctx->param.t
// 2 bytes
//#define YCTX_param_g yctx->param.g
// 1 bytes
// ^^^^ this looks wrong, compiler should be able to constant-propagate the fact that NROM code is dead
//#define YCTX_param_NROM yctx->param.NROM
#ifndef YCTX_param_flags
#define YCTX_param_flags (YESCRYPT_RW | YESCRYPT_ROUNDS_6 | YESCRYPT_GATHER_4 | YESCRYPT_SIMPLE_2 | YESCRYPT_SBOX_12K)
#endif
#ifndef flags___YESCRYPT_RW
#define flags___YESCRYPT_RW ((void)flags, YESCRYPT_RW)
#endif
#ifndef flags___YESCRYPT_MODE_MASK
#define flags___YESCRYPT_MODE_MASK ((void)flags, YESCRYPT_RW)
#endif
// standard ("j9T") values:
#ifndef YCTX_param_N
#define YCTX_param_N 4096
#endif
#ifndef YCTX_param_r
#define YCTX_param_r 32
#endif
#ifndef YCTX_param_p
#define YCTX_param_p 1
#endif
#ifndef YCTX_param_t
#define YCTX_param_t 0
#endif
#ifndef YCTX_param_g
#define YCTX_param_g 0
#endif
#ifndef YCTX_param_NROM
#define YCTX_param_NROM 0
#endif
// "Faster/smaller code" knobs:
// -941 bytes:
#define KDF_UNROLL_COPY 0
// -5324 bytes if 0:
#define KDF_UNROLL_PWXFORM_ROUND 0
// -4864 bytes if 0:
#define KDF_UNROLL_PWXFORM 0
// if both this ^^^^^^^^^^ and PWXFORM_ROUND set to 0: -7666 bytes
// -464 bytes:
#define KDF_UNROLL_SALSA20 0
/**
* Type and possible values for the flags argument of yescrypt_kdf(),
* yescrypt_encode_params_r(), yescrypt_encode_params(). Most of these may be
* OR'ed together, except that YESCRYPT_WORM stands on its own.
* Please refer to the description of yescrypt_kdf() below for the meaning of
* these flags.
*/
/* yescrypt flags:
* bits pos: 7654321076543210
* ss r w
* sbox gg y
*/
/* Public */
#define YESCRYPT_WORM 1
#define YESCRYPT_RW 0x002
#define YESCRYPT_ROUNDS_3 0x000 //r=0
#define YESCRYPT_ROUNDS_6 0x004 //r=1
#define YESCRYPT_GATHER_1 0x000 //gg=00
#define YESCRYPT_GATHER_2 0x008 //gg=01
#define YESCRYPT_GATHER_4 0x010 //gg=10
#define YESCRYPT_GATHER_8 0x018 //gg=11
#define YESCRYPT_SIMPLE_1 0x000 //ss=00
#define YESCRYPT_SIMPLE_2 0x020 //ss=01
#define YESCRYPT_SIMPLE_4 0x040 //ss=10
#define YESCRYPT_SIMPLE_8 0x060 //ss=11
#define YESCRYPT_SBOX_6K 0x000 //sbox=0000
#define YESCRYPT_SBOX_12K 0x080 //sbox=0001
#define YESCRYPT_SBOX_24K 0x100 //sbox=0010
#define YESCRYPT_SBOX_48K 0x180 //sbox=0011
#define YESCRYPT_SBOX_96K 0x200 //sbox=0100
#define YESCRYPT_SBOX_192K 0x280 //sbox=0101
#define YESCRYPT_SBOX_384K 0x300 //sbox=0110
#define YESCRYPT_SBOX_768K 0x380 //sbox=0111
#ifdef YESCRYPT_INTERNAL
/* Private */
#define YESCRYPT_MODE_MASK 0x003
#define YESCRYPT_RW_FLAVOR_MASK 0x3fc
#define YESCRYPT_ALLOC_ONLY 0x08000000
#define YESCRYPT_PREHASH 0x10000000
#endif
#define YESCRYPT_RW_DEFAULTS \
(YESCRYPT_RW | \
YESCRYPT_ROUNDS_6 | YESCRYPT_GATHER_4 | YESCRYPT_SIMPLE_2 | \
YESCRYPT_SBOX_12K)
#define YESCRYPT_DEFAULTS YESCRYPT_RW_DEFAULTS
#ifdef YESCRYPT_INTERNAL
#define YESCRYPT_KNOWN_FLAGS \
(YESCRYPT_MODE_MASK | YESCRYPT_RW_FLAVOR_MASK | \
YESCRYPT_ALLOC_ONLY | YESCRYPT_PREHASH)
#endif
/* How many chars base-64 encoded bytes require? */
#define YESCRYPT_BYTES2CHARS(bytes) ((((bytes) * 8) + 5) / 6)
/* The /etc/passwd-style hash is "<prefix>$<hash><NUL>" */
/*
* "$y$", up to 8 params of up to 6 chars each, '$', salt
* Alternatively, but that's smaller:
* "$7$", 3 params encoded as 1+5+5 chars, salt
*/
#define YESCRYPT_PREFIX_LEN (3 + 8 * 6 + 1 + YESCRYPT_BYTES2CHARS(32))
#define YESCRYPT_HASH_SIZE 32
#define YESCRYPT_HASH_LEN YESCRYPT_BYTES2CHARS(YESCRYPT_HASH_SIZE)
/**
* Internal type used by the memory allocator. Please do not use it directly.
* Use yescrypt_shared_t and yescrypt_local_t as appropriate instead, since
* they might differ from each other in a future version.
*/
typedef struct {
// void *base;
void *aligned;
// size_t base_size;
size_t aligned_size;
} yescrypt_region_t;
/**
* yescrypt parameters combined into one struct. N, r, p are the same as in
* classic scrypt, except that the meaning of p changes when YESCRYPT_RW is
* set. flags, t, g, NROM are special to yescrypt.
*/
typedef struct {
uint32_t flags;
uint32_t r;
uint64_t N;
#if !RESTRICTED_PARAMS
uint32_t p, t, g;
uint64_t NROM;
#endif
} yescrypt_params_t;
typedef struct {
yescrypt_params_t param;
/* salt in binary form */
/* stored here to cut down on the amount of function paramaters */
unsigned char salt[64];
size_t saltlen;
/* used by the memory allocator */
//yescrypt_region_t shared[1];
yescrypt_region_t local[1];
} yescrypt_ctx_t;
/**
* yescrypt_r(shared, local, passwd, passwdlen, setting, key, buf, buflen):
* Compute and encode an scrypt or enhanced scrypt hash of passwd given the
* parameters and salt value encoded in setting. If shared is not NULL, a ROM
* is used and YESCRYPT_RW is required. Otherwise, whether to compute classic
* scrypt, YESCRYPT_WORM (a slight deviation from classic scrypt), or
* YESCRYPT_RW (time-memory tradeoff discouraging modification) is determined
* by the setting string. shared (if not NULL) and local must be initialized
* as described above for yescrypt_kdf(). buf must be large enough (as
* indicated by buflen) to hold the encoded hash string.
*
* Return the encoded hash string on success; or NULL on error.
*
* MT-safe as long as local and buf are local to the thread.
*/
extern char *yescrypt_r(
const uint8_t *passwd, size_t passwdlen,
const uint8_t *setting,
char *buf, size_t buflen
);
+16
View File
@@ -0,0 +1,16 @@
/*
* The compilation unit for yescrypt-related code.
*
* Copyright (C) 2025 by Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_USE_BB_CRYPT_YES) += y.o
#include "libbb.h"
#define YESCRYPT_INTERNAL
#include "alg-yescrypt.h"
#include "alg-sha256.c"
#include "alg-yescrypt-kdf.c"
#include "alg-yescrypt-common.c"
Loaded 100 of 324 files, more files were not shown because too many files have changed in this diff. Show more