Compare commits

..
9 Commits
Author SHA1 Message Date
Denys Vlasenko 0cf9e105e6 Bump version to 1.34.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 22:27:55 +02:00
Denys Vlasenko 0e0dd21497 awk: never return NULL from awk_printf()
function                                             old     new   delta
awk_printf                                           651     628     -23

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Denys Vlasenko 118baea06e awk: code shrink
function                                             old     new   delta
awk_printf                                           652     651      -1

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

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

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

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

function                                             old     new   delta
awk_printf                                           672     665      -7

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Denys Vlasenko 3c9f559a41 chat: hopefully fix infinite spinning on input EOF
function                                             old     new   delta
chat_main                                           1295    1303      +8

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

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

function                                             old     new   delta
awk_printf                                           626     672     +46

Signed-off-by: Daniel Thau <danthau at bedrocklinux.org>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:44 +02:00
Ron Yorston 76ef439154 ash: regressions in process substitution
Stacy Harper reports that this script:

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

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

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

Additionally, these examples of process substitution:

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

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

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

Signed-off-by: Ron Yorston <rmy@pobox.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-09-30 00:15:33 +02:00
Denys Vlasenko 00adcdb64a udhcp: fix build breakage on MIPS
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-08-20 13:35:54 +02:00
870 changed files with 16573 additions and 40025 deletions

No files matched your search

