Compare commits

...
625 Commits
Author SHA1 Message Date
Denys Vlasenko 6412da255d libbb: fix ioloop's limitation of fd < 1024
function                                             old     new   delta
grow_fdsets                                            -      90     +90
ioloop_run                                           438     485     +47
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/0 up/down: 137/0)             Total: 137 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-17 18:23:08 +01:00
Denys Vlasenko 25a61f0feb shell: in math evaluation, use malloc, not alloca
function                                             old     new   delta
evaluate_string                                     1315    1322      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-17 14:44:30 +01:00
Denys Vlasenko d724d7d292 mkfs.vfat: fix creation of 2.5 kbyte FAT12 image
function                                             old     new   delta
mkfs_vfat_main                                      2463    2454      -9
.rodata                                           105036  105007     -29
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-38)             Total: -38 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-16 13:56:51 +01:00
Denys Vlasenko 8d79a6335c mkfs.vfat: fix write buffer allocation for tiny images
function                                             old     new   delta
mkfs_vfat_main                                      2460    2463      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-15 23:06:39 +01:00
Denys Vlasenko 3441a0e4bc mkfs.vfat: add ignored option -a ("disable alignment")
function                                             old     new   delta
.rodata                                           105038  105036      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-15 22:44:24 +01:00
Denys Vlasenko f8f567fb54 mkfs.vfat: implement creation of FAT12/16 filesystems
function                                             old     new   delta
mkfs_vfat_main                                      1858    2460    +602
.rodata                                           105028  105038     +10
packed_usage                                       36569   36575      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 618/0)             Total: 618 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-15 19:18:08 +01:00
Denys Vlasenko 7b38885adf mkfs.vfat: code shrink
function                                             old     new   delta
mkfs_vfat_main                                      1874    1858     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-14 20:04:56 +01:00
Denys Vlasenko 174ee36441 mkfs.vfat: code chrink, prepare for FAT16/12 support
function                                             old     new   delta
mkfs_vfat_main                                      1880    1874      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-14 16:14:12 +01:00
Denys Vlasenko cb53a88831 testsuite: modify 130GB mkfs.vfat test to actually have the very max cluster#
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-14 00:23:59 +01:00
Denys Vlasenko fb32719cb2 testsuite: add 130GB mkfs.vfat test
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 17:30:02 +01:00
Denys Vlasenko d3303c327e mkfs.vfat: add -s SECTORS_PER_CLUSTER
function                                             old     new   delta
mkfs_vfat_main                                      1800    1880     +80
.rodata                                           105000  105028     +28
packed_usage                                       36552   36549      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 108/-3)            Total: 105 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 16:55:59 +01:00
Denys Vlasenko 9f435d8347 mkfs.vfat: if -C, avoid unnecessary zero-filling of newly-created image file
This can save hundreds of megabytes for a QEMU-operated virtual FAT32 disk.

function                                             old     new   delta
mkfs_vfat_main                                      1766    1800     +34
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 34/0)               Total: 34 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 15:09:33 +01:00
Denys Vlasenko 484da7a2b3 mkfs.vfat: add support for -S SECTOR_SIZE
mkfs.vfat -v -F32 -S4096 -C IMAGE_16TB $((1024*1024*1024*16 - 0x10000))
tested to work.

function                                             old     new   delta
mkfs_vfat_main                                      1613    1686     +73
packed_usage                                       36498   36552     +54
.rodata                                           104988  105000     +12
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 139/0)             Total: 139 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 14:49:44 +01:00
Denys Vlasenko d99c769ce3 mkfs.vfat: make -n "NO NAME " create the volume label as requested.
"NO NAME    " has special meaning _only_ in boot sector, not in rootdir's label.

function                                             old     new   delta
mkfs_vfat_main                                      1621    1613      -8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-13 13:53:13 +01:00
Denys Vlasenko c743bd3a9d libbb: if get_volume_size_in_bytes() detects too-small block device, warn about it
The "mkfs.vfar BLOCKDEV 1000000" case where BLOCKDEV is smaller.

function                                             old     new   delta
.rodata                                           104938  104988     +50
get_volume_size_in_bytes                             262     293     +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>
2026-11-13 13:44:25 +01:00
Denys Vlasenko 8eea53bb7a libbb: introduce and use xfstat_mode() and xfstat_size()
function                                             old     new   delta
xfstat_size                                            -      28     +28
add_remove_shell_main                                312     302     -10
mkfs_ext2_main                                      2299    2285     -14
mesg_main                                            157     136     -21
ar_main                                              565     527     -38
ubi_tools_main                                      1164    1125     -39
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/5 up/down: 28/-122)           Total: -94 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 16:40:57 +01:00
Denys Vlasenko 10c9c7faec mkfs.vfat: code shrink
function                                             old     new   delta
xfstat_mode                                            -      26     +26
mkfs_vfat_main                                      2106    1621    -485
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/1 up/down: 26/-485)          Total: -459 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 16:05:41 +01:00
Denys Vlasenko e18ddc4ad3 mkfs.vfat: print how many sectors we ignore on large volumes
It's quite useful to know whether you lose 123 sectors, or 123 gigabytes.

function                                             old     new   delta
mkfs_vfat_main                                      2096    2106     +10
.rodata                                           104951  104938     -13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 10/-13)             Total: -3 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 16:04:41 +01:00
Denys Vlasenko 67a351f7c0 mkfs.vfat: code shrink, tweak comments
function                                             old     new   delta
mkfs_vfat_main                                      2102    2096      -6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 12:33:16 +01:00
Denys Vlasenko 7de358fa8e mkfs.vfat: explain big filesystem sizes with 32 sectors/cluster, no code changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 11:11:29 +01:00
Denys Vlasenko 3e4beef20c mkfs.vfat: support -b N -R N - allows creation of tiny 3KB FAT32 image
function                                             old     new   delta
mkfs_vfat_main                                      1586    2102    +516
.rodata                                           104913  104951     +38
packed_usage                                       36467   36498     +31
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 585/0)             Total: 585 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-12 10:48:49 +01:00
Denys Vlasenko 4f986c0f9d mkfs.vfat: make it possible to create tiny 5KB images
function                                             old     new   delta
mkfs_vfat_main                                      1539    1586     +47
mkswap_main                                          253     256      +3
mkfs_minix_main                                     2575    2578      +3
mkfs_ext2_main                                      2297    2299      +2
.rodata                                           104946  104913     -33
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/1 up/down: 55/-33)             Total: 22 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 18:19:26 +01:00
Denys Vlasenko d03387ebf3 mkfs.vfat: correctly handle huge images with total sectors above 2^32
function                                             old     new   delta
.rodata                                           104897  104946     +49
mkfs_vfat_main                                      1526    1539     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 62/0)               Total: 62 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 16:21:24 +01:00
Denys Vlasenko 292ec317a3 mkfs.ext2: fix "can't open '(null)': Bad address"
function                                             old     new   delta
.rodata                                           104893  104897      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 14:32:38 +01:00
Denys Vlasenko f227dc2eb7 mkfs.vfat: implement -C
function                                             old     new   delta
packed_usage                                       36438   36467     +29
mkfs_vfat_main                                      1518    1526      +8
.rodata                                           104894  104893      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 37/-1)              Total: 36 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 14:29:07 +01:00
Denys Vlasenko a096845640 testsuite: add mkfs.vfat and blkid tests
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 11:46:15 +01:00
Denys Vlasenko 6a839afdee volume_id/fat: follow kernel example in deciding what is FAT32
This will allow detection of small FAT32 volumes which
are mountable by kernel - before this change we misdetected them,
and likely failed to fetch volume label.

While at it, avoid running off FAT if FAT is smaller than necessary
to cover entire data area, and rootdir has clusters beyond this
"shorter FAT". (This matches kernel behavior too)

function                                             old     new   delta
volume_id_probe_vfat                                 856     886     +30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 03:25:03 +01:00
Denys Vlasenko bd8c4f7ce9 volume_id/fat: decrease maximum valid FAT table size to 0x02000000 sectors
It's still enormous (16GByte FAT tables). Real-world maximum
is 16 times smaller since cluster numbers are 28-bit.

function                                             old     new   delta
volume_id_probe_vfat                                 867     856     -11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-10 00:43:35 +01:00
Denys Vlasenko 8015168a75 Share "NO NAME " string
function                                             old     new   delta
bb_NO_NAME_11                                          -      12     +12
static.NO_NAME_11                                     12       -     -12
.rodata                                           104906  104894     -12
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 12/-24)            Total: -12 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-09 23:43:17 +01:00
Denys Vlasenko d04e804bee volume_id/fat: in root dir scan, stop at first cluster# larger than FAT size
Otherwise, we can read non-FAT area and try to interpret it as FAT.

function                                             old     new   delta
volume_id_probe_vfat                                 851     867     +16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-09 12:50:07 +01:00
Denys Vlasenko 0c1060dee1 volume_id/fat: add validity checks for FAT12/16 (rootdir can't have 0 sectors)
function                                             old     new   delta
volume_id_probe_vfat                                 815     852     +37
mkfs_vfat_main                                      1523    1518      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 37/-5)              Total: 32 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-09 12:37:21 +01:00
Denys Vlasenko 484e887ce6 volume_id/fat: avoid rereading of 1st sector - use it when we have it initially
function                                             old     new   delta
volume_id_probe_vfat                                 856     815     -41

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 21:13:58 +01:00
Denys Vlasenko 0338bee40e volume_id/fat: allow FAT partitions with one FAT, tighten some validity checks
function                                             old     new   delta
volume_id_probe_vfat                                 829     856     +27

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 20:54:48 +01:00
Denys Vlasenko 7584233f64 volume_id/fat: remove test for non-zero head count in FAT superblock probe.
From util-linux:

    This change enables the auto-detection of the internal storage on a VTech
    Kidizoom camera, which has a zero head count value in the superblock.

    Microsoft documentation, "FAT: General Overview of On-Disk Format", states
    that the sectors and heads fields are only relevant for media that have
    a geometry.

    The Linux kernel also does not require a non-zero head count, and can
    manually mount the filesystem.

function                                             old     new   delta
volume_id_probe_vfat                                 841     829     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 19:20:57 +01:00
Denys Vlasenko b7c89c493a volume_id/fat: prevent possible division by zero and crash
function                                             old     new   delta
volume_id_probe_vfat                                 830     841     +11

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 18:25:22 +01:00
Dominique Martinet d68f55fc29 tunctl: fix segfault on ioctl failure
libbb now takes "" instead of NULL as format string for nomsg functions,
but this caller had not been updated making busybox segfault on tunctl
commands when ioctl fails.
This can be reproduced by running `tunctl -t tun0` in gdb and blocking
with the tun open after being created, and running `tunctl -d tun0` in
another shell: the later will fail with EBUSY after fixing:
> tunctl: Device or resource busy

function                                             old     new   delta
tunctl_main                                          393     409     +16

Fixes: 4bd70463c7 ("libbb: pass "" rather than NULL as format string in _nomsg functions")
Signed-off-by: Dominique Martinet <dominique.martinet@atmark-techno.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 17:24:12 +01:00
Denys Vlasenko 17080dd399 shell/math: speed up handling of short arithmetic expansions
function                                             old     new   delta
evaluate_string                                     1291    1315     +24

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 16:31:12 +01:00
Denys Vlasenko d03670c64e mount: remove support for "swap" and "sw" mount options, they were added by mistake
Review of git log shows that they were mistakenly added during a rewrite
(confused with *FS type string* "swap" used in fstab to specify swap partitions).
util-linux's mount does not support this.
There is no reason to keep this incompatible extension.

function                                             old     new   delta
mount_main                                          1250    1249      -1
mount_options                                        188     180      -8
mount_option_str                                     385     377      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-17)             Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 13:17:40 +01:00
Denys Vlasenko 604470bec4 mount: disallow -o OPTS, -T ALT_FSTAB, -a,r,w,n,f,i for non-root mount invocations
function                                             old     new   delta
mount_main                                          1259    1250      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-9)               Total: -9 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-08 03:05:09 +01:00
Denys Vlasenko c64ffa2e2b nsloopup: tighten up length checks to avoid out-of-bounds reads
function                                             old     new   delta
parse_reply                                          979    1030     +51

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 20:30:35 +01:00
Denys Vlasenko 5450a8ed71 rpm: bail out if headers have abnormally large entry counts
function                                             old     new   delta
.rodata                                           104880  104906     +26
rpm_gettags                                          419     443     +24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 50/0)               Total: 50 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 20:02:28 +01:00
Denys Vlasenko f3ca54f688 tftp: add commented-out code with non-ISREG check
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 16:14:03 +01:00
Denys Vlasenko 56e9d36bb6 udhcpc[6]: check minimum packet size after reducing it to ip.tot_len
For DHCPv6, also require that all fields up until option array exist in the packet.
I did not find a definitive info that DHCPv6 requires at least one option
to be present, and the code appears to handle empty option array correctly.

function                                             old     new   delta
d6_recv_raw_packet                                   228     230      +2
d4_recv_raw_packet                                   500     501      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 3/0)                 Total: 3 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-07 14:05:35 +01:00
Denys Vlasenko b67f7b7d14 tftpd: make DIR argiment work for non-root too, strip leading /
function                                             old     new   delta
tftpd_main                                           573     589     +16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 20:33:51 +01:00
Denys Vlasenko 7022247743 tftp(d): code shrink by not having two copies of option value
function                                             old     new   delta
tftp_protocol                                       1985    1938     -47

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 19:01:51 +01:00
Denys Vlasenko 1d363c609f tftpd: code shrink
function                                             old     new   delta
tftp_get_option                                      102      93      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 18:09:10 +01:00
Denys Vlasenko 11edcd9eb0 tftpd: comment tweak
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 16:56:02 +01:00
Denys Vlasenko 1a80c25d30 tftpd: increase minimum supported block size to approx. 64
function                                             old     new   delta
tftp_protocol                                       2001    1985     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 16:43:33 +01:00
Denys Vlasenko 8650079721 tftpd: improve sanitization of remote strings in error messages
function                                             old     new   delta
tftp_blksize_check                                    57      64      +7
tftp_protocol                                       2009    2001      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 7/-8)               Total: -1 bytes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 16:18:47 +01:00
Michael Pfeifroth 2d6925708e awk: fix mktime() for dates beyond 2038
do_mktime() returned the result of mktime() as int. Since int is
32 bits wide even on LP64 systems, any time at or after
2038-01-19 03:14:08 UTC was truncated, even with a 64-bit time_t:

  $ TZ=UTC busybox awk 'BEGIN { printf "%.0f\n", mktime("2038 01 19 03 14 08") }'
  -2147483648

Return time_t instead and add a testcase.

function                                             old     new   delta
exec_builtin                                        1130    1136      +6
do_mktime                                            119     121      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 8/0)                 Total: 8 bytes

Signed-off-by: Michael Pfeifroth <micpf@westermo.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-06 15:33:22 +01:00
Denys Vlasenko 3a381903ce lzop: comment out unused variables
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-05 11:02:54 +01:00
Denys Vlasenko 7e4137b6bd init: set RC_REBOOT=YES if shutdown actions are running for reboot (not shutdown)
function                                             old     new   delta
.rodata                                           104866  104880     +14
check_delayed_sigs                                   341     354     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 27/0)               Total: 27 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-11-05 10:57:54 +01:00
Denys Vlasenko 5eee8017a8 ash: do not read past the text of an unset MAIL
Patch by Florian Schmaus <florian.schmaus@codasip.com>:

ash stores each variable as a single "NAME=value" string in var_text,
and accessor macros like mailval() simply skip over the "NAME=" prefix
(var_text + 5). Per the comment above them, they return the null
string for unset variables. That only works if an unset variable's
text still has a NUL where the value would start.

MAIL and MAILPATH are unset by default, and their initial texts are
"MAIL" and "MAILPATH". For "MAIL" (5 bytes including the NUL)
mailval() therefore points one byte past the end of the string. When
MAILPATH is not set, chkmail() falls back to mailval() and hands that
pointer to padvance_magic(), which parses the memory following "MAIL"
as a colon-separated list of mail files. This happens before every
interactive prompt, unless the user sets MAIL or MAILPATH.

What gets read there depends on the binary layout. In an x86_64
defconfig build "MAIL" is directly followed by "MAILPATH", so ash
stat()s ./MAILPATH before every prompt and prints "you have mail"
when a file of that name in the current directory changes. This
stat() of ./MAILPATH was already noticed in 2016 [1], and the
overread itself was recently reported after fuzzing ash with
AddressSanitizer [2].

The texts used to be "MAIL\0" and "MAILPATH\0", as they still are in
dash. Commit 8837c5dec4 ("ash: remove one redundant function,
improve string sharing, better field names") dropped the extra NUL
from all unset-by-default variables, so the literals become plain
strings the compiler can put in mergeable string sections. That is
fine for RANDOM, LC_ALL, LC_CTYPE and HISTFILE, whose values are only
read through lookupvar(), which checks VUNSET. But mailval() is
used without such a check.

Fix the out-of-bounds read by restoring the trailing NULs for MAIL
and MAILPATH, so that mailval() and mpathval() again yield "" for an
unset variable. This matches setvar(), which already allocates a
zeroed buffer of name length + 2 when unsetting a variable at
runtime. MAILPATH is not strictly affected, since mpathval() is only
used after mpathset(), but this keeps both accessors consistent.
Neither literal is shared with any other string, so the cost is two
bytes of .rodata:

function                                             old     new   delta
.rodata                                           102098  102100      +2

We ran into this on a CHERI [3, 4] system. CHERI's architectural
capabilities bound each memory region precisely, so it catches
out-of-bounds accesses that MMU-based protection misses. Here the
one-byte overread of the "MAIL" string literal is a capability length
violation, and every interactive ash dies with SIGSEGV on start-up.

1: https://github.com/gliderlabs/docker-alpine/issues/163
2: https://github.com/vda-linux/busybox_mirror/issues/47
3: https://www.cl.cam.ac.uk/research/security/ctsrd/cheri/
4: https://codasip.com/solutions/riscv-processor-safety-security/cheri/

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-22 07:31:22 +02:00
Denys Vlasenko 87e54246b6 swapon/off: revert the non-portable change made in 2014: use setmntent, not fopen
function                                             old     new   delta
swap_on_off_main                                     449     474     +25

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-22 06:36:05 +02:00
Denys Vlasenko daf8ec40e0 mount: allow longer /proc/mounts lines
Based on patch by Natanael Copa <ncopa@alpinelinux.org>:

Use a bigger buffer for getmntent_r so we can handle entries
with lines longer that 504 chars.

This solves issue when running `mount -o remount,rw ...` in a docker
container on Fedora 43.

ref: https://github.com/k0sproject/k0s/issues/6774
ref: https://lists.busybox.net/pipermail/busybox/2025-December/091859.html

function                                             old     new   delta
mount_main                                          1219    1259     +40
singlemount                                         1315    1323      +8
verbose_mount                                         94      96      +2
mount_it_now                                         358     359      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 51/0)               Total: 51 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 18:44:01 +02:00
Denys Vlasenko 38e2124b32 examples/var_service/dhcp_if/: improve selection of implied router
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 18:17:22 +02:00
Denys Vlasenko e58cb22366 volume_id: code shrink
function                                             old     new   delta
resolve_mount_spec                                    87     158     +71
mount_main                                          1211    1219      +8
fsck_device                                          453     451      -2
findfs_main                                           76      74      -2
blkid_main                                            41      39      -2
display_uuid_cache                                   109     105      -4
get_devname_from_uuid                                 56       -     -56
get_devname_from_label                                62       -     -62
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 2/4 up/down: 79/-128)           Total: -49 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 16:55:01 +02:00
Denys Vlasenko bad78f5e96 fsck: code shrink, improve code comments on resolve_mount_spec() alloc
function                                             old     new   delta
create_fs_device                                     155     140     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 16:31:49 +02:00
Natanael Copa 6fb8efcd6c fsck: resolve LABEL=.../UUID=... spec to device
function                                             old     new   delta
fsck_device                                          433     453     +20

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-18 15:34:07 +02:00
Sören Tempel 9d961aff6f Install lsblk to /bin instead of /usr/bin
On Alpine, the util-linux lsblk utility is installed in /bin and
since BusyBox only gained support for that applet recently, we
should make sure to install it to the same location.

Otherwise, the BusyBox symlink is not overwritten by the lsblk pkg.

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:35:36 +02:00
Natanael Copa 531d9db7b4 app location for cpio, vi and lspci
Adjust location to where alpine linux installs them

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Sören Tempel ec9036610f nologin: Install applet to /sbin instead of /usr/sbin
This is required to retain compatibility with our old custom nologin
applet written in C which was also installed to /sbin.

Compatibility with the old path is required because login shell paths
are hardcoded in /etc/passwd.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Sören Tempel 2e57f66cba adduser: default to /sbin/nologin as shell for system accounts
Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Lauri Tirkkonen 30a8277fa0 blkdiscard: ship link to /sbin instead of /usr/bin
util-linux ships blkdiscard in /sbin, so follow what it does.

Link: https://git.kernel.org/pub/scm/utils/util-linux/util-linux.git/tree/sys-utils/Makemodule.am?id=5a75fb2b9e384c61a4b2afd13fe9bba219d5bd93#n194
Signed-off-by: Lauri Tirkkonen <lauri@hacktheplanet.fi>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 12:34:42 +02:00
Denys Vlasenko 45ad4ce552 tests: fix tarball creation
Without this patch, the chmod 644 invocation takes away the executable
bit from the input_dir directory, thus preventing the chmod of the files
within the input_dir directory (due to lack of x-bit).

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-12 00:00:55 +02:00
Sören Tempel de40fe3350 tests: musl doesn't seem to recognize UTC0 as a timezone
UTC works though.

TODO: Figure out if musl /should/ regonize UTC0.

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:51:14 +02:00
Natanael Copa b58d7e51b0 Add flag for not following symlinks when recursing
function                                             old     new   delta
.rodata                                             7934    7967     +33
diff_longopts                                        253     270     +17
packed_usage                                        1704    1720     +16
diff_main                                           1665    1662      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 66/-3)              Total: 63 bytes

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:46:42 +02:00
Sören Tempel 97e373643d hexdump: skip additional hexdump test on big-endian systems
This one fails on s390x.

Signed-off-by: Sören Tempel <soeren+git@soeren-tempel.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:39:01 +02:00
Natanael Copa 7476cd280d 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)

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:36:27 +02:00
Natanael Copa b9f5de0352 wget: add header Accept: */*
Some servers (like https://netfilter.org) returns failure if the Accept
header is missing. Both GNU wget and curl adds this header, so make
busybox do the same.

fixes: https://bugs.busybox.net/show_bug.cgi?id=15982

function                                             old     new   delta
wget_main                                           3120    3144     +24
.rodata                                            79296   79310     +14
wget_user_headers                                     76      84      +8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 46/0)               Total: 46 bytes
   text	   data	    bss	    dec	    hex	filename
 825278	  14260	   2008	 841546	  cd74a	busybox_old
 825324	  14260	   2008	 841592	  cd778	busybox_unstripped

Signed-off-by: Natanael Copa <ncopa@alpinelinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:36:27 +02:00
Denys Vlasenko f0e5be9fbc awk: fix handling of literal backslashes in replacement
Follow actual gawk behavior.
    https://www.gnu.org/software/gawk/manual/html_node/Gory-Details.html
Erm... wait. Follow *actual* gawk behavior - as seen in testing,
because even Gory-Details.html do not tell the whole awful truth.

function                                             old     new   delta
awk_sub                                              550     658    +108

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 23:15:35 +02:00
Denys Vlasenko 538499b65a ash,hush: fix read builtin versus already-handled signal
function                                             old     new   delta
builtin_read                                         178     205     +27
shell_builtin_read                                  1340    1350     +10
pgetc                                                623     633     +10
dotrap                                               157     164      +7
check_and_run_traps                                  278     285      +7
readcmd                                              227     222      -5
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 5/1 up/down: 61/-5)              Total: 56 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 18:17:43 +02:00
Denys Vlasenko fcdc004c5c ash: docunebt that "timed out waiting for input" goes to stdout
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 16:05:24 +02:00
Denys Vlasenko 049ae38950 ash,hush: print sugnal-related "beautification" (^C etc) to stderr, not stdout
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:54:21 +02:00
Denys Vlasenko 1c7e871e0a less: accept/ignore -T TAGFILE
Patch by Sören Tempel <soeren@soeren-tempel.net>

This option is passed by mandoc(1), while we don't implement the
actual functionality here, this patch allows using tagfile support
with mandoc(1) when a more feature-full less(1) implementation is
installed.

Otherwise, we would have to detect support for -T option in the
pager at run-time in mandoc(1), which would occur run-time costs.
Note that other option (-s and -X) are already ignored by BusyBox
less(1), so this seems like a good solution for mandoc(1) compat.

function                                             old     new   delta
less_main                                           2062    2064      +2
.rodata                                           104845  104847      +2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:52:33 +02:00
Denys Vlasenko 8d4ac0d17b udhcpc: code shrink by reusing "deconfig" code path
function                                             old     new   delta
udhcpc_main                                         2544    2501     -43

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:52:33 +02:00
Denys Vlasenko 15e0ea385d udhcpc6: code shrink by reusing "deconfig" code path
function                                             old     new   delta
udhcpc6_main                                        2772    2651    -121

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 15:52:33 +02:00
Jake Buchholz Göktürk a65bea40f4 udhcpc6: restart acquisition after a zero valid lifetime
A Reply with a zero valid lifetime revokes an address or delegated
prefix. The current client instead applies its minimum lease time and
keeps renewing the revoked lease. When both IA_NA and IA_PD are requested,
the zero can also be replaced by the other IA's nonzero lifetime.

Check the lifetimes of requested IAs before combining or clamping them.
On zero, run deconfig and return to INIT_SELECTING. Clear the requested
address hint, remaining lease, elapsed time and packet counter. Use the
same three-second delay as the existing DHCPv6 NAK recovery path to avoid
repeatedly soliciting an unusable lease. Deconfiguration happens
immediately; the delay applies only to restarting acquisition. This is
an existing implementation convention, not an RFC requirement. Do not
report bound or renew, or honor quit-after-lease, for an unusable lease.

Use option_mask32, which includes the default address request and the
-r no/-l overrides. A zero preferred lifetime with a positive valid
lifetime remains accepted. Stateful address and prefix acquisition
still share one client state: revoking either restarts both.

This addresses the existing zero-lease TODO. It does not implement
independent IA renewal or processing of multiple leases per IA.
Existing partial-Reply handling is unchanged: if a requested companion
IA is missing, the Reply is ignored before this revocation check.

Tested on aarch64: address and prefix revocation, combined leases with
one or both lifetimes zero, replacement acquisition and renewal,
zero first Reply, persistent zero Replies, quit-after-lease, deprecated
addresses, and stateless Information-request. The unpatched baseline
continues renewing revoked state.

Native aarch64, GCC 15.2.0, Alpine configuration; relative to
the preceding patch in this series. Data and BSS are unchanged.

bloat-o-meter:
function                                             old     new   delta
udhcpc6_main                                        3024    3120     +96
.rodata                                            69449   69484     +35
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 131/0)             Total: 131 bytes

Signed-off-by: Jake Buchholz Göktürk <tomalok@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 03:08:34 +02:00
Jake Buchholz Göktürk 57c5bba044 udhcpc6: send proper Rebind messages
The REBINDING state uses the Renew packet builder, so its multicast
fallback sends another Renew containing the original server ID. It
cannot ask a different server to extend the lease.

Reuse the existing builder for both message types. Send D6_MSG_REBIND
without a server ID in REBINDING, preserving the client options and
IA_NA/IA_PD contents. Start a new transaction and reset elapsed time
when entering that state; retransmissions retain the transaction ID.
This follows RFC 9915 section 18.2.5 and resolves the TODO in the
REBINDING state asking whether send_d6_renew() should use D6_MSG_REBIND
instead of D6_MSG_RENEW.

Keep the renewal schedule, retry limits, and multicast option behavior
unchanged.

Tested on aarch64 with Alpine's configuration: initial acquisition and
Renew, server failover with IA_NA, IA_PD, and both, Rebind retransmissions,
and stateless Information-request. The unpatched tree loses its lease
in the same failover test. Packet captures verify the message type,
options, transaction ID, and elapsed time.

Native aarch64, GCC 15.2.0, Alpine configuration; relative to
the preceding patch in this series. Data and BSS are unchanged.

bloat-o-meter:
function                                             old     new   delta
static.send_d6_renew                                 208     256     +48
udhcpc6_main                                        3000    3024     +24
.rodata                                            69447   69449      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 74/0)               Total: 74 bytes

Signed-off-by: Jake Buchholz Göktürk <tomalok@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 02:41:42 +02:00
Jake Buchholz Göktürk 89032255bb udhcp: export IPv6 preferred_lifetime to the script
Export the DHCPv6 preferred address lifetime alongside the existing
valid lifetime in lease.

function                                             old     new   delta
option_to_env                                        711     739     +28
.rodata                                           104781  104808     +27
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 55/0)               Total: 55 bytes

Signed-off-by: Jake Buchholz Göktürk <tomalok@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-11 02:36:32 +02:00
Ron Yorston 5e57539acb test: fix POSIX -nt and -ot when "older" is missing
These should evaluate true if the newer file exists and the older is
missing or older, but it was never true if older is missing.

Note: 'test X -nt Y' is identical to 'test Y -ot X'

  https://pubs.opengroup.org/onlinepubs/9799919799/utilities/test.html

function                                             old     new   delta
binop                                                593     634     +41
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 41/0)               Total: 41 bytes

Signed-off-by: Avi Halachmi (:avih) <avihpit@yahoo.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-10 18:29:56 +02:00
Ron Yorston aeaa7f547c ash: PSSYNTAX: preserve \\ in addition to \$
'\\t' in PS1 was incorrectly displayed as a timestamp instead of
the intended '\t' because '\\' was not preserved.

function                                             old     new   delta
readtoken1                                          3072    3079      +7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 7/0)                 Total: 7 bytes

Signed-off-by: Avi Halachmi (:avih) <avihpit@yahoo.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-10 18:28:51 +02:00
Denys Vlasenko 32653c392c libarchive: comment tweak
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 16:56:50 +02:00
Denys Vlasenko 382008b3f0 tar: protect against Symlink+Hardlink attack
function                                             old     new   delta
create_links_from_list                                93     190     +97

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 16:45:23 +02:00
Denys Vlasenko 5da20102b5 tar: ".." is also an unsafe filename, treat as such
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 15:09:26 +02:00
Denys Vlasenko a040aa2826 ash: follow bash in allowing multiple !s: "! ! CMD" is the same as "CMD"
function                                             old     new   delta
pipeline                                             167     165      -2

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 13:36:11 +02:00
Denys Vlasenko 4a9fe5a0c2 ash: fix !BASH_COMPAT build, tweak variable names, add comments
The work to improve "wait -n" is based on patches by
    Luiz Angelo Daros de Luca <luizluca@gmail.com>
and
    Dominique Martinet <dominique.martinet@atmark-techno.com>

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-09 12:26:51 +02:00
Denys Vlasenko e3e1ad1587 ash: fix "wait -n PID %JOBSPEC" behavior
function                                             old     new   delta
dowait_n                                               -     565    +565
waitcmd                                              346     569    +223
getjob_match_last_pid                                  -      29     +29
waitforjob                                           100     103      +3
showjobs                                              56      59      +3
dowait                                               557       -    -557
------------------------------------------------------------------------------
(add/remove: 2/1 grow/shrink: 3/0 up/down: 823/-557)          Total: 266 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-07 23:45:35 +02:00
Denys Vlasenko 30f2f883bd ash: fix "wait -n" behavior wrt already-exited jobs
function                                             old     new   delta
waitcmd                                              318     346     +28
kill_main                                            907     919     +12
dowait                                               553     557      +4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 44/0)               Total: 44 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-07 11:15:37 +02:00
Denys Vlasenko 730f515626 ash: fix !ASH_BASH_COMPAT build
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-07 00:13:59 +02:00
Denys Vlasenko b829bba950 httpd: do not try to use obviously bogus password from /etc/passwd
If password is 'x' or '*' and yet, /etc/shadow has no entry,
do not run the crypt machinery - go to the next entry.

function                                             old     new   delta
check_user_passwd                                    444     462     +18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-06 00:00:32 +02:00
Ron Yorston f15a204bb2 xxd: '-p -c 0' outputs a single line
vim's xxd allows the combination of options '-p -c 0' to output
a single line of text [1].  A use case is handling cryptographic
material [2].

Add this feature to BusyBox xxd.

[1] https://github.com/vim/vim/pull/9524
[2] https://stackoverflow.com/questions/42192490/aes-cbc-incorrect-usage

function                                             old     new   delta
xxd_main                                            1496    1526     +30
packed_usage                                       35515   35511      -4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 30/-4)              Total: 26 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 21:18:44 +02:00
Denys Vlasenko db7dfff800 ash: make "wait -n" pick up last job, if there is no running processes
This is bash compat

function                                             old     new   delta
waitcmd                                              281     318     +37
dowait                                               546     553      +7
waitforjob                                            98     100      +2
showjobs                                              54      56      +2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/0 up/down: 48/0)               Total: 48 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 20:43:43 +02:00
Denys Vlasenko ef673ec65a ash: propagate exitstatus to wait -n for correct $? value
function                                             old     new   delta
dowait                                               533     532      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko f4406b2d09 ash: rename "int err" in waitproc() to "pid"
function                                             old     new   delta
dowait                                               530     533      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko 3920b0a994 ash: dowait: remove incorrect looping
Prev code:

         rpid = 1;
         do {
                 pid = waitone(block, jp);
                 rpid &= !!pid; <<<<<<<<<<<<<<<<<< HERE
                 if (!pid || (jp && jp->state != JOBRUNNING))
                         block = DOWAIT_NONBLOCK;
         } while (pid >= 0);
         return rpid;

If we got pid == 0, it happens in exactly one case:
we did waitpid(WNOHANG), got 0 ("children exist but none yet
changed its state"), then waited for a signal and got one,
which wasn't SIGCHLD.

The above behavior is requested by only one caller: waitcmd()
- the "wait" builtin.

"wait" builtin is required to be interruptible by signals and
to set exitcode to (128 + sig).

Therefore, if we got pid == 0, we don't need to wait
for any more processes. We need to return to waitcmd()
and let it set $? accordingly.

Instead, we do yet another loop.

I'm not saying that we know
that there are no more processes that finished.

I'm saying we don't care at this point: we know
that we are "wait" builtin and we got interrupted by a signal.

Fix this by not looping if "pid == 0" indicates we got a signal.
ONLY loop if we got a pid > 0 and we either do not wait for a specific job,
or this scpecific job is still RUNNING.

function                                             old     new   delta
dowait                                               546     530     -16

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko e054f9fb4b ash: waiting machinery: add comments explaining the code
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Denys Vlasenko cdd442ebd2 ash: waitproc: unobfuscate and explain what the code does
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 17:40:47 +02:00
Wojtek Kaniewski 85efaab179 id: Fix output in case of groups error
On a severely constrained system (m68k-nommu) I got confusing output from
`id` command:

    ~ # id
    uid=0 gid=0id: can't get groups

After this change it's a bit more readable:

    ~ # id
    uid=0 gid=0
    id: can't get groups

function                                             old     new   delta
id_main                                              474     484     +10

Signed-off-by: Wojtek Kaniewski <wojtekka@toxygen.net>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 00:52:46 +02:00
Denys Vlasenko 6644e8376e ash simplify PS1 initialization
function                                             old     new   delta
.rodata                                           104788  104781      -7
init                                                 432     422     -10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-17)             Total: -17 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 00:36:08 +02:00
Denys Vlasenko 93bacaa199 ash: remove stray semicolon to fix prompt in !EDITING_FANCY_PROMPT case
Patch by Robert Sandholzer.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-05 00:35:36 +02:00
Michele Dionisio via busybox e65b560038 chrt: add -R to set SCHED_RESET_ON_FORK
Add the -R option, as in util-linux's chrt, which ORs the
SCHED_RESET_ON_FORK flag into the policy passed to sched_setscheduler().
Children created by fork() then do not inherit privileged scheduling
policies and priorities.

Provide a fallback definition of SCHED_RESET_ON_FORK for libcs whose
headers lack it, so the #ifdef around the flag masking in the -p query
path is no longer needed.

function                                             old     new   delta
chrt_main                                            474     501     +27
packed_usage                                       36406   36428     +22
.rodata                                           104787  104788      +1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/0 up/down: 50/0)               Total: 50 bytes

Signed-off-by: Michele Dionisio <michele.dionisio@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 19:41:03 +02:00
Karthik D K c6c7ab979e libbb: enable fixed 4k pagesize on RISC-V
function             old     new   delta
dd_main             2728    2760     +32
time_main           1300    1288     -12
procps_scan          884     868     -16
devmem_main          648     632     -16
hexedit_main        1416    1392     -24
mkswap_main          408     372     -36
alloc_buf             64       -     -64
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/5 up/down: 32/-168)  Total: -136 bytes

Signed-off-by: Karthik D K <karthikdk1998@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 18:40:20 +02:00
Harald van Dijk f96d33d28a printf: fix handling of omitted arguments
For numeric formats, this is meant to behave as a "0" literal zero
argument, not an "" empty string argument.

Add a test to ensure that an explicit "" empty string argument still is
treated as an error.

function                                             old     new   delta
printf_main                                          837    1209    +372
print_direc                                          432       -    -432
------------------------------------------------------------------------------
(add/remove: 0/1 grow/shrink: 1/0 up/down: 372/-432)          Total: -60 bytes

Signed-off-by: Harald van Dijk <harald@gigawatt.nl>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 17:48:06 +02:00
Denys Vlasenko b68024b2b8 fatlabel: do not require the 55,AA "bootable" signature
function                                             old     new   delta
fatlabel_main                                        396     384     -12

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 17:27:43 +02:00
Denys Vlasenko 4da3f6df05 fatlabel: require dir_entries = 0 in FAT32 check; fix typos
function                                             old     new   delta
fatlabel_main                                        392     396      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 17:00:56 +02:00
Denys Vlasenko 4366618a25 tls_aes: use bytes for AES state
This is not a code size win on i686. It is "accidentally" a win on x86_64:
my gcc stops trying to use SSE operations for xoring, which is smaller code.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 03:03:37 +02:00
Denys Vlasenko ca70514d85 tftp: fix maximum allowed block size from 65564 to 65464 (location #2)
Patch by Valentin. He did send the patch. Which I didn't notice
in the email, decided "bug clear enough, can do it myself",
missed the second location with a buggy constant,
forgot to attribute the fix, and made *two* typos in the commit message.
:(

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-04 01:28:33 +02:00
Denys Vlasenko 0625fac9fe tftp: fix maximum allowed blcok size form 65564 to 65464
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-03 15:26:15 +02:00
Denys Vlasenko 14f6b6b580 bunzip2: reject blocks whose run-length count overflows
Based ob the patch by Matt Turner <mattst88@gmail.com>:
> get_next_block() accumulates a run length in the unsigned 32-bit runCnt:
>
>         runCnt += (runPos << nextSym);
>
> A crafted stream with a long enough RUNA/RUNB sequence can drive runCnt
> up to ~2^32. Once it is that large, the existing guard
>
>         if (dbufCount + runCnt > bd->dbufSize)
>
> is bypassed: dbufCount + runCnt overflows the unsigned addition and
> wraps to a small value, so the check passes. The following
> byteCount[tmp_byte] += runCnt then overflows byteCount[] (an int) to a
> negative value. The inverse Burrows-Wheeler sort loop computes negative
> cumulative offsets from it and writes before the start of dbuf[], an
> out-of-bounds heap write (confirmed with AddressSanitizer as a write 48
> bytes before the dbuf allocation).

function                                             old     new   delta
get_next_block                                      1452    1458      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-02 20:35:04 +02:00
Denys Vlasenko 904511662e nmeter: make it able to sleep for hours: -d %((60*60*1000))
function                                             old     new   delta
nmeter_main                                          786    1031    +245
packed_usage                                       36379   36406     +27
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 272/0)             Total: 272 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-01 17:28:51 +02:00
Denys Vlasenko c824119226 nmeter: document why %[nIF] format prepends a space
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-10-01 15:48:05 +02:00
Denys Vlasenko e6302b2711 swapon: with no arguments, show /proc/swaps (mimic util-linux 2.41.1)
function                                             old     new   delta
swap_on_off_main                                     419     449     +30

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-29 00:00:42 +02:00
Denys Vlasenko e8cb0a1d14 fdisk: util-linux compat wrt meaning of -u
function                                             old     new   delta
menu                                                 261     282     +21
.rodata                                           104779  104787      +8
packed_usage                                       36390   36379     -11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 29/-11)             Total: 18 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 18:07:32 +02:00
Denys Vlasenko c1289d58d5 fdisk: add a test of adding a 1-sector primary partition
function                                             old     new   delta
packed_usage                                       36323   36390     +67
read_int                                             450     457      +7
read_line_input                                     2664    2669      +5
get_boot                                            1426    1423      -3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 3/1 up/down: 79/-3)              Total: 76 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 17:24:03 +02:00
Denys Vlasenko 928b0384cf fdisk: more readable code in read_extended_chain()
function                                             old     new   delta
get_boot                                            1426    1423      -3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 12:22:10 +02:00
Denys Vlasenko ccf1e30fa2 fdisk: consider partition empty only when it's all-zeros, not merely type 0
Our own message in the source says that Linux does not consider type 0
as "empty". (Linux thinks that size of 0 sectors means "empty").

function                                             old     new   delta
verify                                               726     767     +41
wrong_p_order                                         86     119     +33
get_geometry                                         437     460     +23
get_boot                                            1412    1426     +14
fill_bounds                                          115     124      +9
x_dos_print_disklabel                                227     232      +5
delete_partition                                     334     337      +3
add_logical                                          106     109      +3
fdisk_main                                          2590    2576     -14
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 8/1 up/down: 131/-14)           Total: 117 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 11:44:00 +02:00
Denys Vlasenko bfdf3560d6 fdisk: DOS compat flag off by default - mimic util-linux 2.41.1
function                                             old     new   delta
fdisk_main                                          2610    2590     -20

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 11:16:02 +02:00
Denys Vlasenko 4c9b0e45da fdisk: in add_partition(), only fully zeroed partition entry is free
function                                             old     new   delta
add_partition                                       1038    1041      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 04:04:56 +02:00
Denys Vlasenko 152c6227d0 fdisk: simplify new_partition()
function                                             old     new   delta
input_partition_number                                 -      73     +73
fdisk_main                                          2547    2610     +63
get_partition                                         73       -     -73
get_nonexisting_partition                            100       -    -100
.rodata                                           104879  104779    -100
------------------------------------------------------------------------------
(add/remove: 1/2 grow/shrink: 1/1 up/down: 136/-273)         Total: -137 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 03:23:26 +02:00
Denys Vlasenko 659644d8d6 fdisk: explain how extended partitions work on-disk
Improve messages about "DOS compatibility flag"

function                                             old     new   delta
menu                                                 231     261     +30
valid_55AA_signature                                   -      26     +26
fdisk_main                                          2534    2547     +13
get_boot                                            1406    1412      +6
valid_part_table_flag                                 26       -     -26
.rodata                                           104913  104879     -34
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 3/1 up/down: 75/-60)             Total: 15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-28 02:49:08 +02:00
Denys Vlasenko 25c50c4805 fdisk: remove "devfs kludge"
function                                             old     new   delta
partname                                             184     136     -48

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 23:21:23 +02:00
Denys Vlasenko 03293bc06c fdisk: remove dead code in open_list_and_close()
delete_partition() which deals with extended partition is unnecessary
since we are inside "fdisk -l".
"if (LABEL_IS_AIX) ..." is false since only after successful get_boot()
we can have a detected AIX label.

function                                             old     new   delta
open_list_and_close                                  424     392     -32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 22:57:52 +02:00
Denys Vlasenko 3fc725d413 fdsik: reduce local char mesg[256] to [64]
function                                             old     new   delta
add_partition                                       1246    1038    -208

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 22:50:02 +02:00
Denys Vlasenko dcb8ae589b fdisk: group menu functions together
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 22:31:46 +02:00
Denys Vlasenko ef63f4dec2 fdisk: standardize on XYZ_print_disklabel() as the function for 'p'
list_disk_name_and_sizes() shouldn't be used by gpt's print_disklabel(),
just use it unconditionally for all partition types.

function                                             old     new   delta
static.print_disklabel                                 -     775    +775
x_dos_print_disklabel                                  -     227    +227
print_disk_name_and_sizes                              -      80     +80
print_disk_geometry                                    -      66     +66
open_list_and_close                                  419     424      +5
.rodata                                           104928  104913     -15
list_disk_geometry                                    71       -     -71
list_disk_name_and_sizes                              80       -     -80
x_list_table                                         227       -    -227
static.list_table                                    775       -    -775
------------------------------------------------------------------------------
(add/remove: 4/4 grow/shrink: 1/1 up/down: 1153/-1168)        Total: -15 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 20:32:07 +02:00
Denys Vlasenko 6853c796be fdisk: rename bsd_select() -> if_osf_label_loop_in_menu_until_r()
Much clearer to read the call site.
While at it, shiffle fdisk_osf.c to reduce forward references.
Shorten sprintf() in xbsd_get_part_index().

function                                             old     new   delta
if_osf_label_loop_in_menu_until_r                      -    1546   +1546
xbsd_get_part_index                                   69      67      -2
bsd_select                                          1546       -   -1546
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 1546/-1548)         Total: -2 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 19:44:34 +02:00
Denys Vlasenko 4839711dce fdisk: consistently use uint8_t (not char) for binary data
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 19:00:36 +02:00
Denys Vlasenko e5588888c8 fdisk: rename struct partition to dos_partition
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:34:08 +02:00
Denys Vlasenko 8ce86eb361 fdisk: show "Changes will remain in memory only" more prominently
function                                             old     new   delta
.rodata                                           104735  104928    +193
fdisk_main                                          2522    2534     +12
create_doslabel                                       99      93      -6
msg_part_already_defined                              61       -     -61
msg_building_new_label                               142       -    -142
------------------------------------------------------------------------------
(add/remove: 0/2 grow/shrink: 2/1 up/down: 205/-209)           Total: -4 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:29:42 +02:00
Denys Vlasenko 8c43e2409e fdisk: make write_table_and_exit() NORETURN
function                                             old     new   delta
write_table_and_exit                                   -     153    +153
fdisk_main                                          2537    2522     -15
write_table                                          159       -    -159
------------------------------------------------------------------------------
(add/remove: 1/1 grow/shrink: 0/1 up/down: 153/-174)          Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:10:34 +02:00
Denys Vlasenko fbfc949b26 fdisk: remove get_boot() -> create_doslabel() -> get_boot() recursion
It works, but
get_boot() [table is bad] -> create_doslabel() -> get_boot(CREATE_EMPTY_DOS)
is a mind bender

function                                             old     new   delta
dos_reset_primary_partition_info                       -      73     +73
get_existing_partition                               113     110      -3
fdisk_main                                          2543    2537      -6
create_doslabel                                      108      99      -9
get_boot                                            1477    1406     -71
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/4 up/down: 73/-89)            Total: -16 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 18:02:02 +02:00
Denys Vlasenko 946aba349c fdisk: remove vestiges of SUN and SGI labels support
function                                             old     new   delta
menu                                                 262     231     -31
.rodata                                           104770  104735     -35
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-66)             Total: -66 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 16:46:13 +02:00
Denys Vlasenko e1aeba03f4 fdisk: remove SUN and SGI labels support - obsolete (20+ years)
function                                             old     new   delta
static.list_table                                      -     775    +775
packed_usage                                       36304   36323     +19
read_int                                             434     450     +16
fdisk_swap32                                           3       -      -3
open_list_and_close                                  431     419     -12
verify                                               742     726     -16
partition_type                                        49      28     -21
get_partition                                        100      73     -27
menu                                                 293     262     -31
read_maybe_empty                                      38       -     -38
verify_sun_cmp                                        39       -     -39
get_boot                                            1532    1477     -55
sun_sys_types                                         56       -     -56
write_table                                          251     159     -92
delete_partition                                     432     334     -98
set_sun_partition                                    100       -    -100
get_geometry                                         538     437    -101
print_buffer                                         102       -    -102
fetch_sun                                            207       -    -207
check_sun_label                                      208       -    -208
sun_autoconfigure_scsi                               395       -    -395
verify_sun                                           447       -    -447
sun_drives                                           456       -    -456
new_partition                                       1066       -   -1066
list_table                                          1370       -   -1370
fdisk_main                                          4622    2543   -2079
.rodata                                           107469  104770   -2699
------------------------------------------------------------------------------
(add/remove: 1/13 grow/shrink: 2/11 up/down: 810/-9718)     Total: -8908 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-27 16:38:02 +02:00
Denys Vlasenko 274a087cdc *: users of get_volume_size_in_bytes() should open their file O_RDWR
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-26 19:52:10 +02:00
Denys Vlasenko 69dd61ccbf nc: show connect() errors always, not only with -v or -vv
function                                             old     new   delta
display                                             1485    1481      -4
nc_main                                             1018     992     -26
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/2 up/down: 0/-30)             Total: -30 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-26 19:45:56 +02:00
Denys Vlasenko 13562b9351 volume_id: add FAST_FUNCs
function                                             old     new   delta
volume_id_set_unicode16                              167     181     +14
volume_id_probe_btrfs                                131     139      +8
volume_id_probe_vfat                                 824     830      +6
volume_id_probe_sysv                                 188     193      +5
volume_id_probe_romfs                                 97     100      +3
volume_id_probe_iso9660                              315     316      +1
volume_id_probe_nilfs                                 97      96      -1
volume_id_probe_lfs                                   59      58      -1
volume_id_probe_ext                                  122     121      -1
volume_id_probe_erofs                                 86      85      -1
volume_id_probe_reiserfs                             243     241      -2
volume_id_probe_linux_raid                           128     126      -2
volume_id_free_buffer                                 67      65      -2
volume_id_probe_xfs                                   98      95      -3
volume_id_probe_ocfs2                                107     104      -3
volume_id_probe_linux_swap                           248     245      -3
volume_id_probe_jfs                                  107     104      -3
volume_id_probe_bcache                               104     101      -3
volume_id_set_label_string                            81      77      -4
volume_id_probe_ubifs                                 64      60      -4
volume_id_probe_squashfs                              83      79      -4
volume_id_probe_minix                                 82      78      -4
volume_id_probe_f2fs                                 104     100      -4
volume_id_probe_cramfs                                64      60      -4
volume_id_get_buffer                                 372     368      -4
volume_id_probe_luks                                  89      83      -6
volume_id_probe_udf                                  538     531      -7
volume_id_probe_exfat                                282     275      -7
volume_id_set_label_unicode16                         31      23      -8
volume_id_probe_ntfs                                 285     277      -8
volume_id_probe_all                                  123     113     -10
volume_id_set_uuid                                   178     166     -12
volume_id_probe_hfs_hfsplus                          494     470     -24
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 6/27 up/down: 37/-135)          Total: -98 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-24 16:20:36 +02:00
Denys Vlasenko 30d2839a7c fatlabel: new applet
function                                             old     new   delta
fatlabel_main                                          -     392    +392
.rodata                                           107413  107469     +56
applet_names                                        2885    2894      +9
applet_main                                         1660    1664      +4
packed_usage                                       36307   36304      -3
swaplabel_main                                       274     270      -4
------------------------------------------------------------------------------
(add/remove: 2/0 grow/shrink: 3/2 up/down: 461/-7)            Total: 454 bytes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-24 11:52:58 +02:00
Denys Vlasenko f5c0543fd1 swaplabel: new applet
While at it, make get_volume_size_in_bytes() messages more informative;
do not write to file unless _have to_ extend it.

function                                             old     new   delta
swaplabel_main                                         -     274    +274
.rodata                                           107344  107413     +69
get_volume_size_in_bytes                             221     262     +41
bb_SWAPSPACE2                                          -      10     +10
applet_names                                        2875    2885     +10
packed_usage                                       36298   36307      +9
applet_main                                         1656    1660      +4
applet_install_loc                                   207     208      +1
SWAPSPACE2                                            10       -     -10
------------------------------------------------------------------------------
(add/remove: 3/1 grow/shrink: 6/0 up/down: 418/-10)           Total: 408 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-24 02:21:18 +02:00
Denys Vlasenko d3c8cfa674 tr: special-case "\-" before trying to parse it as escape
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 06:41:53 +02:00
Ron Yorston 0e09d2f857 tr: an escaped dash doesn't indicate a range
Commit d683c5c2f1 (tr: support octal ranges) broke the previous
behaviour that an escaped dash doesn't indicate a range:
'[p\-r]' should match 'p', '-' or 'r', not 'p', 'q' or 'r'.

Add a special case to handle this.

function                                             old     new   delta
expand                                               641     657     +16
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 16/0)               Total: 16 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 06:41:53 +02:00
Denys Vlasenko a21eaf440d *: fix Unicode damage
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 02:53:30 +02:00
Denys Vlasenko c9e11ef570 telnet: make put_iac_subopt_XYZ() more readable
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 02:23:46 +02:00
Denys Vlasenko 5cea24cf6c telnet: remove superfluous bit clearing
function                                             old     new   delta
write_to_net                                         625     621      -4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 02:07:23 +02:00
Denys Vlasenko bf9ebfe168 wget: fix progress bar and message placement on unexpected EOF (and retry)
Correct behavior: "wget: connection closed..." on new line:

$ wget http://127.0.0.1/50g -O/dev/null
Connecting to 127.0.0.1 (127.0.0.1:80)
saving to '/dev/null'
null                   8% |**                       | 4531M  0:00:30 ETA
wget: connection closed at byte 4751158460
Connecting to 127.0.0.1 (127.0.0.1:80)
saving to '/dev/null'
null                  10% |***_

function                                             old     new   delta
progress_meter                                       182     195     +13
retrieve_file_data                                   705     697      -8
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 13/-8)               Total: 5 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 01:25:45 +02:00
Denys Vlasenko 218f328625 wget: support multiple restarts, -t NUM controls how many
function                                             old     new   delta
retrieve_file_data                                   621     705     +84
wget_main                                           2581    2657     +76
ftpcmd                                               133     151     +18
packed_usage                                       36282   36298     +16
get_sanitized_hdr                                    150     156      +6
fgets_trim_sanitize                                  134     137      +3
reset_beg_range_to_zero                               44      46      +2
.rodata                                           107342  107344      +2
progress_meter                                       189     182      -7
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 8/1 up/down: 207/-7)            Total: 200 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-23 00:36:36 +02:00
Denys Vlasenko 61e244e5ee dpkk: stop allowing spaces in NAME: parts. Debian does not do this, it seems
Add mode docs in comments. We probably do not follow them correctly yet.

function                                             old     new   delta
read_package_field                                   211     170     -41

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 16:12:33 +02:00
Denys Vlasenko 39c2dc8c49 httpd: document that P: proxying is not checking passwords
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 13:26:19 +02:00
Denys Vlasenko e97224f8fb tls: fix off-by-one access past the end of the received packet.
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 02:38:38 +02:00
Denys Vlasenko c2dec52d37 libpwdgrp: tokenizer fix for trailing whitespace removeal.
The tokenize() function trims trailing whitespace via
overlapping_strcpy() but continues to reference the stale *end
pointer. Fixing this.

function                                             old     new   delta
tokenize                                             120     119      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 02:19:06 +02:00
Denys Vlasenko 556567f403 mount: document a possible bug in comment, no code changes.
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 01:55:03 +02:00
Denys Vlasenko 9f5cbdcaa5 httpd: allow yescrypt passwords ("$y$....")
function                                             old     new   delta
check_user_passwd                                    439     444      +5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 01:14:47 +02:00
Denys Vlasenko d5cc94063b dpkg: fix field handling in write_status_file()
function                                             old     new   delta
dpkg_main                                           3943    3934      -9

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 01:05:07 +02:00
Denys Vlasenko 7a055991de dpkg: improve --help
function                                             old     new   delta
packed_usage                                       36247   36282     +35

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-22 00:48:46 +02:00
Denys Vlasenko e8a55de7ec dpkg-deb: add a rudimentary test
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 23:34:12 +02:00
Denys Vlasenko 6b366627e1 dpkg: remove const from non-pointer variables
This does not improve anything, only makes code more verbose.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 23:32:37 +02:00
Denys Vlasenko 89a2512144 dpkg: code shrink by improving make_hash() API
function                                             old     new   delta
search_status_hashtable                              109     113      +4
search_name_hashtable                                104     103      -1
make_hash                                            116     113      -3
search_package_hashtable                             120      99     -21
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/3 up/down: 4/-25)             Total: -21 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 22:33:15 +02:00
Denys Vlasenko bef7bcf4ce dpkg: improve --help
function                                             old     new   delta
packed_usage                                       36243   36247      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 22:30:23 +02:00
Denys Vlasenko 21f9c36676 dpkg: avoid strlen in fill_package_struct()
function                                             old     new   delta
fill_package_struct                                  306     291     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 17:16:17 +02:00
Denys Vlasenko 7c611860df dpkg: deindent read_package_field(), rename variables. No logic changes
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 17:13:27 +02:00
Denys Vlasenko f5a4a02a15 dpkg: fix cases where read_package_field() returns offset past NUL
function                                             old     new   delta
read_package_field                                   169     211     +42

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 16:59:56 +02:00
Denys Vlasenko 43a9d7d315 dpkg: reformat code in read_package_field(), exposing why it's buggy
function                                             old     new   delta
read_package_field                                   184     169     -15

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 16:32:43 +02:00
Denys Vlasenko e2c5cc0420 dpkg: free results of read_package_field(), preliminary cleanups in read_package_field()
function                                             old     new   delta
dpkg_main                                           3910    3943     +33
write_buffer_no_status                                92     114     +22
read_package_field                                   204     184     -20
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/1 up/down: 55/-20)             Total: 35 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 16:16:47 +02:00
Denys Vlasenko fd1972099f udhcpc: ensure packet.data.cookie exists before we access it
function                                             old     new   delta
d4_recv_raw_packet                                   497     500      +3

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 12:15:19 +02:00
Denys Vlasenko 9073c1d15c volume_id/romfs: limit the maximum size of label to VOLUME_ID_LABEL_SIZE
function                                             old     new   delta
volume_id_set_label_string                            71      81     +10
volume_id_probe_romfs                                 94      97      +3
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 13/0)               Total: 13 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 05:34:19 +02:00
Denys Vlasenko d0143f8da1 httpd: remove one unnecessary check
function                                             old     new   delta
scan_ip                                              170     165      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 05:20:06 +02:00
Denys Vlasenko 339e3c62f5 httpd: fix handling of "D:1.2.3/999"
An error in allow/deny rule should be interpreted as D:0/0
("deny all") but was interpreted as D:IP/0. Fix this.

function                                             old     new   delta
parse_conf                                          1323    1330      +7

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 04:40:37 +02:00
Denys Vlasenko 89ac82774f tls: fix undersized buffer calculation
All callers of pstm_montgomery_reduce() are currently in pstm_exptmod()
and they all pass a preallocated temporary buffer, so the incorrect code
is unreachable. But fix it anyway.

function                                             old     new   delta
pstm_montgomery_reduce                               431     430      -1

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-21 03:20:39 +02:00
Denys Vlasenko 1b4f8e2a87 awk: allow OFMT='prefix:%SPEC suffix with %%'
function                                             old     new   delta
fmt_num                                              380     394     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-09-14 01:46:32 +02:00
Ali Ahmet Memis 74ac096e89 sort: compute -k END.ENDCHAR from the end field, not the line start
get_key() locates a key in two passes: j=0 walks to the start of the
START field, j=1 walks to the end of the END field. When END carries
an ENDCHAR (-kSTART,N.ENDCHAR), that char position is supposed to be
counted from the start of field N. Instead the code overwrote 'end'
with the raw parsed value, an offset from the very start of the line:

	if (key->range[3]) {
		end = key->range[3];

For END field 1 this happens to be the same thing, but for any later
field it is not. The result usually lands before 'start', which then
gets clamped to 'start', producing an empty key. Sort has an ASCII
whole-line fallback when keys tie, so it silently sorts by the whole
line instead of the requested key:

	$ printf '%s\n' 'b:aa' 'a:ba' 'a:aa' | busybox sort -t : -k 2.1,2.1
	a:aa
	a:ba
	b:aa
	$ printf '%s\n' 'b:aa' 'a:ba' 'a:aa' | sort -t : -k 2.1,2.1
	a:aa
	b:aa
	a:ba

Make the j=1 pass stop at the start of field N instead of its end when
ENDCHAR is given, one field-skip short of the usual pass, and add the
ENDCHAR offset from there. This mirrors how STARTCHAR is already
applied relative to the start of the START field. Verified against
several -k combinations (endchar past the field's own length, multiple
fields skipped, startchar and endchar together) matching GNU sort.

Add a regression test; the existing ENDCHAR test only exercises field
1, where the old absolute offset and the correct field-relative one
happen to coincide.

function                                             old     new   delta
get_key                                              490     516     +26

Signed-off-by: Ali Ahmet Memis <ali@iusegentoo.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 22:54:31 +02:00
Denys Vlasenko 8f4dc3b405 platform.h: UNINITIALIZED_VAR() macro for suppressing gcc warnings
With gcc-15.0.1:

function                                             old     new   delta
tftpd_main                                           603     617     +14
expand_one_var                                      1923    1929      +6
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 20/0)               Total: 20 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 20:03:33 +02:00
Denys Vlasenko c8047030dc vi: explain what vim 9.2 is doing with ":e FILE" escaping
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 16:50:46 +02:00
Denys Vlasenko 6ab4e2a0de vi: code shrink
function                                             old     new   delta
expand_args                                          186     181      -5

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 10:21:20 +02:00
Denys Vlasenko 7406d7a74f inetd: build fix if RPC is selected in .config
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 02:00:36 +02:00
Denys Vlasenko fe215e35d6 devfsd: heed warnings
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 01:55:03 +02:00
Denys Vlasenko 452a4f1ad5 hush: heed warnings about strchr() returning const char*
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 01:14:51 +02:00
Denys Vlasenko 6885d4c310 *: selinux: replace deprecated security_context_t with char*
Suppresses a lot of selinux warnings.
This does not change the code.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-31 01:02:03 +02:00
Romain Guyard 4a2a446472 hdparm: fix ATA identification string output
print_ascii() is intended to skip leading spaces before printing ATA
IDENTIFY strings, but the condition is inverted and skips non-space
characters instead.

As a result, left-justified strings such as serial numbers and firmware
revisions can be printed as empty, while strings containing embedded
spaces, such as model names, are truncated up to the first space.

Fix the condition so only leading spaces are skipped, and add a regression
test covering left-justified strings, embedded spaces, and leading-space
padding.

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

Signed-off-by: Romain Guyard <foss@romainguyard.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-30 20:06:15 +02:00
Denys Vlasenko 9958bbd70a awk: disallow OFMT/CONVFMT to have more than one %SPEC, implement %s
function                                             old     new   delta
fmt_num                                              257     380    +123
.rodata                                           107332  107342     +10
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 133/0)             Total: 133 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-30 18:55:07 +02:00
Anton Skorup 436223e2b7 tar: Sanitize verbose file names
function                                             old     new   delta
writeTarHeader                                       859     869     +10

Signed-off-by: Anton Skorup <anton.skorup@axis.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-30 13:27:23 +02:00
Ediz 15666f3e9a awk: fix 1-byte heap-buffer-overflow in next_token() string parse
When the awk program ends with \<newline> right after the last string
token, nextchar() eats the newline and then reads the terminating NUL
that xmalloc_read_with_initial_buf() appends, advancing past the end
of the buffer. The string-scan loop in next_token() then dereferences
one byte past the buffer (heap-buffer-overflow, READ of size 1).

Fix: test every nextchar() return for NULs.

Reproducer (ASan build):
awk 'BEGIN { print "string\
'

function                                             old     new   delta
next_token                                           934     933      -1

Signed-off-by: Ediz <ediz.research@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-24 10:56:25 +02:00
Denys Vlasenko 92ad65c3a2 stat: code shrink
function                                             old     new   delta
printf_llu                                             -      35     +35
printf_lx                                              -      30     +30
printf_lu                                              -      30     +30
printf_s                                               -      28     +28
printfs                                               28       -     -28
print_statfs                                         338     260     -78
print_stat                                           858     761     -97
------------------------------------------------------------------------------
(add/remove: 4/1 grow/shrink: 0/2 up/down: 123/-203)          Total: -80 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-24 09:49:01 +02:00
Benjamin Robin a61d158d54 stat: fix negative %X/%Y/%Z timestamps after Y2038 on 32-bit builds
Introduce a utility function to always print `time_t` values using either
`long long` or `unsigned long long`, depending on whether `time_t` is
signed. This fixes the bug reported in [1].

Previously, `time_t` values were cast to `long`, which is a 32-bit value
on 32-bit builds.

[1]: https://lists.busybox.net/pipermail/busybox/2026-August/092413.html

function                                             old     new   delta
print_stat                                           869     858     -11

Signed-off-by: Benjamin Robin <benjamin.robin@bootlin.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-24 09:27:10 +02:00
Thorsten B 7473045ad3 tar: fix verbose output with extract-to-stdout
Combining the verbose (-v) and extract-to-stdout (-O) options caused
verbose output and extracted file data to be interleaved unpredictably on
stdout. Verbose listing uses buffered stdio (printf()/puts()), while file
contents are written directly to the stdout file descriptor.

GNU tar also combines buffered verbose output with unbuffered writes for
"-vO", however, GNU tar writes verbose output to stderr, so the two streams
remain separate and consistent.

Fix this by making "tar xvO" send output to stderr.

function                                             old     new   delta
header_verbose_list                                  244     279     +35
header_list                                           15      49     +34
get_header_tar                                      1764    1769      +5
header_verbose_list_ar                                77      78      +1
get_header_ar                                        542     540      -2
get_header_cpio                                      959     948     -11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 4/2 up/down: 75/-13)             Total: 62 bytes

Signed-off-by: Thorsten B <brehmt@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-10 06:30:18 +02:00
Ron Yorston d057384504 rpm2cpio: print name of unknown compression method
Commit f13f68288 (rpm2cpio: extract cpio even if compression is
not known) added an error message if the compression method was
unknown.  When support for lzma was disabled this resulted in a
null pointer being passed to bb_error_msg().

The call to rpm_getstr0() to fetch the name of the compression
method shouldn't depend on lzma being supported.

This doesn't affect the size of a default build.  In a build with
lzma disabled:

function                                             old     new   delta
rpm2cpio_main                                        110     121     +11
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/0 up/down: 11/0)               Total: 11 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-10 05:36:59 +02:00
Ron Yorston fce9d7f35e shell: correctly count backslashes in read built-in
When the read built-in's '-n' option is used to limit the number
of characters read, backslashes should only be counted if the '-r'
option is also suppiled.  This matches how bash behaves.

function                                             old     new   delta
shell_builtin_read                                  1360    1358      -2
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/1 up/down: 0/-2)               Total: -2 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-09 06:51:46 +02:00
Denys Vlasenko 9ad78b4180 shell: read: if poll() fails, attempt to process any data collected so far
This was already done on read() failure, why not on poll()?
Making it consistent.

function                                             old     new   delta
shell_builtin_read                                  1318    1308     -10

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-09 06:49:14 +02:00
Ron Yorston 9b21bb0f89 patch: handle files with no final newline
GNU and BSD patch both handle patches which include the annotation
'\ No newline at end of file'.  BusyBox patch doesn't, even though
its diff emits it.

Implement this feature and add some tests.

function                                             old     new   delta
patch_main                                          1912    2002     +90
do_line                                               88     116     +28
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 118/0)             Total: 118 bytes

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-08-09 06:39:10 +02:00
Denys Vlasenko 3db20fa07b grep: support --quiet
function                                             old     new   delta
static.grep_longopts                                   -      17     +17
packed_usage                                       36237   36243      +6
.rodata                                           107341  107332      -9
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 1/1 up/down: 23/-9)              Total: 14 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-24 18:38:38 +02:00
Denys Vlasenko ec0c5cc142 cp: fix --sparse to have mandatory argument, fix --remove-destination bit position
cp --remove-destination was broken by commit 56bbbfae "cp: implement -n"

function                                             old     new   delta
cp_main                                              527     533      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-14 23:14:24 +02:00
Denys Vlasenko 17908bf760 cp: accept --sparse=ANYTHING
function                                             old     new   delta
cp_main                                              514     527     +13
.rodata                                           107332  107341      +9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 22/0)               Total: 22 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-14 19:00:02 +02:00
Denys Vlasenko 8f0533c576 join: code shrink by making some variables "global"
function                                             old     new   delta
readfields                                           442     437      -5
printfields                                          462     457      -5
join_main                                            843     760     -83
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 0/3 up/down: 0/-93)             Total: -93 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-08 14:38:07 +02:00
Ron Yorston a058289401 join: new applet
function                                             old     new   delta
join_main                                              -     843    +843
printfields                                            -     462    +462
readfields                                             -     442    +442
.rodata                                           107120  107332    +212
packed_usage                                       36078   36237    +159
applet_names                                        2870    2875      +5
applet_main                                         1652    1656      +4
------------------------------------------------------------------------------
(add/remove: 4/0 grow/shrink: 4/0 up/down: 2127/0)           Total: 2127 bytes
   text	   data	    bss	    dec	    hex	filename
1080964	    555	   4992	1086511	 10942f	busybox_old
1083091	    555	   4992	1088638	 109c7e	busybox_unstripped

v2: Add a missing return statement which broke the '-t' option.
    Thanks to Roberto A. Foglietta for pointing this out.

Signed-off-by: Morgan Bartlett <mjmouse9999@gmail.com>
Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-08 07:01:03 +02:00
Sanghyun Park a448b6d5b2 ash: fix out-of-bounds read in ifsbreakup()
ifsfree() does not only release allocated ifsregion nodes; it also clears
the global IFS region state used by ifsbreakup(). If argstr() raises an
error while expanding an argument, ash longjmps out of expandarg() before
that cleanup runs, leaving stale IFS split offsets behind.

A later expansion can reuse the stack for a shorter string. ifsbreakup()
then sees the stale IFS state, trusts the old offsets, and can walk past
the current stack block before dereferencing p.

Follow dash's root-cause fix: when an expansion-related handler catches
EXERROR and continues, restore the handler and call ifsfree(). Apply
the cleanup to redirectsafe(), expandstr(), and evaltree().

Upstream commit:

    Date:   Mon Dec 5 23:02:01 2022 +0800
    expand: Add ifsfree to expand to fix a logic error that causes a buffer over-read

    On Mon, Jun 20, 2022 at 02:27:10PM -0400, Alex Gorinson wrote:
    > Due to a logic error in the ifsbreakup function in expand.c if a
    > heredoc and normal command is run one after the other by means of a
    > semi-colon, when the second command drops into ifsbreakup the command
    > will be evaluated with the ifslastp/ifsfirst struct that was set when
    > the here doc was evaluated. This results in a buffer over-read that
    > can leak the program's heap, stack, and arena addresses which can be
    > used to beat ASLR.
    >
    > Steps to Reproduce:
    > First bug:
    > cmd args: ~/exampleDir/example> dash
    > $ M='AAAAAAAAAAAAAAAAA'    <note: 17 A's>
    > $ q00(){
    > $ <<000;echo
    > $ ${D?$M$M$M$M$M$M}        <note: 6 $M's>
    > $ 000
    > $ }
    > $ q00                      <note: After the q00 is typed in, the leak
    > should be echo'd out; this works with ash, busybox ash, and dash and
    > with all option args.>
    >
    > Patch:
    > Adding the following to expand.c will fix both bugs in one go.
    > (Thank you to Harald van Dijk and Michael Greenberg for doing the
    > heavy lifting for this patch!)
    > ==========================
    > --- a/src/expand.c
    > +++ b/src/expand.c
    > @@ -859,6 +859,7 @@
    > if (discard)
    > return -1;
    >
    > +ifsfree();
    > sh_error("Bad substitution");
    > }
    >
    > @@ -1739,6 +1740,7 @@
    > } else
    > msg = umsg;
    > }
    > +ifsfree();
    > sh_error("%.*s: %s%s", end - var - 1, var, msg, tail);
    >  }
    > ==========================

    Thanks for the report!

    I think it's better to add the ifsfree() call to the exception
    handling path as other sh_error calls may trigger this too.

function                                             old     new   delta
restore_handler_expandarg                              -      33     +33
evaltree                                             725     711     -14
static.redirectsafe                                  141     124     -17
expandstr                                            262     242     -20
------------------------------------------------------------------------------
(add/remove: 1/0 grow/shrink: 0/3 up/down: 36/-45)            Total: -18 bytes

Signed-off-by: Sanghyun Park <sanghyun.park.cnu@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-06 10:30:30 +02:00
Denys Vlasenko 5de0780eaf awk: fix printf "%o\n", -1
function                                             old     new   delta
awk_printf                                          1381    1387      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-06 04:37:44 +02:00
Denys Vlasenko cd8427b8ec svlogd: fix buffer overrun
Patch by mjmouse9999@gmail.com

When running svlogd -tt with a long line of input, the code assumes a buffer
of at least linemax+26 length, but that is two bytes longer than the
actual buffer with the default of linemax = 1000.

fixing that.

No code size change.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-03 08:17:51 +02:00
Anubhav Kokane 71f9960b33 cmp: add KMG suffix for cmp -n MAXCOUNT
Change input to getopt32 from int to char * so that
max_count is parsed as string. Use xatol_sfx to convert
string to long.

function                                             old     new   delta
cmp_main                                             595     631     +36
.rodata                                           107121  107120      -1
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 36/-1)              Total: 35 bytes

Signed-off-by: Anubhav Kokane <dev.anubhavk@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-03 08:14:23 +02:00
Denys Vlasenko 1332023051 awk: optimize 'print "no format specs here\n"' case
function                                             old     new   delta
awk_printf                                          1349    1381     +32

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-02 05:57:28 +02:00
Denys Vlasenko a0667b2def awk: fix printing of very large numbers with printf("%d")
function                                             old     new   delta
awk_printf                                          1086    1349    +263
.rodata                                           107108  107121     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 276/0)             Total: 276 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-02 04:58:08 +02:00
Denys Vlasenko 4e981fe00f awk: rename variables in awk_printf(), no code changes
awk_printf() got bigger, and now variables need better names,
even if this makes them longer.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-02 00:05:11 +02:00
Denys Vlasenko 6ba81ddb0d awk: add '*' as a valid specifier for width and precision in printf
Based on a patch by Anubhav Kokane <dev.anubhavk@gmail.com>

function                                             old     new   delta
awk_printf                                           640    1086    +446
.rodata                                           107131  107108     -23
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 446/-23)           Total: 423 bytes
   text	   data	    bss	    dec	    hex	filename
1080210	    555	   4992	1085757	 10913d	busybox_old
1080633	    555	   4992	1086180	 1092e4	busybox_unstripped

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-07-01 23:38:27 +02:00
Denys Vlasenko 244c0a01ee testing stripts: allow to skip "awk gsub erroneous word start match" test
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-14 16:26:10 +02:00
Denys Vlasenko 0309c02980 hush: placate warning: 'print_pfx_escaped_nl' defined but not used
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-14 16:22:40 +02:00
Denys Vlasenko 8fc70b52e6 tls: use bb_simple_error_msg where appropriate
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-14 16:08:13 +02:00
Denys Vlasenko c83394922e Start 1.39.0 development cycle
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2026-05-13 05:24:28 +02:00
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
438 changed files with 25251 additions and 11681 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
+8 -3
View File
@@ -1,7 +1,7 @@
VERSION = 1
PATCHLEVEL = 37
PATCHLEVEL = 39
SUBLEVEL = 0
EXTRAVERSION =
EXTRAVERSION = .git
NAME = Unnamed
# *DOCUMENTATION*
@@ -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)
+2
View File
@@ -27,6 +27,8 @@ CFLAGS += $(call cc-option,-Wunused -Wunused-parameter,)
CFLAGS += $(call cc-option,-Wunused-function -Wunused-value,)
CFLAGS += $(call cc-option,-Wmissing-prototypes -Wmissing-declarations,)
CFLAGS += $(call cc-option,-Wno-format-security,)
# we use "" format in ioctl_or_perror_and_die(a, b, c, "")
CFLAGS += $(call cc-option,-Wno-format-zero-length,)
# warn about C99 declaration after statement
CFLAGS += $(call cc-option,-Wdeclaration-after-statement,)
# If you want to add more -Wsomething above, make sure that it is
+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
+6 -5
View File
@@ -151,15 +151,15 @@ static int write_ar_header(archive_handle_t *handle)
static int write_ar_archive(archive_handle_t *handle)
{
struct stat st;
off_t st_size;
archive_handle_t *out_handle;
xfstat(handle->src_fd, &st, handle->ar__name);
st_size = xfstat_size(handle->src_fd, handle->ar__name);
/* if archive exists, create a new handle for output.
* we create it in place of the old one.
*/
if (st.st_size != 0) {
if (st_size != 0) {
out_handle = init_handle();
xunlink(handle->ar__name);
out_handle->src_fd = xopen(handle->ar__name, O_WRONLY | O_CREAT | O_TRUNC);
@@ -174,7 +174,7 @@ static int write_ar_archive(archive_handle_t *handle)
out_handle->offset += AR_MAGIC_LEN + 1;
/* skip to the end of the archive if we have to append stuff */
if (st.st_size != 0) {
if (st_size != 0) {
handle->filter = filter_replaceable;
handle->action_data = copy_data;
unpack_ar_archive(handle);
@@ -194,8 +194,9 @@ static int write_ar_archive(archive_handle_t *handle)
}
#endif /* FEATURE_AR_CREATE */
static void FAST_FUNC header_verbose_list_ar(const file_header_t *file_header)
static void FAST_FUNC header_verbose_list_ar(archive_handle_t *archive_handle)
{
const file_header_t *file_header = archive_handle->file_header;
char mode[12];
char *mtime;
+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;
}
+8 -1
View File
@@ -53,7 +53,7 @@
//config: help
//config: Optionally renumber inodes when creating archives.
//applet:IF_CPIO(APPLET(cpio, BB_DIR_BIN, BB_SUID_DROP))
//applet:IF_CPIO(APPLET(cpio, BB_DIR_USR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_CPIO) += cpio.o
@@ -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"
+177 -139
View File
@@ -41,30 +41,30 @@
//kbuild:lib-$(CONFIG_DPKG) += dpkg.o
//usage:#define dpkg_trivial_usage
//usage: "[-ilCPru] [-F OPT] PACKAGE"
//usage: IF_LONG_OPTS("-i|P|r|--unpack|--configure [--force-OPT]")IF_NOT_LONG_OPTS("-i|P|r|u|C [-F OPT]")" PACKAGE | -l [PATTERN]"
//usage:#define dpkg_full_usage "\n\n"
//usage: "Install, remove and manage Debian packages\n"
//usage: "Manage Debian packages\n"
//usage: IF_LONG_OPTS(
//usage: "\n -i,--install Install the package"
//usage: "\n -l,--list List of installed packages"
//usage: "\n --configure Configure an unpackaged package"
//usage: "\n -P,--purge Purge all files of a package"
//usage: "\n -r,--remove Remove all but the configuration files for a package"
//usage: "\n --unpack Unpack a package, but don't configure it"
//usage: "\n -i,--install Install PACKAGE.deb"
//usage: "\n -P,--purge Purge all files of PACKAGE"
//usage: "\n -r,--remove Remove all but configuration files of PACKAGE"
//usage: "\n --unpack Unpack PACKAGE.deb relative to /, don't configure"
//usage: "\n --configure Configure unpacked PACKAGE"
//usage: "\n --force-depends Ignore dependency problems"
//usage: "\n --force-confnew Overwrite existing config files when installing"
//usage: "\n --force-confold Keep old config files when installing"
//usage: "\n -l,--list List installed packages"
//usage: )
//usage: IF_NOT_LONG_OPTS(
//usage: "\n -i Install the package"
//usage: "\n -l List of installed packages"
//usage: "\n -C Configure an unpackaged package"
//usage: "\n -P Purge all files of a package"
//usage: "\n -r Remove all but the configuration files for a package"
//usage: "\n -u Unpack a package, but don't configure it"
//usage: "\n -i Install PACKAGE.deb"
//usage: "\n -P Purge all files of PACKAGE"
//usage: "\n -r Remove all but configuration files of PACKAGE"
//usage: "\n -u Unpack PACKAGE.deb relative to /, don't configure"
//usage: "\n -C Configure unpacked PACKAGE"
//usage: "\n -F depends Ignore dependency problems"
//usage: "\n -F confnew Overwrite existing config files when installing"
//usage: "\n -F confold Keep old config files when installing"
//usage: "\n -l List installed packages"
//usage: )
#include "libbb.h"
@@ -166,8 +166,9 @@ typedef struct deb_file_s {
} deb_file_t;
static void make_hash(const char *key, unsigned *start, unsigned *decrement, const int hash_prime)
static unsigned make_hash(const char *key, unsigned *decrement, int hash_prime)
{
unsigned start;
unsigned long hash_num = key[0];
int len = strlen(key);
int i;
@@ -181,8 +182,9 @@ static void make_hash(const char *key, unsigned *start, unsigned *decrement, con
* no effect */
hash_num += (key[i] + key[i-1]) << ((key[i] * i) % 24);
}
*start = (unsigned) hash_num % hash_prime;
start = (unsigned) hash_num % hash_prime;
*decrement = (unsigned) 1 + (hash_num % (hash_prime - 1));
return start;
}
/* this adds the key to the hash table */
@@ -191,7 +193,7 @@ static int search_name_hashtable(const char *key)
unsigned probe_address;
unsigned probe_decrement;
make_hash(key, &probe_address, &probe_decrement, NAME_HASH_PRIME);
probe_address = make_hash(key, &probe_decrement, NAME_HASH_PRIME);
while (name_hashtable[probe_address] != NULL) {
if (strcmp(name_hashtable[probe_address], key) == 0) {
return probe_address;
@@ -213,7 +215,7 @@ static unsigned search_status_hashtable(const char *key)
unsigned probe_address;
unsigned probe_decrement;
make_hash(key, &probe_address, &probe_decrement, STATUS_HASH_PRIME);
probe_address = make_hash(key, &probe_decrement, STATUS_HASH_PRIME);
while (status_hashtable[probe_address] != NULL) {
if (strcmp(key, name_hashtable[package_hashtable[status_hashtable[probe_address]->package]->name]) == 0) {
break;
@@ -280,7 +282,7 @@ static int version_compare_part(const char *val, const char *ref)
* if ver1 = ver2 return 0,
* if ver1 > ver2 return 1,
*/
static int version_compare(const unsigned ver1, const unsigned ver2)
static int version_compare(unsigned ver1, unsigned ver2)
{
char *ch_ver1 = name_hashtable[ver1];
char *ch_ver2 = name_hashtable[ver2];
@@ -333,9 +335,9 @@ static int version_compare(const unsigned ver1, const unsigned ver2)
return result;
}
static int test_version(const unsigned version1, const unsigned version2, const unsigned operator)
static int test_version(unsigned version1, unsigned version2, unsigned operator)
{
const int version_result = version_compare(version1, version2);
int version_result = version_compare(version1, version2);
switch (operator) {
case VER_ANY:
return TRUE;
@@ -353,12 +355,12 @@ static int test_version(const unsigned version1, const unsigned version2, const
return FALSE;
}
static int search_package_hashtable(const unsigned name, const unsigned version, const unsigned operator)
static int search_package_hashtable(unsigned name, unsigned version, unsigned operator)
{
unsigned probe_address;
unsigned probe_decrement;
make_hash(name_hashtable[name], &probe_address, &probe_decrement, PACKAGE_HASH_PRIME);
probe_address = make_hash(name_hashtable[name], &probe_decrement, PACKAGE_HASH_PRIME);
while (package_hashtable[probe_address] != NULL) {
if (package_hashtable[probe_address]->name == name) {
if (operator == VER_ANY) {
@@ -531,90 +533,98 @@ static void free_package(common_node_t *node)
}
/*
* Gets the next package field from package_buffer, separated into the field name
* and field value, it returns the int offset to the first character of the next field
* Gets the next package field from pkg_buf:
* "NAME:<spaces|tabs>VALUE{\n|NUL}"
* "NAME:<spaces|tabs>VALUE\n
* " VALUE_LINE2{\n|NUL}"
* separated into "NAME" and "VALUE", both strdup()ed.
* (Debian does not allow whitespace before/after NAME).
* Returns offset to the first character of the next field (or to NUL).
* The pkg_buf parameter is NUL-terminated.
*
* https://manpages.debian.org/testing/dpkg-dev/deb-control.5.en.html
* """
* This file contains a number of fields. Each field begins with a tag,
* such as Package or Version (case insensitive), followed by a colon,
* and the body of the field (case sensitive unless stated otherwise).
* Fields are delimited only by field tags. In other words, field text
* may be multiple lines in length, but the installation tools will
* generally join lines when processing the body of the field (except
* in the case of the Description field, see below).
* ...
* Description: short-description (recommended)
* long-description
* The format for the package description is a short brief summary
* on the first line (after the Description field). The following lines
* should be used as a longer, more detailed description. Each line
* of the long description must be preceded by a space, and blank
* lines in the long description must contain a single '.' following
* the preceding space."""
*
* Seen in libgtk-3-0t64_3.24.52: source package's control:
* Recommends: ibus-gtk3,
* libgtk-3-bin,
* librsvg2-common
* gets translated to this in binary package's control:
* Recommends: ibus-gtk3, libgtk-3-bin, librsvg2-common
*/
static int read_package_field(const char *package_buffer, char **field_name, char **field_value)
static int read_package_field(const char *pkg_buf, char **pname, char **pvalue)
{
int offset_name_start = 0;
int offset_name_end = 0;
int offset_value_start = 0;
int offset_value_end = 0;
int offset = 0;
int next_offset;
int name_length;
int value_length;
int exit_flag = FALSE;
int name_start;
int name_end;
int value_start = value_start;
int offset;
if (package_buffer == NULL) {
*field_name = NULL;
*field_value = NULL;
return -1;
}
*pname = NULL;
*pvalue = NULL;
offset = 0;
name_start = 0;
name_end = 0; /* "we did not see ':' yet" */
while (1) {
next_offset = offset + 1;
switch (package_buffer[offset]) {
case '\0':
exit_flag = TRUE;
break;
case ':':
if (offset_name_end == 0) {
offset_name_end = offset;
offset_value_start = next_offset;
}
/* TODO: Name might still have trailing spaces if ':' isn't
* immediately after name */
break;
case '\n':
/* TODO: The char next_offset may be out of bounds */
if (package_buffer[next_offset] != ' ') {
exit_flag = TRUE;
break;
}
case '\t':
case ' ':
/* increment the value start point if its a just filler */
if (offset_name_start == offset) {
offset_name_start++;
}
if (offset_value_start == offset) {
offset_value_start++;
}
break;
}
if (exit_flag) {
/* Check that the names are valid */
offset_value_end = offset;
name_length = offset_name_end - offset_name_start;
value_length = offset_value_end - offset_value_start;
if (name_length == 0) {
break;
char ch = pkg_buf[offset];
switch (ch) {
case ':':
if (name_end == 0) {
offset++;
name_end = offset; /* points AFTER ':' - think of empty NAME case */
while (isblank(pkg_buf[offset])) /* skip spaces/tabs (not newlines!) */
offset++;
value_start = offset;
continue; /* check next char */
}
if ((name_length > 0) && (value_length > 0)) {
break;
case '\n':
if (pkg_buf[offset + 1] == ' ')
break;
/* end of VALUE - fall through */
case '\0':
/* Did we see the ':'? */
if (name_end != 0) {
/* Yes. Check that NAME is not empty */
int nlen = (name_end - 1) - name_start;
if (nlen > 0) {
//TODO: why do we disallow empty NAME? Imagine a ": VALUE\n" line
*pname = xstrndup(&pkg_buf[name_start], nlen);
*pvalue = xstrndup(&pkg_buf[value_start], offset - value_start); /* could be "" */
if (ch)
offset++; /* skip '\n' */
return offset;
}
}
if (!ch)
return offset; /* stop at NUL */
/* If not valid, start fresh with next field */
exit_flag = FALSE;
offset_name_start = offset + 1;
offset_name_end = 0;
offset_value_start = offset + 1;
offset_value_end = offset + 1;
offset++;
/* Not valid: skip '\n', start fresh with next field */
name_start = offset + 1;
name_end = 0; /* "we did not see ':' yet" */
break;
}
offset++;
}
*field_name = NULL;
if (name_length) {
*field_name = xstrndup(&package_buffer[offset_name_start], name_length);
}
*field_value = NULL;
if (value_length > 0) {
*field_value = xstrndup(&package_buffer[offset_value_start], value_length);
}
return next_offset;
} /* while (1) */
}
/* The parameter is NUL-terminated */
static unsigned fill_package_struct(char *control_buffer)
{
static const char field_names[] ALIGN1 =
@@ -623,14 +633,13 @@ static unsigned fill_package_struct(char *control_buffer)
"Conflicts\0""Suggests\0""Recommends\0""Enhances\0";
common_node_t *new_node = xzalloc(sizeof(common_node_t));
char *field_name;
char *field_value;
int field_start = 0;
int num = -1;
int buffer_length = strlen(control_buffer);
int num;
new_node->version = search_name_hashtable("unknown");
while (field_start < buffer_length) {
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
unsigned field_num;
field_start += read_package_field(&control_buffer[field_start],
@@ -689,7 +698,7 @@ static unsigned fill_package_struct(char *control_buffer)
}
/* if num = 1, it returns the want status, 2 returns flag, 3 returns status */
static unsigned get_status(const unsigned status_node, const int num)
static unsigned get_status(unsigned status_node, int num)
{
char *status_string = name_hashtable[status_hashtable[status_node]->status];
char *state_sub_string;
@@ -711,9 +720,9 @@ static unsigned get_status(const unsigned status_node, const int num)
return state_sub_num;
}
static void set_status(const unsigned status_node_num, const char *new_value, const int position)
static void set_status(unsigned status_node_num, const char *new_value, int position)
{
const unsigned new_value_num = search_name_hashtable(new_value);
unsigned new_value_num = search_name_hashtable(new_value);
unsigned want = get_status(status_node_num, 1);
unsigned flag = get_status(status_node_num, 2);
unsigned status = get_status(status_node_num, 3);
@@ -771,9 +780,10 @@ static void index_status_file(const char *filename)
status_node_t *status_node = NULL;
unsigned status_num;
//FIXME: dpkg 1.22.22 recreates empty /var/lib/dpkg/status if it's missing - does not fail
status_file = xfopen_for_read(filename);
while ((control_buffer = xmalloc_fgetline_str(status_file, "\n\n")) != NULL) {
const unsigned package_num = fill_package_struct(control_buffer);
unsigned package_num = fill_package_struct(control_buffer);
if (package_num != -1) {
status_node = xmalloc(sizeof(status_node_t));
/* fill_package_struct doesn't handle the status field */
@@ -799,7 +809,7 @@ static void write_buffer_no_status(FILE *new_status_file, const char *control_bu
char *name;
char *value;
int start = 0;
while (1) {
while (control_buffer[start]) {
start += read_package_field(&control_buffer[start], &name, &value);
if (name == NULL) {
break;
@@ -807,42 +817,42 @@ static void write_buffer_no_status(FILE *new_status_file, const char *control_bu
if (strcmp(name, "Status") != 0) {
fprintf(new_status_file, "%s: %s\n", name, value);
}
free(name);
free(value);
}
}
/* This could do with a cleanup */
static void write_status_file(deb_file_t **deb_file)
{
//FIXME: dpkg 1.22.22 recreates empty /var/lib/dpkg/status if it's missing - does not fail
FILE *old_status_file = xfopen_for_read("/var/lib/dpkg/status");
FILE *new_status_file = xfopen_for_write("/var/lib/dpkg/status.udeb");
char *package_name;
char *status_from_file;
char *control_buffer = NULL;
char *tmp_string;
char *control_buffer;
int status_num;
int field_start = 0;
int write_flag;
int i = 0;
int i;
/* Update previously known packages */
while ((control_buffer = xmalloc_fgetline_str(old_status_file, "\n\n")) != NULL) {
char *package_name;
char *status_from_file;
char *tmp_string;
int write_flag;
tmp_string = strstr(control_buffer, "Package:");
if (tmp_string == NULL) {
free(control_buffer);
continue;
}
tmp_string += 8;
tmp_string += strspn(tmp_string, " \n\t");
tmp_string = skip_whitespace(tmp_string + 8);
package_name = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
write_flag = FALSE;
status_from_file = NULL;
tmp_string = strstr(control_buffer, "Status:");
if (tmp_string != NULL) {
/* Separate the status value from the control buffer */
tmp_string += 7;
tmp_string += strspn(tmp_string, " \n\t");
tmp_string = skip_whitespace(tmp_string + 7);
status_from_file = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
} else {
status_from_file = NULL;
}
/* Find this package in the status hashtable */
@@ -851,7 +861,7 @@ static void write_status_file(deb_file_t **deb_file)
const char *status_from_hashtable = name_hashtable[status_hashtable[status_num]->status];
if (strcmp(status_from_file, status_from_hashtable) != 0) {
/* New status isn't exactly the same as old status */
const int state_status = get_status(status_num, 3);
int state_status = get_status(status_num, 3);
if ((strcmp("installed", name_hashtable[state_status]) == 0)
|| (strcmp("unpacked", name_hashtable[state_status]) == 0)
) {
@@ -870,7 +880,7 @@ static void write_status_file(deb_file_t **deb_file)
}
i++;
}
/* This is temperary, debugging only */
/* This is temporary, debugging only */
if (deb_file[i] == NULL) {
bb_error_msg_and_die("ALERT: cannot find a control file, "
"your status file may be broken, status may be "
@@ -878,14 +888,18 @@ static void write_status_file(deb_file_t **deb_file)
}
}
else if (strcmp("not-installed", name_hashtable[state_status]) == 0) {
int field_start = 0;
/* Only write the Package, Status, Priority and Section lines */
fprintf(new_status_file, "Package: %s\n", package_name);
fprintf(new_status_file, "Status: %s\n", status_from_hashtable);
while (1) {
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
//FIXME: the questionable ": VALUE" lines (empty NAME)
//probably should not stop parsing of the entire file?
if (field_name == NULL) {
break;
}
@@ -894,13 +908,17 @@ static void write_status_file(deb_file_t **deb_file)
) {
fprintf(new_status_file, "%s: %s\n", field_name, field_value);
}
free(field_name);
free(field_value);
}
write_flag = TRUE;
fputs("\n", new_status_file);
}
else if (strcmp("config-files", name_hashtable[state_status]) == 0) {
int field_start = 0;
/* only change the status line */
while (1) {
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
@@ -913,13 +931,15 @@ static void write_status_file(deb_file_t **deb_file)
} else {
fprintf(new_status_file, "%s: %s\n", field_name, field_value);
}
free(field_name);
free(field_value);
}
write_flag = TRUE;
fputs("\n", new_status_file);
}
}
}
/* If the package from the status file wasn't handle above, do it now*/
/* If the package from the status file wasn't handled above, do it now */
if (!write_flag) {
fprintf(new_status_file, "%s\n\n", control_buffer);
}
@@ -927,7 +947,7 @@ static void write_status_file(deb_file_t **deb_file)
free(status_from_file);
free(package_name);
free(control_buffer);
}
} /* while (control_buffer) */
/* Write any new packages */
for (i = 0; deb_file[i] != NULL; i++) {
@@ -994,14 +1014,14 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
/* Create array of package numbers to check against
* installed package for conflicts*/
while (deb_file[i] != NULL) {
const unsigned package_num = deb_file[i]->package;
unsigned package_num = deb_file[i]->package;
conflicts = xrealloc_vector(conflicts, 2, conflicts_num);
conflicts[conflicts_num] = package_num;
conflicts_num++;
/* add provides to conflicts list */
for (j = 0; j < package_hashtable[package_num]->num_of_edges; j++) {
if (package_hashtable[package_num]->edge[j]->type == EDGE_PROVIDES) {
const int conflicts_package_num = search_package_hashtable(
int conflicts_package_num = search_package_hashtable(
package_hashtable[package_num]->edge[j]->name,
package_hashtable[package_num]->edge[j]->version,
package_hashtable[package_num]->edge[j]->operator);
@@ -1036,7 +1056,7 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
const edge_t *package_edge = package_node->edge[j];
if (package_edge->type == EDGE_CONFLICTS) {
const unsigned package_num =
unsigned package_num =
search_package_hashtable(package_edge->name,
package_edge->version,
package_edge->operator);
@@ -1065,7 +1085,7 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
for (i = 0; i < PACKAGE_HASH_PRIME; i++) {
int status_num = 0;
int number_of_alternatives = 0;
const edge_t * root_of_alternatives = NULL;
const edge_t *root_of_alternatives = NULL;
const common_node_t *package_node = package_hashtable[i];
/* If the package node does not exist then this
@@ -1381,12 +1401,12 @@ static void list_packages(const char *pattern)
}
}
static void remove_package(const unsigned package_num, int noisy)
static void remove_package(unsigned package_num, int noisy)
{
const char *package_name = name_hashtable[package_hashtable[package_num]->name];
const char *package_version = name_hashtable[package_hashtable[package_num]->version];
const unsigned status_num = search_status_hashtable(package_name);
const int package_name_length = strlen(package_name);
unsigned status_num = search_status_hashtable(package_name);
int package_name_length = strlen(package_name);
char **remove_files;
char **exclude_files;
char list_name[package_name_length + 25];
@@ -1432,11 +1452,11 @@ static void remove_package(const unsigned package_num, int noisy)
set_status(status_num, "config-files", 3);
}
static void purge_package(const unsigned package_num)
static void purge_package(unsigned package_num)
{
const char *package_name = name_hashtable[package_hashtable[package_num]->name];
const char *package_version = name_hashtable[package_hashtable[package_num]->version];
const unsigned status_num = search_status_hashtable(package_name);
unsigned status_num = search_status_hashtable(package_name);
char **remove_files;
char **exclude_files;
char list_name[strlen(package_name) + 25];
@@ -1654,8 +1674,8 @@ enum {
static void unpack_package(deb_file_t *deb_file)
{
const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
const unsigned status_num = search_status_hashtable(package_name);
const unsigned status_package_num = status_hashtable[status_num]->package;
unsigned status_num = search_status_hashtable(package_name);
unsigned status_package_num = status_hashtable[status_num]->package;
char *info_prefix;
char *list_filename;
archive_handle_t *archive_handle;
@@ -1689,7 +1709,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++;
}
@@ -1745,7 +1765,7 @@ static void configure_package(deb_file_t *deb_file)
{
const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
const char *package_version = name_hashtable[package_hashtable[deb_file->package]->version];
const int status_num = search_status_hashtable(package_name);
int status_num = search_status_hashtable(package_name);
printf("Setting up %s (%s)...\n", package_name, package_version);
@@ -1786,6 +1806,24 @@ int dpkg_main(int argc UNUSED_PARAM, char **argv)
"force-confold\0" No_argument "\xfd"
;
#endif
//--admindir=DIR
// Set the administrative directory to DIR. This directory
// contains many files that give information about status of
// installed or uninstalled packages, etc. Defaults to
// /var/lib/dpkg if DPKG_ADMINDIR has not been set.
//--instdir=DIR
// Set the installation directory, which refers to the directory
// where packages are to be installed. DIR is also the
// directory passed to chroot(2) before running package's
// installation scripts, which means that the scripts see DIR
// as a root directory. Defaults to / if DPKG_ROOT has not
// been set (since dpkg 1.21.10).
//--root=DIR
// Set the root directory to DIR, which sets the
// installation directory to DIR and the administrative
// directory to DIR/var/lib/dpkg if DPKG_ROOT
// has not been set (since dpkg 1.21.10).
//TODO: implement --root=DIR? necessary for testing
INIT_G();
+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
+6 -7
View File
@@ -463,13 +463,12 @@ static int get_next_block(bunzip_data *bd)
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
runCnt += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
//The 32-bit overflow of runCnt wasn't yet seen, but probably can happen.
//This would be the fix (catches too large count way before it can overflow):
// if (runCnt > bd->dbufSize) {
// dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
// runCnt, bd->dbufSize);
// return RETVAL_DATA_ERROR;
// }
/* Catch 32-bit overflow (we have an example .bz2 file) */
if ((int)runCnt < 0) {
dbg("runCnt:%u > dbufSize:%u RETVAL_DATA_ERROR",
runCnt, bd->dbufSize);
return RETVAL_DATA_ERROR;
}
if (runPos < bd->dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
}
+1 -1
View File
@@ -124,7 +124,7 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
typed->name[strcspn(typed->name, " /")] = '\0';
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_header(typed);
archive_handle->action_header(archive_handle);
#if ENABLE_DPKG || ENABLE_DPKG_DEB
if (archive_handle->dpkg__sub_archive) {
struct archive_handle_t *sa = archive_handle->dpkg__sub_archive;
+1 -1
View File
@@ -125,7 +125,7 @@ char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
//cpio: etc/hosts not created: newer or same age file exists
//etc/hosts <-- should NOT show it
//2 blocks <-- should say "0 blocks"
archive_handle->action_header(file_header);
archive_handle->action_header(archive_handle);
} else {
data_skip(archive_handle);
}
+10 -3
View File
@@ -454,15 +454,22 @@ 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 */
cp = last_char_is(file_header->name, '/');
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_header(/*archive_handle->*/ file_header);
archive_handle->action_header(archive_handle);
/* Note that we kill the '/' only after action_header() */
/* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
if (cp)
+7 -2
View File
@@ -5,8 +5,13 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_list(const file_header_t *file_header)
void FAST_FUNC header_list(archive_handle_t *archive_handle)
{
//TODO: cpio -vp DIR should output "DIR/NAME", not just "NAME" */
puts(file_header->name);
const file_header_t *file_header = archive_handle->file_header;
/* "tar xvOf TARFILE >OUTFILE" should use stderr for file list output: */
FILE *fp = (archive_handle->action_data == data_extract_to_stdout) ? stderr : stdout;
fprintf(fp, "%s\n", printable_string(file_header->name));
}
+1 -1
View File
@@ -5,6 +5,6 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_skip(const file_header_t *file_header UNUSED_PARAM)
void FAST_FUNC header_skip(archive_handle_t *archive_handle UNUSED_PARAM)
{
}
+10 -7
View File
@@ -5,11 +5,14 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_verbose_list(const file_header_t *file_header)
void FAST_FUNC header_verbose_list(archive_handle_t *archive_handle)
{
const file_header_t *file_header = archive_handle->file_header;
struct tm tm_time;
struct tm *ptm = &tm_time; //localtime(&file_header->mtime);
char modestr[12];
/* "tar xvvOf TARFILE >OUTFILE" should use stderr for file list output: */
FILE *fp = (archive_handle->action_data == data_extract_to_stdout) ? stderr : stdout;
#if ENABLE_FEATURE_TAR_UNAME_GNAME
char uid[sizeof(int)*3 + 2];
@@ -29,7 +32,7 @@ void FAST_FUNC header_verbose_list(const file_header_t *file_header)
/*sprintf(gid, "%u", (unsigned)file_header->gid);*/
group = utoa(file_header->gid);
}
printf("%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
fprintf(fp, "%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
user,
group,
@@ -40,13 +43,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));
#else /* !FEATURE_TAR_UNAME_GNAME */
localtime_r(&file_header->mtime, ptm);
printf("%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
fprintf(fp, "%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
(unsigned)file_header->uid,
(unsigned)file_header->gid,
@@ -57,13 +60,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);
fprintf(fp, " -> %s", printable_string(file_header->link_target));
}
bb_putchar('\n');
putc('\n', fp);
}
-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;
+36 -6
View File
@@ -5,23 +5,48 @@
#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;
/* if "..": malicious, return "" */
/* (causes harmless errors trying to create or hardlink a file named "") */
if (cp[0] == '.' && cp[1] == '.' && cp[2] == '\0')
return cp + 2;
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 +58,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));
}
+47 -7
View File
@@ -17,25 +17,65 @@ void FAST_FUNC create_or_remember_link(llist_t **link_placeholders,
return;
}
if (symlink(target, linkname) != 0) {
/* shared message */
// shared message
bb_perror_msg_and_die("can't create %slink '%s' to '%s'",
"sym", linkname, target
);
}
}
static int all_dir_components_are_dirs(char *path)
{
struct stat sb;
char *slash;
slash = path;
while ((slash = strchr(slash, '/')) != NULL) {
int ok;
*slash = '\0';
ok = (lstat(path, &sb) == 0 && S_ISDIR(sb.st_mode));
*slash++ = '/';
if (!ok)
return 0;
}
return 1;
}
void FAST_FUNC create_links_from_list(llist_t *list)
{
// This idea sounds better (fewer file ops):
// Create hardlinks first, then symlinks.
// ^^^ but it breaks the "hardlink to symlink" case:
// mkdir dir
// >dir/a
// ln -s ../dir/a dir/b
// ln dir/b dir/c
// mkdir new; tar cf - dir/a dir/b dir/c | tar -C new -xvf -
// On extract, 'c' will have no 'b' to be a hardlink to.
while (list) {
char *target;
char *linkname = list->data + 1;
target = list->data + 1 + strlen(list->data + 1) + 1;
if ((*list->data ? link : symlink) (target, list->data + 1)) {
/* shared message */
bb_error_msg_and_die("can't create %slink '%s' to '%s'",
*list->data ? "hard" : "sym",
list->data + 1, target
target = linkname + strlen(linkname) + 1;
// Check whether the linkname has suspicious components:
// SYMLINK_OUTSIDE_EXTRACT_DIR/etc/passwd sort of thing.
// (Our delayed creation of symlinks is not defending against it,
// we could create SYMLINK_OUTSIDE_EXTRACT_DIR ourself!)
if (!all_dir_components_are_dirs(linkname)) {
errno = ENOTDIR;
goto err;
}
if ((list->data[0] ? link : symlink) (target, linkname)) {
// shared message
err:
bb_perror_msg_and_die("can't create %slink '%s' to '%s'",
list->data[0] ? "hard" : "sym",
linkname, target
);
// Note: GNU tar 1.34 errors out only _after_ all links are (attempted to be) created
// We bail out at once
}
list = list->link;
}
+6 -7
View File
@@ -154,7 +154,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
unsigned lit = 0;
unsigned next_lit = NO_LIT;
unsigned nl;
unsigned long o_m1_a = 0, o_m1_b = 0, o_m2 = 0, o_m3_a = 0, o_m3_b = 0;
// unsigned long o_m1_a = 0, o_m1_b = 0, o_m2 = 0, o_m3_a = 0, o_m3_b = 0;
// LZO_UNUSED(wrkmem);
@@ -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 */
@@ -228,7 +227,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
*litp = (unsigned char)((*litp & ~3) | lit);
/* copy over the 2 literals that replace the match */
copy2(ip-2, m_pos, pd(op, m_pos));
o_m1_a++;
// o_m1_a++;
}
/* test if a literal run follows */
else
@@ -250,7 +249,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit += 2 + t + 3;
*litp = (unsigned char)(lit - 3);
o_m1_b++;
// o_m1_b++;
*op++ = *m_pos++;
*op++ = *m_pos++;
goto copy_literal_run;
@@ -285,7 +284,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
/* set new length of previous literal run */
lit += 3 + t + 3;
*litp = (unsigned char)(lit - 3);
o_m2++;
// o_m2++;
*op++ = *m_pos++;
*op++ = *m_pos++;
*op++ = *m_pos++;
@@ -331,7 +330,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
*litp = (unsigned char)((*litp & ~3) | lit);
/* copy over the 3 literals that replace the match */
copy3(ip-3, m_pos, pd(op, m_pos));
o_m3_a++;
// o_m3_a++;
}
/* test if a literal run follows */
else if (t == 1 && lit <= 3 && nl == 0
@@ -350,7 +349,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit += 3 + t + 3;
*litp = (unsigned char)(lit - 3);
o_m3_b++;
// o_m3_b++;
*op++ = *m_pos++;
*op++ = *m_pos++;
*op++ = *m_pos++;
+15 -4
View File
@@ -116,8 +116,13 @@ static int rpm_gettags(const char *filename)
xread(fd, &header, sizeof(header));
if (header.magic_and_ver != htonl(RPM_HEADER_MAGICnVER))
bb_error_msg_and_die("invalid RPM header magic in '%s'", filename);
#if BB_LITTLE_ENDIAN
header.size = ntohl(header.size);
#endif
cnt = ntohl(header.entries);
/* Prevent multiplication overflow leading to undersized allocations */
if (sizeof(cnt) <= 4 && cnt >= 0x00400000) /* ~4 million */
bb_error_msg_and_die("bad RPM header.entries:%u", cnt);
storepos += sizeof(header) + cnt * 16;
G.tagcount += cnt;
@@ -125,9 +130,11 @@ static int rpm_gettags(const char *filename)
xread(fd, &tags[idx], sizeof(tags[0]) * cnt);
while (cnt--) {
rpm_index *tag = &tags[idx];
#if BB_LITTLE_ENDIAN
tag->tag = ntohl(tag->tag);
tag->type = ntohl(tag->type);
tag->count = ntohl(tag->count);
#endif
tag->offset = storepos + ntohl(tag->offset);
if (pass == 0)
tag->tag -= 743;
@@ -146,7 +153,6 @@ static int rpm_gettags(const char *filename)
storepos = (storepos + G_pagesize) & -(int)G_pagesize;
/* remember size for munmap */
G.mapsize = storepos;
/* some NOMMU systems prefer MAP_PRIVATE over MAP_SHARED */
G.map = mmap_read(fd, storepos);
if (G.map == MAP_FAILED)
bb_perror_msg_and_die("mmap '%s'", filename);
@@ -316,7 +322,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,15 +539,20 @@ 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 = rpm_getstr0(TAG_PAYLOADCOMPRESSOR);
if (ENABLE_FEATURE_SEAMLESS_LZMA
&& (str = rpm_getstr0(TAG_PAYLOADCOMPRESSOR)) != NULL
&& str != NULL
&& strcmp(str, "lzma") == 0
) {
// lzma compression can't be detected
// 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)
+7 -3
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
@@ -427,7 +428,7 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
/* GNU "tar cvvf" prints "extended" listing a-la "ls -l" */
/* We don't have such excesses here: for us "v" == "vv" */
/* '/' is probably a GNUism */
fprintf(vbFd, "%s%s\n", header_name,
fprintf(vbFd, "%s%s\n", printable_string(header_name),
S_ISDIR(statbuf->st_mode) ? "/" : "");
}
@@ -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);
+30 -1
View File
@@ -29,6 +29,11 @@
//config: bool "Enable --reflink[=auto]"
//config: default y
//config: depends on FEATURE_CP_LONG_OPTIONS
//config:
//config:config FEATURE_CP_SPARSE
//config: bool "Enable --sparse=WHEN"
//config: default y
//config: depends on FEATURE_CP_LONG_OPTIONS
//applet:IF_CP(APPLET_NOEXEC(cp, cp, BB_DIR_BIN, BB_SUID_DROP, cp))
/* NOEXEC despite cases when it can be a "runner" (cp -r LARGE_DIR NEW_DIR) */
@@ -108,6 +113,8 @@
#include "libbb.h"
#include "libcoreutils/coreutils.h"
#define DBG_OPTION_PARSING 0
/* This is a NOEXEC applet. Be very careful! */
int cp_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
@@ -129,6 +136,9 @@ int cp_main(int argc, char **argv)
};
# if ENABLE_FEATURE_CP_REFLINK
char *reflink = NULL;
# endif
# if ENABLE_FEATURE_CP_SPARSE
char *sparse = NULL;
# endif
flags = getopt32long(argv, "^"
FILEUTILS_CP_OPTSTR
@@ -158,12 +168,20 @@ int cp_main(int argc, char **argv)
"parents\0" No_argument "\xfe"
# if ENABLE_FEATURE_CP_REFLINK
"reflink\0" Optional_argument "\xfd"
# endif
# if ENABLE_FEATURE_CP_SPARSE
"sparse\0" Required_argument "\xfc"
# endif
, &last
# if ENABLE_FEATURE_CP_REFLINK
, &reflink
# endif
# if ENABLE_FEATURE_CP_SPARSE
// NOP for now
, &sparse
# endif
);
# if ENABLE_FEATURE_CP_REFLINK
BUILD_BUG_ON((int)OPT_reflink != (int)FILEUTILS_REFLINK);
if (flags & FILEUTILS_REFLINK) {
@@ -175,6 +193,16 @@ int cp_main(int argc, char **argv)
bb_show_usage();
}
# endif
# if DBG_OPTION_PARSING
bb_error_msg("flags: 0x%08x", flags);
# define showopt(o) bb_error_msg("flags & %s(%x):\t%x", #o, o, flags & o);
showopt(FILEUTILS_RMDEST );
showopt(OPT_parents );
showopt(OPT_reflink );
showopt(FILEUTILS_REFLINK_ALWAYS);
return 0;
# undef showopt
# endif
#else
flags = getopt32(argv, "^"
FILEUTILS_CP_OPTSTR
@@ -215,7 +243,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.
+2 -1
View File
@@ -156,7 +156,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
const char *prefix;
const char *username;
#if ENABLE_SELINUX
security_context_t scontext = NULL;
char *scontext = NULL;
#endif
if (ENABLE_GROUPS && (!ENABLE_ID || applet_name[0] == 'g')) {
@@ -230,6 +230,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
prefix = ",";
}
} else if (n < 0) { /* error in get_groups() */
bb_putchar('\n');
if (ENABLE_DESKTOP)
bb_simple_error_msg_and_die("can't get groups");
return EXIT_FAILURE;
+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
+2 -2
View File
@@ -73,7 +73,7 @@ static const char install_longopts[] ALIGN1 =
static void setdefaultfilecon(const char *path)
{
struct stat s;
security_context_t scontext = NULL;
char *scontext = NULL;
if (!is_selinux_enabled()) {
return;
@@ -119,7 +119,7 @@ int install_main(int argc, char **argv)
int ret = EXIT_SUCCESS;
int isdir;
#if ENABLE_SELINUX
security_context_t scontext;
char *scontext;
bool use_default_selinux_context = 1;
#endif
enum {
+546
View File
@@ -0,0 +1,546 @@
/* vi: set sw=4 ts=4: */
/*
* join -- equality join on two files
*
* Written by Morgan Bartlett
* Copyright (C) 2025 Morgan Bartlett
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config JOIN
//config: bool "join (6.6 kb)"
//config: default y
//config: help
//config: Equality join on two files
//applet:IF_JOIN(APPLET_NOEXEC(join, join, BB_DIR_USR_BIN, BB_SUID_DROP, join))
//kbuild:lib-$(CONFIG_JOIN) += join.o
//usage:#define join_trivial_usage
//usage: "[-a 1|2 | -v 1|2] [-e STR] [-o LIST] [-t SEP_CHAR] [-1 NUM] [-2 NUM] FILE1 FILE2"
//usage:#define join_full_usage "\n\n"
//usage: "Join FILE1 and FILE2, writing to stdout\n"
//usage: "\n -a 1|2 Also write unpaired lines from FILE1/2"
//usage: "\n -v 1|2 Only write unpaired lines from FILE1/2"
//usage: "\n -e STR Replace empty fields with STR"
//usage: "\n -o LIST Write the fields in LIST"
//usage: "\n -t CHAR Use a different field separator"
//usage: "\n -1 NUM Join on field NUM from FILE1"
//usage: "\n -2 NUM Join on field NUM from FILE2"
//usage: "\n"
//usage: "\nLIST is a space or comma separated list of 1/2.FIELD or 0 (the join field)"
#include "libbb.h"
#include "unicode.h"
#include "common_bufsiz.h"
/* This is a NOEXEC applet. Be very careful! */
typedef struct {
char *line;
char **fields;
int fieldcount;
} LINE;
typedef struct {
FILE *fp;
int idx; /* index of join field in fields array */
const char *field; /* pointer to lines[0].fields[idx] or "" */
LINE *lines;
LINE pushback;
int linecount; /* number of lines currently cached */
int linecap; /* current capacity of lines array */
} FDAT;
/* "globals" can be made local to main(), but then passing them
down the callchains as parameters requires ~90 bytes of code (on x86).
*/
struct globals {
int *format; // = NULL;
const char *empty_str;
/* \0 can't be separator, 0 means: "whitespace+" pattern */
char sep; // = 0;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
#define INIT_G() do { \
setup_common_bufsiz(); \
/* we have to zero it out because of NOEXEC */ \
memset(&G, 0, sizeof(G)); \
} while (0)
/* split s by sep, and put the results into *curr */
static void field_split(char *s, LINE *curr)
{
/* compare awk_split from editors/awk.c */
int n;
char *ps = s;
char *s1 = s;
char **sl;
size_t sn;
/* in worst case, every character is a separator */
curr->fields = sl = xzalloc(sizeof(char*) * (strlen(s) + 2));
curr->line = s;
n = 0;
if (G.sep != '\0') { /* single-character split */
while ((s1 = strchr(ps, G.sep)) != NULL) {
sl[n] = ps;
*s1 = '\0';
ps = s1 + 1;
n++;
}
/* Add the last field */
sl[n] = ps;
n++;
curr->fieldcount = n;
return;
}
/* default split: skip the initial whitespace and then any run
of non-whitespace characters is a field */
while (*s) {
/* blanks are space and tab in the POSIX locale */
while (*s == ' ' || *s == '\t')
s++;
if (!*s)
break;
s1 = strpbrk(s, " \t");
if (s1 == NULL) {
/* last field */
sn = strlen(s);
} else {
sn = s1 - s;
*s1 = '\0';
}
sl[n] = s;
n++;
s += sn + 1;
}
curr->fieldcount = n;
}
static inline void freefields(LINE *lp)
{
free(lp->line);
free(lp->fields);
lp->line = NULL;
lp->fields = NULL;
}
static void freelines(FDAT *f)
{
for (int n = 0; n < f->linecount; n++) {
freefields(f->lines + n);
}
f->linecount = 0;
f->field = "";
}
static void readfields(FDAT *f)
{
LINE curr = { .line = NULL, .fields = NULL, .fieldcount = 0 };
char *line;
const char *field2;
bool first = TRUE;
freelines(f);
while (true) {
if (first && f->pushback.fields) {
/* first check for a pushed back line */
curr = f->pushback;
f->pushback = (LINE) { .line = NULL, .fields = NULL, .fieldcount = 0 };
} else {
/* read a line and split */
line = xmalloc_fgetline(f->fp);
if (line == NULL) {
return;
}
field_split(line, &curr);
}
if (f->idx >= curr.fieldcount)
field2 = "";
else
field2 = curr.fields[f->idx];
/* Ensure strcmp() matches on first pass through loop */
if (first)
f->field = field2;
if (strcmp(f->field, field2) == 0) {
/* add to the stack */
if (f->linecount == f->linecap) {
f->linecap = f->linecap ? f->linecap * 2 : 8;
f->lines = xrealloc(f->lines, sizeof(LINE) * f->linecap);
}
f->lines[f->linecount++] = curr;
} else {
f->pushback = curr;
return;
}
first = FALSE;
}
}
static inline const char *fieldorempty(const char *field)
{
if (*field == '\0')
return G.empty_str;
return field;
}
static void printfields(FDAT *f1, FDAT *f2)
{
const char *field = (f1 == NULL) ? f2->field : f1->field;
int linef1;
int linef2;
int fn;
int format_fl;
int format_idx;
int *formatcurr;
bool first;
char sep;
LINE *l1;
LINE *l2;
sep = (G.sep == '\0') ? ' ' : G.sep;
for (linef1 = 0; linef1 < (f1 ? f1->linecount : 1); linef1++) {
l1 = f1 ? &f1->lines[linef1] : NULL;
for (linef2 = 0; linef2 < (f2 ? f2->linecount : 1); linef2++) {
l2 = f2 ? &f2->lines[linef2] : NULL;
if (G.format) {
/*
Format is a sort of null-terminated array:
They are indexed by [n] for file number and [n + 1] for field number.
If file number is 0 then that is the null-terminator.
If file number is neither 1 nor 2 then we have the join field.
*/
first = true;
formatcurr = G.format;
while (formatcurr[0]) {
if (first)
first = false;
else
bb_putchar(sep);
format_fl = formatcurr[0];
format_idx = formatcurr[1];
if (format_fl == 1) {
if (l1 != NULL && l1->fieldcount > format_idx)
fputs_stdout(fieldorempty(l1->fields[format_idx]));
else
fputs_stdout(G.empty_str);
} else if (format_fl == 2) {
if (l2 != NULL && l2->fieldcount > format_idx)
fputs_stdout(fieldorempty(l2->fields[format_idx]));
else
fputs_stdout(G.empty_str);
} else
fputs_stdout(fieldorempty(field));
formatcurr += 2;
}
} else {
fputs_stdout(fieldorempty(field));
fn = 0;
if (l1 != NULL)
while (l1->fields[fn]) {
if (fn != f1->idx) {
bb_putchar(sep);
fputs_stdout(fieldorempty(l1->fields[fn]));
}
fn++;
}
fn = 0;
if (l2 != NULL)
while (l2->fields[fn]) {
if (fn != f2->idx) {
bb_putchar(sep);
fputs_stdout(fieldorempty(l2->fields[fn]));
}
fn++;
}
}
bb_putchar('\n');
}
}
}
static void parsejformat(const char *format_str)
{
int *format;
int field_idx;
char scache[20] = { 0 };
int n = 0;
const char *s1 = format_str;
size_t sn;
/* The most formats we can have is if the format_str is noted as 0,0,0,0
which ends up being (strlen + 1) / 2
and then we need to have two for each entry plus one for the terminator.
( (strlen+1) / 2 * 2 is optimized out in the alloc) */
G.format = format = xzalloc(sizeof(format[0]) * ((strlen(format_str) + 1) + 1));
/* default split: skip the initial whitespace and then any run
of non-whitespace characters is a field */
while (*format_str) {
/* blanks are space and tab in the POSIX locale */
while (*format_str == ' ' || *format_str == '\t' || *format_str == ',')
format_str++;
if (!*format_str)
break;
s1 = strpbrk(format_str, " \t,");
if (s1 == NULL)
/* last field */
sn = strlen(format_str);
else
sn = s1 - format_str;
if (sn == 1 && *format_str == '0') {
format[n * 2] = 3;
} else if (sn >= 3 && (*format_str == '1' || *format_str == '2') && format_str[1] == '.') {
if (sn > 21) /* res_str > 19 */
bb_simple_error_msg_and_die("field specifier too large");
memcpy(scache, format_str + 2, sn - 2);
scache[sn - 2] = '\0';
field_idx = xatoi_positive(scache);
if (--field_idx < 0)
bb_simple_error_msg_and_die("field number can't be 0");
format[n * 2] = *format_str - '0';
format[n * 2 + 1] = field_idx;
} else {
bb_simple_error_msg_and_die("field specifier must be 0, 1.x or 2.x");
}
n++;
format_str += sn;
}
}
int join_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int join_main(int argc UNUSED_PARAM, char **argv)
{
struct {
llist_t *unpaired_list; // = NULL;
const char *format_str; // = NULL;
bool print1unpaired; // = false;
bool print2unpaired; // = false;
bool printpaired;
FDAT f1; // = { };
FDAT f2; // = { };
} L;
#define unpaired_list L.unpaired_list
#define format_str L.format_str
#define print1unpaired L.print1unpaired
#define print2unpaired L.print2unpaired
#define printpaired L.printpaired
#define f1 L.f1
#define f2 L.f2
char *separator;
uint32_t opts;
/* Must match getopt32 call */
enum {
FLAG_UNPAIRED_ADD = (1 << 0),
FLAG_UNPAIRED_ONLY = (1 << 1),
FLAG_EMPTY_STRING = (1 << 2),
FLAG_LIST_OUTPUT = (1 << 3),
FLAG_SEP_USED = (1 << 4),
FLAG_FIELD_1 = (1 << 5),
FLAG_FIELD_2 = (1 << 6),
};
INIT_G();
G.empty_str = "";
memset(&L, 0, sizeof(L));
init_unicode();
opts = getopt32(argv,
"^a:*v:*"
"e:"
"o:"
"t:"
"1:+2:+"
"\0""=2:a--v:v--a",
&unpaired_list,
&unpaired_list,
&G.empty_str,
&format_str,
&separator,
&f1.idx,
&f2.idx);
argv += optind;
printpaired = !(opts & FLAG_UNPAIRED_ONLY);
if (opts & (FLAG_UNPAIRED_ADD|FLAG_UNPAIRED_ONLY)) {
char *unpaired_str;
while ((unpaired_str = llist_pop(&unpaired_list)) != NULL) {
if (*unpaired_str == '1')
print1unpaired = true;
else if (*unpaired_str == '2')
print2unpaired = true;
else
bb_show_usage();
if (unpaired_str[1])
bb_show_usage();
}
}
if (((opts & FLAG_FIELD_1) && --f1.idx < 0)
|| ((opts & FLAG_FIELD_2) && --f2.idx < 0)
) {
bb_simple_error_msg_and_die("field 0 doesn't exist");
}
if (opts & FLAG_SEP_USED) {
if (separator[0] && separator[1])
bb_simple_error_msg_and_die("separators are single characters");
G.sep = *separator;
}
if (opts & FLAG_LIST_OUTPUT)
parsejformat(format_str);
f1.fp = xfopen_stdin(argv[0]);
f2.fp = xfopen_stdin(argv[1]);
if (f1.fp == f2.fp)
bb_simple_error_msg_and_die("can't combine stdin with itself");
/*
Outline of the program:
- Read a line set from each file into cache
- While there are cached current lines from both files:
- If the two indexing fields are the same:
- If no unpaired_only options:
- Print joined line set formatted with fields
- Read line sets from both files
- Elseif indexing1 < indexing2 then
- If print1unpaired:
- Print line set from file 1
- Read another line set from file 1
- Elseif indexing1 > indexing2 then
- If print2unpaired:
- Print line set from file 2
- Read another line set from file 2
- If there are cached lines from file 1 AND print1unpaired:
- Print the rest of the lines from file 1
- If there are cached lines from file 2 AND print2unpaired:
- Print the rest of the lines from file 2
*/
/*
Notes for POSIX:
https://pubs.opengroup.org/onlinepubs/9699919799/utilities/join.html
Multiple instances of the same key are meant to give combinatorial results.
E.g:
file1:
a 1
a 2
file2:
a A
a B
a C
result:
a 1 A
a 1 B
a 1 C
a 2 A
a 2 B
a 2 C
This is done in this implementation by reading all the lines that have the same key
and then iterating through the combinations when printing them.
(test with `./busybox join <(printf 'a 1\na 2\n';) <(printf 'a A\na B\na C\n')`)
*/
readfields(&f1);
readfields(&f2);
while (f1.linecount != 0 && f2.linecount != 0) {
int res = strcmp(f1.field, f2.field);
if (res == 0) {
if (printpaired)
printfields(&f1, &f2);
readfields(&f1);
readfields(&f2);
} else if (res < 0) {
if (print1unpaired)
printfields(&f1, NULL);
readfields(&f1);
} else {
if (print2unpaired)
printfields(NULL, &f2);
readfields(&f2);
}
}
if (print1unpaired) {
while (f1.linecount != 0) {
printfields(&f1, NULL);
readfields(&f1);
}
}
if (print2unpaired) {
while (f2.linecount != 0) {
printfields(NULL, &f2);
readfields(&f2);
}
}
#if ENABLE_FEATURE_CLEAN_UP
if (f1.linecap) {
freelines(&f1);
free(f1.lines);
}
if (f2.linecap) {
freelines(&f2);
free(f2.lines);
}
free(G.format);
fclose_if_not_stdin(f1.fp);
fclose_if_not_stdin(f2.fp);
#endif
fflush_stdout_and_exit_SUCCESS();
}
+1 -1
View File
@@ -26,7 +26,7 @@ mode_t FAST_FUNC getopt_mk_fifo_nod(char **argv)
mode_t mode = 0666;
char *smode = NULL;
#if ENABLE_SELINUX
security_context_t scontext;
char *scontext;
#endif
int opt;
opt = getopt32(argv, "m:" IF_SELINUX("Z:"), &smode IF_SELINUX(,&scontext));
+179 -91
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),
};
/*
@@ -283,7 +311,7 @@ struct dnode {
const char *name; /* usually basename, but think "ls -l dir/file" */
const char *fullname; /* full name (usable for stat etc) */
struct dnode *dn_next; /* for linked list */
IF_SELINUX(security_context_t sid;)
IF_SELINUX(char *sid;)
smallint fname_allocated;
/* Used to avoid re-doing [l]stat at printout stage
@@ -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);
}
}
+1 -1
View File
@@ -57,7 +57,7 @@ int mkdir_main(int argc UNUSED_PARAM, char **argv)
unsigned opt;
char *smode;
#if ENABLE_SELINUX
security_context_t scontext;
char *scontext;
#endif
opt = getopt32long(argv, "m:pv" IF_SELINUX("Z:"),
+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)
+8 -8
View File
@@ -354,7 +354,8 @@ 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);
const char *arg = "0";
/* needed - try "printf %" without it */
if (p == NULL || *f == '\0') {
bb_error_msg("%s: invalid format", direc_start);
@@ -373,15 +374,14 @@ static char **print_formatted(char *f, char **argv, int *conv_err)
direc_length += 2;
direc_start = p;
} else {
if (p - format_chars >= 11) /* %c or %s? */
++arg; /* "" */
p = NULL;
}
if (*argv) {
print_direc(direc_start, direc_length, field_width,
precision, *argv++);
} else {
print_direc(direc_start, direc_length, field_width,
precision, "");
}
if (*argv)
arg = *argv++;
print_direc(direc_start, direc_length, field_width,
precision, arg);
*conv_err |= errno;
free(p);
}
+13 -6
View File
@@ -163,13 +163,18 @@ static char *get_key(char *str, struct sort_key *key, int flags)
/* Loop through fields */
else {
unsigned char ch = 0;
/* -kSTART,N.ENDCHAR: stop at the start of field N instead
* of its end, ENDCHAR below is an offset from there */
unsigned fields = key->range[2*j] + j;
if (j && key->range[3])
fields--;
end = 0;
for (i = 1; i < key->range[2*j] + j; i++) {
for (i = 1; i < fields; i++) {
if (key_separator) {
/* Skip body of key and separator */
while ((ch = str[end]) != '\0') {
end++;
end++;
if (ch == key_separator)
break;
}
@@ -186,9 +191,9 @@ static char *get_key(char *str, struct sort_key *key, int flags)
}
}
/* Remove last delim: "abc:def:" => "abc:def" */
if (j && ch) {
if (j && ch && !key->range[3]) {
//if (str[end-1] != key_separator)
// bb_error_msg(_and_die("BUG! "
// bb_error_msg_and_die("BUG! "
// "str[start:%d,end:%d]:'%.*s'",
// start, end, (int)(end-start), &str[start]);
end--;
@@ -203,9 +208,11 @@ static char *get_key(char *str, struct sort_key *key, int flags)
/* Strip trailing whitespace if necessary */
if (flags & FLAG_bb)
while (end > start && isspace(str[end-1])) end--;
/* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based) */
/* -kSTART,N.ENDCHAR: honor ENDCHAR (1-based), counted from the
* start of field N, which the loop above stopped at
*/
if (key->range[3]) {
end = key->range[3];
end += key->range[3];
if (end > len) end = len;
}
/* -kN.STARTCHAR[,...]: honor STARTCHAR (1-based) */
+84 -72
View File
@@ -248,53 +248,84 @@ static void strcatc(char *str, char c)
str[len] = '\0';
}
static void printfs(char *pformat, const char *msg)
/* printf is a vararg function, on some arches varargs
* require more code, increasing code size win
* from factoring out common uses of printf into
* non-vararg functions.
*/
static void printf_s(char *pformat, const char *msg)
{
strcatc(pformat, 's');
printf(pformat, msg);
}
static void printf_lu(char *pformat, unsigned long v)
{
strcat(pformat, "lu");
printf(pformat, v);
}
static void printf_llu(char *pformat, unsigned long long v)
{
strcat(pformat, "llu");
printf(pformat, v);
}
static void printf_lx(char *pformat, unsigned long v)
{
strcat(pformat, "lx");
printf(pformat, v);
}
static void printf_llx(char *pformat, unsigned long long v)
{
strcat(pformat, "llx");
printf(pformat, v);
}
static void printf_time_t(char *pformat, time_t val)
{
#define TYPE_SIGNED(t) ((t) -1 < (t) 0)
if (TYPE_SIGNED(time_t)) {
strcat(pformat, "lld");
printf(pformat, (long long) val);
} else {
printf_llu(pformat, val);
}
}
#if ENABLE_FEATURE_STAT_FILESYSTEM
/* print statfs info */
static void FAST_FUNC print_statfs(char *pformat, const char m,
const char *const filename, const void *data
IF_SELINUX(, security_context_t scontext))
IF_SELINUX(, char *scontext))
{
const struct statfs *statfsbuf = data;
if (m == 'n') {
printfs(pformat, filename);
printf_s(pformat, filename);
} else if (m == 'i') {
strcat(pformat, "llx");
printf(pformat, get_f_fsid(statfsbuf));
printf_llx(pformat, get_f_fsid(statfsbuf));
} else if (m == 'l') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statfsbuf->f_namelen);
printf_lu(pformat, statfsbuf->f_namelen);
} else if (m == 't') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statfsbuf->f_type); /* no equiv */
printf_lx(pformat, statfsbuf->f_type); /* no equiv */
} else if (m == 'T') {
printfs(pformat, human_fstype(statfsbuf->f_type));
printf_s(pformat, human_fstype(statfsbuf->f_type));
} else if (m == 'b') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_blocks);
printf_llu(pformat, statfsbuf->f_blocks);
} else if (m == 'f') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_bfree);
printf_llu(pformat, statfsbuf->f_bfree);
} else if (m == 'a') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_bavail);
printf_llu(pformat, statfsbuf->f_bavail);
} else if (m == 's' || m == 'S') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statfsbuf->f_bsize);
printf_lu(pformat, statfsbuf->f_bsize);
} else if (m == 'c') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_files);
printf_llu(pformat, statfsbuf->f_files);
} else if (m == 'd') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statfsbuf->f_ffree);
printf_llu(pformat, statfsbuf->f_ffree);
# if ENABLE_SELINUX
} else if (m == 'C' && (option_mask32 & OPT_SELINUX)) {
printfs(pformat, scontext);
printf_s(pformat, scontext);
# endif
} else {
strcatc(pformat, 'c');
@@ -306,15 +337,14 @@ static void FAST_FUNC print_statfs(char *pformat, const char m,
/* print stat info */
static void FAST_FUNC print_stat(char *pformat, const char m,
const char *const filename, const void *data
IF_SELINUX(, security_context_t scontext))
IF_SELINUX(, char *scontext))
{
#define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
struct stat *statbuf = (struct stat *) data;
struct passwd *pw_ent;
struct group *gw_ent;
if (m == 'n') {
printfs(pformat, filename);
printf_s(pformat, filename);
} else if (m == 'N') {
strcatc(pformat, 's');
if (S_ISLNK(statbuf->st_mode)) {
@@ -327,78 +357,60 @@ static void FAST_FUNC print_stat(char *pformat, const char m,
printf(pformat, filename);
}
} else if (m == 'd') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_dev);
printf_llu(pformat, statbuf->st_dev);
} else if (m == 'D') {
strcat(pformat, "llx");
printf(pformat, (unsigned long long) statbuf->st_dev);
printf_llx(pformat, statbuf->st_dev);
} else if (m == 'i') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_ino);
printf_llu(pformat, statbuf->st_ino);
} else if (m == 'a') {
strcat(pformat, "lo");
printf(pformat, (unsigned long) (statbuf->st_mode & (S_ISUID|S_ISGID|S_ISVTX|S_IRWXU|S_IRWXG|S_IRWXO)));
} else if (m == 'A') {
char modestr[12];
printfs(pformat, bb_mode_string(modestr, statbuf->st_mode));
printf_s(pformat, bb_mode_string(modestr, statbuf->st_mode));
} else if (m == 'f') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) statbuf->st_mode);
printf_lx(pformat, statbuf->st_mode);
} else if (m == 'F') {
printfs(pformat, file_type(statbuf));
printf_s(pformat, file_type(statbuf));
} else if (m == 'h') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_nlink);
printf_lu(pformat, statbuf->st_nlink);
} else if (m == 'u') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_uid);
printf_lu(pformat, statbuf->st_uid);
} else if (m == 'U') {
pw_ent = getpwuid(statbuf->st_uid);
printfs(pformat, (pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN");
printf_s(pformat, (pw_ent != NULL) ? pw_ent->pw_name : "UNKNOWN");
} else if (m == 'g') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_gid);
printf_lu(pformat, statbuf->st_gid);
} else if (m == 'G') {
gw_ent = getgrgid(statbuf->st_gid);
printfs(pformat, (gw_ent != NULL) ? gw_ent->gr_name : "UNKNOWN");
printf_s(pformat, (gw_ent != NULL) ? gw_ent->gr_name : "UNKNOWN");
} else if (m == 't') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) major(statbuf->st_rdev));
printf_lx(pformat, major(statbuf->st_rdev));
} else if (m == 'T') {
strcat(pformat, "lx");
printf(pformat, (unsigned long) minor(statbuf->st_rdev));
printf_lx(pformat, minor(statbuf->st_rdev));
} else if (m == 's') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_size);
printf_llu(pformat, statbuf->st_size);
} else if (m == 'B') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) 512); //ST_NBLOCKSIZE
printf_lu(pformat, 512); //ST_NBLOCKSIZE
} else if (m == 'b') {
strcat(pformat, "llu");
printf(pformat, (unsigned long long) statbuf->st_blocks);
printf_llu(pformat, statbuf->st_blocks);
} else if (m == 'o') {
strcat(pformat, "lu");
printf(pformat, (unsigned long) statbuf->st_blksize);
printf_lu(pformat, statbuf->st_blksize);
} else if (m == 'x') {
printfs(pformat, human_time(&statbuf->st_atim));
printf_s(pformat, human_time(&statbuf->st_atim));
} else if (m == 'X') {
strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
/* note: (unsigned long) would be wrong:
* imagine (unsigned long64)int32 */
printf(pformat, (long) statbuf->st_atime);
printf_time_t(pformat, statbuf->st_atime);
} else if (m == 'y') {
printfs(pformat, human_time(&statbuf->st_mtim));
printf_s(pformat, human_time(&statbuf->st_mtim));
} else if (m == 'Y') {
strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
printf(pformat, (long) statbuf->st_mtime);
printf_time_t(pformat, statbuf->st_mtime);
} else if (m == 'z') {
printfs(pformat, human_time(&statbuf->st_ctim));
printf_s(pformat, human_time(&statbuf->st_ctim));
} else if (m == 'Z') {
strcat(pformat, TYPE_SIGNED(time_t) ? "ld" : "lu");
printf(pformat, (long) statbuf->st_ctime);
printf_time_t(pformat, statbuf->st_ctime);
# if ENABLE_SELINUX
} else if (m == 'C' && (option_mask32 & OPT_SELINUX)) {
printfs(pformat, scontext);
printf_s(pformat, scontext);
# endif
} else {
strcatc(pformat, 'c');
@@ -408,9 +420,9 @@ static void FAST_FUNC print_stat(char *pformat, const char m,
static void print_it(const char *masterformat,
const char *filename,
void FAST_FUNC (*print_func)(char*, char, const char*, const void* IF_SELINUX(, security_context_t scontext)),
void FAST_FUNC (*print_func)(char*, char, const char*, const void* IF_SELINUX(, char *scontext)),
const void *data
IF_SELINUX(, security_context_t scontext))
IF_SELINUX(, char *scontext))
{
/* Create a working copy of the format string */
char *format = xstrdup(masterformat);
@@ -475,7 +487,7 @@ static bool do_statfs(const char *filename, const char *format)
const char *format;
#endif
#if ENABLE_SELINUX
security_context_t scontext = NULL;
char *scontext = NULL;
if (option_mask32 & OPT_SELINUX) {
if ((option_mask32 & OPT_DEREFERENCE
@@ -590,7 +602,7 @@ static bool do_stat(const char *filename, const char *format)
{
struct stat statbuf;
#if ENABLE_SELINUX
security_context_t scontext = NULL;
char *scontext = NULL;
if (option_mask32 & OPT_SELINUX) {
if ((option_mask32 & OPT_DEREFERENCE
+52 -49
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)
@@ -624,75 +621,65 @@ static int binop(void)
/* if (is_file_op(op->op_num)) */
{
struct stat b1, b2;
int sb1 = stat(opnd1, &b1);
int sb2 = stat(opnd2, &b2);
if (stat(opnd1, &b1) || stat(opnd2, &b2))
return 0; /* false, since at least one stat failed */
if (op->op_num == FILNT)
return b1.st_mtime > b2.st_mtime;
return !sb1 && (sb2 || b1.st_mtime > b2.st_mtime);
if (op->op_num == FILOT)
return b1.st_mtime < b2.st_mtime;
return !sb2 && (sb1 || b1.st_mtime < b2.st_mtime);
/*if (op->op_num == FILEQ)*/
return b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
return !sb1 && !sb2 && b1.st_dev == b2.st_dev && b1.st_ino == b2.st_ino;
}
/*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;
}
+15 -11
View File
@@ -113,15 +113,20 @@ static unsigned expand(char *arg, char **buffer_p)
*buffer_p = buffer = xrealloc(buffer, size);
}
if (*arg == '\\') {
const char *z;
arg++;
z = arg;
ac = bb_process_escape_sequence(&z);
arg = (char *)z;
arg--;
char *z = ++arg;
if (*z == '-') {
/* "\-X" isn't a range, but a literal dash and X */
buffer[pos++] = '-';
continue;
}
ac = bb_process_escape_sequence((void*)&z);
// if unknown seq "\k": ac='\', z->k: store '\' before 'k'
// if known seq "\n": ac='\n', z->past n: store '\n' into 'n'
// if known seq "\041": ac='!', z->past 1: store '!' into '1'
arg = z - 1;
*arg = ac;
/*
* fall through, there may be a range.
* fall through, there may be a range. Example: "\n-@"
* If not, current char will be treated anyway.
*/
}
@@ -134,10 +139,9 @@ static unsigned expand(char *arg, char **buffer_p)
i = (unsigned char) *arg;
arg += 3; /* skip 0-9 or 0-\ */
if (ac == '\\') {
const char *z;
z = arg;
ac = bb_process_escape_sequence(&z);
arg = (char *)z;
char *z = arg;
ac = bb_process_escape_sequence((void*)&z);
arg = z;
}
while (i <= ac) /* ok: i is unsigned _int_ */
buffer[pos++] = i++;
+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.
+24 -12
View File
@@ -40,6 +40,15 @@
//config: fsck is used to check and optionally repair one or more filesystems.
//config: In actuality, fsck is simply a front-end for the various file system
//config: checkers (fsck.fstype) available under Linux.
//config:
//config:config FEATURE_FSCK_LABEL
//config: bool "Support specifying devices by label or UUID"
//config: default y
//config: depends on FSCK
//config: select VOLUMEID
//config: help
//config: This allows for specifying a device by label or uuid, rather than by
//config: name. This feature utilizes the same functionality as blkid/findfs.
//applet:IF_FSCK(APPLET(fsck, BB_DIR_SBIN, BB_SUID_DROP))
@@ -60,6 +69,11 @@
//usage: "\n -t TYPE List of filesystem types to check"
#include "libbb.h"
#if ENABLE_FEATURE_FSCK_LABEL
# include "volume_id.h"
#else
# define resolve_mount_spec(fsname) ((void)0)
#endif
#include "common_bufsiz.h"
/* "progress indicator" code is somewhat buggy and ext[23] specific.
@@ -318,7 +332,7 @@ static struct fs_info *create_fs_device(const char *device, const char *mntpnt,
if (strchr(type, ','))
type = (char *)"auto";
fs->type = xstrdup(type);
fs->opts = xstrdup(opts ? opts : "");
fs->opts = xstrdup(opts); /* can be NULL */
fs->passno = passno < 0 ? 1 : passno;
/*fs->flags = 0; */
/*fs->next = NULL; */
@@ -358,7 +372,7 @@ static void load_fs_info(const char *filename)
}
/* Lookup filesys in /etc/fstab and return the corresponding entry. */
static struct fs_info *lookup(char *filesys)
static struct fs_info *lookup_in_fs_info(const char *filesys)
{
struct fs_info *fs;
@@ -423,13 +437,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;
@@ -524,7 +536,7 @@ static int wait_many(int flags)
* Execute a particular fsck program, and link it into the list of
* child processes we are waiting for.
*/
static void execute(const char *type, const char *device,
static void execute(const char *type, char *device,
const char *mntpt /*, int interactive */)
{
int i;
@@ -544,7 +556,10 @@ static void execute(const char *type, const char *device,
}
#endif
G.args[G.num_args - 2] = (char*)device;
/* int free_the_pointer = */ resolve_mount_spec(&device);
/* NB: the possible new pointer is malloced, we leak it */
G.args[G.num_args - 2] = device;
/* G.args[G.num_args - 1] = NULL; - already is */
if (G.verbose || G.noexecute) {
@@ -632,7 +647,7 @@ static void fsck_device(struct fs_info *fs /*, int interactive */)
* Returns TRUE if a partition on the same disk is already being
* checked.
*/
static int device_already_active(char *device)
static int device_already_active(const char *device)
{
struct fsck_instance *inst;
char *base;
@@ -973,9 +988,6 @@ int fsck_main(int argc UNUSED_PARAM, char **argv)
/* "/dev/blk" or "/path" or "UUID=xxx" or "LABEL=xxx" */
if ((arg[0] == '/' && !opts_for_fsck) || strchr(arg, '=')) {
// FIXME: must check that arg is a blkdev, or resolve
// "/path", "UUID=xxx" or "LABEL=xxx" into block device name
// ("UUID=xxx"/"LABEL=xxx" can probably shifted to fsck.auto duties)
devices = xrealloc_vector(devices, 2, num_devices);
devices[num_devices++] = arg;
continue;
@@ -1095,7 +1107,7 @@ int fsck_main(int argc UNUSED_PARAM, char **argv)
break;
}
fs = lookup(devices[i]);
fs = lookup_in_fs_info(devices[i]);
if (!fs)
fs = create_fs_device(devices[i], "", "auto", NULL, -1);
fsck_device(fs /*, interactive */);
+390 -146
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)
@@ -896,24 +890,30 @@ static char *nextword(char **s)
return p;
}
/* Note: will NOT stop at NUL (either on <NUL> or \<newline><NUL>):
* *s will be advanced past NUL!
* Make sure you always check NUL return before continuing.
*/
static char nextchar(char **s)
{
char c, *pps;
char c;
again:
c = *(*s)++;
pps = *s;
if (c == '\\')
if (c == '\\') {
char *pps = *s;
c = bb_process_escape_sequence((const char**)s);
/* Example awk statement:
* s = "abc\"def"
* we must treat \" as "
*/
if (c == '\\' && *s == pps) { /* unrecognized \z? */
c = *(*s); /* yes, fetch z */
if (c) { /* advance unless z = NUL */
(*s)++;
if (c == '\n') /* \<newline>? eat it */
goto again;
/* Example awk statement:
* s = "abc\"def"
* we must treat \" as "
*/
if (c == '\\' && *s == pps) { /* unrecognized \z? */
c = *(*s); /* yes, fetch z */
if (c) { /* advance unless z = NUL */
(*s)++;
if (c == '\n') /* \<newline>? eat it */
goto again;
}
}
}
return c;
@@ -967,20 +967,71 @@ static double my_strtod_or_hexoct(char **pp)
/* -------- working with variables (set/get/copy/etc) -------- */
/* Perform OFMT or CONVFMT float-to-string conversion.
* According to POSIX, awk's behavior is undefined if OFMT
* contains anything but a floating-point conversion specification.
* However, GNU awk 5.3.0 allows prefix and suffix: "N:%.1f!"
* integer formats (%d et al), %s formats.
* It even allows %c, but we don't implement this.
* GNU awk also supports %ld, %lx, we don't (yet). GNU awk doesn't support %lld.
*/
static const char *fmt_num(const char *format, double n)
{
if (n == (long long)n) {
snprintf(g_buf, MAXVARFMT, "%lld", (long long)n);
if (n == trunc(n)) {
/* No fractionals? Try: awk -v OFMT='R:%d!' 'BEGIN { print 2**128 }' */
snprintf(g_buf, MAXVARFMT, "%.0f", n);
} else {
const char *s = format;
const char *p2;
char c;
do { c = *s; } while (c && *++s);
/* Find %SPEC in format string */
for (;;) {
s = strchr(s, '%');
if (!s)
goto print_verbatim;
if (s[1] != '%')
break;
s += 2; /* skip "%%" */
}
/* We are at %SPEC. Is there a second %SPEC? (%% and trailing % aren't %SPEC) */
p2 = s;
for (;;) {
p2 = strchr(p2 + 1, '%');
if (!p2) break; /* no more %SPEC: ok */
if (*++p2 == '\0') break; /* trailing lone %: ok */
if (*p2 != '%') goto INV_FMT; /* more than one %SPEC: error */
/* else: %% - ok, look for %SPEC past it by iterating once more */
}
//TODO: factor out awk_printf machinery to make %d print large numbers too. Example:
// awk -v OFMT='R:%d!' 'BEGIN { print 184467440737095.1 }'
// R:184467440737095!
/* Find the format letter */
for (;;) {
c = *++s;
if (!c) /* unterminated "....%SPEC" */
goto print_verbatim;
if (c == '*')
goto INV_FMT; /* CONVFMT/OFMT='%*f' is not allowed */
if (isalpha(c))
break;
}
if (strchr("diouxX", c)) {
snprintf(g_buf, MAXVARFMT, format, (int)n);
} else if (strchr("eEfFgGaA", c)) {
print_verbatim:
snprintf(g_buf, MAXVARFMT, format, n);
} else if (c == 's') {
/* GNU awk OFMT="%..s" formats number through "%.6g",
* then prints string through %s:
*/
char nbuf[sizeof(n)*3 + 12]; /* +5 should do? +12 is paranoia */
sprintf(nbuf, "%.6g", n);
snprintf(g_buf, MAXVARFMT, format, nbuf);
} else {
INV_FMT:
syntax_error(EMSG_INV_FMT);
}
}
@@ -1168,9 +1219,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;
@@ -1211,11 +1262,22 @@ static uint32_t next_token(uint32_t expected)
/* it's a string */
char *s = t_string = ++p;
while (*p != '"') {
char *pp;
if (*p == '\0' || *p == '\n')
char c, *pp;
/* Since we need to handle \<newline><NUL>
* below, we can handle ordinary NUL there as well,
* instead of here. Thus commented out.
*/
if (/* *p == '\0' || */ *p == '\n')
syntax_error(EMSG_UNEXP_EOS);
pp = p;
*s++ = nextchar(&pp);
c = *s++ = nextchar(&pp);
/* awk 'BEGIN { print "unterminated\
* '
* results in NUL here after nextchar() eats \<newline>
*/
if (c == '\0')
syntax_error(EMSG_UNEXP_EOS);
p = pp;
}
p++;
@@ -2426,9 +2488,9 @@ static int awk_getline(rstream *rsm, var *v)
#endif
static char *awk_printf(node *n, size_t *len)
{
char *b;
char *fmt, *f;
size_t i;
char *fmt, *fmt_cur;
char *res_buf;
size_t res_len;
//tmpvar = nvalloc(1);
#define TMPVAR (&G.awk_printf__tmpvar)
@@ -2436,103 +2498,245 @@ static char *awk_printf(node *n, size_t *len)
// to decrease memory consumption in deeply-recursive awk programs.
// The rule to work safely is to never call evaluate() while our static
// TMPVAR's value is still needed.
fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), TMPVAR)));
fmt = fmt_cur = xstrdup(getvar_s(evaluate(nextarg(&n), TMPVAR)));
// ^^^^^^^^^ here we immediately strdup() the value, so the later call
// to evaluate() potentially recursing into another awk_printf() can't
// mangle the value.
b = NULL;
i = 0;
res_buf = NULL;
res_len = 0;
while (1) { /* "print one format spec" loop */
char *s;
char c;
char sv;
var *arg;
/* s is the next string to append to res_buf.
* it can be either a literal trailing segment of fmt (then c == NUL),
* or allocated result of the formatting */
char *s;
size_t slen;
char *after_fmt;
int starred;
int width;
int prec;
enum { MAX_FMT_LEN = sizeof("%+- 0#'99.99llx plus paranoia") + 2 * sizeof(int)*3 };
char baked_format[MAX_FMT_LEN];
char *baked_cur;
char *use_fmt;
const char *diouxX;
/* Find end of the next format spec, or end of line */
s = f;
while (1) {
c = *f;
if (!c) /* no percent chars found at all */
goto nul;
f++;
if (c == '%')
break;
}
/* we are past % in "....%..." */
c = *f;
if (!c) /* "....%" */
/* find end of the next format spec, or end of string */
s = fmt_cur;
//bb_error_msg("s:'%s'", s);
fmt_cur = strchrnul(fmt_cur, '%');
c = *fmt_cur;
if (!c) { /* no more percent chars */
goto nul;
if (c == '%') { /* "....%%...." */
slen = f - s;
s = xstrndup(s, slen);
f++;
goto append; /* print "....%" part verbatim */
}
fmt_cur++;
/* we are past % in "....%..." */
c = *fmt_cur;
if (c == '%') { /* "....%%...." */
slen = fmt_cur - s;
fmt_cur++;
goto append_slen; /* append "....%" part verbatim */
}
/* find trailing letter of the %FMT */
starred = 0;
after_fmt = fmt_cur;
while (1) {
if (!c) { /* unterminated "....%FMT" */
fmt_cur = after_fmt;
nul:
slen = fmt_cur - s;
//bb_error_msg("fmt:'%s', res_buf:'%s'", fmt, res_buf);
if (!res_buf) { /* the entire fmt had no (valid) %FMTs? */
/* optimize this case (avoid xrealloc+free) */
res_buf = fmt;
res_len = slen;
goto ret;
}
goto tail; /* append remaining string, exit loop */
}
//TODO: GNU awk 5.3.0 also supports %ld, %lx, we don't (yet). It does not support %lld.
if (isalpha(c))
break;
if (c == '*') /* gawk supports %*d and %*.*f, we don't... */
syntax_error("%*x formats are not supported");
c = *++f;
if (!c) { /* "....%...." and no letter found after % */
/* Example: awk 'BEGIN { printf "^^^%^^^\n"; }' */
nul:
slen = f - s;
goto tail; /* print remaining string, exit loop */
starred |= (c == '*');
c = *++after_fmt;
}
diouxX = strchr("diouxX", c);
if (!(diouxX || strchr("cs""eEfFgGaA", c))
|| (after_fmt - fmt_cur) >= MAX_FMT_LEN
) {
/* unknown, or overlong "....%FMT...." */
/* append "....%<notletters><letter>" part verbatim */
//this works (unknown conversion char means "print %FMT verbatim"):
// awk 'BEGIN { printf "%W\n"; }
//since we check for this early, even this works:
// awk 'BEGIN { printf "%*W\n"; }
//whereas GNU awk 5.3.0 says "not enough arguments to satisfy format string"
fmt_cur = after_fmt + 1;
slen = fmt_cur - s;
goto append_slen;
}
if (*s != '%') {
/* the %FMT does not start immediately at the beginning of s */
if (starred || diouxX) {
/* It is a "%*s"-like starred %FMT, or an integer conversion.
* In this case we will use fixed baked_format[].
* Which means "literal_prefix%FMT" can't be used as one piece.
* Append "literal_prefix" to res_buf.
*/
fmt_cur--;
slen = fmt_cur - s;
append_slen:
//s = xstrndup(s, slen);
//goto append;
/* a bit bloaty, but avoids dup+free: */
res_buf = xrealloc(res_buf, res_len + slen + 1);
strncpy(res_buf + res_len, s, slen); /* s can't contain NULs here */
res_len += slen;
continue;
}
}
/* we are at A in "....%...A..." */
/* NUL-terminate "...%FMT" */
after_fmt++;
if (*after_fmt && *after_fmt != '%') {
// optimization for common cases:
// printf "Number:%d\n" (one extra char between %FMT and EOL)
// printf "String:'%s'\n" (two extra chars)
// - we can handle a small tail of literals after %FMT in one pass!
// (careful: they are added to baked_format[] array, do not overflow it!)
after_fmt++;
if (*after_fmt && *after_fmt != '%')
after_fmt++;
}
sv = *after_fmt;
*after_fmt = '\0';
/* flags */
baked_cur = baked_format;
*baked_cur++ = '%';
c = *fmt_cur;
while (strchr("+- 0#'", c) && (baked_cur - baked_format) <= 6) {
*baked_cur++ = c;
c = *++fmt_cur;
}
/* width */
width = -1;
if (c == '*') {
width = (int)getvar_i(evaluate(nextarg(&n), TMPVAR));
//bb_error_msg("*width=%d", width);
c = *++fmt_cur;
//if (isdigit(c)) /* we do not support "%*2$d" format */
// syntax_error("invalid format specifier");
} else if (isdigit(c)) {
width = atoi(fmt_cur);
do
c = *++fmt_cur;
while (isdigit(c));
}
/* precision? */
prec = -1;
if (c == '.') {
c = *++fmt_cur;
if (c == '*') {
prec = (int)getvar_i(evaluate(nextarg(&n), TMPVAR));
//bb_error_msg("*prec=%d", prec);
c = *++fmt_cur;
//if (isdigit(c)) /* we do not support "%5.*2$d" format */
// syntax_error("invalid format specifier");
} else if (isdigit(c)) {
prec = atoi(fmt_cur);
//do
// c = *++fmt_cur;
//while (isdigit(c));
//^^^^ unnecessary, while () below skips everything to format type letter
}
}
while (!isalpha(c))
c = *++fmt_cur;
/* we are at A in "....%fmtA..." */
arg = evaluate(nextarg(&n), TMPVAR);
/* Result can be arbitrarily long. Example:
* printf "%99999s", "BOOM"
*/
sv = *++f;
*f = '\0';
use_fmt = s;
//bb_error_msg("w:%d p:%d conv:'%c' fmt_cur:%p after_fmt:%p", width, prec, c, fmt_cur, after_fmt);
if (starred || diouxX) {
if (width >= 0
|| (starred && (c == 's' || c == 'c'))
//GNU awk 5.3.0 compat: "%*s",-10,"A" works like "%-10s","A"
) {
baked_cur += sprintf(baked_cur, "%d", width);
}
if (diouxX) {
/* print %d, %i, positive %u as floats: */
/* this avoids losing most-significant bits, try */
/* awk 'BEGIN { printf "%d\n", 2**128 }' */
sprintf(baked_cur, ".0f%s", fmt_cur + 1);
} else {
if (prec >= 0)
baked_cur += sprintf(baked_cur, ".%u", prec);
sprintf(baked_cur, "%s", fmt_cur);
}
use_fmt = baked_format;
//bb_error_msg("baked_format:'%s'", baked_format);
}
if (c == 'c') {
char cc = is_numeric(arg) ? getvar_i(arg) : *getvar_s(arg);
char *r = xasprintf(s, cc ? cc : '^' /* else strlen will be wrong */);
char *r = xasprintf(use_fmt, cc ? cc : '^' /* else strlen will be wrong */);
slen = strlen(r);
if (cc == '\0') /* if cc is NUL, re-format the string with it */
sprintf(r, s, cc);
if (cc == '\0') { /* if cc is NUL, re-format the string with it */
sprintf(r, use_fmt, cc);
}
s = r;
} else {
if (c == 's') {
s = xasprintf(s, getvar_s(arg));
} else {
const char *cs = getvar_s(arg);
//bb_error_msg("format_s:'%s'", use_fmt);
s = xasprintf(use_fmt, cs);
} else { /* numeric conversion */
double d = getvar_i(arg);
if (strchr("diouxX", c)) {
//TODO: make it wider here (%x -> %llx etc)?
//Can even print the value into a temp string with %.0f,
//then replace diouxX with s and print that string.
//This will correctly print even very large numbers,
//but some replacements are not equivalent:
//%09d -> %09s: breaks zero-padding;
//%+d -> %+s: won't prepend +; etc
s = xasprintf(s, (int)d);
} else if (strchr("eEfFgGaA", c)) {
s = xasprintf(s, d);
if (diouxX)
d = trunc(d);
//bb_error_msg("d:%f", d);
if ((c|0x20) == 'x' || c == 'o' || (c == 'u' && d < 0)) {
sprintf(baked_cur, "ll%s", fmt_cur);
// -1.9 => -1 => integer (0xfff..fff)
// => interpret as unsigned integer
// awk 'BEGIN { printf "%u\n",-1.9; }': 18446744073709551615
// awk 'BEGIN { printf "%x\n",-1.9; }': ffffffffffffffff
s = xasprintf(use_fmt, (unsigned long long)d);
} else {
/* gawk 5.1.1 printf("%W") prints "%W", does not error out */
s = xstrndup(s, f - s);
s = xasprintf(use_fmt, d);
}
}
slen = strlen(s);
}
*f = sv;
append:
if (i == 0) {
b = s;
i = slen;
*after_fmt = sv;
fmt_cur = after_fmt;
//bb_error_msg("after_fmt:'%s'", after_fmt);
//bb_error_msg("slen:%d", slen);
if (res_len == 0) {
//bb_error_msg("initial:'%.*s'", slen, s);
res_buf = s;
res_len = slen;
continue;
}
tail:
b = xrealloc(b, i + slen + 1);
strcpy(b + i, s);
i += slen;
if (slen != 0 || res_len == 0) {
//bb_error_msg("appending:'%.*s'", slen, s);
res_buf = xrealloc(res_buf, res_len + slen + 1);
((char*)mempcpy(res_buf + res_len, s, slen))[0] = '\0';
res_len += slen;
}
if (!c) /* s is NOT allocated and this is the last part of string? */
break;
free(s);
@@ -2541,12 +2745,12 @@ static char *awk_printf(node *n, size_t *len)
free(fmt);
//nvfree(tmpvar, 1);
#undef TMPVAR
ret:
#if ENABLE_FEATURE_AWK_GNU_EXTENSIONS
if (len)
*len = i;
*len = res_len;
#endif
return b;
return res_buf;
}
/* Common substitution routine.
@@ -2554,9 +2758,8 @@ static char *awk_printf(node *n, size_t *len)
* store result into (dest), return number of substitutions.
* If nm = 0, replace all matches.
* If src or dst is NULL, use $0.
* If subexp != 0, enable subexpression matching (\0-\9).
*/
static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,int subexp*/)
static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,int in_gensub*/)
{
char *resbuf;
const char *sp;
@@ -2565,7 +2768,7 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
regmatch_t pmatch[10];
regex_t sreg, *regex;
/* True only if called to implement gensub(): */
int subexp = (src != dest);
int in_gensub = (src != dest);
#if defined(REG_STARTEND)
const char *src_string;
size_t src_strlen;
@@ -2613,32 +2816,74 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
residx += eo;
if (++match_no >= nm) {
const char *s;
int bslash;
/* replace */
residx -= (eo - so);
bslash = 0;
for (s = repl; *s; s++) {
char c = *s;
if (c == '\\' && s[1]) {
bslash ^= 1;
if (bslash)
continue;
s = repl;
while (*s) {
// https://www.gnu.org/software/gawk/manual/html_node/Gory-Details.html
// Table 9.2: gawk rules for sub() and backslash:
// You type sub() sees sub() generates
// \\q \q A literal ‘\q’ <<-- THIS IS DIFFERENT
// & & The matched text
// \\& \& A literal ‘&’
// \\\\ \\ Two literal ‘\’s <<-- THIS IS DIFFERENT
// \\\\& \\& A literal ‘\’, then the matched text
// \\\\\\& \\\& A literal ‘\&’
// \\\\\\q \\\q Two literal ‘\’s and literal ‘\q’ <<-- THIS IS DIFFERENT
// (^^^ non-POSIX special-casing of two backslashes by gawk)
// Table 9.4: Escape sequence processing for gensub():
// You type gensub() sees gensub() generates
// \\q \q A literal ‘q’ <<-- THIS IS DIFFERENT
// & & The matched text
// \\& \& A literal ‘&’
// \\\\ \\ A literal ‘\’ <<-- THIS IS DIFFERENT
// \\\\& \\& A literal ‘\’, then the matched text
// \\\\\\& \\\& A literal ‘\&’
// \\\\\\q \\\q A literal ‘\’ and literal ‘q’ <<-- THIS IS DIFFERENT
char c;
unsigned bslash = 0;
while ((c = *s++) == '\\' && *s) {
bslash++;
}
if ((!bslash && c == '&')
|| (subexp && bslash && c >= '0' && c <= '9')
if ((!(bslash & 1) && c == '&')
|| (in_gensub && (bslash & 1) && c >= '0' && c <= '9')
) {
int n, j = 0;
if (c != '&') {
j = c - '0';
}
bslash /= 2;
while (bslash) {
resbuf[residx++] = '\\';
bslash--;
}
n = pmatch[j].rm_eo - pmatch[j].rm_so;
resbuf = qrealloc(resbuf, residx + replen + n, &resbufsize);
memcpy(resbuf + residx, sp + pmatch[j].rm_so - start_ofs, n);
residx += n;
} else
resbuf[residx++] = c;
bslash = 0;
continue;
}
// We saw N backslashes, and we are at a "normal char", not special one.
// The "normal char" can be a "&" or backslash, examples:
// "\\\\\\&..." (in awk program) -> (what we process here) "\\\&...": escaped "&" become "normal".
// "\\\\\\" (in awk program) -> (what we process here) "\\\": last unpaired backslash is "normal".
//bb_error_msg("in_gensub:%d bslash:%d c:'%c'",in_gensub,bslash,c);
if (!in_gensub) {
// for non-gensub:
// special-case "two backslashes" case, including "\\\q" case which is logically "\\"+"\q"
// if (c != '&' && (bslash == 2 || bslash == 3)) // what doc claims
if (c != '&' && (bslash & 2)) // the actual logic in gawk-5.3.0 special-cases NOT ONLY 2,3 - but every two out of four!
bslash += 2;
if (c != '&') // gensub removes backslash from \q, sub does not:
bslash++; // if odd no.of backslashes, print one more, if even: no change
}
bslash /= 2;
while (bslash) {
resbuf[residx++] = '\\';
bslash--;
}
resbuf[residx++] = c;
}
}
@@ -2669,7 +2914,7 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
return match_no;
}
static NOINLINE int do_mktime(const char *ds)
static NOINLINE time_t do_mktime(const char *ds)
{
struct tm then;
int count;
@@ -2847,7 +3092,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 {
@@ -3155,8 +3400,7 @@ static var *evaluate(node *op, var *res)
for (;;) {
var *v = evaluate(nextarg(&op1), TMPVAR0);
if (v->type & VF_NUMBER) {
fputs(fmt_num(getvar_s(intvar[OFMT]), getvar_i(v)),
F);
fputs(fmt_num(getvar_s(intvar[OFMT]), getvar_i(v)), F);
} else {
fputs(getvar_s(v), F);
}
+31 -18
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,11 +40,11 @@
#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 OPT_STR "sln:"
#define CMP_OPT_s (1<<0)
#define CMP_OPT_l (1<<1)
#define CMP_OPT_n (1<<2)
@@ -46,13 +54,14 @@ 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;
unsigned long long max_count = max_count;
int line_pos = 1; /* Hopefully won't overflow... */
const char *fmt;
int c1, c2;
unsigned opt;
int retval = 0;
int max_count = -1;
char *max_count_str;
#if !ENABLE_LONG_OPTS
opt = getopt32(argv, "^"
@@ -61,7 +70,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
IF_DESKTOP(":?4")
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
&max_count
&max_count_str
);
#else
static const char cmp_longopts[] ALIGN1 =
@@ -77,7 +86,7 @@ int cmp_main(int argc UNUSED_PARAM, char **argv)
IF_NOT_DESKTOP(":?2")
":l--s:s--l",
cmp_longopts,
&max_count
&max_count_str
);
#endif
argv += optind;
@@ -86,13 +95,16 @@ 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);
}
}
}
if (opt & CMP_OPT_n)
max_count = xatoull_sfx(max_count_str, kmg_i_suffixes);
xfunc_error_retval = 2; /* missing file results in exitcode 2 */
if (opt & CMP_OPT_s)
logmode = 0; /* -s suppresses open error messages */
@@ -113,11 +125,11 @@ 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)
if ((opt & CMP_OPT_n) && max_count-- == 0)
break;
c1 = getc(fp1);
c2 = getc(fp2);
@@ -146,8 +158,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;
}
+8 -2
View File
@@ -113,6 +113,9 @@
//usage: "\n -N Treat absent files as empty"
//usage: "\n -q Output only whether files differ"
//usage: "\n -r Recurse"
//usage: IF_LONG_OPTS(
//usage: "\n --no-dereference Don't follow symlinks"
//usage: )
//usage: "\n -S Start with FILE when comparing directories"
//usage: "\n -T Make tabs line up by prefixing a tab when necessary"
//usage: "\n -s Report when two files are the same"
@@ -154,6 +157,7 @@ enum { /* Commandline flags */
FLAG_p, /* not implemented */
FLAG_B,
FLAG_E, /* not implemented */
FLAG_no_deref,
};
#define FLAG(x) (1 << FLAG_##x)
@@ -741,7 +745,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();
@@ -867,7 +871,8 @@ static void diffdir(char *p[2], const char *s_start)
* Using list.len to specify its length,
* add_to_dirlist will remove it. */
list[i].len = strlen(p[i]);
recursive_action(p[i], ACTION_RECURSE | ACTION_FOLLOWLINKS,
recursive_action(p[i], ACTION_RECURSE |
((option_mask32 & FLAG(no_deref)) ? 0 : ACTION_FOLLOWLINKS),
add_to_dirlist, skip_dir, &list[i]);
/* Sort dl alphabetically.
* GNU diff does this ignoring any number of trailing dots.
@@ -964,6 +969,7 @@ static const char diff_longopts[] ALIGN1 =
"report-identical-files\0" No_argument "s"
"starting-file\0" Required_argument "S"
"minimal\0" No_argument "d"
"no-dereference\0" No_argument "\xff"
;
# define GETOPT32 getopt32long
# define LONGOPTS ,diff_longopts
+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);
+29 -4
View File
@@ -57,6 +57,7 @@ struct double_list {
struct double_list *next;
struct double_list *prev;
char *data;
int no_newline;
};
// Free all the elements of a linked list
@@ -76,7 +77,7 @@ static void dlist_free(struct double_list *list, void (*freeit)(void *data))
static struct double_list *dlist_add(struct double_list **list, char *data)
{
struct double_list *llist;
struct double_list *line = xmalloc(sizeof(*line));
struct double_list *line = xzalloc(sizeof(*line));
line->data = data;
llist = *list;
@@ -140,7 +141,8 @@ static void do_line(void *data)
if (TT.state > 1 && *dlist->data != TT.state)
fdprintf(TT.state == 2 ? 2 : TT.fileout,
"%s\n", dlist->data + (TT.state > 3 ? 1 : 0));
dlist->no_newline && TT.state != 2 ? "%s" : "%s\n",
dlist->data + (TT.state > 3 ? 1 : 0));
if (PATCH_DEBUG) fdprintf(2, "DO %d: %s\n", TT.state, dlist->data);
@@ -433,7 +435,17 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// Are we assembling a hunk?
if (state >= 2) {
if (*patchline == ' ' || *patchline == '+' || *patchline == '-') {
switch (*patchline) {
case '\\':
// '\ No newline at end of file' detected, mark
// previous line, if it exists.
if (TT.current_hunk->prev)
TT.current_hunk->prev->no_newline = TRUE;
free(patchline);
continue;
case ' ':
case '+':
case '-':
dlist_add(&TT.current_hunk, patchline);
if (*patchline != '+') oldlen--;
@@ -445,7 +457,20 @@ int patch_main(int argc UNUSED_PARAM, char **argv)
// If we've consumed all expected hunk lines, apply the hunk.
if (!oldlen && !newlen) state = apply_one_hunk();
if (!oldlen && !newlen) {
// Peek ahead for '\ No newline at end of file', mark
// previous line, if it exists.
int c = getchar();
ungetc(c, stdin);
if (c == '\\') {
if (TT.current_hunk->prev)
TT.current_hunk->prev->no_newline = TRUE;
do {
c = getchar();
} while (c != EOF && c != '\n');
}
state = apply_one_hunk();
}
continue;
}
fail_hunk();
+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. */
+134 -132
View File
@@ -176,7 +176,7 @@
//config: Enable more verbose reporting of the results of yank, change,
//config: delete, undo and substitution commands.
//applet:IF_VI(APPLET(vi, BB_DIR_BIN, BB_SUID_DROP))
//applet:IF_VI(APPLET(vi, BB_DIR_USR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_VI) += vi.o
@@ -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,27 @@ static void setops(char *args, int flg_no)
# if ENABLE_FEATURE_VI_COLON_EXPAND
static char *expand_args(char *args)
{
char *s, *t;
const char *replace;
char *s;
args = xstrdup(args);
for (s = args; *s; s++) {
const char *replace;
unsigned n;
//NB: vim 9.2 replaces "\%" with "%" _over entire string_,
//then replaces "\c" with "c". Result:
// "\%" is "%" (ok),
// "\\" is "\" (ok),
// "\\%" is "\%" (!!!), not "\CURFILE" as you would think.
//We don't do that. Should we?
if (*s == '%') {
replace = current_filename;
} else if (*s == '#') {
replace = alt_filename;
} else {
if (*s == '\\' && s[1] != '\0') {
for (t = s++; *t; t++)
*t = t[1];
overlapping_strcpy(s, s + 1);
s++;
}
continue;
}
@@ -2705,11 +2715,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 +2795,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 +2854,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 +2879,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 +2920,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 +2963,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 +3003,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 +3011,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 +3029,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 +3109,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 +3142,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 +3160,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 +3189,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 +3204,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 +3221,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 +3271,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 +3342,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 +3360,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 +3382,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 +3398,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 +3411,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 +4796,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
+11 -2
View File
@@ -50,9 +50,17 @@ if ! test "$mask"; then
fi
# some servers do not return router option.
# assume DHCP server is the router.
# assume either DHCP relay or DHCP server is the router.
if ! test "$router"; then
if test "$serverid"; then
# serverid is:
# = not necessarily an IP addr at all (but usually is).
# = can be NOT on our network (can use relays).
# If giaddr is set, the relay is in use and that's its IP address -
# will try using that.
if test "$giaddr"; then
router="$giaddr"
echo "No 'router' from the server, assuming 'giaddr' is the router: $giaddr"
elif test "$serverid"; then
router="$serverid"
echo "No 'router' from the server, assuming 'serverid' is the router: $serverid"
fi
@@ -66,6 +74,7 @@ test "$ip" && test "$mask" \
&& echo "ipmask[\$cfg]='$ip/$mask'"
test "$router" && echo "gw[\$cfg]='$router'"
test "$dns" && echo "dns[\$cfg]='$dns'"
# TODO: I never saw a dhcp server which correctly announces
# which subnet(s) is/are available thru advertised router
# Assume 0/0
+2 -2
View File
@@ -467,7 +467,7 @@ IF_FEATURE_FIND_INUM( ACTS(inum, ino_t inode_num;))
IF_FEATURE_FIND_SAMEFILE(ACTS(samefile, ino_t inode_num; dev_t device;))
IF_FEATURE_FIND_USER( ACTS(user, uid_t uid;))
IF_FEATURE_FIND_SIZE( ACTS(size, char size_char; off_t size;))
IF_FEATURE_FIND_CONTEXT(ACTS(context, security_context_t context;))
IF_FEATURE_FIND_CONTEXT(ACTS(context, char *context;))
IF_FEATURE_FIND_PAREN( ACTS(paren, action ***subexpr;))
IF_FEATURE_FIND_PRUNE( ACTS(prune))
IF_FEATURE_FIND_QUIT( ACTS(quit))
@@ -983,7 +983,7 @@ ACTF(empty)
#if ENABLE_FEATURE_FIND_CONTEXT
ACTF(context)
{
security_context_t con;
char *con;
int rc;
if (G.recurse_flags & ACTION_FOLLOWLINKS) {
+70 -7
View File
@@ -73,10 +73,10 @@
//usage: "\n -c Show only count of matching lines"
//usage: "\n -o Show only the matching part of line"
//usage: "\n -q Quiet. Return 0 if PATTERN is found, 1 otherwise"
//usage: "\n -v Select non-matching lines"
//usage: "\n -s Suppress open and read errors"
//usage: "\n -r Recurse"
//usage: "\n -R Recurse and dereference symlinks"
//usage: "\n -v Select non-matching lines"
//usage: "\n -i Ignore case"
//usage: "\n -w Match whole words only"
//usage: "\n -x Match whole lines only"
@@ -105,6 +105,58 @@
//usage:#define fgrep_trivial_usage NOUSAGE_STR
//usage:#define fgrep_full_usage ""
// GNU grep 3.7 options:
// s:short option supported by our code
// S:short option "supported" by ignoring it
// l:long option supported
// .:not supported
// s. | -E, --extended-regexp
// s. | -F, --fixed-strings
// .. | -G, --basic-regexp: Interpret PATTERNS as basic regular expressions (this is the default)
// .. | -P, --perl-regexp
// s. | -e PATTERNS, --regexp=PATTERNS
// s. | -f FILE, --file=FILE
// s. | -i, --ignore-case (-y is an obsolete synonym)
// . | --no-ignore-case
// s. | -v, --invert-match
// s. | -w, --word-regexp
// s. | -x, --line-regexp
// s. | -c, --count
// l. | --color[=WHEN], --colour[=WHEN]
// s. | -L, --files-without-match
// s. | -l, --files-with-matches
// s. | -m NUM, --max-count=NUM
// s. | -o, --only-matching
// sl.| -q, --quiet, --silent
// s. | -s, --no-messages
// .. | -b, --byte-offset
// s. | -H, --with-filename
// s. | -h, --no-filename
// . | --label=LABEL: Display input coming from standard input as input coming from file LABEL
// s. | -n, --line-number
// .. | -T, --initial-tab
// .. | -Z, --null: Output zero byte (the ASCII NUL character) instead of the character that normally follows filename
// s. | -A NUM, --after-context=NUM
// s. | -B NUM, --before-context=NUM
// s. | -C NUM, --context=NUM
// . | -NUM: same as -C NUM
// . | --group-separator=SEP: When -A, -B, or -C are in use, print SEP instead of -- between groups of lines
// . | --no-group-separator: When -A, -B, or -C are in use, do not print a separator between groups of lines
// s. | -a, --text
// . | --binary-files=TYPE
// S | -I: Process binary files as if they did not contain matching data (equivalent to --binary-files=without-match)
// .. | -D ACTION, --devices=ACTION
// .. | -d ACTION, --directories=ACTION
// . | --exclude=GLOB: Skip any file with a name suffix that matches the pattern GLOB
// . | --exclude-from=FILE: Skip files whose base name matches any of the file-name globs read from FILE
// . | --exclude-dir=GLOB: Skip any directory with a name suffix that matches the pattern GLOB
// . | --include=GLOB: Search only files whose base name matches GLOB
// s. | -r, --recursive
// s. | -R, --dereference-recursive
// . | --line-buffered
// .. | -U, --binary
// s. | -z, --null-data
/* -e,-f are lists; -m,-A,-B,-C have numeric param */
#define OPTSTR_GREP \
"lnqvscFiHhe:*f:*LorRm:+wx" \
@@ -712,23 +764,31 @@ int grep_main(int argc UNUSED_PARAM, char **argv)
llist_t *fopt = NULL;
#if ENABLE_FEATURE_GREP_CONTEXT
int Copt, opts;
#endif
#if ENABLE_LONG_OPTS
static const char grep_longopts[] ALIGN1 =
"quiet\0" No_argument "q"
"color\0" Optional_argument "\xff"
;
# define GETOPT32 getopt32long
#else
# define GETOPT32 getopt32
#endif
INIT_G();
/* For grep, exitcode of 1 is "not found". Other errors are 2: */
xfunc_error_retval = 2;
/* do normal option parsing */
#if ENABLE_FEATURE_GREP_CONTEXT
/* -H unsets -h; -C unsets -A,-B */
opts = getopt32long(argv, "^"
opts = GETOPT32(argv, "^"
OPTSTR_GREP
"\0"
"H-h:C-AB",
"color\0" Optional_argument "\xff",
IF_LONG_OPTS(grep_longopts,)
&pattern_head, &fopt, &max_matches,
&lines_after, &lines_before, &Copt
, NULL
IF_LONG_OPTS(, NULL)
);
if (opts & OPT_C) {
@@ -753,8 +813,11 @@ int grep_main(int argc UNUSED_PARAM, char **argv)
}
#else
/* with auto sanity checks */
getopt32(argv, "^" OPTSTR_GREP "\0" "H-h:c-n:q-n:l-n:", // why trailing ":"?
&pattern_head, &fopt, &max_matches);
GETOPT32(argv, "^" OPTSTR_GREP "\0" "H-h:c-n:q-n:l-n",
IF_LONG_OPTS(grep_longopts,)
&pattern_head, &fopt, &max_matches
IF_LONG_OPTS(, NULL)
);
#endif
invert_search = ((option_mask32 & OPT_v) != 0); /* 0 | 1 */
+6 -5
View File
@@ -68,7 +68,7 @@ typedef struct archive_handle_t {
llist_t *link_placeholders;
/* Process the header component, e.g. tar -t */
void FAST_FUNC (*action_header)(const file_header_t *);
void FAST_FUNC (*action_header)(struct archive_handle_t *);
/* Process the data component, e.g. extract to filesystem */
void FAST_FUNC (*action_data)(struct archive_handle_t *);
@@ -187,9 +187,9 @@ void data_extract_all(archive_handle_t *archive_handle) FAST_FUNC;
void data_extract_to_stdout(archive_handle_t *archive_handle) FAST_FUNC;
void data_extract_to_command(archive_handle_t *archive_handle) FAST_FUNC;
void header_skip(const file_header_t *file_header) FAST_FUNC;
void header_list(const file_header_t *file_header) FAST_FUNC;
void header_verbose_list(const file_header_t *file_header) FAST_FUNC;
void header_skip(archive_handle_t *archive_handle) FAST_FUNC;
void header_list(archive_handle_t *archive_handle) FAST_FUNC;
void header_verbose_list(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_ar(archive_handle_t *archive_handle) FAST_FUNC;
char get_header_cpio(archive_handle_t *archive_handle) FAST_FUNC;
@@ -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,
+293 -104
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,14 +451,21 @@ 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 */
# define BB_ARCH_FIXED_PAGESIZE 4096
#elif defined(__riscv) /* both rv32 and rv64 have fixed page size of 4KiB */
# define BB_ARCH_FIXED_PAGESIZE 4096
#else /* if defined(ARCH) */
/* add you favorite arch today! */
//From Linux kernel inspection:
//xtenza,s390[x],riscv,nios2,csky,sparc32: fixed 4k pages
//xtenza,s390[x],nios2,csky,sparc32: fixed 4k pages
//sparc64,alpha,openrisc: fixed 8k pages
#endif
@@ -491,16 +507,17 @@ enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing th
#endif
#define FILEUTILS_CP_OPTSTR "pdRfinlsLHarPvuTt:" IF_SELINUX("c")
/* How many bits in FILEUTILS_CP_OPTSTR? */
FILEUTILS_CP_OPTBITS = 18 - !ENABLE_SELINUX,
FILEUTILS_CP_OPTBITS = (18 - !ENABLE_SELINUX),
FILEUTILS_RMDEST = 1 << (19 - !ENABLE_SELINUX), /* cp --remove-destination */
/* bit 18 skipped for "cp --parents" */
FILEUTILS_RMDEST = 1 << (18 - !ENABLE_SELINUX), /* cp --remove-destination */
/* bit 19 is used in cp for "cp --parents" */
FILEUTILS_REFLINK = 1 << (20 - !ENABLE_SELINUX), /* cp --reflink=auto */
FILEUTILS_REFLINK_ALWAYS = 1 << (21 - !ENABLE_SELINUX), /* cp --reflink[=always] */
/* bit 21 is used in cp for "cp --sparse=... */
/*
* Hole. cp may have some bits set here,
* they should not affect remove_file()/copy_file()
*/
FILEUTILS_REFLINK_ALWAYS = 1 << 29, /* cp --reflink, --reflink=always */
#if ENABLE_SELINUX
FILEUTILS_SET_SECURITY_CONTEXT = 1 << 30,
#endif
@@ -643,6 +660,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! */
@@ -662,6 +681,8 @@ void bb_unsetenv_and_free(char *key) FAST_FUNC;
void xunlink(const char *pathname) FAST_FUNC;
void xstat(const char *pathname, struct stat *buf) FAST_FUNC;
void xfstat(int fd, struct stat *buf, const char *errmsg) FAST_FUNC;
mode_t FAST_FUNC xfstat_mode(int fd, const char *file_name);
off_t FAST_FUNC xfstat_size(int fd, const char *file_name);
int open3_or_warn(const char *pathname, int flags, int mode) FAST_FUNC;
int open_or_warn(const char *pathname, int flags) FAST_FUNC;
int xopen3(const char *pathname, int flags, int mode) FAST_FUNC;
@@ -676,10 +697,11 @@ off_t xlseek(int fd, off_t offset, int whence) FAST_FUNC;
int xmkstemp(char *template) FAST_FUNC;
off_t fdlength(int fd) FAST_FUNC;
/* NB: code requires that minsize is 2 bytes or larger */
uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
const char *override,
unsigned override_units,
int extend);
unsigned minsize_extend);
void xpipe(int *filedes) FAST_FUNC;
/* In this form code with pipes is much more readable */
@@ -687,6 +709,82 @@ 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*);
/* select() fd sets, sized to fit the largest fd seen so far.
* One allocation: [rdbits: N longs][wrbits: N longs], N = wrbits - rdbits.
* Both NULL initially (N = 0).
*/
unsigned long *rdbits, *wrbits;
} 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->rdbits); /* frees wrbits too */
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 +813,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 +923,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 +949,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 +978,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 +1006,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 +1029,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 +1042,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 +1121,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 +1223,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 +1338,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 +1364,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 +1586,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 +1693,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
@@ -1738,10 +1893,10 @@ void getcaps(void *caps) FAST_FUNC;
#if ENABLE_SELINUX
extern void renew_current_security_context(void) FAST_FUNC;
extern void set_current_security_context(security_context_t sid) FAST_FUNC;
extern context_t set_security_context_component(security_context_t cur_context,
extern void set_current_security_context(char *sid) FAST_FUNC;
extern context_t set_security_context_component(char *cur_context,
char *user, char *role, char *type, char *range) FAST_FUNC;
extern void setfscreatecon_or_die(security_context_t scontext) FAST_FUNC;
extern void setfscreatecon_or_die(char *scontext) FAST_FUNC;
extern void selinux_preserve_fcontext(int fdesc) FAST_FUNC;
#else
#define selinux_preserve_fcontext(fdesc) ((void)0)
@@ -1792,18 +1947,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 +2099,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 +2137,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 +2161,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 +2176,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 +2196,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 +2225,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 +2280,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 +2314,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 +2342,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 +2360,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;
@@ -2308,6 +2496,11 @@ extern const char bb_PATH_root_path[] ALIGN1; /* BB_PATH_ROOT_PATH */
*/
#define bb_default_path (bb_PATH_root_path + sizeof("PATH=/sbin:/usr/sbin"))
/* Stored without terminating NUL */
extern const char bb_SWAPSPACE2[sizeof("SWAPSPACE2")-1];
/* Stored with terminating NUL */
extern const char bb_NO_NAME_11[sizeof("NO NAME ")];
extern const int const_int_0;
//extern const int const_int_1;
@@ -2323,26 +2516,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 +2537,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.
@@ -2434,6 +2621,8 @@ do { \
BUG_wrong_field_size(); \
} while (0)
#define FETCH_LE16(field) \
(sizeof(field) == 2 ? SWAP_LE16(field) : BUG_wrong_field_size())
#define FETCH_LE32(field) \
(sizeof(field) == 4 ? SWAP_LE32(field) : BUG_wrong_field_size())
+22 -1
View File
@@ -151,6 +151,21 @@
# endif
#endif
/* Somewhere after gcc-9, it stopped recognizing "int var = var;" initializer
* as the "this variable is intentionally not initialized, don't warn" idiom.
*/
#if !__GNUC_PREREQ(10,0)
# define UNINITIALIZED_VAR(var,zero) var = var
#else
# define UNINITIALIZED_VAR(var,zero) var = zero
/* NB: in case newer gcc is able to see that the variable
* is never used before initialization on all possible code paths,
* you can use int UNINITIALIZED_VAR(var,var);
* instead of int UNINITIALIZED_VAR(var,0);
* and avoid having extra zeroing instruction.
*/
#endif
/* ---- Endian Detection ------------------------------------ */
@@ -187,7 +202,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 +224,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 +236,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
@@ -267,6 +287,7 @@ typedef uint64_t bb__aliased_uint64_t FIX_ALIASING;
#endif
/* Unaligned, fixed-endian accessors */
#define get_unaligned_le16(buf) ({ uint16_t v; move_from_unaligned16(v, buf); SWAP_LE16(v); })
#define get_unaligned_le32(buf) ({ uint32_t v; move_from_unaligned32(v, buf); SWAP_LE32(v); })
#define get_unaligned_be32(buf) ({ uint32_t v; move_from_unaligned32(v, buf); SWAP_BE32(v); })
#define put_unaligned_le32(val, buf) move_to_unaligned32(buf, SWAP_LE32(val))
+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
+8 -7
View File
@@ -17,15 +17,16 @@
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
int FAST_FUNC add_to_uuid_cache(const char *device);
void FAST_FUNC display_uuid_cache(int scan_devices);
char *get_devname_from_label(const char *spec);
char *get_devname_from_uuid(const char *spec);
void display_uuid_cache(int scan_devices);
//static: char *get_devname_from_label(const char *spec);
//static: char *get_devname_from_uuid(const char *spec);
/* Returns:
* 0: no UUID= or LABEL= prefix found
* 1: UUID= or LABEL= prefix found. In this case,
* *fsname is replaced if device with such UUID or LABEL is found
* *fsname is replaced if device with such UUID or LABEL is found.
* The new string is malloced. The old string is NOT freed!
* *fsname is NOT replaced in "LABEL=notfound" case! [FIXME: return 2 in this case to make distinguishable?]
*/
int resolve_mount_spec(char **fsname);
int add_to_uuid_cache(const char *device);
int FAST_FUNC resolve_mount_spec(char **fsname);
+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);
+31 -12
View File
@@ -27,14 +27,14 @@
//config: requires no special support.
//config:
//config:config FEATURE_USE_INITTAB
//config: bool "Support reading an inittab file"
//config: bool "Read /etc/inittab file"
//config: default y
//config: depends on INIT || LINUXRC
//config: help
//config: Allow init to read an inittab file when the system boot.
//config: init will read /etc/inittab.
//config:
//config:config FEATURE_KILL_REMOVED
//config: bool "Support killing processes that have been removed from inittab"
//config: bool "Kill processes that have been removed from inittab"
//config: default n
//config: depends on FEATURE_USE_INITTAB
//config: help
@@ -113,10 +113,10 @@
//config: wipes all the arguments but argv[0] and rewrites argv[0] to
//config: contain only "init", so that its command line appears solely as
//config: "init" in tools such as ps.
//config: If this option is set to Y, init will keep its original behavior,
//config: otherwise, all the arguments including argv[0] will be preserved,
//config: If this option is set to Y, init clears its command line.
//config: Otherwise, all arguments including argv[0] will be preserved,
//config: be they parsed or ignored by init.
//config: The original command-line used to launch init can then be
//config: The original command line used to launch init can then be
//config: retrieved in /proc/1/cmdline on Linux, for example.
//applet:IF_INIT(APPLET(init, BB_DIR_SBIN, BB_SUID_DROP))
@@ -766,6 +766,7 @@ static void run_shutdown_and_kill_processes(void)
/* Send signals to every process _except_ pid 1 */
kill(-1, SIGTERM);
//TODO: also send SIGCONT?
message(L_CONSOLE, "Sent SIG%s to all processes", "TERM");
sync();
sleep1();
@@ -821,17 +822,23 @@ static void halt_reboot_pwoff(int sig)
*/
reset_sighandlers_and_unblock_sigs();
run_shutdown_and_kill_processes();
m = "halt";
m = "halt"; // SIGPWR/SIGUSR1 case
rb = RB_HALT_SYSTEM;
if (sig == SIGTERM) {
m = "reboot";
rb = RB_AUTOBOOT;
// Some users want to be able to know whether they reboot or shut down the machine: e.g.
// "I want to be notified on unattended shutdowns signaled by UPS discharge,
// but I don't want to get 42 'SHUTDOWN!' text messages while I debug my server."
// Setting RC_REBOOT=YES only on reboot mimics openrc's behavior:
putenv((char*)"RC_REBOOT=YES");
} else if (sig == SIGUSR2) {
m = "poweroff";
rb = RB_POWER_OFF;
}
run_shutdown_and_kill_processes();
message(L_CONSOLE, "Requesting system %s", m);
pause_and_low_level_reboot(rb);
/* not reached */
@@ -1198,17 +1205,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
+3 -3
View File
@@ -118,10 +118,10 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
#if ENABLE_SELINUX
if ((flags & FILEUTILS_PRESERVE_SECURITY_CONTEXT) && is_selinux_enabled() > 0) {
security_context_t con;
char *con;
if (lgetfilecon(source, &con) >= 0) {
if (setfscreatecon(con) < 0) {
bb_perror_msg("can't set setfscreatecon %s", con);
bb_perror_msg("can't setfscreatecon %s", con);
freecon(con);
return -1;
}
@@ -327,7 +327,7 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
if ((flags & (FILEUTILS_PRESERVE_SECURITY_CONTEXT|FILEUTILS_SET_SECURITY_CONTEXT))
&& is_selinux_enabled() > 0
) {
security_context_t con;
char *con;
if (getfscreatecon(&con) == -1) {
bb_simple_perror_msg("getfscreatecon");
return -1;
+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;
}
/*
+31 -17
View File
@@ -8,41 +8,55 @@
*/
#include "libbb.h"
#define ULL(x) ((unsigned long long)(x))
uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
const char *override,
unsigned override_units,
int extend)
unsigned minsize_extend)
{
uoff_t result;
#define extend ((minsize_extend) & 1)
#define minsize ((minsize_extend) & ~1u)
if (override) {
result = XATOOFF(override);
if (result >= (uoff_t)(MAXINT(off_t)) / override_units)
bb_simple_error_msg_and_die("image size is too big");
bb_error_msg_and_die("image size %lld is too big", ULL(result));
result *= override_units;
/* seek past end fails on block devices but works on files */
if (result < minsize) // NB: we expect caller to pass nonzero minsize
goto insane;
// Do we need to extend the file?
// Seek past end fails on block devices but works on files!
if (lseek(fd, result - 1, SEEK_SET) != (off_t)-1) {
if (extend)
xwrite(fd, "", 1); /* file grows if needed */
char dummy;
//NB: here, fd needs a O_RDWR open, not O_WRONLY!
if (extend && safe_read(fd, &dummy, 1) != 1) {
// the file is shorter
xwrite(fd, "", 1); // grow it
}
} else {
// we use %lld instead of %llu in order for small negative offsets
// (which are often results of underflow in some buggy math)
// to be easily seen as such: show -1, not 18446744073709551615.
bb_error_msg("warning, block device is smaller than %lld bytes", ULL(result));
}
//else {
// bb_error_msg("warning, block device is smaller");
//}
} else {
/* more portable than BLKGETSIZE[64] */
// more portable than BLKGETSIZE[64]
result = xlseek(fd, 0, SEEK_END);
}
xlseek(fd, 0, SEEK_SET);
/* Prevent things like this:
* $ dd if=/dev/zero of=foo count=1 bs=1024
* $ mkswap foo
* Setting up swapspace version 1, size = 18446744073709548544 bytes
*
* Picked 16k arbitrarily: */
if (result < 16*1024)
bb_simple_error_msg_and_die("image is too small");
// Prevent things like this:
// $ dd if=/dev/zero of=foo count=1 bs=1024
// $ mkswap foo
// Setting up swapspace version 1, size = 18446744073709548544 bytes
if (result < minsize) {
insane:
/* common message */
bb_error_msg_and_die("image is too small: %lld bytes", ULL(result));
}
return result;
}
+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 */
+315
View File
@@ -0,0 +1,315 @@
/* 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);
}
/* Linux select() is not limited to FD_SETSIZE fds, but FD_SET/FD_ISSET are
* (with _FORTIFY_SOURCE, glibc aborts on fd >= FD_SETSIZE).
* Use our own bit ops on variable-sized sets.
*/
#define BPL (sizeof(long) * 8)
#define FDBIT_SET(set, fd) ((set)[(unsigned)(fd) / BPL] |= 1UL << ((unsigned)(fd) % BPL))
#define FDBIT_ISSET(set, fd) (((set)[(unsigned)(fd) / BPL] >> ((unsigned)(fd) % BPL)) & 1)
/* NB: bit ops must stay on longs: on big-endian, fd_set bit order
* within bytes differs from "byte fd/8, bit fd%8" */
#define IO_FDBYTES(io) ((uint8_t*)((io)->wrbits) - (uint8_t*)((io)->rdbits))
#define IO_FDBITS(io) (IO_FDBYTES(io) * 8)
static NOINLINE void grow_fdsets(ioloop_state_t *io, unsigned fd)
{
uint8_t *p;
/* Kernel reads fd_sets in longs: size must be a multiple of sizeof(long)
* (this also keeps wrbits aligned) */
unsigned new = (fd / BPL + 1) * sizeof(long);
unsigned old = IO_FDBYTES(io);
if (new <= old) return; /* paranoia */
/* Must preserve bits: we are called in the middle of filling the sets */
p = xrealloc(io->rdbits, 2 * new);
io->rdbits = (void*)p;
io->wrbits = (void*)(p + new);
/* [old, 2*old) -> [new, new+old) may overlap if new < 2*old */
memmove(p + new, p + old, old); /* move wrbits */
memset(p + new + old, 0, new - old); /* wrbits tail */
memset(p + old, 0, new - old); /* rdbits tail */
}
static ALWAYS_INLINE int track_maxfd(ioloop_state_t *io, int fd, int maxfd)
{
if (fd > maxfd) {
if ((unsigned)fd >= IO_FDBITS(io))
grow_fdsets(io, fd);
maxfd = fd;
}
return maxfd;
}
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;
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:
/* The sets are contiguous: one memset clears both.
* (Guard is needed: memset's arg is declared nonnull,
* the compiler may assume rdbits != NULL afterwards).
*/
if (io->rdbits)
memset(io->rdbits, 0, 2 * IO_FDBYTES(io));
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;
/* track_maxfd() before FDBIT_SET(): it may grow the sets */
if (rcw > 0) {
maxfd = track_maxfd(io, conn->write_fd, maxfd);
FDBIT_SET(io->wrbits, conn->write_fd);
}
if (rcr > 0) {
maxfd = track_maxfd(io, conn->read_fd, maxfd);
FDBIT_SET(io->rdbits, 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++; /* now: highest fd + 1, or 0 if no fds to wait on */
/* If maxfd == 0, sets are not accessed (they may be NULL) */
count = select(maxfd, (fd_set*)io->rdbits, (fd_set*)io->wrbits, 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;
int fd;
/* We do check for valid fd >=0: this means that conns
* may prevent I/O of other conns by setting fds to -1.
* fd < maxfd check: conns inserted (or fds changed) after
* the sets were filled may have fds beyond the sets' size.
*/
fd = conn->write_fd;
dbg("conn->write_fd:%d ?", fd);
if (fd >= 0 && fd < maxfd && FDBIT_ISSET(io->wrbits, fd)) {
dbg("conn->write_fd:%d ready", fd);
rcw = write_from_buf(conn);
if (rcw < 0) {
/* often indicates that conn is gone (freed), do not use it anymore */
goto next1;
}
}
fd = conn->read_fd;
dbg("conn->read_fd:%d ?", fd);
if (fd >= 0 && fd < maxfd && FDBIT_ISSET(io->rdbits, fd)) {
dbg("conn->read_fd:%d ready", 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) {
+67 -54
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);
@@ -2490,8 +2502,8 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
* (example: interactive python ^Z-backgrounded,
* tty is still in "raw mode").
*/
parse_and_put_prompt(prompt);
fflush_all();
parse_and_put_prompt(prompt);
if (fgets(command, maxsize, stdin) == NULL)
len = -1; /* EOF or error */
else
@@ -2536,6 +2548,7 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
#endif
#define command command_must_not_be_used
fflush_all();
tcsetattr_stdin_TCSANOW(&new_settings);
#if 0
-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
+8
View File
@@ -33,6 +33,14 @@ const char bb_default_login_shell[] ALIGN1 = LIBBB_DEFAULT_LOGIN_SHELL;
* but I want to save a few bytes here. Check libbb.h before changing! */
const char bb_PATH_root_path[] ALIGN1 = BB_PATH_ROOT_PATH;
#if ENABLE_MKSWAP || ENABLE_SWAPLABEL
/* Stored without terminating NUL */
const char bb_SWAPSPACE2[sizeof("SWAPSPACE2")-1] ALIGN1 = "SWAPSPACE2";
#endif
#if ENABLE_MKDOSFS || ENABLE_MKFS_VFAT || ENABLE_FEATURE_VOLUMEID_FAT
/* Stored with terminating NUL */
const char bb_NO_NAME_11[] = "NO NAME ";
#endif
//const int const_int_1 = 1;
/* explicitly = 0, otherwise gcc may make it a common variable
+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;
}
Loaded 100 of 438 files, more files were not shown because too many files have changed in this diff. Show more