-3
View File
@@ -181,6 +181,3 @@ Jie Zhang <jie.zhang@analog.com>
Maxime Coste <mawww@kakoune.org>
paste implementation
Roger Knecht <rknecht@pm.me>
tree
-18
View File
@@ -108,17 +108,6 @@ config LFS
programs that can benefit from large file support include dd, gzip,
cp, mount, tar.
config TIME64
bool "Support 64bit wide time types"
default y
depends on LFS
help
Make times later than 2038 representable for several libc syscalls
(stat, clk_gettime etc.). Note this switch is specific to glibc
and has no effect on platforms that already use 64bit wide time types
(i.e. all 64bit archs and some selected 32bit archs (currently riscv
and x32)).
config PAM
bool "Support PAM (Pluggable Authentication Modules)"
default n
@@ -204,13 +193,6 @@ 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
+12 -10
View File
@@ -1,7 +1,7 @@
VERSION = 1
PATCHLEVEL = 39
SUBLEVEL = 0
EXTRAVERSION = .git
PATCHLEVEL = 34
SUBLEVEL = 1
EXTRAVERSION =
NAME = Unnamed
# *DOCUMENTATION*
@@ -476,7 +476,6 @@ libs-y := \
findutils/ \
init/ \
libbb/ \
libbb/yescrypt/ \
libpwdgrp/ \
loginutils/ \
mailutils/ \
@@ -613,12 +612,8 @@ 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
@@ -972,7 +967,6 @@ endif # CONFIG_MODULES
# Directories & files removed with 'make clean'
CLEAN_DIRS += $(MODVERDIR) _install 0_lib
CLEAN_FILES += busybox busybox_unstripped* busybox.links \
busybox*.suid busybox*.nosuid \
System.map .kernelrelease \
.tmp_kallsyms* .tmp_version .tmp_busybox* .tmp_System.map
@@ -1307,6 +1301,14 @@ quiet_cmd_rmdirs = $(if $(wildcard $(rm-dirs)),CLEAN $(wildcard $(rm-dirs)))
quiet_cmd_rmfiles = $(if $(wildcard $(rm-files)),CLEAN $(wildcard $(rm-files)))
cmd_rmfiles = rm -f $(rm-files)
a_flags = -Wp,-MD,$(depfile) $(AFLAGS) $(AFLAGS_KERNEL) \
$(NOSTDINC_FLAGS) $(CPPFLAGS) \
$(modkern_aflags) $(EXTRA_AFLAGS) $(AFLAGS_$(*F).o)
quiet_cmd_as_o_S = AS $@
cmd_as_o_S = $(CC) $(a_flags) -c -o $@ $<
# read all saved command lines
targets := $(wildcard $(sort $(targets)))
+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 --quotes=none $< > $@
$(Q)-pod2text $< > $@
docs/busybox.1: docs/busybox.pod
$(disp_doc)
$(Q)-mkdir -p docs
$(Q)-pod2man --quotes=none --center=busybox --release="version $(KERNELVERSION)" $< > $@
$(Q)-pod2man --center=busybox --release="version $(KERNELVERSION)" $< > $@
docs/BusyBox.html: docs/busybox.net/BusyBox.html
$(disp_doc)
+7 -13
View File
@@ -15,7 +15,6 @@ CPPFLAGS += \
-include include/autoconf.h \
-D_GNU_SOURCE -DNDEBUG \
$(if $(CONFIG_LFS),-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64) \
$(if $(CONFIG_TIME64),-D_TIME_BITS=64) \
-DBB_VER=$(squote)$(quote)$(BB_VER)$(quote)$(squote)
CFLAGS += $(call cc-option,-Wall,)
@@ -27,8 +26,6 @@ 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
@@ -50,7 +47,7 @@ endif
# gcc 3.x emits bogus "old style proto" warning on find.c:alloc_action()
CFLAGS += $(call cc-ifversion, -ge, 0400, -Wold-style-definition)
ifneq ($(lastword $(subst -, ,$(CC))),clang)
ifneq ($(CC),clang)
# "clang-9: warning: optimization flag '-finline-limit=0' is not supported
CFLAGS += $(call cc-option,-finline-limit=0,)
endif
@@ -68,7 +65,7 @@ CFLAGS += $(call cc-option,-static-libgcc,)
endif
CFLAGS += $(call cc-option,-falign-functions=1,)
ifneq ($(lastword $(subst -, ,$(CC))),clang)
ifneq ($(CC),clang)
# "clang-9: warning: optimization flag '-falign-jumps=1' is not supported" (and same for other two)
CFLAGS += $(call cc-option,-falign-jumps=1 -falign-labels=1 -falign-loops=1,)
endif
@@ -81,7 +78,7 @@ CFLAGS += $(call cc-option,-fno-asynchronous-unwind-tables,)
CFLAGS += $(call cc-option,-fno-builtin-printf,)
# clang-9 does not like "str" + N and "if (CONFIG_ITEM && cond)" constructs
ifeq ($(lastword $(subst -, ,$(CC))),clang)
ifeq ($(CC),clang)
CFLAGS += $(call cc-option,-Wno-string-plus-int -Wno-constant-logical-operand)
endif
@@ -90,14 +87,14 @@ endif
#CFLAGS += $(call cc-option,-Wconversion,)
ifneq ($(CONFIG_DEBUG),y)
CFLAGS += $(call cc-option,-Oz,$(call cc-option,-Os,$(call cc-option,-O2,)))
CFLAGS += $(call cc-option,-Os,$(call cc-option,-O2,))
else
CFLAGS += $(call cc-option,-g,)
#CFLAGS += "-D_FORTIFY_SOURCE=2"
ifeq ($(CONFIG_DEBUG_PESSIMIZE),y)
CFLAGS += $(call cc-option,-O0,)
else
CFLAGS += $(call cc-option,-Oz,$(call cc-option,-Os,$(call cc-option,-O2,)))
CFLAGS += $(call cc-option,-Os,$(call cc-option,-O2,))
endif
endif
ifeq ($(CONFIG_DEBUG_SANITIZE),y)
@@ -154,8 +151,8 @@ LDLIBS += m
# gcc-4.2.1 fails if we try to feed C source on stdin:
# echo 'int main(void){return 0;}' | $(CC) $(CFLAGS) -lcrypt -o /dev/null -xc -
# fall back to using a temp file:
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) $(CFLAGS_busybox) -lcrypt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
RT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) $(CFLAGS_busybox) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) -lcrypt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
RT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
endif
@@ -190,9 +187,6 @@ ifeq ($(CONFIG_FEATURE_NSLOOKUP_BIG),y)
ifneq (,$(findstring linux,$(shell $(CC) $(CFLAGS) -dumpmachine)))
LDLIBS += resolv
endif
ifneq (,$(findstring gnu,$(shell $(CC) $(CFLAGS) -dumpmachine)))
LDLIBS += resolv
endif
endif
ifeq ($(CONFIG_EFENCE),y)
-1
View File
@@ -336,7 +336,6 @@ setuidgid - noexec. spawner
sha1sum - noexec. runner
sha256sum - noexec. runner
sha3sum - noexec. runner
sha384sum - noexec. runner
sha512sum - noexec. runner
showkey - interactive, longterm
shred - runner
+2
View File
@@ -222,6 +222,8 @@ Minor stuff:
---
unify progress_meter. wget, flash_eraseall, pipe_progress, fbsplash, setfiles.
---
support start-stop-daemon -d <chdir-path>
---
(TODO list after discussion 11.05.2009)
+1 -1
View File
@@ -20,5 +20,5 @@ int main(int argc, char **argv)
void bb_show_usage(void)
{
fputs_stdout(APPLET_full_usage "\n");
exit_FAILURE();
exit(EXIT_FAILURE);
}
+5 -12
View File
@@ -67,37 +67,30 @@ int main(void)
}
if (col == 0) {
col = 6;
printf("\t");
} else {
printf(", ");
}
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);
}
printf("%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]
) {
/* This is the heading that will be linked from the command list. */
printf("=head2 %s\n\n", usage_array[i].aname);
printf("=item B<%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,15 +35,4 @@ 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 -8
View File
@@ -151,15 +151,15 @@ static int write_ar_header(archive_handle_t *handle)
static int write_ar_archive(archive_handle_t *handle)
{
off_t st_size;
struct stat st;
archive_handle_t *out_handle;
st_size = xfstat_size(handle->src_fd, handle->ar__name);
xfstat(handle->src_fd, &st, handle->ar__name);
/* if archive exists, create a new handle for output.
* we create it in place of the old one.
*/
if (st_size != 0) {
if (st.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_size != 0) {
if (st.st_size != 0) {
handle->filter = filter_replaceable;
handle->action_data = copy_data;
unpack_ar_archive(handle);
@@ -194,13 +194,11 @@ static int write_ar_archive(archive_handle_t *handle)
}
#endif /* FEATURE_AR_CREATE */
static void FAST_FUNC header_verbose_list_ar(archive_handle_t *archive_handle)
static void FAST_FUNC header_verbose_list_ar(const file_header_t *file_header)
{
const file_header_t *file_header = archive_handle->file_header;
char mode[12];
const char *mode = bb_mode_string(file_header->mode);
char *mtime;
bb_mode_string(mode, file_header->mode);
mtime = ctime(&file_header->mtime);
mtime[16] = ' ';
memmove(&mtime[17], &mtime[20], 4);
+7 -7
View File
@@ -71,8 +71,8 @@ int FAST_FUNC bbunpack(char **argv,
goto err;
} else {
/* "clever zcat" with FILE */
/* die_if_not_compressed because zcat refuses uncompressed input */
int fd = open_zipped(filename, /*die_if_not_compressed:*/ 1);
/* fail_if_not_compressed because zcat refuses uncompressed input */
int fd = open_zipped(filename, /*fail_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, /*die_if_not_compressed*/ 1))
if (setup_unzip_on_fd(STDIN_FILENO, /*fail_if_not_compressed*/ 1))
goto err;
}
@@ -415,7 +415,7 @@ int gunzip_main(int argc UNUSED_PARAM, char **argv)
//usage: "Decompress to stdout"
//config:config BUNZIP2
//config: bool "bunzip2 (9.1 kb)"
//config: bool "bunzip2 (8.7 kb)"
//config: default y
//config: select FEATURE_BZIP2_DECOMPRESS
//config: help
@@ -429,7 +429,7 @@ int gunzip_main(int argc UNUSED_PARAM, char **argv)
//config: should probably say N here.
//config:
//config:config BZCAT
//config: bool "bzcat (9 kb)"
//config: bool "bzcat (8.7 kb)"
//config: default y
//config: select FEATURE_BZIP2_DECOMPRESS
//config: help
@@ -485,7 +485,7 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//usage: "Decompress to stdout"
//config:config UNLZMA
//config: bool "unlzma (7.8 kb)"
//config: bool "unlzma (7.5 kb)"
//config: default y
//config: help
//config: unlzma is a compression utility using the Lempel-Ziv-Markov chain
@@ -494,7 +494,7 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//config: compressors.
//config:
//config:config LZCAT
//config: bool "lzcat (7.8 kb)"
//config: bool "lzcat (7.5 kb)"
//config: default y
//config: help
//config: Alias to "unlzma -c".
-35
View File
@@ -1,35 +0,0 @@
/*
* Copyright (C) 2021 Denys Vlasenko <vda.linux@googlemail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-$(CONFIG_FEATURE_TAR_CREATE) += chksum_and_xwrite_tar_header.o
//kbuild:lib-$(CONFIG_SMEMCAP) += chksum_and_xwrite_tar_header.o
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC chksum_and_xwrite_tar_header(int fd, struct tar_header_t *hp)
{
/* POSIX says that checksum is done on unsigned bytes
* (Sun and HP-UX gets it wrong... more details in
* GNU tar source) */
const unsigned char *cp;
unsigned int chksum, size;
strcpy(hp->magic, "ustar ");
/* Calculate and store the checksum (the sum of all of the bytes of
* the header). The checksum field must be filled with blanks for the
* calculation. The checksum field is formatted differently from the
* other fields: it has 6 digits, a NUL, then a space -- rather than
* digits, followed by a NUL like the other fields... */
memset(hp->chksum, ' ', sizeof(hp->chksum));
cp = (const unsigned char *) hp;
chksum = 0;
size = sizeof(*hp);
do { chksum += *cp++; } while (--size);
sprintf(hp->chksum, "%06o", chksum);
xwrite(fd, hp, sizeof(*hp));
}
+4 -62
View File
@@ -38,22 +38,8 @@
//config: depends on FEATURE_CPIO_O
//config: help
//config: Passthrough mode. Rarely used.
//config:
//config:config FEATURE_CPIO_IGNORE_DEVNO
//config: bool "Support --ignore-devno like GNU cpio"
//config: default y
//config: depends on FEATURE_CPIO_O && LONG_OPTS
//config: help
//config: Optionally ignore device numbers when creating archives.
//config:
//config:config FEATURE_CPIO_RENUMBER_INODES
//config: bool "Support --renumber-inodes like GNU cpio"
//config: default y
//config: depends on FEATURE_CPIO_O && LONG_OPTS
//config: help
//config: Optionally renumber inodes when creating archives.
//applet:IF_CPIO(APPLET(cpio, BB_DIR_USR_BIN, BB_SUID_DROP))
//applet:IF_CPIO(APPLET(cpio, BB_DIR_BIN, BB_SUID_DROP))
//kbuild:lib-$(CONFIG_CPIO) += cpio.o
@@ -62,7 +48,7 @@
//usage: " [-ti"IF_FEATURE_CPIO_O("o")"]" IF_FEATURE_CPIO_P(" [-p DIR]")
//usage: " [EXTR_FILE]..."
//usage:#define cpio_full_usage "\n\n"
//usage: "Extract (-i) or list (-t) files from a cpio archive on stdin"
//usage: "Extract (-i) or list (-t) files from a cpio archive"
//usage: IF_FEATURE_CPIO_O(", or"
//usage: "\ntake file list from stdin and create an archive (-o)"
//usage: IF_FEATURE_CPIO_P(" or copy files (-p)")
@@ -88,13 +74,7 @@
//usage: "\n -F FILE Input (-t,-i,-p) or output (-o) file"
//usage: "\n -R USER[:GRP] Set owner of created files"
//usage: "\n -L Dereference symlinks"
//usage: "\n -0 NUL terminated input"
//usage: IF_FEATURE_CPIO_IGNORE_DEVNO(
//usage: "\n --ignore-devno"
//usage: )
//usage: IF_FEATURE_CPIO_RENUMBER_INODES(
//usage: "\n --renumber-inodes"
//usage: )
//usage: "\n -0 Input is separated by NULs"
/* GNU cpio 2.9 --help (abridged):
@@ -182,22 +162,17 @@ enum {
IF_FEATURE_CPIO_P(OPTBIT_PASSTHROUGH,)
IF_LONG_OPTS( OPTBIT_QUIET ,)
IF_LONG_OPTS( OPTBIT_2STDOUT ,)
IF_FEATURE_CPIO_IGNORE_DEVNO(OPTBIT_IGNORE_DEVNO,)
IF_FEATURE_CPIO_RENUMBER_INODES(OPTBIT_RENUMBER_INODES,)
OPT_CREATE = IF_FEATURE_CPIO_O((1 << OPTBIT_CREATE )) + 0,
OPT_FORMAT = IF_FEATURE_CPIO_O((1 << OPTBIT_FORMAT )) + 0,
OPT_PASSTHROUGH = IF_FEATURE_CPIO_P((1 << OPTBIT_PASSTHROUGH)) + 0,
OPT_QUIET = IF_LONG_OPTS( (1 << OPTBIT_QUIET )) + 0,
OPT_2STDOUT = IF_LONG_OPTS( (1 << OPTBIT_2STDOUT )) + 0,
OPT_IGNORE_DEVNO = IF_FEATURE_CPIO_IGNORE_DEVNO((1 << OPTBIT_IGNORE_DEVNO)) + 0,
OPT_RENUMBER_INODES = IF_FEATURE_CPIO_RENUMBER_INODES((1 << OPTBIT_RENUMBER_INODES)) + 0,
};
#define OPTION_STR "it0uvdmLF:R:"
struct globals {
struct bb_uidgid_t owner_ugid;
ino_t next_inode;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
void BUG_cpio_globals_too_big(void);
@@ -231,9 +206,6 @@ static NOINLINE int cpio_o(void)
struct inodes_s *next;
struct name_s *names;
struct stat st;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
ino_t mapped_inode;
#endif
};
struct inodes_s *links = NULL;
@@ -288,10 +260,6 @@ static NOINLINE int cpio_o(void)
l = xzalloc(sizeof(*l));
l->st = st;
l->next = links;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
if (option_mask32 & OPT_RENUMBER_INODES)
l->mapped_inode = ++G.next_inode;
#endif
links = l;
break;
}
@@ -310,11 +278,6 @@ static NOINLINE int cpio_o(void)
free(line);
continue;
}
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
else if (option_mask32 & OPT_RENUMBER_INODES) {
st.st_ino = ++G.next_inode;
}
#endif
} else { /* line == NULL: EOF */
next_link:
if (links) {
@@ -322,10 +285,6 @@ static NOINLINE int cpio_o(void)
st = links->st;
name = links->names->name;
links->names = links->names->next;
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
if (links->mapped_inode)
st.st_ino = links->mapped_inode;
#endif
/* GNU cpio is reported to emit file data
* only for the last instance. Mimic that. */
if (links->names == NULL)
@@ -345,17 +304,6 @@ static NOINLINE int cpio_o(void)
}
}
#if ENABLE_FEATURE_CPIO_IGNORE_DEVNO
if (option_mask32 & OPT_IGNORE_DEVNO)
st.st_dev = st.st_rdev = 0;
#endif
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 */
@@ -427,17 +375,10 @@ 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"
"to-stdout\0" No_argument "\xfe"
#if ENABLE_FEATURE_CPIO_IGNORE_DEVNO
"ignore-devno\0" No_argument "\xfd"
#endif
#if ENABLE_FEATURE_CPIO_RENUMBER_INODES
"renumber-inodes\0" No_argument "\xfc"
#endif
;
#endif
@@ -511,6 +452,7 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
goto dump;
}
/* parent */
USE_FOR_NOMMU(argv[-optind][0] &= 0x7f); /* undo fork_or_rexec() damage */
xchdir(*argv++);
close(pp.wr);
xmove_fd(pp.rd, STDIN_FILENO);
+140 -178
View File
@@ -41,30 +41,30 @@
//kbuild:lib-$(CONFIG_DPKG) += dpkg.o
//usage:#define dpkg_trivial_usage
//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: "[-ilCPru] [-F OPT] PACKAGE"
//usage:#define dpkg_full_usage "\n\n"
//usage: "Manage Debian packages\n"
//usage: "Install, remove and manage Debian packages\n"
//usage: IF_LONG_OPTS(
//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 -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 --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 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 -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 -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,9 +166,8 @@ typedef struct deb_file_s {
} deb_file_t;
static unsigned make_hash(const char *key, unsigned *decrement, int hash_prime)
static void make_hash(const char *key, unsigned *start, unsigned *decrement, const int hash_prime)
{
unsigned start;
unsigned long hash_num = key[0];
int len = strlen(key);
int i;
@@ -182,9 +181,8 @@ static unsigned make_hash(const char *key, unsigned *decrement, int hash_prime)
* 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 */
@@ -193,7 +191,7 @@ static int search_name_hashtable(const char *key)
unsigned probe_address;
unsigned probe_decrement;
probe_address = make_hash(key, &probe_decrement, NAME_HASH_PRIME);
make_hash(key, &probe_address, &probe_decrement, NAME_HASH_PRIME);
while (name_hashtable[probe_address] != NULL) {
if (strcmp(name_hashtable[probe_address], key) == 0) {
return probe_address;
@@ -215,7 +213,7 @@ static unsigned search_status_hashtable(const char *key)
unsigned probe_address;
unsigned probe_decrement;
probe_address = make_hash(key, &probe_decrement, STATUS_HASH_PRIME);
make_hash(key, &probe_address, &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;
@@ -282,7 +280,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(unsigned ver1, unsigned ver2)
static int version_compare(const unsigned ver1, const unsigned ver2)
{
char *ch_ver1 = name_hashtable[ver1];
char *ch_ver2 = name_hashtable[ver2];
@@ -335,9 +333,9 @@ static int version_compare(unsigned ver1, unsigned ver2)
return result;
}
static int test_version(unsigned version1, unsigned version2, unsigned operator)
static int test_version(const unsigned version1, const unsigned version2, const unsigned operator)
{
int version_result = version_compare(version1, version2);
const int version_result = version_compare(version1, version2);
switch (operator) {
case VER_ANY:
return TRUE;
@@ -355,12 +353,12 @@ static int test_version(unsigned version1, unsigned version2, unsigned operator)
return FALSE;
}
static int search_package_hashtable(unsigned name, unsigned version, unsigned operator)
static int search_package_hashtable(const unsigned name, const unsigned version, const unsigned operator)
{
unsigned probe_address;
unsigned probe_decrement;
probe_address = make_hash(name_hashtable[name], &probe_decrement, PACKAGE_HASH_PRIME);
make_hash(name_hashtable[name], &probe_address, &probe_decrement, PACKAGE_HASH_PRIME);
while (package_hashtable[probe_address] != NULL) {
if (package_hashtable[probe_address]->name == name) {
if (operator == VER_ANY) {
@@ -533,98 +531,90 @@ static void free_package(common_node_t *node)
}
/*
* 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
* 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
*/
static int read_package_field(const char *pkg_buf, char **pname, char **pvalue)
static int read_package_field(const char *package_buffer, char **field_name, char **field_value)
{
int name_start;
int name_end;
int value_start = value_start;
int offset;
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;
*pname = NULL;
*pvalue = NULL;
offset = 0;
name_start = 0;
name_end = 0; /* "we did not see ':' yet" */
if (package_buffer == NULL) {
*field_name = NULL;
*field_value = NULL;
return -1;
}
while (1) {
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 */
}
break;
case '\n':
if (pkg_buf[offset + 1] == ' ')
next_offset = offset + 1;
switch (package_buffer[offset]) {
case '\0':
exit_flag = TRUE;
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;
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;
}
if ((name_length > 0) && (value_length > 0)) {
break;
}
if (!ch)
return offset; /* stop at NUL */
/* Not valid: skip '\n', start fresh with next field */
name_start = offset + 1;
name_end = 0; /* "we did not see ':' yet" */
break;
/* 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++;
}
offset++;
} /* while (1) */
}
*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;
}
/* The parameter is NUL-terminated */
static unsigned fill_package_struct(char *control_buffer)
{
static const char field_names[] ALIGN1 =
@@ -633,13 +623,14 @@ 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;
int num = -1;
int buffer_length = strlen(control_buffer);
new_node->version = search_name_hashtable("unknown");
while (control_buffer[field_start]) {
char *field_name;
char *field_value;
while (field_start < buffer_length) {
unsigned field_num;
field_start += read_package_field(&control_buffer[field_start],
@@ -698,7 +689,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(unsigned status_node, int num)
static unsigned get_status(const unsigned status_node, const int num)
{
char *status_string = name_hashtable[status_hashtable[status_node]->status];
char *state_sub_string;
@@ -720,9 +711,9 @@ static unsigned get_status(unsigned status_node, int num)
return state_sub_num;
}
static void set_status(unsigned status_node_num, const char *new_value, int position)
static void set_status(const unsigned status_node_num, const char *new_value, const int position)
{
unsigned new_value_num = search_name_hashtable(new_value);
const 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);
@@ -780,10 +771,9 @@ 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) {
unsigned package_num = fill_package_struct(control_buffer);
const 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 */
@@ -809,7 +799,7 @@ static void write_buffer_no_status(FILE *new_status_file, const char *control_bu
char *name;
char *value;
int start = 0;
while (control_buffer[start]) {
while (1) {
start += read_package_field(&control_buffer[start], &name, &value);
if (name == NULL) {
break;
@@ -817,42 +807,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 *control_buffer;
char *package_name;
char *status_from_file;
char *control_buffer = NULL;
char *tmp_string;
int status_num;
int i;
int field_start = 0;
int write_flag;
int i = 0;
/* 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 = skip_whitespace(tmp_string + 8);
package_name = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
tmp_string += 8;
tmp_string += strspn(tmp_string, " \n\t");
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) {
tmp_string = skip_whitespace(tmp_string + 7);
/* Separate the status value from the control buffer */
tmp_string += 7;
tmp_string += strspn(tmp_string, " \n\t");
status_from_file = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
} else {
status_from_file = NULL;
}
/* Find this package in the status hashtable */
@@ -861,7 +851,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 */
int state_status = get_status(status_num, 3);
const int state_status = get_status(status_num, 3);
if ((strcmp("installed", name_hashtable[state_status]) == 0)
|| (strcmp("unpacked", name_hashtable[state_status]) == 0)
) {
@@ -880,7 +870,7 @@ static void write_status_file(deb_file_t **deb_file)
}
i++;
}
/* This is temporary, debugging only */
/* This is temperary, 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 "
@@ -888,18 +878,14 @@ 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 (control_buffer[field_start]) {
while (1) {
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;
}
@@ -908,17 +894,13 @@ 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 (control_buffer[field_start]) {
while (1) {
char *field_name;
char *field_value;
field_start += read_package_field(&control_buffer[field_start], &field_name, &field_value);
@@ -931,15 +913,13 @@ 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 handled above, do it now */
/* If the package from the status file wasn't handle above, do it now*/
if (!write_flag) {
fprintf(new_status_file, "%s\n\n", control_buffer);
}
@@ -947,7 +927,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++) {
@@ -1014,14 +994,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) {
unsigned package_num = deb_file[i]->package;
const 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) {
int conflicts_package_num = search_package_hashtable(
const 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);
@@ -1056,7 +1036,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) {
unsigned package_num =
const unsigned package_num =
search_package_hashtable(package_edge->name,
package_edge->version,
package_edge->operator);
@@ -1085,7 +1065,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
@@ -1135,7 +1115,7 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
if (package_edge->type == EDGE_PRE_DEPENDS
|| package_edge->type == EDGE_DEPENDS
) {
int result = 1;
int result=1;
status_num = 0;
/* If we are inside an alternative then check
@@ -1401,12 +1381,12 @@ static void list_packages(const char *pattern)
}
}
static void remove_package(unsigned package_num, int noisy)
static void remove_package(const 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];
unsigned status_num = search_status_hashtable(package_name);
int package_name_length = strlen(package_name);
const unsigned status_num = search_status_hashtable(package_name);
const int package_name_length = strlen(package_name);
char **remove_files;
char **exclude_files;
char list_name[package_name_length + 25];
@@ -1452,11 +1432,11 @@ static void remove_package(unsigned package_num, int noisy)
set_status(status_num, "config-files", 3);
}
static void purge_package(unsigned package_num)
static void purge_package(const 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];
unsigned status_num = search_status_hashtable(package_name);
const unsigned status_num = search_status_hashtable(package_name);
char **remove_files;
char **exclude_files;
char list_name[strlen(package_name) + 25];
@@ -1674,8 +1654,8 @@ enum {
static void unpack_package(deb_file_t *deb_file)
{
const char *package_name = name_hashtable[package_hashtable[deb_file->package]->name];
unsigned status_num = search_status_hashtable(package_name);
unsigned status_package_num = status_hashtable[status_num]->package;
const unsigned status_num = search_status_hashtable(package_name);
const unsigned status_package_num = status_hashtable[status_num]->package;
char *info_prefix;
char *list_filename;
archive_handle_t *archive_handle;
@@ -1709,7 +1689,7 @@ static void unpack_package(deb_file_t *deb_file)
accept_list = NULL;
i = 0;
while (i < ARRAY_SIZE(all_control_files)) {
char *c = concat_path_file(".", all_control_files[i]);
char *c = xasprintf("./%s", all_control_files[i]);
llist_add_to(&accept_list, c);
i++;
}
@@ -1765,7 +1745,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];
int status_num = search_status_hashtable(package_name);
const int status_num = search_status_hashtable(package_name);
printf("Setting up %s (%s)...\n", package_name, package_version);
@@ -1806,24 +1786,6 @@ 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();
+1 -1
View File
@@ -5,7 +5,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config DPKG_DEB
//config: bool "dpkg-deb (29 kb)"
//config: bool "dpkg-deb (30 kb)"
//config: default y
//config: select FEATURE_SEAMLESS_GZ
//config: help
-3
View File
@@ -2215,9 +2215,6 @@ 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,7 +12,6 @@ COMMON_FILES:= \
data_extract_all.o \
data_extract_to_stdout.o \
\
unsafe_prefix.o \
unsafe_symlink_target.o \
\
filter_accept_all.o \
@@ -33,6 +32,7 @@ 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
lib-$(CONFIG_TAR) += get_header_tar.o unsafe_prefix.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
lib-$(CONFIG_UNZIP) += open_transformer.o decompress_gunzip.o unsafe_prefix.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
+1 -1
View File
@@ -107,7 +107,7 @@ void fallbackSimpleSort(uint32_t* fmap,
#define FALLBACK_QSORT_SMALL_THRESH 10
#define FALLBACK_QSORT_STACK_SIZE 100
static NOINLINE
static
void fallbackQSort3(uint32_t* fmap,
uint32_t* eclass,
int32_t loSt,
+4 -3
View File
@@ -99,8 +99,9 @@ void BZ2_bzCompressInit(bz_stream *strm, int blockSize100k)
s->ptr = (uint32_t*)s->arr1;
s->arr2 = xmalloc((n + BZ_N_OVERSHOOT) * sizeof(uint32_t));
s->block = (uint8_t*)s->arr2;
s->ftab = xmalloc(65537 * sizeof(uint32_t));
crc32_filltable(s->crc32table, 1);
s->crc32table = crc32_filltable(NULL, 1);
s->state = BZ_S_INPUT;
s->mode = BZ_M_RUNNING;
@@ -368,8 +369,8 @@ void BZ2_bzCompressEnd(bz_stream *strm)
s = strm->state;
free(s->arr1);
free(s->arr2);
//free(s->ftab); // made it array member of s
//free(s->crc32table); // ditto
free(s->ftab);
free(s->crc32table);
free(s);
}
+4 -7
View File
@@ -134,7 +134,7 @@ typedef struct EState {
/* for doing the block sorting */
uint32_t *arr1;
uint32_t *arr2;
//uint32_t *ftab; //moved into this struct, see below
uint32_t *ftab;
uint16_t *quadrant;
int32_t budget;
@@ -160,6 +160,9 @@ typedef struct EState {
uint32_t bsBuff;
int32_t bsLive;
/* guess what */
uint32_t *crc32table;
/* block and combined CRCs */
uint32_t blockCRC;
uint32_t combinedCRC;
@@ -182,12 +185,6 @@ typedef struct EState {
uint8_t len[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
/* guess what */
uint32_t crc32table[256];
/* for doing the block sorting */
uint32_t ftab[65537];
/* stack-saving measures: these can be local, but they are too big */
int32_t sendMTFValues__code [BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
int32_t sendMTFValues__rfreq[BZ_N_GROUPS][BZ_MAX_ALPHA_SIZE];
+2 -13
View File
@@ -65,18 +65,6 @@ 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, '/');
@@ -189,7 +177,8 @@ 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 "/"
* or symlinks starting with "/", unless a magic
* envvar is set.
*
* For example, consider a .tar created via:
* $ tar cvf bug.tar anything.txt
+8 -7
View File
@@ -463,12 +463,13 @@ 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 */
/* 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;
}
//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;
// }
if (runPos < bd->dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
}
@@ -653,7 +654,7 @@ static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* Subtract the 1 copy we'd output anyway to get extras */
--bd->writeCopies;
}
} /* for (;;) */
} /* for(;;) */
/* Decompression of this input block completed successfully */
bd->writeCRC = CRC = ~CRC;
+2 -6
View File
@@ -92,12 +92,8 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
/* Only size is always present, the rest may be missing in
* long filename pseudo file. Thus we decode the rest
* after dealing with long filename pseudo file.
*
* GNU binutils in deterministic mode hard codes mode to 0644 (NOT
* 0100644). AR archives can only contain files, so force file
* mode.
*/
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode)) | S_IFREG;
typed->mode = read_num(ar.formatted.mode, 8, sizeof(ar.formatted.mode));
typed->gid = read_num(ar.formatted.gid, 10, sizeof(ar.formatted.gid));
typed->uid = read_num(ar.formatted.uid, 10, sizeof(ar.formatted.uid));
typed->mtime = read_num(ar.formatted.date, 10, sizeof(ar.formatted.date));
@@ -124,7 +120,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(archive_handle);
archive_handle->action_header(typed);
#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(archive_handle);
archive_handle->action_header(file_header);
} else {
data_skip(archive_handle);
}
+6 -21
View File
@@ -147,14 +147,6 @@ static void process_pax_hdr(archive_handle_t *archive_handle, unsigned sz, int g
#endif
}
#if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
static void die_if_bad_fnamesize(off_t sz)
{
if ((uoff_t)sz > 0xfff) /* more than 4k?! no funny business please */
bb_simple_error_msg_and_die("bad archive");
}
#endif
char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
{
file_header_t *file_header = archive_handle->file_header;
@@ -339,6 +331,8 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
file_header->name = xstrdup(tar.name);
}
/* Set bits 12-15 of the files mode */
/* (typeflag was not trashed because chksum does not use getOctal) */
switch (tar_typeflag) {
case '1': /* hardlink */
/* we mark hardlinks as regular files with zero size and a link name */
@@ -347,7 +341,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
* ... For tar archives written by pre POSIX.1-1988
* implementations, the size field usually contains the size of
* the file and needs to be ignored as no data may follow this
* header type. For POSIX.1-1988 compliant archives, the size
* header type. For POSIX.1- 1988 compliant archives, the size
* field needs to be 0. For POSIX.1-2001 compliant archives,
* the size field may be non zero, indicating that file data is
* included in the archive.
@@ -396,7 +390,6 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
/* free: paranoia: tar with several consecutive longnames */
free(p_longname);
/* For paranoia reasons we allocate extra NUL char */
die_if_bad_fnamesize(file_header->size);
p_longname = xzalloc(file_header->size + 1);
/* We read ASCIZ string, including NUL */
xread(archive_handle->src_fd, p_longname, file_header->size);
@@ -407,7 +400,6 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
goto again;
case 'K':
free(p_linkname);
die_if_bad_fnamesize(file_header->size);
p_linkname = xzalloc(file_header->size + 1);
xread(archive_handle->src_fd, p_linkname, file_header->size);
archive_handle->offset += file_header->size;
@@ -454,22 +446,15 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
#endif
/* Everything up to and including last ".." component is stripped */
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);
}
overlapping_strcpy(file_header->name, strip_unsafe_prefix(file_header->name));
//TODO: do the same for 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);
archive_handle->action_header(/*archive_handle->*/ file_header);
/* Note that we kill the '/' only after action_header() */
/* (like GNU tar 1.15.1: verbose mode outputs "dir/dir/") */
if (cp)
+2 -7
View File
@@ -5,13 +5,8 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_list(archive_handle_t *archive_handle)
void FAST_FUNC header_list(const file_header_t *file_header)
{
//TODO: cpio -vp DIR should output "DIR/NAME", not just "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));
puts(file_header->name);
}
+1 -1
View File
@@ -5,6 +5,6 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_skip(archive_handle_t *archive_handle UNUSED_PARAM)
void FAST_FUNC header_skip(const file_header_t *file_header UNUSED_PARAM)
{
}
+9 -13
View File
@@ -5,14 +5,10 @@
#include "libbb.h"
#include "bb_archive.h"
void FAST_FUNC header_verbose_list(archive_handle_t *archive_handle)
void FAST_FUNC header_verbose_list(const file_header_t *file_header)
{
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];
@@ -32,8 +28,8 @@ void FAST_FUNC header_verbose_list(archive_handle_t *archive_handle)
/*sprintf(gid, "%u", (unsigned)file_header->gid);*/
group = utoa(file_header->gid);
}
fprintf(fp, "%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
printf("%s %s/%s %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
user,
group,
file_header->size,
@@ -43,14 +39,14 @@ void FAST_FUNC header_verbose_list(archive_handle_t *archive_handle)
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec,
printable_string(file_header->name));
file_header->name);
#else /* !FEATURE_TAR_UNAME_GNAME */
localtime_r(&file_header->mtime, ptm);
fprintf(fp, "%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(modestr, file_header->mode),
printf("%s %u/%u %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
(unsigned)file_header->uid,
(unsigned)file_header->gid,
file_header->size,
@@ -60,13 +56,13 @@ void FAST_FUNC header_verbose_list(archive_handle_t *archive_handle)
ptm->tm_hour,
ptm->tm_min,
ptm->tm_sec,
printable_string(file_header->name));
file_header->name);
#endif /* FEATURE_TAR_UNAME_GNAME */
/* NB: GNU tar shows "->" for symlinks and "link to" for hardlinks */
if (file_header->link_target) {
fprintf(fp, " -> %s", printable_string(file_header->link_target));
printf(" -> %s", file_header->link_target);
}
putc('\n', fp);
bb_putchar('\n');
}
+2
View File
@@ -797,6 +797,7 @@ 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) {
@@ -810,6 +811,7 @@ 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;
+12 -14
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 die_if_not_compressed)
static transformer_state_t *setup_transformer_on_fd(int fd, int fail_if_not_compressed)
{
transformer_state_t *xstate;
@@ -204,7 +204,7 @@ static transformer_state_t *setup_transformer_on_fd(int fd, int die_if_not_compr
}
/* No known magic seen */
if (die_if_not_compressed)
if (fail_if_not_compressed)
bb_simple_error_msg_and_die("no gzip"
IF_FEATURE_SEAMLESS_BZ2("/bzip2")
IF_FEATURE_SEAMLESS_XZ("/xz")
@@ -240,15 +240,13 @@ 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 die_if_not_compressed)
int FAST_FUNC setup_unzip_on_fd(int fd, int fail_if_not_compressed)
{
transformer_state_t *xstate = setup_transformer_on_fd(fd, die_if_not_compressed);
transformer_state_t *xstate = setup_transformer_on_fd(fd, fail_if_not_compressed);
if (!xstate->xformer) {
/* Not compressed */
int retval = xstate->signature_skipped; /* never zero */
free(xstate);
return retval;
return 1;
}
fork_transformer_and_free(xstate);
@@ -266,7 +264,7 @@ void FAST_FUNC setup_lzma_on_fd(int fd)
}
#endif
static transformer_state_t *open_transformer(const char *fname, int die_if_not_compressed)
static transformer_state_t *open_transformer(const char *fname, int fail_if_not_compressed)
{
transformer_state_t *xstate;
int fd;
@@ -286,18 +284,18 @@ static transformer_state_t *open_transformer(const char *fname, int die_if_not_c
}
}
xstate = setup_transformer_on_fd(fd, die_if_not_compressed);
xstate = setup_transformer_on_fd(fd, fail_if_not_compressed);
return xstate;
}
int FAST_FUNC open_zipped(const char *fname, int die_if_not_compressed)
int FAST_FUNC open_zipped(const char *fname, int fail_if_not_compressed)
{
int fd;
transformer_state_t *xstate;
xstate = open_transformer(fname, die_if_not_compressed);
if (!xstate) /* open error */
xstate = open_transformer(fname, fail_if_not_compressed);
if (!xstate)
return -1;
fd = xstate->src_fd;
@@ -328,7 +326,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, /*die_if_not_compressed:*/ 0);
xstate = open_transformer(fname, /*fail_if_not_compressed:*/ 0);
if (!xstate) /* file open error */
return NULL;
@@ -373,7 +371,7 @@ void* FAST_FUNC xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_
int fd;
char *image;
fd = open_zipped(fname, /*die_if_not_compressed:*/ 0);
fd = open_zipped(fname, /*fail_if_not_compressed:*/ 0);
if (fd < 0)
return NULL;
+6 -36
View File
@@ -5,48 +5,23 @@
#include "libbb.h"
#include "bb_archive.h"
const char* FAST_FUNC skip_unsafe_prefix(const char *str)
const char* FAST_FUNC strip_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) {
const char *cp2;
char *cp2;
if (*cp == '/') {
cp++;
continue;
}
/* 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] == '/') {
if (is_prefixed_with(cp, "/../"+1)) {
cp += 3;
continue;
}
cp2 = cp;
find_dotdot:
cp2 = strstr(cp2, "/..");
cp2 = strstr(cp, "/../");
if (!cp2)
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;
break;
cp = cp2 + 4;
}
if (cp != str) {
static smallint warned = 0;
@@ -58,8 +33,3 @@ const char* FAST_FUNC skip_unsafe_prefix(const char *str)
}
return cp;
}
void FAST_FUNC strip_unsafe_prefix(char *str)
{
overlapping_strcpy(str, skip_unsafe_prefix(str));
}
+7 -47
View File
@@ -17,65 +17,25 @@ 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 = 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
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
);
// Note: GNU tar 1.34 errors out only _after_ all links are (attempted to be) created
// We bail out at once
}
list = list->link;
}
+1 -1
View File
@@ -545,7 +545,7 @@ static enum xz_ret XZ_FUNC dec_block_header(struct xz_dec *s)
return XZ_OK;
}
static NOINLINE enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
static enum xz_ret XZ_FUNC dec_main(struct xz_dec *s, struct xz_buf *b)
{
enum xz_ret ret;
+8 -7
View File
@@ -25,7 +25,7 @@
"Minimalized" for busybox by Alain Knaff
*/
//config:config LZOP
//config: bool "lzop (13 kb)"
//config: bool "lzop (12 kb)"
//config: default y
//config: help
//config: Lzop compression/decompresion.
@@ -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,6 +208,7 @@ 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 */
@@ -227,7 +228,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
@@ -249,7 +250,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;
@@ -284,7 +285,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++;
@@ -330,7 +331,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
@@ -349,7 +350,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++;
+4 -15
View File
@@ -116,13 +116,8 @@ 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;
@@ -130,11 +125,9 @@ 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;
@@ -153,6 +146,7 @@ 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);
@@ -322,7 +316,7 @@ static void extract_cpio(int fd, const char *source_rpm)
archive_handle->src_fd = fd;
/*archive_handle->offset = 0; - init_handle() did it */
setup_unzip_on_fd(archive_handle->src_fd, /*die_if_not_compressed:*/ 1);
setup_unzip_on_fd(archive_handle->src_fd, /*fail_if_not_compressed:*/ 1);
while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
continue;
}
@@ -539,20 +533,15 @@ 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 != NULL
&& (str = rpm_getstr0(TAG_PAYLOADCOMPRESSOR)) != NULL
&& strcmp(str, "lzma") == 0
) {
// lzma compression can't be detected
// set up decompressor without detection
setup_lzma_on_fd(rpm_fd);
} else {
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);
}
setup_unzip_on_fd(rpm_fd, /*fail_if_not_compressed:*/ 1);
}
if (bb_copyfd_eof(rpm_fd, STDOUT_FILENO) < 0)
+33 -10
View File
@@ -119,7 +119,6 @@
#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
@@ -255,6 +254,32 @@ static void putOctal(char *cp, int len, off_t value)
}
#define PUT_OCTAL(a, b) putOctal((a), sizeof(a), (b))
static void chksum_and_xwrite(int fd, struct tar_header_t* hp)
{
/* POSIX says that checksum is done on unsigned bytes
* (Sun and HP-UX gets it wrong... more details in
* GNU tar source) */
const unsigned char *cp;
int chksum, size;
strcpy(hp->magic, "ustar ");
/* Calculate and store the checksum (i.e., the sum of all of the bytes of
* the header). The checksum field must be filled with blanks for the
* calculation. The checksum field is formatted differently from the
* other fields: it has 6 digits, a null, then a space -- rather than
* digits, followed by a null like the other fields... */
memset(hp->chksum, ' ', sizeof(hp->chksum));
cp = (const unsigned char *) hp;
chksum = 0;
size = sizeof(*hp);
do { chksum += *cp++; } while (--size);
putOctal(hp->chksum, sizeof(hp->chksum)-1, chksum);
/* Now write the header out to disk */
xwrite(fd, hp, sizeof(*hp));
}
# if ENABLE_FEATURE_TAR_GNU_EXTENSIONS
static void writeLongname(int fd, int type, const char *name, int dir)
{
@@ -285,7 +310,7 @@ static void writeLongname(int fd, int type, const char *name, int dir)
/* + dir: account for possible '/' */
PUT_OCTAL(header.size, size);
chksum_and_xwrite_tar_header(fd, &header);
chksum_and_xwrite(fd, &header);
/* Write filename[/] and pad the block. */
/* dir=0: writes 'name<NUL>', pads */
@@ -416,7 +441,8 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
header_name, S_ISDIR(statbuf->st_mode));
# endif
chksum_and_xwrite_tar_header(tbInfo->tarFd, &header);
/* Now write the header out to disk */
chksum_and_xwrite(tbInfo->tarFd, &header);
/* Now do the verbose thing (or not) */
if (tbInfo->verboseFlag) {
@@ -428,7 +454,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", printable_string(header_name),
fprintf(vbFd, "%s%s\n", header_name,
S_ISDIR(statbuf->st_mode) ? "/" : "");
}
@@ -476,7 +502,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 = skip_unsafe_prefix(fileName);
header_name = strip_unsafe_prefix(fileName);
if (header_name[0] == '\0')
return TRUE;
@@ -622,7 +648,7 @@ static void NOINLINE vfork_compressor(int tar_fd, const char *gzip)
execlp(gzip, gzip, "-f", (char *)0);
vfork_exec_errno = errno;
_exit_FAILURE();
_exit(EXIT_FAILURE);
}
/* parent */
@@ -1134,9 +1160,6 @@ 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;
@@ -1168,7 +1191,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, /*die_if_not_compressed:*/ 0);
tar_handle->src_fd = open_zipped(tar_filename, /*fail_if_not_compressed:*/ 0);
if (tar_handle->src_fd < 0)
bb_perror_msg_and_die("can't open '%s'", tar_filename);
} else {
+4 -22
View File
@@ -56,7 +56,7 @@
//kbuild:lib-$(CONFIG_UNZIP) += unzip.o
//usage:#define unzip_trivial_usage
//usage: "[-lnojpqK] FILE[.zip] [FILE]... [-x FILE]... [-d DIR]"
//usage: "[-lnojpq] FILE[.zip] [FILE]... [-x FILE]... [-d DIR]"
//usage:#define unzip_full_usage "\n\n"
//usage: "Extract FILEs from ZIP archive\n"
//usage: "\n -l List contents (with -q for short form)"
@@ -66,7 +66,6 @@
//usage: "\n -p Write to stdout"
//usage: "\n -t Test"
//usage: "\n -q Quiet"
//usage: "\n -K Do not clear SUID bit"
//usage: "\n -x FILE Exclude FILEs"
//usage: "\n -d DIR Extract into DIR"
@@ -119,8 +118,6 @@ typedef union {
#define FIX_ENDIANNESS_ZIP(zip) \
do { if (BB_BIG_ENDIAN) { \
(zip).fmt.method = SWAP_LE16((zip).fmt.method ); \
(zip).fmt.modtime = SWAP_LE16((zip).fmt.modtime ); \
(zip).fmt.moddate = SWAP_LE16((zip).fmt.moddate ); \
(zip).fmt.crc32 = SWAP_LE32((zip).fmt.crc32 ); \
(zip).fmt.cmpsize = SWAP_LE32((zip).fmt.cmpsize ); \
(zip).fmt.ucmpsize = SWAP_LE32((zip).fmt.ucmpsize ); \
@@ -495,7 +492,6 @@ int unzip_main(int argc, char **argv)
OPT_l = (1 << 0),
OPT_x = (1 << 1),
OPT_j = (1 << 2),
OPT_K = (1 << 3),
};
unsigned opts;
smallint quiet = 0;
@@ -559,14 +555,9 @@ int unzip_main(int argc, char **argv)
* 204372 1 file
*/
//TODO: accept and ignore these?
// -a convert to text files with 't' label, -aa: all files
// -b do not convert to text - bbox: we don't convert anything
// -D skip restoration of timestamps for extracted items - bbox: we don't restore these (yet?)
// -X restore user:group ownership
opts = 0;
/* '-' makes getopt return 1 for non-options */
while ((i = getopt(argc, argv, "-d:lnotpqxjvK")) != -1) {
while ((i = getopt(argc, argv, "-d:lnotpqxjv")) != -1) {
switch (i) {
case 'd': /* Extract to base directory */
base_dir = optarg;
@@ -588,7 +579,6 @@ int unzip_main(int argc, char **argv)
xmove_fd(xopen("/dev/null", O_WRONLY), STDOUT_FILENO);
/*fallthrough*/
// NB: -c extract files to stdout/screen (unlike -p, also prints .zip and file names to stdout)
case 'p': /* Extract files to stdout */
dst_fd = STDOUT_FILENO;
/*fallthrough*/
@@ -610,10 +600,6 @@ int unzip_main(int argc, char **argv)
opts |= OPT_j;
break;
case 'K':
opts |= OPT_K;
break;
case 1:
if (!src_fn) {
/* The zip file */
@@ -831,10 +817,7 @@ int unzip_main(int argc, char **argv)
# endif
if ((cdf.fmt.version_made_by >> 8) == 3) {
/* This archive is created on Unix */
file_mode = (cdf.fmt.external_attributes >> 16);
if (!(opts & OPT_K))
file_mode &= ~(mode_t)(S_ISUID | S_ISGID);
dir_mode = file_mode;
dir_mode = file_mode = (cdf.fmt.external_attributes >> 16);
}
}
#endif
@@ -859,8 +842,7 @@ int unzip_main(int argc, char **argv)
unzip_skip(zip.fmt.extra_len);
/* Guard against "/abspath", "/../" and similar attacks */
// NB: UnZip 6.00 has option -: to disable this
strip_unsafe_prefix(dst_fn);
overlapping_strcpy(dst_fn, strip_unsafe_prefix(dst_fn));
/* Filter zip entries */
if (find_list_entry(zreject, dst_fn)
-47
View File
@@ -1,47 +0,0 @@
/* Add SORT_BY_ALIGNMENT to linker script (found in busybox_unstripped.out):
## .rodata : { *(.rodata SORT_BY_ALIGNMENT(.rodata.*) .gnu.linkonce.r.*) }
## .data : { *(.data SORT_BY_ALIGNMENT(.data.*) .gnu.linkonce.d.*) }
## .bss : { *(.bss SORT_BY_ALIGNMENT(.bss.*) .gnu.linkonce.b.*) }
## This will eliminate most of the padding (~3kb).
## Hmm, "ld --sort-section alignment" should do it too.
##
## There is a ld hack which is meant to decrease disk usage
## at the cost of more RAM usage (??!!) in standard ld script:
## . = ALIGN (0x1000) - ((0x1000 - .) & (0x1000 - 1)); . = DATA_SEGMENT_ALIGN (0x1000, 0x1000);
## Replace it with:
## . = ALIGN (0x1000); . = DATA_SEGMENT_ALIGN (0x1000, 0x1000);
## to unconditionally align .data to the next page boundary,
## instead of "next page, plus current offset in this page"
*/
/* To reduce the number of VMAs each bbox process has,
## move *(.bss SORT_BY_ALIGNMENT(.bss.*) ...)
## part from .bss : {...} block to .data : { ... } block.
## (This usually increases .data section by only one page).
## Result:
##
## text data bss dec hex filename
## 1050792 560 7580 1058932 102874 busybox.bss
## 1050792 8149 0 1058941 10287d busybox.nobss
##
## $ exec busybox.bss pmap $$
## 0000000008048000 1028K r-xp /path/to/busybox.bss
## 0000000008149000 8K rw-p /path/to/busybox.bss
## 000000000814b000 4K rw-p [ anon ] <---- this VMA is eliminated
## 00000000085f5000 4K ---p [heap]
## 00000000085f6000 4K rw-p [heap]
## 00000000f7778000 8K rw-p [ anon ]
## 00000000f777a000 12K r--p [vvar]
## 00000000f777d000 8K r-xp [vdso]
## 00000000ff7e9000 132K rw-p [stack]
##
## $ exec busybox.nobss pmap $$
## 0000000008048000 1028K r-xp /path/to/busybox.nobss
## 0000000008149000 12K rw-p /path/to/busybox.nobss
## 00000000086f0000 4K ---p [heap]
## 00000000086f1000 4K rw-p [heap]
## 00000000f7783000 8K rw-p [ anon ]
## 00000000f7785000 12K r--p [vvar]
## 00000000f7788000 8K r-xp [vdso]
## 00000000ffac0000 132K rw-p [stack]
*/
-1
View File
@@ -703,7 +703,6 @@ CONFIG_FEATURE_INETD_RPC=y
CONFIG_IP=y
CONFIG_FEATURE_IP_ADDRESS=y
CONFIG_FEATURE_IP_LINK=y
CONFIG_FEATURE_IP_LINK_CAN=y
CONFIG_FEATURE_IP_ROUTE=y
CONFIG_FEATURE_IP_TUNNEL=y
CONFIG_FEATURE_IP_RULE=y
+366 -604
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CHVT
//config: bool "chvt (2.2 kb)"
//config: bool "chvt (2 kb)"
//config: default y
//config: help
//config: This program is used to change to another terminal.
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CLEAR
//config: bool "clear (371 bytes)"
//config: bool "clear (tiny)"
//config: default y
//config: help
//config: This program clears the terminal screen.
+1 -1
View File
@@ -8,7 +8,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config DEALLOCVT
//config: bool "deallocvt (2.2 kb)"
//config: bool "deallocvt (1.9 kb)"
//config: default y
//config: help
//config: This program deallocates unused virtual consoles.
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config DUMPKMAP
//config: bool "dumpkmap (1.9 kb)"
//config: bool "dumpkmap (1.6 kb)"
//config: default y
//config: help
//config: This program dumps the kernel's keyboard translation table to
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config FGCONSOLE
//config: bool "fgconsole (1.8 kb)"
//config: bool "fgconsole (1.5 kb)"
//config: default y
//config: help
//config: This program prints active (foreground) console number.
+1 -1
View File
@@ -9,7 +9,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config KBD_MODE
//config: bool "kbd_mode (4.3 kb)"
//config: bool "kbd_mode (4.1 kb)"
//config: default y
//config: help
//config: This program reports and sets keyboard mode.
+1 -1
View File
@@ -10,7 +10,7 @@
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config LOADFONT
//config: bool "loadfont (5.4 kb)"
//config: bool "loadfont (5.2 kb)"
//config: default y
//config: help
//config: This program loads a console font from standard input.
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config LOADKMAP
//config: bool "loadkmap (2.1 kb)"
//config: bool "loadkmap (1.8 kb)"
//config: default y
//config: help
//config: This program loads a keyboard translation table from
+1 -1
View File
@@ -8,7 +8,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config OPENVT
//config: bool "openvt (7.4 kb)"
//config: bool "openvt (7.2 kb)"
//config: default y
//config: help
//config: This program is used to start a command on an unused
+3 -3
View File
@@ -8,7 +8,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config RESET
//config: bool "reset (676 bytes)"
//config: bool "reset (345 bytes)"
//config: default y
//config: help
//config: This program is used to reset the terminal screen, if it
@@ -21,7 +21,7 @@
//usage:#define reset_trivial_usage
//usage: ""
//usage:#define reset_full_usage "\n\n"
//usage: "Reset terminal (ESC codes) and termios (signals, buffering, echo)"
//usage: "Reset the screen"
/* "Standard" version of this tool is in ncurses package */
@@ -36,7 +36,7 @@ int stty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int reset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int reset_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
{
static const char *const args[] ALIGN_PTR = {
static const char *const args[] = {
"stty", "sane", NULL
};
+3 -15
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config RESIZE
//config: bool "resize (1.2 kb)"
//config: bool "resize (903 bytes)"
//config: default y
//config: help
//config: This program is used to (re)set the width and height of your current
@@ -45,7 +45,7 @@ static void
onintr(int sig UNUSED_PARAM)
{
tcsetattr(STDERR_FILENO, TCSANOW, old_termios_p);
_exit_FAILURE();
_exit(EXIT_FAILURE);
}
int resize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
@@ -74,19 +74,7 @@ int resize_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
+ (1 << SIGTERM)
+ (1 << SIGALRM)
, onintr);
/* Users report:
* The resize command messes up the terminal.
* In my case it looks like it is hanging and
* I need to press ctrl-c to get a prompt.
* Actually the program does not hang but just
* the terminal is messed up.
* Replaced TCSANOW with TCSAFLUSH:
* "the change occurs after all output written to fd
* has been transmitted, and all input that has been
* received but not read will be discarded before
* the change is made.
*/
tcsetattr(STDERR_FILENO, TCSAFLUSH, &new);
tcsetattr(STDERR_FILENO, TCSANOW, &new);
/* save_cursor_pos 7
* scroll_whole_screen [r
+1 -1
View File
@@ -8,7 +8,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config SETCONSOLE
//config: bool "setconsole (3.8 kb)"
//config: bool "setconsole (3.6 kb)"
//config: default y
//config: help
//config: Redirect writes to /dev/console to another device,
+1 -1
View File
@@ -9,7 +9,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config SETKEYCODES
//config: bool "setkeycodes (2.4 kb)"
//config: bool "setkeycodes (2.1 kb)"
//config: default y
//config: help
//config: This program loads entries into the kernel's scancode-to-keycode
+1 -1
View File
@@ -9,7 +9,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config SETLOGCONS
//config: bool "setlogcons (2 kb)"
//config: bool "setlogcons (1.8 kb)"
//config: default y
//config: help
//config: This program redirects the output console of kernel messages.
+3 -3
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config SHOWKEY
//config: bool "showkey (4.9 kb)"
//config: bool "showkey (4.7 kb)"
//config: default y
//config: help
//config: Shows keys pressed.
@@ -70,8 +70,8 @@ int showkey_main(int argc UNUSED_PARAM, char **argv)
INIT_G();
// a,k,s are all mutually exclusive
getopt32(argv, "^" "aks" "\0" "a--ks:k--as:s--ak");
// FIXME: aks are all mutually exclusive
getopt32(argv, "aks");
// prepare for raw mode
xget1(&tio, &tio0);
+4 -15
View File
@@ -5,6 +5,10 @@
menu "Coreutils"
INSERT
comment "Common options"
config FEATURE_VERBOSE
bool "Support verbose options (usually -v) for various applets"
default y
@@ -13,19 +17,6 @@ config FEATURE_VERBOSE
Also enables long option (--verbose) if it exists.
Without this option, -v is accepted but ignored.
comment "Common options for date and touch"
config FEATURE_TIMEZONE
bool "Allow timezone in dates"
default y
depends on DESKTOP
help
Permit the use of timezones when parsing user-provided data
strings, e.g. '1996-04-09 12:45:00 -0500'.
This requires support for the '%z' extension to strptime() which
may not be available in all implementations.
comment "Common options for cp and mv"
depends on CP || MV
@@ -46,6 +37,4 @@ config FEATURE_HUMAN_READABLE
help
Allow df, du, and ls to have human readable output.
INSERT
endmenu
+25 -39
View File
@@ -14,7 +14,7 @@
* 3) Save some space by using strcmp(). Calling strncmp() here was silly.
*/
//config:config BASENAME
//config: bool "basename (3.7 kb)"
//config: bool "basename (438 bytes)"
//config: default y
//config: help
//config: basename is used to strip the directory and suffix from filenames,
@@ -29,11 +29,9 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
//usage:#define basename_trivial_usage
//usage: "FILE [SUFFIX] | -a FILE... | -s SUFFIX FILE..."
//usage: "FILE [SUFFIX]"
//usage:#define basename_full_usage "\n\n"
//usage: "Strip directory path and SUFFIX from FILE\n"
//usage: "\n -a All arguments are FILEs"
//usage: "\n -s SUFFIX Remove SUFFIX (implies -a)"
//usage: "Strip directory path and .SUFFIX from FILE"
//usage:
//usage:#define basename_example_usage
//usage: "$ basename /usr/local/bin/foo\n"
@@ -50,43 +48,31 @@
int basename_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int basename_main(int argc UNUSED_PARAM, char **argv)
{
unsigned opts;
const char *suffix = NULL;
size_t m, n;
char *s;
/* '+': stop at first non-option */
opts = getopt32(argv, "^+" "as:"
"\0" "-1" /* At least one argument */
, &suffix
);
argv += optind;
if (argv[1] && strcmp(argv[1], "--") == 0) {
argv++;
}
if (!argv[1])
bb_show_usage();
do {
char *s;
size_t m;
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*++argv);
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*argv++);
m = strlen(s);
if (!opts) {
if (*argv) {
suffix = *argv;
if (argv[1])
bb_show_usage();
}
m = strlen(s);
if (*++argv) {
if (argv[1])
bb_show_usage();
n = strlen(*argv);
if ((m > n) && (strcmp(s+m-n, *argv) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
}
if (suffix) {
size_t n = strlen(suffix);
if ((m > n) && (strcmp(s + m - n, suffix) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
}
}
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
/* NB: != is correct here: */
if (full_write(STDOUT_FILENO, s, m) != (ssize_t)m)
return EXIT_FAILURE;
} while (opts && *argv);
}
return EXIT_SUCCESS;
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
/* NB: != is correct here: */
return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
}
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config CAT
//config: bool "cat (5.8 kb)"
//config: bool "cat (5.6 kb)"
//config: default y
//config: help
//config: cat is used to concatenate files and print them to the standard
+2 -4
View File
@@ -88,12 +88,10 @@ static int FAST_FUNC fileAction(struct recursive_state *state,
if (chmod(fileName, newmode) == 0) {
if (OPT_VERBOSE
|| (OPT_CHANGED
&& (statbuf->st_mode & 07777) != (newmode & 07777))
|| (OPT_CHANGED && statbuf->st_mode != newmode)
) {
char modestr[12];
printf("mode of '%s' changed to %04o (%s)\n", fileName,
newmode & 07777, bb_mode_string(modestr, newmode)+1);
newmode & 07777, bb_mode_string(newmode)+1);
}
return TRUE;
}
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CHROOT
//config: bool "chroot (4 kb)"
//config: bool "chroot (3.7 kb)"
//config: default y
//config: help
//config: chroot is used to change the root directory and run a command.
+3 -3
View File
@@ -7,11 +7,11 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CKSUM
//config: bool "cksum (4.3 kb)"
//config: bool "cksum (4.1 kb)"
//config: default y
//config:
//config:config CRC32
//config: bool "crc32 (4.2 kb)"
//config: bool "crc32 (4.1 kb)"
//config: default y
// APPLET_NOEXEC:name main location suid_type help
@@ -39,7 +39,7 @@ int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cksum_main(int argc UNUSED_PARAM, char **argv)
{
uint32_t *crc32_table = crc32_filltable(NULL, IS_CKSUM);
exitcode_t exit_code = EXIT_SUCCESS;
int exit_code = EXIT_SUCCESS;
#if ENABLE_DESKTOP
getopt32(argv, ""); /* cksum coreutils 6.9 compat */
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config COMM
//config: bool "comm (4.4 kb)"
//config: bool "comm (4.2 kb)"
//config: default y
//config: help
//config: comm is used to compare two files line by line and return
+1 -30
View File
@@ -29,11 +29,6 @@
//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) */
@@ -113,8 +108,6 @@
#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;
@@ -136,9 +129,6 @@ 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
@@ -168,20 +158,12 @@ 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) {
@@ -193,16 +175,6 @@ 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
@@ -243,8 +215,7 @@ 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_stat2(last, &dest_stat,
(flags & FILEUTILS_NO_TARGET_DIR) ? lstat : stat);
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
+168 -272
View File
@@ -9,7 +9,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CUT
//config: bool "cut (6.7 kb)"
//config: bool "cut (5.8 kb)"
//config: default y
//config: help
//config: cut is used to print selected parts of lines from
@@ -27,34 +27,21 @@
//kbuild:lib-$(CONFIG_CUT) += cut.o
//usage:#define cut_trivial_usage
//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: "[OPTIONS] [FILE]..."
//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: 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 -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: "\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 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 -s Output only lines containing delimiter"
//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"
@@ -66,6 +53,11 @@
#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! */
@@ -73,349 +65,253 @@
/* option vars */
#define OPT_STR "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
#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)
#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_REGEX (option_mask32 & OPT_REGEX)
struct cut_range {
unsigned startpos;
unsigned endpos;
struct cut_list {
int startpos;
int endpos;
};
static int cmpfunc(const void *a, const void *b)
{
const struct cut_range *aa = a;
const struct cut_range *bb = b;
return aa->startpos - bb->startpos;
return (((struct cut_list *) a)->startpos -
((struct cut_list *) b)->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_range *cut_list)
const struct cut_list *cut_lists, unsigned nlists)
{
char *line;
unsigned linenum = 0; /* keep these zero-based to be consistent */
int first_print = 1;
regex_t reg;
int spos, shoe = option_mask32 & CUT_OPT_REGEX_FLGS;
if (shoe) xregcomp(&reg, delim, REG_EXTENDED);
/* 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 */
unsigned linelen = strlen(line);
int linelen = strlen(line);
char *printed = xzalloc(linelen + 1);
char *orig_line = line;
unsigned cl_pos = 0;
/* 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;
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (option_mask32 & (CUT_OPT_CHAR_FLGS | CUT_OPT_BYTE_FLGS)) {
/* print the chars specified in each cut list */
for (; NOT_END_OF_LIST(cut_list[cl_pos]); cl_pos++) {
unsigned spos = cut_list[cl_pos].startpos;
while (spos < linelen) {
for (; cl_pos < nlists; cl_pos++) {
for (spos = cut_lists[cl_pos].startpos; 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]);
}
spos++;
if (spos > cut_list[cl_pos].endpos) {
/* will print OSEP (if not empty) */
need_odelim = (odelim && odelim[0]);
if (++spos > cut_lists[cl_pos].endpos) {
break;
}
}
}
free(printed);
/* Cut by lines */
} else if (!opt_REGEX && *delim == '\n') {
unsigned spos = cut_list[cl_pos].startpos;
} else if (*delim == '\n') { /* cut by lines */
spos = cut_lists[cl_pos].startpos;
linenum++;
/* get out if we have no more ranges to process or if the lines
/* get out if we have no more lists to process or if the lines
* are lower than what we're interested in */
if (linenum <= spos || END_OF_LIST(cut_list[cl_pos]))
if (((int)linenum < spos) || (cl_pos >= nlists))
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 < linenum) {
while (spos < (int)linenum) {
spos++;
/* go to the next list if we're at the end of this one */
if (spos > cut_list[cl_pos].endpos) {
if (spos > cut_lists[cl_pos].endpos) {
cl_pos++;
/* get out if there's no more ranges to process */
if (END_OF_LIST(cut_list[cl_pos]))
/* get out if there's no more lists to process */
if (cl_pos >= nlists)
goto next_line;
spos = cut_list[cl_pos].startpos;
spos = cut_lists[cl_pos].startpos;
/* get out if the current line is lower than the one
* we just became interested in */
if (linenum <= spos)
if ((int)linenum < spos)
goto next_line;
}
}
/* If we made it here, it means we've found the line we're
* looking for, so print it */
if (first_print) {
first_print = 0;
fputs_stdout(line);
} else
printf("%s%s", odelim, line);
puts(line);
goto next_line;
/* 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;
} else { /* cut by fields */
unsigned uu = 0, start = 0, end = 0, out = 0;
int dcount = 0;
/* Loop through bytes, finding next delimiter */
for (;;) {
/* End of current range? */
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");
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;
}
/* End of current line? */
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)
if (uu == linelen) {
/* If we've seen no delimiters, check -s */
if (!cl_pos && !dcount && !shoe) {
if (option_mask32 & CUT_OPT_SUPPRESS_FLGS)
goto next_line;
/* 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 if (dcount<cut_lists[cl_pos].startpos)
start = linelen;
end = linelen;
} else {
/* Find next delimiter */
#if ENABLE_FEATURE_CUT_REGEX
if (opt_REGEX) {
regmatch_t rr;
regex_t *reg = (void*) delim;
if (shoe) {
regmatch_t rr = {-1, -1};
if (regexec(reg, line + next, 1, &rr, REG_NOTBOL|REG_NOTEOL) != 0) {
/* not found, go to "end of line" logic */
next = linelen;
if (!regexec(&reg, line+uu, 1, &rr, REG_NOTBOL|REG_NOTEOL)) {
end = uu + rr.rm_so;
uu += rr.rm_eo;
} else {
uu = linelen;
continue;
}
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;
} else if (line[end = uu++] != *delim)
continue;
/* Got delimiter. Loop if not yet within range. */
if (dcount++ < cut_lists[cl_pos].startpos) {
start = uu;
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 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 (end != start || !shoe)
printf("%s%.*s", out++ ? odelim : "", end-start, line + start);
start = uu;
if (!dcount)
break;
}
}
/* if we printed anything, finish with newline */
putchar('\n');
next_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');
linenum++;
free(printed);
free(orig_line);
}
}
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 ranges */
struct cut_range *cut_list = NULL;
unsigned nranges = 0; /* number of elements in above list */
char *LIST, *ltok;
/* 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;
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")
#if ENABLE_LONG_OPTS
opt = getopt32long
#else
opt = getopt32
#endif
(argv, "^"
opt = getopt32(argv, "^"
OPT_STR // = "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
"\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";
"\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;
// argc -= optind;
argv += optind;
//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
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");
/* 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);
/* 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);
}
}
/*
* parse list and put values into startpos and endpos.
* valid range formats: N, N-, N-M, -M
* more than one range can be separated by commas
* valid list formats: N, N-, N-M, -M
* more than one list can be separated by commas
*/
/* take apart the ranges, one by one (separated with commas) */
while ((ltok = strsep(&LIST, ",")) != NULL) {
{
char *ntok;
int s, e;
int s = 0, e = 0;
/* it's actually legal to pass an empty list */
//if (!ltok[0])
// continue;
//^^^ testcase?
/* take apart the lists, one by one (they are separated with commas) */
while ((ltok = strsep(&sopt, ",")) != NULL) {
/* 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;
/* 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 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;
}
/* make sure we got some cut positions out of all that */
if (nlists == 0)
bb_simple_error_msg_and_die("missing list of positions");
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++;
/* 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);
}
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;
int retval = EXIT_SUCCESS;
if (!*argv)
*--argv = (char *)"-";
@@ -426,12 +322,12 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
retval = EXIT_FAILURE;
continue;
}
cut_file(file, delim, odelim, cut_list);
cut_file(file, delim, odelim, cut_lists, nlists);
fclose_if_not_stdin(file);
} while (*++argv);
if (ENABLE_FEATURE_CLEAN_UP)
free(cut_list);
free(cut_lists);
fflush_stdout_and_exit(retval);
}
}
+5 -6
View File
@@ -19,7 +19,7 @@
much as possible, missed out a lot of bounds checking */
//config:config DATE
//config: bool "date (7.2 kb)"
//config: bool "date (7 kb)"
//config: default y
//config: help
//config: date is used to set the system date or display the
@@ -266,7 +266,6 @@ int date_main(int argc UNUSED_PARAM, char **argv)
/* If date string is given, update tm_time, and maybe set date */
if (date_str != NULL) {
int check_dst = 1;
/* Zero out fields - take her back to midnight! */
tm_time.tm_sec = 0;
tm_time.tm_min = 0;
@@ -277,19 +276,19 @@ int date_main(int argc UNUSED_PARAM, char **argv)
if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
} else {
check_dst = parse_datestr(date_str, &tm_time);
parse_datestr(date_str, &tm_time);
}
/* Correct any day of week and day of year etc. fields */
/* Be sure to recheck dst (but not if date is UTC) */
if (check_dst)
/* Be sure to recheck dst (but not if date is time_t format) */
if (date_str[0] != '@')
tm_time.tm_isdst = -1;
ts.tv_sec = validate_tm_time(date_str, &tm_time);
ts.tv_nsec = 0;
/* if setting time, set it */
if ((opt & OPT_SET) && clock_settime(CLOCK_REALTIME, &ts) < 0) {
bb_simple_perror_msg_and_die("can't set date");
bb_simple_perror_msg("can't set date");
}
}
+13 -23
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config DD
//config: bool "dd (8.3 kb)"
//config: bool "dd (7.5 kb)"
//config: default y
//config: help
//config: dd copies a file (from standard input to standard output,
@@ -200,7 +200,6 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
}
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
static int clear_O_DIRECT(int fd)
{
if (errno == EINVAL) {
@@ -212,7 +211,6 @@ static int clear_O_DIRECT(int fd)
}
return 0;
}
# endif
#endif
static ssize_t dd_read(void *ibuf, size_t ibs)
@@ -227,10 +225,8 @@ static ssize_t dd_read(void *ibuf, size_t ibs)
#endif
n = safe_read(ifd, ibuf, ibs);
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
if (n < 0 && (G.flags & FLAG_IDIRECT) && clear_O_DIRECT(ifd))
goto read_again;
# endif
#endif
return n;
}
@@ -243,10 +239,8 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
IF_FEATURE_DD_IBS_OBS(write_again:)
n = full_write(ofd, buf, len);
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
if (n < 0 && (G.flags & FLAG_ODIRECT) && clear_O_DIRECT(ofd))
goto write_again;
# endif
#endif
#if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
@@ -272,6 +266,12 @@ 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)
{
@@ -369,7 +369,7 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
OP_oflag_direct,
#endif
};
exitcode_t exitcode = EXIT_FAILURE;
smallint exitcode = EXIT_FAILURE;
int i;
size_t ibs = 512;
char *ibuf;
@@ -451,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 = XATOOFF_SFX(val, cwbkMG_suffixes);
count = XATOU_SFX(val, cwbkMG_suffixes);
/*continue;*/
}
if (what == OP_seek) {
seek = XATOOFF_SFX(val, cwbkMG_suffixes);
seek = XATOU_SFX(val, cwbkMG_suffixes);
/*continue;*/
}
if (what == OP_skip) {
skip = XATOOFF_SFX(val, cwbkMG_suffixes);
skip = XATOU_SFX(val, cwbkMG_suffixes);
/*continue;*/
}
if (what == OP_if) {
@@ -501,13 +501,8 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (infile) {
int iflag = O_RDONLY;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_IDIRECT) {
# ifdef O_DIRECT
if (G.flags & FLAG_IDIRECT)
iflag |= O_DIRECT;
# else
bb_error_msg_and_die("O_DIRECT not supported on this platform");
# endif
}
#endif
xmove_fd(xopen(infile, iflag), ifd);
} else {
@@ -521,13 +516,8 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (G.flags & FLAG_APPEND)
oflag |= O_APPEND;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_ODIRECT) {
# ifdef O_DIRECT
if (G.flags & FLAG_ODIRECT)
oflag |= O_DIRECT;
# else
bb_error_msg_and_die("O_DIRECT not supported on this platform");
# endif
}
#endif
xmove_fd(xopen(outfile, oflag), ofd);
+15 -42
View File
@@ -18,7 +18,7 @@
* Implement -P and -B; better coreutils compat; cleanup
*/
//config:config DF
//config: bool "df (7.1 kb)"
//config: bool "df (6.8 kb)"
//config: default y
//config: help
//config: df reports the amount of disk space used and available
@@ -32,26 +32,6 @@
//config: -a Show all filesystems
//config: -i Inodes
//config: -B <SIZE> Blocksize
//config:
//config:config FEATURE_SKIP_ROOTFS
//config: bool "Skip rootfs in mount table"
//config: default y
//config: depends on DF
//config: help
//config: Ignore rootfs entry in mount table.
//config:
//config: In Linux, kernel has a special filesystem, rootfs, which is initially
//config: mounted on /. It contains initramfs data, if kernel is configured
//config: to have one. Usually, another file system is mounted over / early
//config: in boot process, and therefore most tools which manipulate
//config: mount table, such as df, will skip rootfs entry.
//config:
//config: However, some systems do not mount anything on /.
//config: If you need to configure busybox for one of these systems,
//config: you may find it useful to turn this option off to make df show
//config: initramfs statistics.
//config:
//config: Otherwise, choose Y.
//applet:IF_DF(APPLET_NOEXEC(df, df, BB_DIR_BIN, BB_SUID_DROP, df))
@@ -113,22 +93,21 @@ int df_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int df_main(int argc UNUSED_PARAM, char **argv)
{
unsigned long df_disp_hr = 1024;
exitcode_t status = EXIT_SUCCESS;
int status = EXIT_SUCCESS;
unsigned opt;
FILE *mount_table;
struct mntent *mount_entry;
struct statvfs s;
enum {
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_t = (1 << 3),
OPT_ALL = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 6) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_HUMANDEC = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (6 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_t = (1 << 3),
OPT_ALL = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 6) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
@@ -145,7 +124,7 @@ int df_main(int argc UNUSED_PARAM, char **argv)
opt = getopt32(argv, "^"
"kPTt:"
IF_FEATURE_DF_FANCY("aiB:")
IF_FEATURE_HUMAN_READABLE("hHm")
IF_FEATURE_HUMAN_READABLE("hm")
"\0"
#if ENABLE_FEATURE_HUMAN_READABLE && ENABLE_FEATURE_DF_FANCY
"k-mB:m-Bk:B-km"
@@ -155,9 +134,6 @@ 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;
@@ -175,11 +151,8 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
if (opt & (OPT_HUMAN|OPT_HUMANDEC)) {
if (opt & OPT_HUMAN) {
df_disp_hr = 0;
//TODO: need to add support in make_human_readable_str() for "decimal human readable"
//if (opt & OPT_HUMANDEC)
// df_disp_hr--;
disp_units_hdr = " Size";
}
if (opt & OPT_INODE)
@@ -188,8 +161,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;
* if -P, unit=1 (print it in full, no KMG suffixes) */
/* print df_disp_hr, show no fractionals,
* use suffixes if OPT_POSIX is set in opt */
make_human_readable_str(df_disp_hr, 0, !!(opt & OPT_POSIX))
);
#else
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config DIRNAME
//config: bool "dirname (611 bytes)"
//config: bool "dirname (329 bytes)"
//config: default y
//config: help
//config: dirname is used to strip a non-directory suffix from
+2 -2
View File
@@ -12,14 +12,14 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config DOS2UNIX
//config: bool "dos2unix (5.5 kb)"
//config: bool "dos2unix (5.2 kb)"
//config: default y
//config: help
//config: dos2unix is used to convert a text file from DOS format to
//config: UNIX format, and vice versa.
//config:
//config:config UNIX2DOS
//config: bool "unix2dos (5.5 kb)"
//config: bool "unix2dos (5.2 kb)"
//config: default y
//config: help
//config: unix2dos is used to convert a text file from UNIX format to
+1 -1
View File
@@ -19,7 +19,7 @@
* 4) Fixed busybox bug #1284 involving long overflow with human_readable.
*/
//config:config DU
//config: bool "du (6.5 kb)"
//config: bool "du (6.3 kb)"
//config: default y
//config: help
//config: du is used to report the amount of disk space used
+1 -3
View File
@@ -19,7 +19,7 @@
* The previous version did not allow 4-digit octals.
*/
//config:config ECHO
//config: bool "echo (2 kb)"
//config: bool "echo (1.8 kb)"
//config: default y
//config: help
//config: echo prints a specified string to stdout.
@@ -321,8 +321,6 @@ int echo_main(int argc, char **argv)
if (*arg == '0' && (unsigned char)(arg[1] - '0') < 8) {
arg++;
}
//FIXME? we also accept non-0 starting sequences (see echo-prints-slash_41 test)
// echo -ne '-\41-' prints "-!-". bash 5.0.17 does not (prints "-\41-").
/* bb_process_escape_sequence can handle nul correctly */
c = bb_process_escape_sequence( (void*) &arg);
}
+2 -2
View File
@@ -24,7 +24,7 @@
* - use xfunc_error_retval
*/
//config:config ENV
//config: bool "env (4.3 kb)"
//config: bool "env (4 kb)"
//config: default y
//config: help
//config: env is used to set an environment variable and run
@@ -100,7 +100,7 @@ int env_main(int argc UNUSED_PARAM, char **argv)
}
}
fflush_stdout_and_exit_SUCCESS();
fflush_stdout_and_exit(EXIT_SUCCESS);
}
/*
+3 -3
View File
@@ -21,13 +21,13 @@
* Caveat: this versions of expand and unexpand don't accept tab lists.
*/
//config:config EXPAND
//config: bool "expand (5.3 kb)"
//config: bool "expand (5.1 kb)"
//config: default y
//config: help
//config: By default, convert all tabs to spaces.
//config:
//config:config UNEXPAND
//config: bool "unexpand (5.5 kb)"
//config: bool "unexpand (5.3 kb)"
//config: default y
//config: help
//config: By default, convert only leading sequences of blanks to tabs.
@@ -192,7 +192,7 @@ int expand_main(int argc UNUSED_PARAM, char **argv)
FILE *file;
unsigned tab_size;
unsigned opt;
exitcode_t exit_status = EXIT_SUCCESS;
int exit_status = EXIT_SUCCESS;
init_unicode();
+1 -1
View File
@@ -23,7 +23,7 @@
* provided they all associate ((x op x) op x).
*/
//config:config EXPR
//config: bool "expr (6.8 kb)"
//config: bool "expr (6.6 kb)"
//config: default y
//config: help
//config: expr is used to calculate numbers and print the result
+38 -37
View File
@@ -4,7 +4,7 @@
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config FACTOR
//config: bool "factor (3.2 kb)"
//config: bool "factor (2.7 kb)"
//config: default y
//config: help
//config: factor factorizes integers
@@ -48,40 +48,38 @@ typedef unsigned long half_t;
* Larger wheels improve sieving only slightly, but quickly grow in size
* (adding just one prime, 13, results in 5766 element sieve).
*/
#define R(a,b,c,d,e,f,g,h,i,j,A,B,C,D,E,F,G,H,I,J,x) \
(((uint64_t)(a<<0) | (b<<3) | (c<<6) | (d<<9) | (e<<12) | (f<<15) | (g<<18) | (h<<21) | (i<<24) | (j<<27)) << 1) | \
(((uint64_t)(A<<0) | (B<<3) | (C<<6) | (D<<9) | (E<<12) | (F<<15) | (G<<18) | (H<<21) | (I<<24) | (J<<27)) << 31) | \
((uint64_t)x << 61)
#define P(a,b,c,d,e,f,g,h,i,j,A,B,C,D,E,F,G,H,I,J,x) \
#define R(a,b,c,d,e,f,g,h,i,j,A,B,C,D,E,F,G,H,I,J) \
(((uint64_t)(a<<0) | (b<<3) | (c<<6) | (d<<9) | (e<<12) | (f<<15) | (g<<18) | (h<<21) | (i<<24) | (j<<27)) << 1) | \
(((uint64_t)(A<<0) | (B<<3) | (C<<6) | (D<<9) | (E<<12) | (F<<15) | (G<<18) | (H<<21) | (I<<24) | (J<<27)) << 31)
#define P(a,b,c,d,e,f,g,h,i,j,A,B,C,D,E,F,G,H,I,J) \
R( (a/2),(b/2),(c/2),(d/2),(e/2),(f/2),(g/2),(h/2),(i/2),(j/2), \
(A/2),(B/2),(C/2),(D/2),(E/2),(F/2),(G/2),(H/2),(I/2),(J/2), \
(x/2) \
)
(A/2),(B/2),(C/2),(D/2),(E/2),(F/2),(G/2),(H/2),(I/2),(J/2) )
static const uint64_t packed_wheel[] = {
/* 1, 2, */
P( 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6),
P( 8, 4, 2, 4, 2, 4,14, 4, 6, 2,10, 2, 6, 6, 4, 2, 4, 6, 2,10, 2),
P( 4, 2,12,10, 2, 4, 2, 4, 6, 2, 6, 4, 6, 6, 6, 2, 6, 4, 2, 6, 4),
P( 6, 8, 4, 2, 4, 6, 8, 6,10, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6),
P( 4, 2, 6,10, 2,10, 2, 4, 2, 4, 6, 8, 4, 2, 4,12, 2, 6, 4, 2, 6),
P( 4, 6,12, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6,10, 2, 4, 6, 2),
P( 6, 4, 2, 4, 2,10, 2,10, 2, 4, 6, 6, 2, 6, 6, 4, 6, 6, 2, 6, 4),
P( 2, 6, 4, 6, 8, 4, 2, 6, 4, 8, 6, 4, 6, 2, 4, 6, 8, 6, 4, 2,10),
P( 2, 6, 4, 2, 4, 2,10, 2,10, 2, 4, 2, 4, 8, 6, 4, 2, 4, 6, 6, 2),
P( 6, 4, 8, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 6, 6, 6, 2, 6, 6, 4),
P( 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2,10, 2, 6, 4, 6, 2, 6, 4, 2, 4),
P( 6, 6, 8, 4, 2, 6,10, 8, 4, 2, 4, 2, 4, 8,10, 6, 2, 4, 8, 6, 6),
P( 4, 2, 4, 6, 2, 6, 4, 6, 2,10, 2,10, 2, 4, 2, 4, 6, 2, 6, 4, 2),
P( 4, 6, 6, 2, 6, 6, 6, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4, 8, 4, 6),
P( 2, 6, 6, 4, 2, 4, 6, 8, 4, 2, 4, 2,10, 2,10, 2, 4, 2, 4, 6, 2),
P(10, 2, 4, 6, 8, 6, 4, 2, 6, 4, 6, 8, 4, 6, 2, 4, 8, 6, 4, 6, 2),
P( 4, 6, 2, 6, 6, 4, 6, 6, 2, 6, 6, 4, 2,10, 2,10, 2, 4, 2, 4, 6),
P( 2, 6, 4, 2,10, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2,12, 6, 4),
P( 6, 2, 4, 6, 2,12, 4, 2, 4, 8, 6, 4, 2, 4, 2,10, 2,10, 6, 2, 4),
P( 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2,10, 6, 8, 6, 4, 2, 4, 8, 6),
P( 4, 6, 2, 4, 6, 2, 6, 6, 6, 4, 6, 2, 6, 4, 2, 4, 2,10,12, 2, 4),
P( 2,10, 2, 6, 4, 2, 4, 6, 6, 2,10, 2, 6, 4,14, 4, 2, 4, 2, 4, 8),
P( 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4,12, 2,12),
/*1, 2, 2, 4, 2,*/
P( 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4), //01
P( 2, 4, 2, 4,14, 4, 6, 2,10, 2, 6, 6, 4, 2, 4, 6, 2,10, 2, 4), //02
P( 2,12,10, 2, 4, 2, 4, 6, 2, 6, 4, 6, 6, 6, 2, 6, 4, 2, 6, 4), //03
P( 6, 8, 4, 2, 4, 6, 8, 6,10, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2), //04
P( 6, 4, 2, 6,10, 2,10, 2, 4, 2, 4, 6, 8, 4, 2, 4,12, 2, 6, 4), //05
P( 2, 6, 4, 6,12, 2, 4, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6,10, 2), //06
P( 4, 6, 2, 6, 4, 2, 4, 2,10, 2,10, 2, 4, 6, 6, 2, 6, 6, 4, 6), //07
P( 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 6, 4, 8, 6, 4, 6, 2, 4, 6), //08
P( 8, 6, 4, 2,10, 2, 6, 4, 2, 4, 2,10, 2,10, 2, 4, 2, 4, 8, 6), //09
P( 4, 2, 4, 6, 6, 2, 6, 4, 8, 4, 6, 8, 4, 2, 4, 2, 4, 8, 6, 4), //10
P( 6, 6, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2,10, 2), //11
P( 6, 4, 6, 2, 6, 4, 2, 4, 6, 6, 8, 4, 2, 6,10, 8, 4, 2, 4, 2), //12
P( 4, 8,10, 6, 2, 4, 8, 6, 6, 4, 2, 4, 6, 2, 6, 4, 6, 2,10, 2), //13
P(10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 6, 6, 4, 6, 8), //14
P( 4, 2, 4, 2, 4, 8, 6, 4, 8, 4, 6, 2, 6, 6, 4, 2, 4, 6, 8, 4), //15
P( 2, 4, 2,10, 2,10, 2, 4, 2, 4, 6, 2,10, 2, 4, 6, 8, 6, 4, 2), //16
P( 6, 4, 6, 8, 4, 6, 2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6, 4, 6), //17
P( 6, 2, 6, 6, 4, 2,10, 2,10, 2, 4, 2, 4, 6, 2, 6, 4, 2,10, 6), //18
P( 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2,12, 6, 4, 6, 2, 4, 6, 2), //19
P(12, 4, 2, 4, 8, 6, 4, 2, 4, 2,10, 2,10, 6, 2, 4, 6, 2, 6, 4), //20
P( 2, 4, 6, 6, 2, 6, 4, 2,10, 6, 8, 6, 4, 2, 4, 8, 6, 4, 6, 2), //21
P( 4, 6, 2, 6, 6, 6, 4, 6, 2, 6, 4, 2, 4, 2,10,12, 2, 4, 2,10), //22
P( 2, 6, 4, 2, 4, 6, 6, 2,10, 2, 6, 4,14, 4, 2, 4, 2, 4, 8, 6), //23
P( 4, 6, 2, 4, 6, 2, 6, 6, 4, 2, 4, 6, 2, 6, 4, 2, 4,12, 2,12), //24
};
#undef P
#undef R
@@ -95,8 +93,8 @@ static const uint64_t packed_wheel[] = {
* function old new delta
* wheel_tab - 485 +485
* 3-bit-packed insanity:
* packed_wheel - 184 +184
* factor_main 108 163 +55
* packed_wheel - 192 +192
* factor_main 108 171 +63
*/
static void unpack_wheel(void)
{
@@ -106,7 +104,10 @@ static void unpack_wheel(void)
setup_common_bufsiz();
wheel_tab[0] = 1;
wheel_tab[1] = 2;
p = &wheel_tab[2];
wheel_tab[2] = 2;
wheel_tab[3] = 4;
wheel_tab[4] = 2;
p = &wheel_tab[5];
for (i = 0; i < ARRAY_SIZE(packed_wheel); i++) {
uint64_t v = packed_wheel[i];
while ((v & 0xe) != 0) {
@@ -136,7 +137,7 @@ static void factorize(wide_t N);
static half_t isqrt_odd(wide_t N)
{
half_t s = isqrt_ull(N);
half_t s = isqrt(N);
/* s^2 is <= N, (s+1)^2 > N */
/* If s^2 in fact is EQUAL to N, it's very lucky.
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config FALSE
//config: bool "false (314 bytes)"
//config: bool "false (tiny)"
//config: default y
//config: help
//config: false returns an exit code of FALSE (1).
+2 -2
View File
@@ -11,7 +11,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config FOLD
//config: bool "fold (4.8 kb)"
//config: bool "fold (4.6 kb)"
//config: default y
//config: help
//config: Wrap text to fit a specific width.
@@ -77,7 +77,7 @@ int fold_main(int argc UNUSED_PARAM, char **argv)
char *line_out = NULL;
const char *w_opt = "80";
unsigned width;
exitcode_t exitcode = EXIT_SUCCESS;
smallint exitcode = EXIT_SUCCESS;
init_unicode();
+4 -4
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config HEAD
//config: bool "head (4 kb)"
//config: bool "head (3.8 kb)"
//config: default y
//config: help
//config: head is used to print the first specified number of lines
@@ -76,7 +76,7 @@ print_except_N_last_bytes(FILE *fp, unsigned count)
{
unsigned char *circle = xmalloc(++count);
unsigned head = 0;
for (;;) {
for(;;) {
int c;
c = getc(fp);
if (c == EOF)
@@ -105,7 +105,7 @@ print_except_N_last_lines(FILE *fp, unsigned count)
{
char **circle = xzalloc((++count) * sizeof(circle[0]));
unsigned head = 0;
for (;;) {
for(;;) {
char *c;
c = xmalloc_fgets(fp);
if (!c)
@@ -127,7 +127,7 @@ print_except_N_last_lines(FILE *fp, unsigned count)
}
ret:
head = 0;
for (;;) {
for(;;) {
free(circle[head++]);
if (head == count)
break;
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config HOSTID
//config: bool "hostid (566 bytes)"
//config: bool "hostid (286 bytes)"
//config: default y
//config: help
//config: hostid prints the numeric identifier (in hexadecimal) for
+3 -4
View File
@@ -13,13 +13,13 @@
* Added -G option Tito Ragusa (C) 2008 for SUSv3.
*/
//config:config ID
//config: bool "id (7.1 kb)"
//config: bool "id (7 kb)"
//config: default y
//config: help
//config: id displays the current user and group ID names.
//config:
//config:config GROUPS
//config: bool "groups (6.8 kb)"
//config: bool "groups (6.7 kb)"
//config: default y
//config: help
//config: Print the group names associated with current user id.
@@ -156,7 +156,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
const char *prefix;
const char *username;
#if ENABLE_SELINUX
char *scontext = NULL;
security_context_t scontext = NULL;
#endif
if (ENABLE_GROUPS && (!ENABLE_ID || applet_name[0] == 'g')) {
@@ -230,7 +230,6 @@ 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
$BUSYBOX adduser -s /bin/true -g "" -H -D "$TEST_USER" || exit 1
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
+9 -11
View File
@@ -73,7 +73,7 @@ static const char install_longopts[] ALIGN1 =
static void setdefaultfilecon(const char *path)
{
struct stat s;
char *scontext = NULL;
security_context_t 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
char *scontext;
security_context_t scontext;
bool use_default_selinux_context = 1;
#endif
enum {
@@ -244,15 +244,6 @@ int install_main(int argc, char **argv)
}
}
/* Set the user and group id */
/* (must be before chmod, or else chown may clear suid/gid bits) */
if ((opts & (OPT_OWNER|OPT_GROUP))
&& lchown(dest, uid, gid) == -1
) {
bb_perror_msg("can't change %s of %s", "ownership", dest);
ret = EXIT_FAILURE;
}
/* Set the file mode (always, not only with -m).
* GNU coreutils 6.10 is not affected by umask. */
if (chmod(dest, mode) == -1) {
@@ -263,6 +254,13 @@ int install_main(int argc, char **argv)
if (use_default_selinux_context)
setdefaultfilecon(dest);
#endif
/* Set the user and group id */
if ((opts & (OPT_OWNER|OPT_GROUP))
&& lchown(dest, uid, gid) == -1
) {
bb_perror_msg("can't change %s of %s", "ownership", dest);
ret = EXIT_FAILURE;
}
next:
if (ENABLE_FEATURE_CLEAN_UP && isdir)
free(dest);
-546
View File
@@ -1,546 +0,0 @@
/* 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
char *scontext;
security_context_t scontext;
#endif
int opt;
opt = getopt32(argv, "m:" IF_SELINUX("Z:"), &smode IF_SELINUX(,&scontext));
+1 -1
View File
@@ -6,7 +6,7 @@
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config LINK
//config: bool "link (3.5 kb)"
//config: bool "link (3.2 kb)"
//config: default y
//config: help
//config: link creates hard links between files.
+2 -2
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config LN
//config: bool "ln (5.1 kb)"
//config: bool "ln (4.9 kb)"
//config: default y
//config: help
//config: ln is used to create hard or soft links between files.
@@ -52,7 +52,7 @@
int ln_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int ln_main(int argc, char **argv)
{
exitcode_t status = EXIT_SUCCESS;
int status = EXIT_SUCCESS;
int opts;
char *last;
char *src_name;
+1 -1
View File
@@ -16,7 +16,7 @@
* a diagnostic message and an error return.
*/
//config:config LOGNAME
//config: bool "logname (1.4 kb)"
//config: bool "logname (1.1 kb)"
//config: default y
//config: help
//config: logname is used to print the current user's login name.
+97 -193
View File
@@ -126,8 +126,6 @@
//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"
@@ -161,8 +159,6 @@
//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: )
@@ -200,47 +196,27 @@ SPLIT_SUBDIR = 2,
/* -Cadi1l Std options, busybox always supports */
/* -gnsxA Std options, busybox always supports */
/* -Q GNU option, busybox always supports: */
/* -Q, --quote-name */
/* enclose entry names in double quotes */
/* -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 */
/* -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 \
"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
"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 */
enum {
OPT_C = (1 << 0),
@@ -254,31 +230,29 @@ enum {
OPT_s = (1 << 8),
OPT_x = (1 << 9),
OPT_A = (1 << 10),
//OPT_k = (1 << 11),
OPTBIT_F = 11,
OPTBIT_p, /* 12 */
OPTBIT_F = 12,
OPTBIT_p, /* 13 */
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, /* 16 */
OPTBIT_t, /* 17 */
OPTBIT_u, /* 18 */
OPTBIT_c, /* 17 */
OPTBIT_t, /* 18 */
OPTBIT_u, /* 19 */
OPTBIT_S = OPTBIT_c + 3 * ENABLE_FEATURE_LS_TIMESTAMPS,
OPTBIT_X, /* 20 */
OPTBIT_r, /* 21 */
OPTBIT_v, /* 22 */
OPTBIT_X, /* 21 */
OPTBIT_r, /* 22 */
OPTBIT_v, /* 23 */
OPTBIT_L = OPTBIT_S + 4 * ENABLE_FEATURE_LS_SORTFILES,
OPTBIT_H, /* 24 */
OPTBIT_H, /* 25 */
OPTBIT_h = OPTBIT_L + 2 * ENABLE_FEATURE_LS_FOLLOWLINKS,
OPTBIT_T = OPTBIT_h + 1 * ENABLE_FEATURE_HUMAN_READABLE,
OPTBIT_w, /* 27 */
OPTBIT_w, /* 28 */
OPTBIT_full_time = OPTBIT_T + 2 * ENABLE_FEATURE_LS_WIDTH,
OPTBIT_dirs_first,
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 */
OPTBIT_color, /* 31 */
/* with long opts, we use all 32 bits */
OPT_F = (1 << OPTBIT_F) * ENABLE_FEATURE_LS_FILETYPES,
OPT_p = (1 << OPTBIT_p) * ENABLE_FEATURE_LS_FILETYPES,
@@ -300,8 +274,6 @@ 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),
};
/*
@@ -311,7 +283,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(char *sid;)
IF_SELINUX(security_context_t sid;)
smallint fname_allocated;
/* Used to avoid re-doing [l]stat at printout stage
@@ -355,7 +327,6 @@ 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)
@@ -372,21 +343,16 @@ 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 = ~0U;) \
IF_FEATURE_LS_WIDTH(G_terminal_width = TERMINAL_WIDTH;) \
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)
@@ -449,6 +415,28 @@ 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.
@@ -456,86 +444,27 @@ static char append_char(mode_t mode)
* 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;
if (!(option_mask32 & (OPT_q|OPT_Q))) {
fputs_stdout(name);
return strlen(name);
}
// TODO: quote tab as \t, etc, if -Q
name = printable_string2(&uni_stat, 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 + strlen(name);
len = 2 + uni_stat.unicode_width;
putchar('"');
while (*name) {
unsigned char ch = (unsigned char)*name;
if (ch < ' ' || ch > 0x7e) {
if (*name == '"' || *name == '\\') {
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++;
}
put_ch:
putchar(ch);
putchar(*name);
name++;
}
putchar('"');
@@ -569,20 +498,12 @@ static NOINLINE unsigned display_single(const struct dnode *dn)
if (opt & OPT_i) /* show inode# */
column += printf("%7llu ", (long long) dn->dn_ino);
if (opt & OPT_s) { /* show allocated blocks */
if (opt & OPT_h) {
column += printf("%"HUMAN_READABLE_MAX_WIDTH_STR"s ",
/* print size, show one fractional, use suffixes */
make_human_readable_str((off_t)dn->dn_blocks << 9, 1, 0)
);
} else {
column += printf("%6"OFF_FMT"u ", (off_t)(dn->dn_blocks >> 1));
}
}
//TODO: -h should affect -s too:
if (opt & OPT_s) /* show allocated blocks */
column += printf("%6"OFF_FMT"u ", (off_t) (dn->dn_blocks >> 1));
if (opt & OPT_l) {
/* long listing: show mode */
char modestr[12];
column += printf("%-10s ", bb_mode_string(modestr, dn->dn_mode));
column += printf("%-10s ", (char *) bb_mode_string(dn->dn_mode));
/* long listing: show number of links */
column += printf("%4lu ", (long) dn->dn_nlink);
/* long listing: show user/group */
@@ -597,10 +518,10 @@ static NOINLINE unsigned display_single(const struct dnode *dn)
#if ENABLE_FEATURE_LS_USERNAME
else {
if (opt & OPT_g) {
column += printf("%-8s ",
column += printf("%-8.8s ",
get_cached_groupname(dn->dn_gid));
} else {
column += printf("%-8s %-8s ",
column += printf("%-8.8s %-8.8s ",
get_cached_username(dn->dn_uid),
get_cached_groupname(dn->dn_gid));
}
@@ -717,7 +638,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 columnar output */
unsigned column_width = 0; /* used only by coulmnal output */
if (option_mask32 & (OPT_l|OPT_1)) {
ncols = 1;
@@ -762,11 +683,6 @@ 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');
@@ -1166,11 +1082,25 @@ 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
@@ -1206,29 +1136,6 @@ 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())
@@ -1242,7 +1149,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 (G_isatty()) {
if (isatty(STDOUT_FILENO)) {
/* check isatty() last because it's expensive (syscall) */
G_show_color = 1;
}
@@ -1251,28 +1158,23 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
if (opt & OPT_color) {
if (color_opt[0] == 'n')
G_show_color = 0;
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;
}
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;
}
}
}
#endif
skip_if_ftpd:
/* sort out which command line options take precedence */
if (ENABLE_FEATURE_LS_RECURSIVE && (opt & OPT_d))
opt = option_mask32 &= ~OPT_R; /* no recurse if listing only dir */
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 */
@@ -1280,17 +1182,19 @@ 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)) {
opt = option_mask32 |= OPT_t;
option_mask32 |= OPT_t;
}
}
}
/* choose a display format if one was not already specified by an option */
if (!(opt & (OPT_l|OPT_1|OPT_x|OPT_C)))
opt = option_mask32 |= (G_isatty() ? OPT_C : OPT_1);
if (!(option_mask32 & (OPT_l|OPT_1|OPT_x|OPT_C)))
option_mask32 |= (isatty(STDOUT_FILENO) ? OPT_C : OPT_1);
if (!(opt & OPT_q) && G_isatty())
opt = option_mask32 |= OPT_q;
if (ENABLE_FTPD && applet_name[0] == 'f') {
/* ftpd secret backdoor. dirs first are much nicer */
option_mask32 |= OPT_dirs_first;
}
argv += optind;
if (!argv[0])
+42 -80
View File
@@ -6,48 +6,42 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config MD5SUM
//config: bool "md5sum (6.7 kb)"
//config: bool "md5sum (6.5 kb)"
//config: default y
//config: help
//config: Compute and check MD5 message digest
//config:
//config:config SHA1SUM
//config: bool "sha1sum (6.7 kb)"
//config: bool "sha1sum (5.9 kb)"
//config: default y
//config: help
//config: Compute and check SHA1 message digest
//config:
//config:config SHA256SUM
//config: bool "sha256sum (8.2 kb)"
//config: bool "sha256sum (7 kb)"
//config: default y
//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: bool "sha512sum (7.4 kb)"
//config: default y
//config: help
//config: Compute and check SHA512 message digest
//config:
//config:config SHA3SUM
//config: bool "sha3sum (6.3 kb)"
//config: bool "sha3sum (6.1 kb)"
//config: default y
//config: help
//config: Compute and check SHA3 message digest
//config:
//config:comment "Common options for md5sum, sha1sum, sha256sum, ..., sha3sum"
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || SHA384SUM || SHA512SUM || SHA3SUM
//config:comment "Common options for md5sum, sha1sum, sha256sum, sha512sum, sha3sum"
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || 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 || SHA384SUM || SHA512SUM || SHA3SUM
//config: depends on MD5SUM || SHA1SUM || SHA256SUM || SHA512SUM || SHA3SUM
//config: help
//config: Enabling the -c options allows files to be checked
//config: against pre-calculated hash values.
@@ -57,13 +51,11 @@
//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
@@ -107,16 +99,6 @@
//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"
@@ -148,18 +130,16 @@
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,
@@ -171,18 +151,15 @@ static unsigned char *hash_bin_to_hex(unsigned char *hash_value,
return (unsigned char *)hex_value;
}
#define BUFSZ (CONFIG_FEATURE_COPYBUF_KB < 4 ? 4096 : CONFIG_FEATURE_COPYBUF_KB * 1024)
#if !ENABLE_SHA3SUM
# define hash_file(b,f,w) hash_file(b,f)
# define hash_file(f,w) hash_file(f)
#endif
static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned sha3_width)
static uint8_t *hash_file(const char *filename, unsigned sha3_width)
{
int src_fd, count;
int src_fd, hash_len, 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;
@@ -204,31 +181,25 @@ 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;
}
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;
hash_len = 32;
}
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) {
@@ -246,7 +217,9 @@ static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned
) {
bb_error_msg_and_die("bad -a%u", sha3_width);
}
context.sha3.input_block_bytes = 1600/8 - sha3_width/4;
sha3_width /= 4;
context.sha3.input_block_bytes = 1600/8 - sha3_width;
hash_len = sha3_width/2;
}
#endif
else {
@@ -254,16 +227,18 @@ static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned
}
{
while ((count = safe_read(src_fd, in_buf, BUFSZ)) > 0) {
RESERVE_CONFIG_UBUFFER(in_buf, 4096);
while ((count = safe_read(src_fd, in_buf, 4096)) > 0) {
update(&context, in_buf, count);
}
hash_value = NULL;
if (count < 0)
bb_perror_msg("can't read '%s'", filename);
else /* count == 0 */ {
unsigned hash_len = final(&context, in_buf);
final(&context, in_buf);
hash_value = hash_bin_to_hex(in_buf, hash_len);
}
RELEASE_CONFIG_BUFFER(in_buf);
}
if (src_fd != STDIN_FILENO) {
@@ -276,30 +251,24 @@ static uint8_t *hash_file(unsigned char *in_buf, const char *filename, unsigned
int md5_sha1_sum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
{
unsigned char *in_buf;
int return_value = EXIT_SUCCESS;
unsigned flags;
#if ENABLE_SHA3SUM
unsigned sha3_width = 224;
#endif
const char *fmt = "%s %s\n";
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK) {
/* -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) */
/* -b "binary", -t "text" are ignored (shaNNNsum compat) */
/* -s and -w require -c */
#if ENABLE_SHA3SUM
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);
if (applet_name[3] == HASH_SHA3)
flags = getopt32(argv, "^" "scwbta:+" "\0" "s?c:w?c", &sha3_width);
else
#endif
flags = getopt32(argv, "^" "scwbt" "\0" "t-b:s?c:w?c");
if (flags & FLAG_BINARY)
fmt = "%s *%s\n";
flags = getopt32(argv, "^" "scwbt" "\0" "s?c:w?c");
} else {
#if ENABLE_SHA3SUM
if (applet_name[3] == HASH_SHA3 && (!ENABLE_SHA384SUM || applet_name[4] != '8'))
if (applet_name[3] == HASH_SHA3)
getopt32(argv, "a:+", &sha3_width);
else
#endif
@@ -310,12 +279,6 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
if (!*argv)
*--argv = (char*)"-";
/* The buffer is not alloc/freed for each input file:
* for big values of COPYBUF_KB, this helps to keep its pages
* pre-faulted and possibly even fully cached on local CPU.
*/
in_buf = xmalloc(BUFSZ);
do {
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK && (flags & FLAG_CHECK)) {
FILE *pre_computed_stream;
@@ -330,8 +293,12 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
char *filename_ptr;
count_total++;
filename_ptr = strchr(line, ' ');
if (!filename_ptr) {
filename_ptr = strstr(line, " ");
/* handle format for binary checksums */
if (filename_ptr == NULL) {
filename_ptr = strstr(line, " *");
}
if (filename_ptr == NULL) {
if (flags & FLAG_WARN) {
bb_simple_error_msg("invalid format");
}
@@ -340,17 +307,12 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
free(line);
continue;
}
*filename_ptr++ = '\0';
/* coreutils 9.1 allows "HASH FILENAME" format,
* with only one space. Skip the 'correct'
* " " or " *" delimiter if it is there:
*/
if (*filename_ptr == ' ' || *filename_ptr == '*')
filename_ptr++;
*filename_ptr = '\0';
filename_ptr += 2;
hash_value = hash_file(in_buf, filename_ptr, sha3_width);
hash_value = hash_file(filename_ptr, sha3_width);
if (hash_value && (strcasecmp((char*)hash_value, line) == 0)) {
if (hash_value && (strcmp((char*)hash_value, line) == 0)) {
if (!(flags & FLAG_SILENT))
printf("%s: OK\n", filename_ptr);
} else {
@@ -377,11 +339,11 @@ int md5_sha1_sum_main(int argc UNUSED_PARAM, char **argv)
}
fclose_if_not_stdin(pre_computed_stream);
} else {
uint8_t *hash_value = hash_file(in_buf, *argv, sha3_width);
uint8_t *hash_value = hash_file(*argv, sha3_width);
if (hash_value == NULL) {
return_value = EXIT_FAILURE;
} else {
printf(fmt, hash_value, *argv);
printf("%s %s\n", hash_value, *argv);
free(hash_value);
}
}
+2 -2
View File
@@ -14,7 +14,7 @@
/* Nov 28, 2006 Yoshinori Sato <ysato@users.sourceforge.jp>: Add SELinux Support.
*/
//config:config MKDIR
//config: bool "mkdir (4.7 kb)"
//config: bool "mkdir (4.5 kb)"
//config: default y
//config: help
//config: mkdir is used to create directories with the specified names.
@@ -57,7 +57,7 @@ int mkdir_main(int argc UNUSED_PARAM, char **argv)
unsigned opt;
char *smode;
#if ENABLE_SELINUX
char *scontext;
security_context_t scontext;
#endif
opt = getopt32long(argv, "m:pv" IF_SELINUX("Z:"),
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config MKFIFO
//config: bool "mkfifo (4 kb)"
//config: bool "mkfifo (3.8 kb)"
//config: default y
//config: help
//config: mkfifo is used to create FIFOs (named pipes).
+1 -1
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config MKNOD
//config: bool "mknod (4.6 kb)"
//config: bool "mknod (4.5 kb)"
//config: default y
//config: help
//config: mknod is used to create FIFOs or block/character special
+2 -16
View File
@@ -29,7 +29,7 @@
* -p; else /tmp [deprecated]
*/
//config:config MKTEMP
//config: bool "mktemp (4.5 kb)"
//config: bool "mktemp (4.2 kb)"
//config: default y
//config: help
//config: mktemp is used to create unique temporary files
@@ -72,27 +72,13 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
OPT_t = 1 << 2,
OPT_p = 1 << 3,
OPT_u = 1 << 4,
OPT_tmpdir = (1 << 5) * ENABLE_LONG_OPTS,
};
path = getenv("TMPDIR");
if (!path || path[0] == '\0')
path = "/tmp";
#if ENABLE_LONG_OPTS
opts = getopt32long(argv, "^"
"dqtp:u"
"\0"
"?1" /* 1 arg max */,
"directory\0" No_argument "d"
"quiet\0" No_argument "q"
"dry-run\0" No_argument "u"
"tmpdir\0" Optional_argument "\xff"
, &path, &path
);
#else
opts = getopt32(argv, "^" "dqtp:u" "\0" "?1"/*1 arg max*/, &path);
#endif
chp = argv[optind];
if (!chp) {
@@ -109,7 +95,7 @@ int mktemp_main(int argc UNUSED_PARAM, char **argv)
goto error;
}
#endif
if (opts & (OPT_t|OPT_p|OPT_tmpdir))
if (opts & (OPT_t|OPT_p))
chp = concat_path_file(path, chp);
if (opts & OPT_u) {
+2 -2
View File
@@ -71,9 +71,9 @@ int mv_main(int argc, char **argv)
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
IF_FEATURE_VERBOSE(
"verbose\0" No_argument "v"
"verbose\0" No_argument "v",
&last
)
, &last
);
argc -= optind;
argv += optind;
+2 -2
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config NICE
//config: bool "nice (2.3 kb)"
//config: bool "nice (2.1 kb)"
//config: default y
//config: help
//config: nice runs a program with modified scheduling priority.
@@ -33,7 +33,7 @@ int nice_main(int argc UNUSED_PARAM, char **argv)
if (!*++argv) { /* No args, so (GNU) output current nice value. */
printf("%d\n", old_priority);
fflush_stdout_and_exit_SUCCESS();
fflush_stdout_and_exit(EXIT_SUCCESS);
}
adjustment = 10; /* Set default adjustment. */
+1 -1
View File
@@ -5,7 +5,7 @@
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//config:config NL
//config: bool "nl (4.9 kb)"
//config: bool "nl (4.6 kb)"
//config: default y
//config: help
//config: nl is used to number lines of files.
+1 -1
View File
@@ -11,7 +11,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config NOHUP
//config: bool "nohup (2.2 kb)"
//config: bool "nohup (2 kb)"
//config: default y
//config: help
//config: run a command immune to hangups, with output to a non-tty.
+11 -9
View File
@@ -4,7 +4,7 @@
* Licensed under GPLv2, see LICENSE in this source tree
*/
//config:config NPROC
//config: bool "nproc (3.9 kb)"
//config: bool "nproc (3.7 kb)"
//config: default y
//config: help
//config: Print number of CPUs
@@ -23,11 +23,13 @@
//usage: "\n --ignore=N Exclude N CPUs"
//usage: )
#include <sched.h>
#include "libbb.h"
int nproc_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
{
unsigned long mask[1024];
int count = 0;
#if ENABLE_LONG_OPTS
int ignore = 0;
@@ -50,16 +52,16 @@ int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
}
} else
#endif
{
if (sched_getaffinity(0, sizeof(mask), (void*)mask) == 0) {
int i;
unsigned sz = 2 * 1024;
unsigned long *mask = get_malloc_cpu_affinity(0, &sz);
sz /= sizeof(long);
for (i = 0; i < sz; i++) {
if (mask[i] != 0) /* most mask[i] are usually 0 */
count += bb_popcnt_long(mask[i]);
for (i = 0; i < ARRAY_SIZE(mask); i++) {
unsigned long m = mask[i];
while (m) {
if (m & 1)
count++;
m >>= 1;
}
}
IF_FEATURE_CLEAN_UP(free(mask);)
}
IF_LONG_OPTS(count -= ignore;)
+25 -50
View File
@@ -22,9 +22,7 @@
//usage:#if !ENABLE_DESKTOP
//usage:#define od_trivial_usage
//usage: "[-abcdeFfhiloxsv] [FILE]"
// We also support -BDOHXIL, but they are not documented in coreutils 9.1
// manpage/help, so don't show them either.
//usage: "[-aBbcDdeFfHhIiLlOovXx] [FILE]"
//usage:#define od_full_usage "\n\n"
//usage: "Print FILE (or stdin) unambiguously, as octal bytes by default"
//usage:#endif
@@ -146,50 +144,29 @@ odoffset(dumper_t *dumper, int argc, char ***argvp)
}
}
// bb_dump_add():
// A format string contains format units separated by [optional] whitespace.
// A format unit contains up to three items: an iteration count, a byte count,
// and a format.
// The iteration count is an optional integer (default 1).
// Each format is applied iteration count times.
// The byte count is an optional integer. It defines the number
// of bytes to be interpreted by each iteration of the format.
// If an iteration count and/or a byte count is specified, a slash must be
// placed after the iteration count and/or before the byte count
// to disambiguate them.
// The printf-style format is required and must be surrounded by " "s.
// (Below, each string contains two format units)
static const char *const add_strings[] ALIGN_PTR = {
"16/1 \" %3_u\"" "\"\n\"", /* 0: a */
"8/2 \" %06o\"" "\"\n\"", /* 1: B (undocumented in od), o */
"16/1 \" %03o\"" "\"\n\"", /* 2: b */
"16/1 \" %3_c\"" "\"\n\"", /* 3: c */
"8/2 \" %5u\"" "\"\n\"", /* 4: d */
"4/4 \" %10u\"" "\"\n\"", /* 5: D */
"2/8 \" %24.14e\"" "\"\n\"", /* 6: e (undocumented in od), F */
"4/4 \" %15.7e\"" "\"\n\"", /* 7: f */
"4/4 \" %08x\"" "\"\n\"", /* 8: H, X */
"8/2 \" %04x\"" "\"\n\"", /* 9: h, x */
"4/4 \" %11d\"" "\"\n\"", /* 10: i */
"4/4 \" %011o\"" "\"\n\"", /* 11: O */
"8/2 \" %6d\"" "\"\n\"", /* 12: s */
/* -I,L,l: depend on word width of the arch (what is "long"?) */
#if ULONG_MAX > 0xffffffff
"2/8 \" %20lld\"" "\"\n\"", /* 13: I, L, l */
#define L_ 13
#else
/* 32-bit arch: -I,L,l are the same as -i */
#define L_ 10
#endif
static const char *const add_strings[] = {
"16/1 \"%3_u \" \"\\n\"", /* a */
"8/2 \" %06o \" \"\\n\"", /* B, o */
"16/1 \"%03o \" \"\\n\"", /* b */
"16/1 \"%3_c \" \"\\n\"", /* c */
"8/2 \" %05u \" \"\\n\"", /* d */
"4/4 \" %010u \" \"\\n\"", /* D */
"2/8 \" %21.14e \" \"\\n\"", /* e (undocumented in od), F */
"4/4 \" %14.7e \" \"\\n\"", /* f */
"4/4 \" %08x \" \"\\n\"", /* H, X */
"8/2 \" %04x \" \"\\n\"", /* h, x */
"4/4 \" %11d \" \"\\n\"", /* I, L, l */
"8/2 \" %6d \" \"\\n\"", /* i */
"4/4 \" %011o \" \"\\n\"", /* O */
};
static const char od_opts[] ALIGN1 = "aBbcDdeFfHhIiLlOoXxsv";
static const char od_opts[] ALIGN1 = "aBbcDdeFfHhIiLlOoXxv";
static const char od_o2si[] ALIGN1 = {
0, 1, 2, 3, 5, /* aBbcD */
4, 6, 6, 7, 8, /* deFfH */
9, L_, 10, L_, L_, /* hIiLl */
11, 1, 8, 9, 12 /* OoXxs */
0, 1, 2, 3, 5,
4, 6, 6, 7, 8,
9, 0xa, 0xb, 0xa, 0xa,
0xb, 1, 8, 9,
};
int od_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
@@ -207,21 +184,19 @@ int od_main(int argc, char **argv)
if (first) {
first = 0;
bb_dump_add(dumper, "\"%07.7_Ao\n\"");
bb_dump_add(dumper, "\"%07.7_ao\"");
bb_dump_add(dumper, "\"%07.7_ao \"");
} else {
bb_dump_add(dumper, "\" \"");
bb_dump_add(dumper, "\" \"");
}
bb_dump_add(dumper, add_strings[(int)od_o2si[(p - od_opts)]]);
} else { /* P, p, w, or other unhandled */
} else { /* P, p, s, w, or other unhandled */
bb_show_usage();
}
}
if (!dumper->fshead) {
bb_dump_add(dumper, "\"%07.7_Ao\n\"");
bb_dump_add(dumper, "\"%07.7_ao\"");
bb_dump_add(dumper, add_strings[1]); /* -o format is default */
bb_dump_add(dumper, "\"%07.7_ao \" 8/2 \"%06o \" \"\\n\"");
}
dumper->od_eofstring = "\n";
argc -= optind;
argv += optind;
@@ -230,7 +205,7 @@ int od_main(int argc, char **argv)
return bb_dump_dump(dumper, argv);
}
#endif /* !ENABLE_DESKTOP */
#endif /* ENABLE_DESKTOP */
/*-
* Copyright (c) 1990 The Regents of the University of California.
Loaded 100 of 870 files, more files were not shown because too many files have changed in this diff. Show more