Compare commits

..
10 Commits
Author SHA1 Message Date
Denys Vlasenko b84194b133 Bump version to 1.29.3
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-09-09 20:56:49 +02:00
Denys Vlasenko 2993551efc Revert "libbb: remove unnecessary variable in xmalloc_fgets"
The variable is in fact necessary.

    commit 2da9724b56
    Author: Quentin Rameau <quinq@fifth.space>
    Date:   Sun Apr 1 17:05:35 2018 +0200
        libbb: remove unnecessary variable in xmalloc_fgets

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-09-02 18:48:50 +02:00
Denys Vlasenko ab4caf099c Bump version to 1.29.2
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-31 14:31:12 +02:00
Denys Vlasenko 1c3bcfc79f fdisk: sync up with some util-linux 2.31 behavior
= display default is no longer in cylinders
= +sizeC is no longer supported
= add +sizeT suffix - terabytes are here
= K,M,G,T and k,m,g,t suffixes all are binary, not decimal
= +sizeM results in last sector +(size * 1Mbyte - 1), not +(size * 1Mbyte)
= fix comparison to "YES" answer for sgi/sun

function                                             old     new   delta
read_int                                             492     519     +27
fdisk_main                                          2644    2640      -4
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 27/-4)              Total: 23 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-30 18:02:27 +02:00
Denys Vlasenko 096ccd6a69 fdisk: use strtoul[l] instead of atoi, closes 11176
Couldn't create partitions bigger than 1TB (when using 512 bytes sectors,
on 32 bits architectures).

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-30 18:02:27 +02:00
Denys Vlasenko d674b2e2ae gzip: unbreak FEATURE_GZIP_LEVELS, closes 11171
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-30 18:02:27 +02:00
Denys Vlasenko abe8fc3663 hexedit: fixes for redraw and down movement causing SEGV on attempt to access
"Go to:" command was not updating row position, making next "down" movements
for one screenful print empty lines instead of showing the contents.

If the file is whole pages long, "down" movement at EOF was advancing position
+16 bytes, mapping the next portion (entirely past the end of the file),
then finding out that the new position is beyond the EOF, rolling it back
-16 bytes... ending up with this postion pointing *before* the mapped portion.
Any next access (e.g. "move right" key) SEGVs.

function                                             old     new   delta
hexedit_main                                        1170    1184     +14

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-30 18:02:27 +02:00
Denys Vlasenko 981c0b109d Bump version to 1.29.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-15 14:55:20 +02:00
Raffaello D. Di Napoli 6673497d3b sendmail: fix parsing of addresses in angle brackets
Pointer e needs to be wound back in order to overwrite '>' with '\0'.
Regression introduced in 20077c1429

Signed-off-by: Raffaello D. Di Napoli <rafdev@dinapo.li>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-15 14:52:21 +02:00
Denys Vlasenko 7236b6d717 wget: fix fetching of https URLs without http proxy
The "fix fetching of https URLs with http proxy" commit
broke the usual http-to-https redirect:

$ wget http://busybox.net/downloads/busybox-1.29.0.tar.bz2
Connecting to busybox.net (140.211.167.122:80)
Connecting to busybox.net (140.211.167.122:443)
wget: server returned error: HTTP/1.1 400 Bad Request

Fixing...

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2018-07-15 14:52:21 +02:00
1385 changed files with 29384 additions and 78669 deletions

No files matched your search

-11
View File
@@ -50,14 +50,3 @@ cscope.files
cscope.in.out
cscope.out
cscope.po.out
#
# ctags output
#
tags
TAGS
#
# user-supplied scripts
#
/embed
-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
+15 -57
View File
@@ -12,7 +12,7 @@ config HAVE_DOT_CONFIG
menu "Settings"
config DESKTOP
bool "Enable compatibility for full-blown desktop systems (8kb)"
bool "Enable compatibility for full-blown desktop systems"
default y
help
Enable applet options and features which are not essential.
@@ -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
@@ -167,13 +156,12 @@ config FEATURE_PIDFILE
config PID_FILE_PATH
string "Directory for pidfiles"
default "/var/run"
depends on FEATURE_PIDFILE || FEATURE_CROND_SPECIAL_TIMES
depends on FEATURE_PIDFILE
help
This is the default path where pidfiles are created. Applets which
allow you to set the pidfile path on the command line will override
this value. The option has no effect on applets that require you to
specify a pidfile path. When crond has the 'Support special times'
option enabled, the 'crond.reboot' file is also stored here.
specify a pidfile path.
config BUSYBOX
bool "Include busybox applet"
@@ -190,11 +178,6 @@ config BUSYBOX
Running "busybox APPLET [ARGS...]" will still work, of course.
config FEATURE_SHOW_SCRIPT
bool "Support --show SCRIPT"
default y
depends on BUSYBOX
config FEATURE_INSTALLER
bool "Support --install [-s] to install applet links at runtime"
default y
@@ -204,13 +187,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
@@ -330,6 +306,7 @@ config BUSYBOX_EXEC_PATH
config SELINUX
bool "Support NSA Security Enhanced Linux"
default n
select PLATFORM_LINUX
help
Enable support for SELinux in applets ls, ps, and id. Also provide
the option of compiling in SELinux applets.
@@ -357,15 +334,6 @@ config FEATURE_CLEAN_UP
Don't enable this unless you have a really good reason to clean
things up manually.
config FEATURE_SYSLOG_INFO
bool "Support LOG_INFO level syslog messages"
default y
depends on FEATURE_SYSLOG
help
Applets which send their output to syslog use either LOG_INFO or
LOG_ERR log levels, but by disabling this option all messages will
be logged at the LOG_ERR level, saving just under 200 bytes.
# These are auto-selected by other options
config FEATURE_SYSLOG
@@ -375,6 +343,17 @@ config FEATURE_SYSLOG
#This option is auto-selected when you select any applet which may
#send its output to syslog. You do not need to select it manually.
config PLATFORM_LINUX
bool #No description makes it a hidden option
default n
#help
#For the most part, busybox requires only POSIX compatibility
#from the target system, but some applets and features use
#Linux-specific interfaces.
#
#This is automatically selected if any applet or feature requires
#Linux-specific interfaces. You do not need to select it manually.
comment 'Build Options'
config STATIC
@@ -547,14 +526,6 @@ config STACK_OPTIMIZATION_386
do not work with it (they use SSE instructions without
ensuring stack alignment).
config STATIC_LIBGCC
bool "Use -static-libgcc"
default y
help
This option instructs gcc to link in a static version of its
support library, libgcc. This means that the binary will require
one fewer dynamic library at run time.
comment 'Installation Options ("make install" behavior)'
choice
@@ -676,19 +647,6 @@ config WERROR
Most people should answer N.
config WARN_SIMPLE_MSG
bool "Warn about single parameter bb_xx_msg calls"
default n
help
This will cause warnings to be shown for any instances of
bb_error_msg(), bb_error_msg_and_die(), bb_perror_msg(),
bb_perror_msg_and_die(), bb_herror_msg() or bb_herror_msg_and_die()
being called with a single parameter. In these cases the equivalent
bb_simple_xx_msg function should be used instead.
Note that use of STRERROR_FMT may give false positives.
If you aren't developing busybox, say N here.
choice
prompt "Additional debugging library"
default NO_DEBUG_LIB
+13 -16
View File
@@ -1,7 +1,7 @@
VERSION = 1
PATCHLEVEL = 39
SUBLEVEL = 0
EXTRAVERSION = .git
PATCHLEVEL = 29
SUBLEVEL = 3
EXTRAVERSION =
NAME = Unnamed
# *DOCUMENTATION*
@@ -361,7 +361,7 @@ scripts/basic/%: scripts_basic ;
# This target generates Kbuild's and Config.in's from *.c files
PHONY += gen_build_files
gen_build_files: $(wildcard $(srctree)/*/*.c) $(wildcard $(srctree)/*/*/*.c) $(wildcard $(srctree)/embed/*)
gen_build_files: $(wildcard $(srctree)/*/*.c) $(wildcard $(srctree)/*/*/*.c)
$(Q)$(srctree)/scripts/gen_build_files.sh $(srctree) $(objtree)
# bbox: we have helpers in applets/
@@ -476,7 +476,6 @@ libs-y := \
findutils/ \
init/ \
libbb/ \
libbb/yescrypt/ \
libpwdgrp/ \
loginutils/ \
mailutils/ \
@@ -613,12 +612,7 @@ quiet_cmd_busybox__ ?= LINK $@
"$(core-y)" \
"$(libs-y)" \
"$(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
@@ -856,14 +850,11 @@ quiet_cmd_gen_common_bufsiz = GEN include/common_bufsiz.h
cmd_gen_common_bufsiz = $(srctree)/scripts/generate_BUFSIZ.sh include/common_bufsiz.h
quiet_cmd_split_autoconf = SPLIT include/autoconf.h -> include/config/*
cmd_split_autoconf = scripts/basic/split-include include/autoconf.h include/config
quiet_cmd_gen_embedded_scripts = GEN include/embedded_scripts.h
cmd_gen_embedded_scripts = $(srctree)/scripts/embedded_scripts include/embedded_scripts.h $(srctree)/embed $(srctree)/applets_sh
#bbox# piggybacked generation of few .h files
include/config/MARKER: scripts/basic/split-include include/autoconf.h $(wildcard $(srctree)/embed/*) $(wildcard $(srctree)/applets_sh/*) $(srctree)/scripts/embedded_scripts
include/config/MARKER: scripts/basic/split-include include/autoconf.h
$(call cmd,split_autoconf)
$(call cmd,gen_bbconfigopts)
$(call cmd,gen_common_bufsiz)
$(call cmd,gen_embedded_scripts)
@touch $@
# Generate some files
@@ -972,7 +963,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
@@ -984,7 +974,6 @@ MRPROPER_FILES += .config .config.old include/asm .version .old_version \
include/autoconf.h \
include/bbconfigopts.h \
include/bbconfigopts_bz2.h \
include/embedded_scripts.h \
include/usage_compressed.h \
include/applet_tables.h \
include/applets.h \
@@ -1307,6 +1296,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)
+15 -45
View File
@@ -15,8 +15,7 @@ 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)
-D"BB_VER=KBUILD_STR($(BB_VER))"
CFLAGS += $(call cc-option,-Wall,)
CFLAGS += $(call cc-option,-Wshadow,)
@@ -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,29 +47,12 @@ 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)
# "clang-9: warning: optimization flag '-finline-limit=0' is not supported
CFLAGS += $(call cc-option,-finline-limit=0,)
endif
CFLAGS += $(call cc-option,-fno-builtin-strlen -fomit-frame-pointer -ffunction-sections -fdata-sections,)
CFLAGS += $(call cc-option,-fno-builtin-strlen -finline-limit=0 -fomit-frame-pointer -ffunction-sections -fdata-sections,)
# -fno-guess-branch-probability: prohibit pseudo-random guessing
# of branch probabilities (hopefully makes bloatcheck more stable):
CFLAGS += $(call cc-option,-fno-guess-branch-probability,)
CFLAGS += $(call cc-option,-funsigned-char,)
ifeq ($(CONFIG_STATIC_LIBGCC),y)
# Disable it, for example, if you get
# "clang-9: warning: argument unused during compilation: '-static-libgcc'"
CFLAGS += $(call cc-option,-static-libgcc,)
endif
CFLAGS += $(call cc-option,-falign-functions=1,)
ifneq ($(lastword $(subst -, ,$(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
CFLAGS += $(call cc-option,-funsigned-char -static-libgcc,)
CFLAGS += $(call cc-option,-falign-functions=1 -falign-jumps=1 -falign-labels=1 -falign-loops=1,)
# Defeat .eh_frame bloat (gcc 4.6.3 x86-32 defconfig: 20% smaller busybox binary):
CFLAGS += $(call cc-option,-fno-unwind-tables,)
CFLAGS += $(call cc-option,-fno-asynchronous-unwind-tables,)
@@ -80,24 +60,19 @@ CFLAGS += $(call cc-option,-fno-asynchronous-unwind-tables,)
# (try disabling this and comparing assembly, it's instructive)
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)
CFLAGS += $(call cc-option,-Wno-string-plus-int -Wno-constant-logical-operand)
endif
# FIXME: These warnings are at least partially to be concerned about and should
# be fixed..
#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)
@@ -148,20 +123,15 @@ CFLAGS += --sysroot=$(CONFIG_SYSROOT)
export SYSROOT=$(CONFIG_SYSROOT)
endif
# libm may be needed for dc, awk, ntpd
LDLIBS += m
# Android has no separate crypt library
# 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;}' >crypttest.c; $(CC) $(CFLAGS) -lcrypt -o /dev/null crypttest.c >/dev/null 2>&1 && echo "y"; rm crypttest.c)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
endif
# librt may be needed for clock_gettime()
ifeq ($(RT_AVAILABLE),y)
LDLIBS += rt
LDLIBS += m crypt
else
LDLIBS += m
endif
# libpam may use libpthread, libdl and/or libaudit.
@@ -187,13 +157,8 @@ LDLIBS += $(if $(SELINUX_LIBS),$(SELINUX_LIBS:-l%=%),$(SELINUX_PC_MODULES:lib%=%
endif
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)
LDLIBS += efence
@@ -218,6 +183,11 @@ LDFLAGS += $(strip $(subst ",,$(CONFIG_EXTRA_LDFLAGS)))
#"))
endif
ifneq ($(CONFIG_EXTRA_LDLIBS),)
LDLIBS += $(strip $(subst ",,$(CONFIG_EXTRA_LDLIBS)))
#"))
endif
# Busybox is a stack-fatty so make sure we increase default size
# TODO: use "make stksizes" to find & fix big stack users
# (we stole scripts/checkstack.pl from the kernel... thanks guys!)
-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)
+2 -14
View File
@@ -20,10 +20,6 @@
#undef ARRAY_SIZE
#define ARRAY_SIZE(x) ((unsigned)(sizeof(x) / sizeof((x)[0])))
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#include "../include/autoconf.h"
#include "../include/applet_metadata.h"
@@ -56,7 +52,7 @@ static int cmp_name(const void *a, const void *b)
static int str_isalnum_(const char *s)
{
while (*s) {
if (!isalnum((unsigned char)*s) && *s != '_')
if (!isalnum(*s) && *s != '_')
return 0;
s++;
}
@@ -88,15 +84,7 @@ int main(int argc, char **argv)
qsort(applets, NUM_APPLETS, sizeof(applets[0]), cmp_name);
for (i = j = 0; i < NUM_APPLETS-1; ++i) {
if (cmp_name(applets+i, applets+i+1) == 0) {
fprintf(stderr, "%s: duplicate applet name '%s'\n", argv[0],
applets[i].name);
j = 1;
}
}
if (j != 0 || !argv[1])
if (!argv[1])
return 1;
snprintf(tmp1, PATH_MAX, "%s.%u.new", argv[1], (int) getpid());
i = open(tmp1, O_WRONLY | O_TRUNC | O_CREAT, 0666);
-16
View File
@@ -1,16 +0,0 @@
#!/bin/sh
# Make busybox scripted applet list file.
# input $1: full path to Config.h
# input $2: full path to applets.h
# output (stdout): list of pathnames that should be linked to busybox
export LC_ALL=POSIX
export LC_CTYPE=POSIX
CONFIG_H=${1:-include/autoconf.h}
APPLETS_H=${2:-include/applets.h}
$HOSTCC -E -DMAKE_SCRIPTS -include $CONFIG_H $APPLETS_H |
awk '/^[ \t]*SCRIPT/{
print $2
}'
+2 -2
View File
@@ -19,6 +19,6 @@ int main(int argc, char **argv)
void bb_show_usage(void)
{
fputs_stdout(APPLET_full_usage "\n");
exit_FAILURE();
fputs(APPLET_full_usage "\n", stdout);
exit(EXIT_FAILURE);
}
+1 -1
View File
@@ -83,7 +83,7 @@ install -m 755 busybox "$prefix/bin/busybox" || exit 1
for i in $h; do
appdir=`dirname "$i"`
app=`basename "$i"`
if [ x"$noclobber" = x"1" ] && ([ -e "$prefix/$i" ] || [ -h "$prefix/$i" ]); then
if [ x"$noclobber" = x"1" ] && [ -e "$prefix/$i" ]; then
echo " $prefix/$i already exists"
continue
fi
+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(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;
}
+5
View File
@@ -0,0 +1,5 @@
This directory contains examples of applets implemented as shell scripts.
So far these scripts are not hooked to the build system and are not
installed by "make install". If you want to use them,
you need to install them by hand.
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# TODO: use getopt to avoid parsing options as filenames,
# and to support -- and --help
[ $# -ne 0 ] && DASH_I=-i
sed $DASH_I -e 's/\r$//' "$@"
-39
View File
@@ -1,39 +0,0 @@
#!/bin/sh
MIMFILE="Mimfile"
if [ $# -ge 2 ] && [ "$1" = "-f" ]
then
MIMFILE="$2"
shift 2
fi
exec <"$MIMFILE" || exit 1
{
INCASE=false
while read -r REPLY
do
case $REPLY in
*:)
if ! $INCASE
then
printf '[ $# -eq 0 ] && set -- "%s"
TARGET="$1"
shift
case "$TARGET" in
' "${REPLY%:}"
else
printf ';;\n'
fi
printf '%s)\n' "${REPLY%:}"
INCASE=true
;;
"") ;;
*) printf '%s\n' "${REPLY##[ ]}";;
esac
done
$INCASE && printf ';;\n'
printf '*)
echo "Unknown command $TARGET"
exit 1
;;
esac
'
} | sh -s "$@"
+2 -1
View File
@@ -1,3 +1,4 @@
cat /etc/nologin.txt 2>/dev/null || echo This account is not available
#!/bin/sh
cat /etc/nologin.txt 2>/dev/null || echo "This account is not available"
sleep 5
exit 1
Executable
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
# TODO: use getopt to avoid parsing options as filenames,
# and to support -- and --help
for i in "$@"
do
sed -e '1!G;h;$!d' "$i"
done
+5
View File
@@ -0,0 +1,5 @@
#!/bin/sh
# TODO: use getopt to avoid parsing options as filenames,
# and to support -- and --help
[ $# -ne 0 ] && DASH_I=-i
sed $DASH_I -e 's/$/\r/' "$@"
-8
View File
@@ -11,11 +11,3 @@ ifeq ($(CONFIG_STACK_OPTIMIZATION_386),y)
# from aligning stack to 16 bytes. (Which is gcc's way of supporting SSE).
CFLAGS += $(call cc-option,-mpreferred-stack-boundary=2,)
endif
# "Control how GCC aligns variables.
# Supported values for type are compat uses increased alignment value
# compatible uses GCC 4.8 and earlier, abi uses alignment value as specified by the psABI,
# and cacheline uses increased alignment value to match the cache line size.
# compat is the default."
# "abi" seems to be somewhat successful in preventing oversealous data alignment.
CFLAGS += $(call cc-option,-malign-data=abi,)
-11
View File
@@ -1,11 +0,0 @@
# ==========================================================================
# Build system
# ==========================================================================
# "Control how GCC aligns variables.
# Supported values for type are compat uses increased alignment value
# compatible uses GCC 4.8 and earlier, abi uses alignment value as specified by the psABI,
# and cacheline uses increased alignment value to match the cache line size.
# compat is the default."
# "abi" seems to be somewhat successful in preventing oversealous data alignment.
CFLAGS += $(call cc-option,-malign-data=abi,)
-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
+35 -40
View File
@@ -48,9 +48,19 @@
//kbuild:lib-$(CONFIG_AR) += ar.o
//usage:#define ar_trivial_usage
//usage: "[-o] [-v] [-p] [-t] [-x] ARCHIVE FILES"
//usage:#define ar_full_usage "\n\n"
//usage: "Extract or list FILES from an ar archive\n"
//usage: "\n -o Preserve original dates"
//usage: "\n -p Extract to stdout"
//usage: "\n -t List"
//usage: "\n -x Extract"
//usage: "\n -v Verbose"
#include "libbb.h"
#include "bb_archive.h"
#include "ar_.h"
#include "ar.h"
#if ENABLE_FEATURE_AR_CREATE
/* filter out entries with same names as specified on the command line */
@@ -151,15 +161,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 +184,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 +204,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);
@@ -212,36 +220,23 @@ static void FAST_FUNC header_verbose_list_ar(archive_handle_t *archive_handle)
);
}
//usage:#define ar_trivial_usage
//usage: "x|p|t"IF_FEATURE_AR_CREATE("|r")" [-ov] ARCHIVE [FILE]..."
//usage:#define ar_full_usage "\n\n"
//usage: "Extract or list FILEs from an ar archive"IF_FEATURE_AR_CREATE(", or create it")"\n"
//usage: "\n x Extract"
//usage: "\n p Extract to stdout"
//usage: "\n t List"
//usage: IF_FEATURE_AR_CREATE(
//usage: "\n r Create"
//usage: )
//usage: "\n -o Restore mtime"
//usage: "\n -v Verbose"
#define AR_OPT_VERBOSE (1 << 0)
#define AR_OPT_PRESERVE_DATE (1 << 1)
/* "ar r" implies create, but warns about it. c suppresses warning.
* bbox accepts but ignores it: */
#define AR_OPT_CREATE (1 << 2)
#define AR_CMD_PRINT (1 << 3)
#define FIRST_CMD AR_CMD_PRINT
#define AR_CMD_LIST (1 << 4)
#define AR_CMD_EXTRACT (1 << 5)
#define AR_CMD_INSERT (1 << 6)
int ar_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int ar_main(int argc UNUSED_PARAM, char **argv)
{
archive_handle_t *archive_handle;
unsigned opt, t;
enum {
OPT_VERBOSE = (1 << 0),
OPT_PRESERVE_DATE = (1 << 1),
/* "ar r" implies create, but warns about it. c suppresses warning.
* bbox accepts but ignores it: */
OPT_CREATE = (1 << 2),
CMD_PRINT = (1 << 3),
FIRST_CMD = CMD_PRINT,
CMD_LIST = (1 << 4),
CMD_EXTRACT = (1 << 5),
CMD_INSERT = ((1 << 6) * ENABLE_FEATURE_AR_CREATE),
};
archive_handle = init_handle();
@@ -261,26 +256,26 @@ int ar_main(int argc UNUSED_PARAM, char **argv)
if (t & (t-1)) /* more than one of p,t,x[,r] are specified */
bb_show_usage();
if (opt & CMD_PRINT) {
if (opt & AR_CMD_PRINT) {
archive_handle->action_data = data_extract_to_stdout;
}
if (opt & CMD_LIST) {
if (opt & AR_CMD_LIST) {
archive_handle->action_header = header_list;
}
if (opt & CMD_EXTRACT) {
if (opt & AR_CMD_EXTRACT) {
archive_handle->action_data = data_extract_all;
}
if (opt & OPT_PRESERVE_DATE) {
if (opt & AR_OPT_PRESERVE_DATE) {
archive_handle->ah_flags |= ARCHIVE_RESTORE_DATE;
}
if (opt & OPT_VERBOSE) {
if (opt & AR_OPT_VERBOSE) {
archive_handle->action_header = header_verbose_list_ar;
}
#if ENABLE_FEATURE_AR_CREATE
archive_handle->ar__name = *argv;
#endif
archive_handle->src_fd = xopen(*argv++,
(opt & CMD_INSERT)
(opt & AR_CMD_INSERT)
? O_RDWR | O_CREAT
: O_RDONLY
);
@@ -292,7 +287,7 @@ int ar_main(int argc UNUSED_PARAM, char **argv)
}
#if ENABLE_FEATURE_AR_CREATE
if (opt & CMD_INSERT)
if (opt & AR_CMD_INSERT)
return write_ar_archive(archive_handle);
#endif
+17 -23
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;
}
@@ -114,7 +114,7 @@ int FAST_FUNC bbunpack(char **argv,
/* Check that the input is sane */
if (!(option_mask32 & BBUNPK_OPT_FORCE) && isatty(STDIN_FILENO)) {
bb_simple_error_msg_and_die("compressed data not read from terminal, "
bb_error_msg_and_die("compressed data not read from terminal, "
"use -f to force it");
}
@@ -219,7 +219,7 @@ char* FAST_FUNC make_new_name_generic(char *filename, const char *expected_ext)
//usage:#define uncompress_trivial_usage
//usage: "[-cf] [FILE]..."
//usage:#define uncompress_full_usage "\n\n"
//usage: "Decompress FILEs (or stdin)\n"
//usage: "Decompress .Z file[s]\n"
//usage: "\n -c Write to stdout"
//usage: "\n -f Overwrite"
@@ -284,7 +284,7 @@ int uncompress_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define gunzip_example_usage
//usage: "$ ls -la /tmp/BusyBox*\n"
@@ -299,7 +299,7 @@ int uncompress_main(int argc UNUSED_PARAM, char **argv)
//usage: "Decompress to stdout"
//config:config GUNZIP
//config: bool "gunzip (11 kb)"
//config: bool "gunzip (12 kb)"
//config: default y
//config: select FEATURE_GZIP_DECOMPRESS
//config: help
@@ -308,7 +308,7 @@ int uncompress_main(int argc UNUSED_PARAM, char **argv)
//config: an archive, without decompressing it.
//config:
//config:config ZCAT
//config: bool "zcat (24 kb)"
//config: bool "zcat (25 kb)"
//config: default y
//config: select FEATURE_GZIP_DECOMPRESS
//config: help
@@ -386,7 +386,7 @@ int gunzip_main(int argc UNUSED_PARAM, char **argv)
* Normally, "zcat" is just "gunzip -c".
* But if seamless magic is enabled, then we are much more clever.
*/
if (ENABLE_ZCAT && applet_name[1] == 'c')
if (ENABLE_ZCAT && (!ENABLE_GUNZIP || applet_name[1] == 'c'))
option_mask32 |= BBUNPK_OPT_STDOUT | BBUNPK_SEAMLESS_MAGIC;
return bbunpack(argv, unpack_gz_stream, make_new_name_gunzip, /*unused:*/ NULL);
@@ -407,15 +407,13 @@ int gunzip_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define bzcat_trivial_usage
//usage: "[FILE]..."
//usage:#define bzcat_full_usage "\n\n"
//usage: "Decompress to stdout"
//config:config BUNZIP2
//config: bool "bunzip2 (9.1 kb)"
//config: bool "bunzip2 (8.8 kb)"
//config: default y
//config: select FEATURE_BZIP2_DECOMPRESS
//config: help
@@ -429,7 +427,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.8 kb)"
//config: default y
//config: select FEATURE_BZIP2_DECOMPRESS
//config: help
@@ -463,21 +461,19 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//usage:#define unlzma_trivial_usage
//usage: "[-cfk] [FILE]..."
//usage:#define unlzma_full_usage "\n\n"
//usage: "Decompress FILEs (or stdin)\n"
//usage: "Decompress FILE (or stdin)\n"
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define lzma_trivial_usage
//usage: "-d [-cfk] [FILE]..."
//usage:#define lzma_full_usage "\n\n"
//usage: "Decompress FILEs (or stdin)\n"
//usage: "Decompress FILE (or stdin)\n"
//usage: "\n -d Decompress"
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define lzcat_trivial_usage
//usage: "[FILE]..."
@@ -485,7 +481,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 (8.6 kb)"
//config: default y
//config: help
//config: unlzma is a compression utility using the Lempel-Ziv-Markov chain
@@ -494,7 +490,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 (8.5 kb)"
//config: default y
//config: help
//config: Alias to "unlzma -c".
@@ -536,21 +532,19 @@ int unlzma_main(int argc UNUSED_PARAM, char **argv)
//usage:#define unxz_trivial_usage
//usage: "[-cfk] [FILE]..."
//usage:#define unxz_full_usage "\n\n"
//usage: "Decompress FILEs (or stdin)\n"
//usage: "Decompress FILE (or stdin)\n"
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define xz_trivial_usage
//usage: "-d [-cfk] [FILE]..."
//usage:#define xz_full_usage "\n\n"
//usage: "Decompress FILEs (or stdin)\n"
//usage: "Decompress FILE (or stdin)\n"
//usage: "\n -d Decompress"
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define xzcat_trivial_usage
//usage: "[FILE]..."
+5 -7
View File
@@ -7,7 +7,7 @@
* about bzip2 library code.
*/
//config:config BZIP2
//config: bool "bzip2 (16 kb)"
//config: bool "bzip2 (18 kb)"
//config: default y
//config: help
//config: bzip2 is a compression utility using the Burrows-Wheeler block
@@ -50,19 +50,17 @@
//kbuild:lib-$(CONFIG_BZIP2) += bzip2.o
//usage:#define bzip2_trivial_usage
//usage: "[-cfk" IF_FEATURE_BZIP2_DECOMPRESS("dt") "123456789] [FILE]..."
//usage: "[OPTIONS] [FILE]..."
//usage:#define bzip2_full_usage "\n\n"
//usage: "Compress FILEs (or stdin) with bzip2 algorithm\n"
//usage: "\n -1..9 Compression level"
//usage: IF_FEATURE_BZIP2_DECOMPRESS(
//usage: "\n -d Decompress"
//usage: "\n -t Test file integrity"
//usage: )
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: IF_FEATURE_BZIP2_DECOMPRESS(
//usage: "\n -t Test integrity"
//usage: )
#include "libbb.h"
#include "bb_archive.h"
@@ -147,7 +145,7 @@ IF_DESKTOP(long long) int bz_write(bz_stream *strm, void* rbuf, ssize_t rlen, vo
if (n2 != n) {
if (n2 >= 0)
errno = 0; /* prevent bogus error message */
bb_simple_perror_msg(n2 >= 0 ? "short write" : bb_msg_write_error);
bb_perror_msg(n2 >= 0 ? "short write" : bb_msg_write_error);
return -1;
}
}
@@ -189,7 +187,7 @@ IF_DESKTOP(long long) int FAST_FUNC compressStream(transformer_state_t *xstate U
while (1) {
count = full_read(STDIN_FILENO, rbuf, IOBUF_SIZE);
if (count < 0) {
bb_simple_perror_msg(bb_msg_read_error);
bb_perror_msg(bb_msg_read_error);
total = -1;
break;
}
-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));
}
+8 -76
View File
@@ -11,7 +11,7 @@
* Only supports new ASCII and CRC formats
*/
//config:config CPIO
//config: bool "cpio (15 kb)"
//config: bool "cpio (14 kb)"
//config: default y
//config: help
//config: cpio is an archival utility program used to create, modify, and
@@ -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)")
@@ -78,22 +64,14 @@
//usage: "\n -p DIR Copy files to DIR"
//usage: )
//usage: "\nOptions:"
//usage: IF_FEATURE_CPIO_O(
//usage: "\n -H newc Archive format"
//usage: )
//usage: "\n -d Make leading directories"
//usage: "\n -m Restore mtime"
//usage: "\n -m Preserve mtime"
//usage: "\n -v Verbose"
//usage: "\n -u Overwrite"
//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: IF_FEATURE_CPIO_O(
//usage: "\n -H newc Archive format"
//usage: )
/* GNU cpio 2.9 --help (abridged):
@@ -182,22 +160,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 +204,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 +258,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 +276,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 +283,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 +302,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 +373,9 @@ 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
@@ -477,8 +415,7 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
if (argv[0] == NULL)
bb_show_usage();
if (opt & OPT_CREATE_LEADING_DIR)
/* GNU cpio 2.13: "cpio -d -p a/b/c" works */
bb_make_directory(argv[0], -1, FILEUTILS_RECUR);
mkdir(argv[0], 0777);
/* Crude existence check:
* close(xopen(argv[0], O_RDONLY | O_DIRECTORY));
* We can also xopen, fstat, IS_DIR, later fchdir.
@@ -488,11 +425,6 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
* a diffrerent problem earlier.
* This is good enough for now.
*/
//FIXME: GNU cpio -d -p DIR does not immediately create DIR -
//it just prepends "DIR/" to the names of files to be created.
//The first file (fails to) be copied, and then the -d logic
//triggers and creates all necessary directories.
//IOW: bare "cpio -d -p DIR" + ^C shouldn't create anything.
#if !BB_MMU
pp.rd = 3;
pp.wr = 4;
@@ -511,6 +443,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);
@@ -580,7 +513,6 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
if (archive_handle->cpio__blocks != (off_t)-1
&& !(opt & OPT_QUIET)
) {
fflush_all();
fprintf(stderr, "%"OFF_FMT"u blocks\n", archive_handle->cpio__blocks);
}
+149 -210
View File
@@ -26,7 +26,7 @@
* - (unknown, please let me know when you find any)
*/
//config:config DPKG
//config: bool "dpkg (43 kb)"
//config: bool "dpkg (44 kb)"
//config: default y
//config: select FEATURE_SEAMLESS_GZ
//config: help
@@ -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) {
@@ -489,7 +487,7 @@ static void add_split_dependencies(common_node_t *parent_node, const char *whole
} else if (strncmp(version, ">=", offset_ch) == 0) {
edge->operator = VER_MORE_EQUAL;
} else {
bb_simple_error_msg_and_die("illegal operator");
bb_error_msg_and_die("illegal operator");
}
}
/* skip to start of version numbers */
@@ -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);
@@ -739,7 +730,7 @@ static void set_status(unsigned status_node_num, const char *new_value, int posi
status = new_value_num;
break;
default:
bb_simple_error_msg_and_die("DEBUG ONLY: this shouldnt happen");
bb_error_msg_and_die("DEBUG ONLY: this shouldnt happen");
}
new_status = xasprintf("%s %s %s", name_hashtable[want], name_hashtable[flag], name_hashtable[status]);
@@ -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++) {
@@ -964,10 +944,10 @@ static void write_status_file(deb_file_t **deb_file)
/* Create a separate backfile to dpkg */
if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) {
if (errno != ENOENT)
bb_simple_error_msg_and_die("can't create backup status file");
bb_error_msg_and_die("can't create backup status file");
/* Its ok if renaming the status file fails because status
* file doesn't exist, maybe we are starting from scratch */
bb_simple_error_msg("no status file found, creating new one");
bb_error_msg("no status file found, creating new one");
}
xrename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status");
@@ -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
@@ -1224,27 +1204,6 @@ static char **create_list(const char *filename)
return file_list;
}
/** This tests if the filename is an "important" directory, which might be symlinked.
* Debians dpkg test if directories are used by other packages, this
* implementation doesn't and would remove for ex. an lib -> usr/lib symlink.
*/
static int is_builtin_exclude(const char *name)
{
if (*name++ != '/')
return 0;
if (index_in_strings(".\0" "etc\0" "opt\0" "srv\0" "var\0" "var/lib\0",
name) >= 0)
return 1;
if (is_prefixed_with(name, "usr/")) {
name += sizeof("usr/") - 1;
if (is_prefixed_with(name, "local/"))
name += sizeof("local/") - 1;
}
return index_in_strings("bin\0" "lib\0" "lib32\0" "lib64\0" "sbin\0",
name) >= 0;
}
/* maybe i should try and hook this into remove_file.c somehow */
static int remove_file_array(char **remove_names, char **exclude_names)
{
@@ -1256,8 +1215,6 @@ static int remove_file_array(char **remove_names, char **exclude_names)
return 0;
}
for (i = 0; remove_names[i] != NULL; i++) {
if (is_builtin_exclude(remove_names[i]))
continue;
if (exclude_names != NULL) {
for (j = 0; exclude_names[j] != NULL; j++) {
if (strcmp(remove_names[i], exclude_names[j]) == 0) {
@@ -1324,7 +1281,7 @@ postrm abort-install <old_version>
postrm abort-upgrade <old_version>
postrm disappear <overwriter> <version>
*/
static const char *const all_control_files[] ALIGN_PTR = {
static const char *const all_control_files[] = {
"preinst", "postinst", "prerm", "postrm",
"list", "md5sums", "shlibs", "conffiles",
"config", "templates"
@@ -1401,12 +1358,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 +1409,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 +1631,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 +1666,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 +1722,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 +1763,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();
@@ -1877,7 +1816,7 @@ int dpkg_main(int argc UNUSED_PARAM, char **argv)
init_archive_deb_control(archive_handle);
deb_file[deb_count]->control_file = deb_extract_control_file_to_buffer(archive_handle, control_list);
if (deb_file[deb_count]->control_file == NULL) {
bb_simple_error_msg_and_die("can't extract control file");
bb_error_msg_and_die("can't extract control file");
}
deb_file[deb_count]->filename = xstrdup(argv[0]);
package_num = fill_package_struct(deb_file[deb_count]->control_file);
@@ -1940,13 +1879,13 @@ int dpkg_main(int argc UNUSED_PARAM, char **argv)
argv++;
}
if (!deb_count)
bb_simple_error_msg_and_die("no package files specified");
bb_error_msg_and_die("no package files specified");
deb_file[deb_count] = NULL;
/* Check that the deb file arguments are installable */
if (!(opt & OPT_force_ignore_depends)) {
if (!check_deps(deb_file, 0 /*, deb_count*/)) {
bb_simple_error_msg_and_die("dependency check failed");
bb_error_msg_and_die("dependency check failed");
}
}
+2 -2
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"
//config: default y
//config: select FEATURE_SEAMLESS_GZ
//config: help
@@ -28,7 +28,7 @@
//usage: "\n -f Print control fields"
//usage: "\n -e Extract control files to DIR (default: ./DEBIAN)"
//usage: "\n -x Extract files to DIR (no default)"
//usage: "\n -X Verbose extract"
//usage: "\n -X Verbose -x"
//usage:
//usage:#define dpkg_deb_example_usage
//usage: "$ dpkg-deb -X ./busybox_0.48-1_i386.deb /tmp\n"
+63 -78
View File
@@ -22,7 +22,7 @@ gzip: bogus: No such file or directory
aa: 85.1% -- replaced with aa.gz
*/
//config:config GZIP
//config: bool "gzip (17 kb)"
//config: bool "gzip (19 kb)"
//config: default y
//config: help
//config: gzip is used to compress files.
@@ -52,7 +52,7 @@ aa: 85.1% -- replaced with aa.gz
//config: help
//config: Enable support for compression levels 4-9. The default level
//config: is 6. If levels 1-3 are specified, 4 is used.
//config: If this option is not selected, -N options are ignored and -6
//config: If this option is not selected, -N options are ignored and -9
//config: is used.
//config:
//config:config FEATURE_GZIP_DECOMPRESS
@@ -77,13 +77,11 @@ aa: 85.1% -- replaced with aa.gz
//usage: )
//usage: IF_FEATURE_GZIP_DECOMPRESS(
//usage: "\n -d Decompress"
//usage: "\n -t Test file integrity"
//usage: )
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: IF_FEATURE_GZIP_DECOMPRESS(
//usage: "\n -t Test integrity"
//usage: )
//usage:
//usage:#define gzip_example_usage
//usage: "$ ls -la /tmp/busybox*\n"
@@ -101,7 +99,7 @@ aa: 85.1% -- replaced with aa.gz
/* Diagnostic functions */
#ifdef DEBUG
static int verbose;
# define Assert(cond,msg) { if (!(cond)) bb_simple_error_msg(msg); }
# define Assert(cond,msg) { if (!(cond)) bb_error_msg(msg); }
# define Trace(x) fprintf x
# define Tracev(x) {if (verbose) fprintf x; }
# define Tracevv(x) {if (verbose > 1) fprintf x; }
@@ -261,13 +259,12 @@ enum {
#if !ENABLE_FEATURE_GZIP_LEVELS
comp_level_minus4 = 6 - 4,
max_chain_length = 128,
max_chain_length = 4096,
/* To speed up deflation, hash chains are never searched beyond this length.
* A higher limit improves compression ratio but degrades the speed.
*/
max_lazy_match = 16,
max_lazy_match = 258,
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
@@ -279,7 +276,7 @@ enum {
* max_insert_length is used only for compression levels <= 3.
*/
good_match = 8,
good_match = 32,
/* Use a faster search when the previous match is longer than this */
/* Values for max_lazy_match, good_match and max_chain_length, depending on
@@ -288,7 +285,7 @@ enum {
* found for specific files.
*/
nice_match = 128, /* Stop searching when current match exceeds this */
nice_match = 258, /* Stop searching when current match exceeds this */
/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
* For deflate_fast() (levels <= 3) good is ignored and lazy has a different
* meaning.
@@ -337,16 +334,14 @@ struct globals {
#define head (G1.prev + WSIZE) /* hash head (see deflate.c) */
#if ENABLE_FEATURE_GZIP_LEVELS
unsigned comp_level_minus4; /* can be a byte */
unsigned max_chain_length;
unsigned max_lazy_match;
unsigned good_match;
unsigned nice_match;
#define comp_level_minus4 (G1.comp_level_minus4)
#define max_chain_length (G1.max_chain_length)
#define max_lazy_match (G1.max_lazy_match)
#define good_match (G1.good_match)
#define nice_match (G1.nice_match)
#define max_chain_length (G1.max_chain_length)
#define max_lazy_match (G1.max_lazy_match)
#define good_match (G1.good_match)
#define nice_match (G1.nice_match)
#endif
/* =========================================================================== */
@@ -509,7 +504,7 @@ static ALWAYS_INLINE void flush_outbuf_if_32bit_optimized(void)
* pointer, then initialize the crc shift register contents instead.
* Return the current crc in either case.
*/
static void updcrc(uch *s, unsigned n)
static void updcrc(uch * s, unsigned n)
{
G1.crc = crc32_block_endian0(G1.crc, s, n, global_crc32_table /*G1.crc_32_tab*/);
}
@@ -612,7 +607,7 @@ static void bi_windup(void)
* Copy a stored block to the zip file, storing first the length and its
* one's complement if requested.
*/
static void copy_block(const char *buf, unsigned len, int header)
static void copy_block(char *buf, unsigned len, int header)
{
bi_windup(); /* align on byte boundary */
@@ -792,7 +787,7 @@ static void check_match(IPos start, IPos match, int length)
/* check that the match is indeed a match */
if (memcmp(G1.window + match, G1.window + start, length) != 0) {
bb_error_msg(" start %d, match %d, length %d", start, match, length);
bb_simple_error_msg("invalid match");
bb_error_msg("invalid match");
}
if (verbose > 1) {
bb_error_msg("\\[%d,%d]", start - match, length);
@@ -1012,8 +1007,7 @@ struct globals2 {
tree_desc d_desc;
tree_desc bl_desc;
/* was "ush", but "unsigned" results in smaller code */
unsigned bl_count[MAX_BITS + 1];
ush bl_count[MAX_BITS + 1];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
@@ -1124,7 +1118,7 @@ static void init_block(void)
(tree[n].Freq < tree[m].Freq \
|| (tree[n].Freq == tree[m].Freq && G2.depth[n] <= G2.depth[m]))
static void pqdownheap(const ct_data *tree, int k)
static void pqdownheap(ct_data * tree, int k)
{
int v = G2.heap[k];
int j = k << 1; /* left son of k */
@@ -1158,15 +1152,22 @@ static void pqdownheap(const ct_data *tree, int k)
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
static void gen_bitlen(const tree_desc *desc)
static void gen_bitlen(tree_desc * desc)
{
#define tree desc->dyn_tree
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int overflow; /* number of elements with bit length too large */
ct_data *tree = desc->dyn_tree;
const uint8_t *extra = desc->extra_bits;
int base = desc->extra_base;
int max_code = desc->max_code;
int max_length = desc->max_length;
ct_data *stree = desc->static_tree;
int h; /* heap index */
int n, m; /* iterate over the tree elements */
int bits; /* bit length */
int xbits; /* extra bits */
ush f; /* frequency */
int overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits < ARRAY_SIZE(G2.bl_count); bits++)
for (bits = 0; bits <= MAX_BITS; bits++)
G2.bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
@@ -1174,32 +1175,28 @@ static void gen_bitlen(const tree_desc *desc)
*/
tree[G2.heap[G2.heap_max]].Len = 0; /* root of the heap */
overflow = 0;
for (h = G2.heap_max + 1; h < HEAP_SIZE; h++) {
ulg f; /* frequency */
int xbits; /* extra bits */
n = G2.heap[h];
bits = tree[tree[n].Dad].Len + 1;
if (bits > desc->max_length) {
bits = desc->max_length;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n].Len = (ush) bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > desc->max_code)
if (n > max_code)
continue; /* not a leaf node */
G2.bl_count[bits]++;
xbits = 0;
if (n >= desc->extra_base)
xbits = desc->extra_bits[n - desc->extra_base];
if (n >= base)
xbits = extra[n - base];
f = tree[n].Freq;
G2.opt_len += f * (bits + xbits);
G2.opt_len += (ulg) f *(bits + xbits);
if (desc->static_tree)
G2.static_len += f * (desc->static_tree[n].Len + xbits);
if (stree)
G2.static_len += (ulg) f * (stree[n].Len + xbits);
}
if (overflow == 0)
return;
@@ -1209,14 +1206,14 @@ static void gen_bitlen(const tree_desc *desc)
/* Find the first bit length which could increase: */
do {
bits = desc->max_length - 1;
bits = max_length - 1;
while (G2.bl_count[bits] == 0)
bits--;
G2.bl_count[bits]--; /* move one leaf down the tree */
G2.bl_count[bits + 1] += 2; /* move one overflow item as its brother */
G2.bl_count[desc->max_length]--;
G2.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[desc->max_length]
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
@@ -1226,11 +1223,11 @@ static void gen_bitlen(const tree_desc *desc)
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = desc->max_length; bits != 0; bits--) {
for (bits = max_length; bits != 0; bits--) {
n = G2.bl_count[bits];
while (n != 0) {
m = G2.heap[--h];
if (m > desc->max_code)
if (m > max_code)
continue;
if (tree[m].Len != (unsigned) bits) {
Trace((stderr, "code %d bits %d->%d\n", m, tree[m].Len, bits));
@@ -1240,7 +1237,6 @@ static void gen_bitlen(const tree_desc *desc)
n--;
}
}
#undef tree
}
/* ===========================================================================
@@ -1251,13 +1247,12 @@ static void gen_bitlen(const tree_desc *desc)
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
static void gen_codes(ct_data *tree, int max_code)
static void gen_codes(ct_data * tree, int max_code)
{
/* next_code[] and code used to be "ush", but "unsigned" results in smaller code */
unsigned next_code[MAX_BITS + 1]; /* next code value for each bit length */
unsigned code = 0; /* running code value */
int bits; /* bit index */
int n; /* code index */
ush next_code[MAX_BITS + 1]; /* next code value for each bit length */
ush code = 0; /* running code value */
int bits; /* bit index */
int n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
@@ -1309,7 +1304,7 @@ do { \
pqdownheap(tree, SMALLEST); \
} while (0)
static void build_tree(tree_desc *desc)
static void build_tree(tree_desc * desc)
{
ct_data *tree = desc->dyn_tree;
ct_data *stree = desc->static_tree;
@@ -1387,10 +1382,10 @@ static void build_tree(tree_desc *desc)
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(desc);
gen_bitlen((tree_desc *) desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code);
gen_codes((ct_data *) tree, max_code);
}
/* ===========================================================================
@@ -1399,7 +1394,7 @@ static void build_tree(tree_desc *desc)
* counts. (The contribution of the bit length codes will be added later
* during the construction of bl_tree.)
*/
static void scan_tree(ct_data *tree, int max_code)
static void scan_tree(ct_data * tree, int max_code)
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
@@ -1451,7 +1446,7 @@ static void scan_tree(ct_data *tree, int max_code)
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
static void send_tree(const ct_data *tree, int max_code)
static void send_tree(ct_data * tree, int max_code)
{
int n; /* iterates over all tree elements */
int prevlen = -1; /* last emitted length */
@@ -1627,7 +1622,7 @@ static int ct_tally(int dist, int lc)
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
static void compress_block(const ct_data *ltree, const ct_data *dtree)
static void compress_block(ct_data * ltree, ct_data * dtree)
{
unsigned dist; /* distance of matched string */
int lc; /* match length or unmatched char (if dist == 0) */
@@ -1677,7 +1672,7 @@ static void compress_block(const ct_data *ltree, const ct_data *dtree)
* trees or store, and output the encoded block to the zip file. This function
* returns the total compressed length for the file so far.
*/
static void flush_block(const char *buf, ulg stored_len, int eof)
static void flush_block(char *buf, ulg stored_len, int eof)
{
ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
int max_blindex; /* index of last bit length code of non zero freq */
@@ -1924,7 +1919,7 @@ static void bi_init(void)
/* ===========================================================================
* Initialize the "longest match" routines for a new file
*/
static void lm_init(void)
static void lm_init(unsigned *flags16p)
{
unsigned j;
@@ -1932,6 +1927,8 @@ static void lm_init(void)
memset(head, 0, HASH_SIZE * sizeof(*head));
/* prev will be initialized on the fly */
/* speed options for the general purpose bit flag */
*flags16p |= 2; /* FAST 4, SLOW 2 */
/* ??? reduce max_chain_length for binary files */
//G1.strstart = 0; // globals are zeroed in pack_gzip()
@@ -2079,16 +2076,10 @@ static void zip(void)
bi_init();
ct_init();
lm_init();
deflate_flags = 0; /* pkzip -es, -en or -ex equivalent */
lm_init(&deflate_flags);
deflate_flags = 0x300; /* extra flags. OS id = 3 (Unix) */
#if ENABLE_FEATURE_GZIP_LEVELS
/* Note that comp_level < 4 do not exist in this version of gzip */
if (comp_level_minus4 == 9 - 4) {
deflate_flags |= 0x02; /* SLOW flag */
}
#endif
put_16bit(deflate_flags);
put_16bit(deflate_flags | 0x300); /* extra flags. OS id = 3 (Unix) */
/* The above 32-bit misaligns outbuf (10 bytes are stored), flush it */
flush_outbuf_if_32bit_optimized();
@@ -2215,9 +2206,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));
@@ -2234,11 +2222,8 @@ int gzip_main(int argc UNUSED_PARAM, char **argv)
#if ENABLE_FEATURE_GZIP_LEVELS
opt >>= (BBUNPK_OPTSTRLEN IF_FEATURE_GZIP_DECOMPRESS(+ 2) + 1); /* drop cfkvq[dt]n bits */
if (opt == 0)
opt = 1 << 5; /* default: 6 */
opt = 1 << 6; /* default: 6 */
opt = ffs(opt >> 4); /* Maps -1..-4 to [0], -5 to [1] ... -9 to [5] */
comp_level_minus4 = opt;
max_chain_length = 1 << gzip_level_config[opt].chain_shift;
good_match = gzip_level_config[opt].good;
max_lazy_match = gzip_level_config[opt].lazy2 * 2;
+3 -4
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
@@ -91,7 +91,6 @@ lib-$(CONFIG_FEATURE_SEAMLESS_LZMA) += open_transformer.o decompress_unlzma.
lib-$(CONFIG_FEATURE_SEAMLESS_XZ) += open_transformer.o decompress_unxz.o
lib-$(CONFIG_FEATURE_COMPRESS_USAGE) += open_transformer.o decompress_bunzip2.o
lib-$(CONFIG_FEATURE_COMPRESS_BBCONFIG) += open_transformer.o decompress_bunzip2.o
lib-$(CONFIG_FEATURE_SH_EMBEDDED_SCRIPTS) += open_transformer.o decompress_bunzip2.o
ifneq ($(lib-y),)
lib-y += $(COMMON_FILES)
+2 -2
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,
@@ -459,7 +459,7 @@ int mainGtU(EState* state,
* usually small, typically <= 20.
*/
static
const uint32_t incs[14] ALIGN4 = {
const uint32_t incs[14] = {
1, 4, 13, 40, 121, 364, 1093, 3280,
9841, 29524, 88573, 265720,
797161, 2391484
+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];
+4 -19
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, '/');
@@ -115,7 +103,7 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
struct stat existing_sb;
if (lstat(dst_name, &existing_sb) == -1) {
if (errno != ENOENT) {
bb_simple_perror_msg_and_die("can't stat old file");
bb_perror_msg_and_die("can't stat old file");
}
}
else if (existing_sb.st_mtime >= file_header->mtime) {
@@ -171,10 +159,6 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
break;
}
case S_IFDIR:
//TODO: this causes problems if tarball contains a r-xr-xr-x directory:
// we create this directory, and then fail to create files inside it
// (if tar xf isn't run as root).
// GNU tar works around this by chmod-ing directories *after* all files are extracted.
res = mkdir(dst_name, file_header->mode);
if ((res != 0)
&& (errno != EISDIR) /* btw, Linux doesn't return this */
@@ -189,7 +173,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
@@ -222,7 +207,7 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
}
break;
default:
bb_simple_error_msg_and_die("unrecognized file type");
bb_error_msg_and_die("unrecognized file type");
}
if (!S_ISLNK(file_header->mode)) {
@@ -20,7 +20,7 @@ enum {
TAR_MAX,
};
static const char *const tar_var[] ALIGN_PTR = {
static const char *const tar_var[] = {
// "FILETYPE",
"MODE",
"FILENAME",
+15 -44
View File
@@ -107,7 +107,7 @@ struct bunzip_data {
uint8_t selectors[32768]; /* nSelectors=15 bits */
struct group_data groups[MAX_GROUPS]; /* Huffman coding tables */
};
typedef struct bunzip_data bunzip_data;
/* typedef struct bunzip_data bunzip_data; -- done in .h file */
/* Return the next nnn bits of input. All reads from the compressed input
@@ -235,9 +235,9 @@ static int get_next_block(bunzip_data *bd)
/* Get next value */
int n = 0;
while (get_bits(bd, 1)) {
n++;
if (n >= groupCount)
return RETVAL_DATA_ERROR;
n++;
}
/* Decode MTF to get the next selector */
tmp_byte = mtfSymbol[n];
@@ -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;
}
@@ -574,7 +575,7 @@ static int get_next_block(bunzip_data *bd)
in outbuf. IOW: on EOF returns len ("all bytes are not filled"), not 0.
(Why? This allows to get rid of one local variable)
*/
static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
int FAST_FUNC read_bunzip(bunzip_data *bd, char *outbuf, int len)
{
const uint32_t *dbuf;
int pos, current, previous;
@@ -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;
@@ -698,7 +699,7 @@ static int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* Because bunzip2 is used for help text unpacking, and because bb_show_usage()
should work for NOFORK applets too, we must be extremely careful to not leak
any allocations! */
static int FAST_FUNC start_bunzip(
int FAST_FUNC start_bunzip(
void *jmpbuf,
bunzip_data **bdp,
int in_fd,
@@ -758,7 +759,7 @@ static int FAST_FUNC start_bunzip(
return RETVAL_OK;
}
static void FAST_FUNC dealloc_bunzip(bunzip_data *bd)
void FAST_FUNC dealloc_bunzip(bunzip_data *bd)
{
free(bd->dbuf);
free(bd);
@@ -808,7 +809,7 @@ unpack_bz2_stream(transformer_state_t *xstate)
/* Observed case when i == RETVAL_OK:
* "bzcat z.bz2", where "z.bz2" is a bzipped zero-length file
* (to be exact, z.bz2 is exactly these 14 bytes:
* 42 5a 68 39 17 72 45 38 50 90 00 00 00 00).
* 42 5a 68 39 17 72 45 38 50 90 00 00 00 00).
*/
&& i != RETVAL_OK
) {
@@ -816,7 +817,7 @@ unpack_bz2_stream(transformer_state_t *xstate)
break;
}
if (bd->headerCRC != bd->totalCRC) {
bb_simple_error_msg("CRC error");
bb_error_msg("CRC error");
break;
}
@@ -846,36 +847,6 @@ unpack_bz2_stream(transformer_state_t *xstate)
return i ? i : IF_DESKTOP(total_written) + 0;
}
char* FAST_FUNC
unpack_bz2_data(const char *packed, int packed_len, int unpacked_len)
{
char *outbuf = NULL;
bunzip_data *bd;
int i;
jmp_buf jmpbuf;
/* Setup for I/O error handling via longjmp */
i = setjmp(jmpbuf);
if (i == 0) {
i = start_bunzip(&jmpbuf,
&bd,
/* src_fd: */ -1,
/* inbuf: */ packed,
/* len: */ packed_len
);
}
/* read_bunzip can longjmp and end up here with i != 0
* on read data errors! Not trivial */
if (i == 0) {
/* Cannot use xmalloc: will leak bd in NOFORK case! */
outbuf = malloc_or_warn(unpacked_len);
if (outbuf)
read_bunzip(bd, outbuf, unpacked_len);
}
dealloc_bunzip(bd);
return outbuf;
}
#ifdef TESTING
static char *const bunzip_errors[] = {
+59 -73
View File
@@ -39,8 +39,7 @@ typedef struct huft_t {
unsigned char e; /* number of extra bits or operation */
unsigned char b; /* number of bits in this code or subcode */
union {
unsigned n; /* literal, length base, or distance base */
/* ^^^^^ was "unsigned short", but that results in larger code */
unsigned short n; /* literal, length base, or distance base */
struct huft_t *t; /* pointer to next level of table */
} v;
} huft_t;
@@ -185,26 +184,29 @@ static const uint16_t mask_bits[] ALIGN2 = {
0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
};
/* Put lengths/offsets and extra bits in a struct of arrays
* to make calls to huft_build() have one fewer parameter.
*/
struct cp_ext {
uint16_t cp[31];
uint8_t ext[31];
/* Copy lengths for literal codes 257..285 */
static const uint16_t cplens[] ALIGN2 = {
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
};
/* Copy lengths and extra bits for literal codes 257..285 */
/* note: see note #13 above about the 258 in this list. */
static const struct cp_ext lit ALIGN2 = {
/*257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 */
/*0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 */
{ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 },
{ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99 } /* 99 == invalid */
/* Extra bits for literal codes 257..285 */
static const uint8_t cplext[] ALIGN1 = {
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5,
5, 5, 5, 0, 99, 99
}; /* 99 == invalid */
/* Copy offsets for distance codes 0..29 */
static const uint16_t cpdist[] ALIGN2 = {
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
};
/* Copy offsets and extra bits for distance codes 0..29 */
static const struct cp_ext dist ALIGN2 = {
/*0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 */
{ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 },
{ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }
/* Extra bits for distance codes */
static const uint8_t cpdext[] ALIGN1 = {
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
11, 11, 12, 12, 13, 13
};
/* Tables for deflate from PKZIP's appnote.txt. */
@@ -220,19 +222,10 @@ static const uint8_t border[] ALIGN1 = {
* each table.
* t: table to free
*/
#define BAD_HUFT(p) ((uintptr_t)(p) & 1)
#define ERR_RET ((huft_t*)(uintptr_t)1)
static void huft_free(huft_t *p)
{
huft_t *q;
/*
* If 'p' has the error bit set we have to clear it, otherwise we might run
* into a segmentation fault or an invalid pointer to free(p)
*/
//if (BAD_HUFT(p)) // commented out, since bit clearing has effect only if condition is true
p = (huft_t*)((uintptr_t)p & ~(uintptr_t)ERR_RET);
/* Go through linked list, freeing from the malloced (t[-1]) address. */
while (p) {
q = (--p)->v.t;
@@ -284,23 +277,22 @@ static unsigned fill_bitbuffer(STATE_PARAM unsigned bitbuffer, unsigned *current
/* Given a list of code lengths and a maximum table size, make a set of
* tables to decode that set of codes.
* tables to decode that set of codes. Return zero on success, one if
* the given code set is incomplete (the tables are still built in this
* case), two if the input is invalid (an oversubscribed set of lengths)
* - in this case stores NULL in *t.
*
* b: code lengths in bits (all assumed <= BMAX)
* n: number of codes (assumed <= N_MAX)
* s: number of simple-valued codes (0..s-1)
* cp_ext->cp,ext: list of base values/extra bits for non-simple codes
* d: list of base values for non-simple codes
* e: list of extra bits for non-simple codes
* t: result: starting table
* m: maximum lookup bits, returns actual
* result: starting table
*
* On error, returns a value with lowest-bit set on error.
* It can be just the value of 0x1,
* or a valid pointer to a Huffman table, ORed with 0x1 if incompete table
* is given: "fixed inflate" decoder feeds us such data.
*/
static huft_t* huft_build(const unsigned *b, const unsigned n,
const unsigned s, const struct cp_ext *cp_ext,
unsigned *m)
static int huft_build(const unsigned *b, const unsigned n,
const unsigned s, const unsigned short *d,
const unsigned char *e, huft_t **t, unsigned *m)
{
unsigned a; /* counter for codes of length k */
unsigned c[BMAX + 1]; /* bit length count table */
@@ -322,12 +314,12 @@ static huft_t* huft_build(const unsigned *b, const unsigned n,
unsigned *xp; /* pointer into x */
int y; /* number of dummy codes added */
unsigned z; /* number of entries in current table */
huft_t *result;
huft_t **t;
/* Length of EOB code, if any */
eob_len = n > 256 ? b[256] : BMAX;
*t = NULL;
/* Generate counts for each bit length */
memset(c, 0, sizeof(c));
p = b;
@@ -343,8 +335,9 @@ static huft_t* huft_build(const unsigned *b, const unsigned n,
q[1].b = 1;
q[2].e = 99; /* invalid code marker */
q[2].b = 1;
*t = q + 1;
*m = 1;
return q + 1;
return 0;
}
/* Find minimum and maximum length, bound *m by those */
@@ -360,11 +353,11 @@ static huft_t* huft_build(const unsigned *b, const unsigned n,
for (y = 1 << j; j < i; j++, y <<= 1) {
y -= c[j];
if (y < 0)
return ERR_RET; /* bad input: more codes than bits */
return 2; /* bad input: more codes than bits */
}
y -= c[i];
if (y < 0)
return ERR_RET;
return 2;
c[i] += y;
/* Generate starting offsets into the value table for each length */
@@ -391,8 +384,6 @@ static huft_t* huft_build(const unsigned *b, const unsigned n,
} while (++i < n);
/* Generate the Huffman codes and for each, make the table entries */
result = ERR_RET;
t = &result;
x[0] = i = 0; /* first Huffman code is zero */
p = v; /* grab values in bit order */
htl = -1; /* no tables yet--level -1 */
@@ -458,8 +449,8 @@ static huft_t* huft_build(const unsigned *b, const unsigned n,
r.e = (unsigned char) (*p < 256 ? 16 : 15); /* 256 is EOB code */
r.v.n = (unsigned short) (*p++); /* simple code is just the value */
} else {
r.e = (unsigned char) cp_ext->ext[*p - s]; /* non-simple--look up in lists */
r.v.n = cp_ext->cp[*p++ - s];
r.e = (unsigned char) e[*p - s]; /* non-simple--look up in lists */
r.v.n = d[*p++ - s];
}
/* fill code-like entries with r */
@@ -484,11 +475,8 @@ static huft_t* huft_build(const unsigned *b, const unsigned n,
/* return actual size of base table */
*m = ws[1];
if (y != 0 && g != 1) /* we were given an incomplete table */
/* return "result" ORed with 1 */
return (void*)((uintptr_t)result | 1);
return result;
/* Return 1 if we were given an incomplete table */
return y != 0 && g != 1;
}
@@ -789,17 +777,14 @@ static int inflate_block(STATE_PARAM smallint *e)
for (; i < 288; i++) /* make a complete, but wrong code set */
ll[i] = 8;
bl = 7;
inflate_codes_tl = huft_build(ll, 288, 257, &lit, &bl);
/* ^^^ never returns error here - we use known data */
huft_build(ll, 288, 257, cplens, cplext, &inflate_codes_tl, &bl);
/* huft_build() never return nonzero - we use known data */
/* set up distance table */
for (i = 0; i < 30; i++) /* make an incomplete code set */
ll[i] = 5;
bd = 5;
inflate_codes_td = huft_build(ll, 30, 0, &dist, &bd);
/* ^^^ does return error here! (lsb bit is set) - we gave it incomplete code set */
/* clearing error bit: */
inflate_codes_td = (void*)((uintptr_t)inflate_codes_td & ~(uintptr_t)1);
huft_build(ll, 30, 0, cpdist, cpdext, &inflate_codes_td, &bd);
/* set up data for inflate_codes() */
inflate_codes_setup(PASS_STATE bl, bd);
@@ -865,9 +850,9 @@ static int inflate_block(STATE_PARAM smallint *e)
/* build decoding table for trees - single level, 7 bit lookup */
bl = 7;
inflate_codes_tl = huft_build(ll, 19, 19, NULL, &bl);
if (BAD_HUFT(inflate_codes_tl)) {
abort_unzip(PASS_STATE_ONLY); /* incomplete code set */
i = huft_build(ll, 19, 19, NULL, NULL, &inflate_codes_tl, &bl);
if (i != 0) {
abort_unzip(PASS_STATE_ONLY); //return i; /* incomplete code set */
}
/* read in literal and distance code lengths */
@@ -930,13 +915,14 @@ static int inflate_block(STATE_PARAM smallint *e)
/* build the decoding tables for literal/length and distance codes */
bl = lbits;
inflate_codes_tl = huft_build(ll, nl, 257, &lit, &bl);
if (BAD_HUFT(inflate_codes_tl)) {
i = huft_build(ll, nl, 257, cplens, cplext, &inflate_codes_tl, &bl);
if (i != 0) {
abort_unzip(PASS_STATE_ONLY);
}
bd = dbits;
inflate_codes_td = huft_build(ll + nl, nd, 0, &dist, &bd);
if (BAD_HUFT(inflate_codes_td)) {
i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &inflate_codes_td, &bd);
if (i != 0) {
abort_unzip(PASS_STATE_ONLY);
}
@@ -1026,7 +1012,7 @@ inflate_unzip_internal(STATE_PARAM transformer_state_t *xstate)
error_msg = "corrupted data";
if (setjmp(error_jmp)) {
/* Error from deep inside zip machinery */
bb_simple_error_msg(error_msg);
bb_error_msg(error_msg);
n = -1;
goto ret;
}
@@ -1099,7 +1085,7 @@ static int top_up(STATE_PARAM unsigned n)
bytebuffer_offset = 0;
bytebuffer_size = full_read(gunzip_src_fd, &bytebuffer[count], bytebuffer_max - count);
if ((int)bytebuffer_size < 0) {
bb_simple_error_msg(bb_msg_read_error);
bb_error_msg(bb_msg_read_error);
return 0;
}
bytebuffer_size += count;
@@ -1225,7 +1211,7 @@ unpack_gz_stream(transformer_state_t *xstate)
if (full_read(xstate->src_fd, &magic2, 2) != 2) {
bad_magic:
bb_simple_error_msg("invalid magic");
bb_error_msg("invalid magic");
return -1;
}
if (magic2 == COMPRESS_MAGIC) {
@@ -1247,7 +1233,7 @@ unpack_gz_stream(transformer_state_t *xstate)
again:
if (!check_header_gzip(PASS_STATE xstate)) {
bb_simple_error_msg("corrupted data");
bb_error_msg("corrupted data");
total = -1;
goto ret;
}
@@ -1260,7 +1246,7 @@ unpack_gz_stream(transformer_state_t *xstate)
total += n;
if (!top_up(PASS_STATE 8)) {
bb_simple_error_msg("corrupted data");
bb_error_msg("corrupted data");
total = -1;
goto ret;
}
@@ -1268,7 +1254,7 @@ unpack_gz_stream(transformer_state_t *xstate)
/* Validate decompression - crc */
v32 = buffer_read_le_u32(PASS_STATE_ONLY);
if ((~gunzip_crc) != v32) {
bb_simple_error_msg("crc error");
bb_error_msg("crc error");
total = -1;
goto ret;
}
@@ -1276,7 +1262,7 @@ unpack_gz_stream(transformer_state_t *xstate)
/* Validate decompression - size */
v32 = buffer_read_le_u32(PASS_STATE_ONLY);
if ((uint32_t)gunzip_bytes_out != v32) {
bb_simple_error_msg("incorrect length");
bb_error_msg("incorrect length");
total = -1;
}
+5 -5
View File
@@ -113,7 +113,7 @@ unpack_Z_stream(transformer_state_t *xstate)
/* xread isn't good here, we have to return - caller may want
* to do some cleanup (e.g. delete incomplete unpacked file etc) */
if (full_read(xstate->src_fd, inbuf, 1) != 1) {
bb_simple_error_msg("short read");
bb_error_msg("short read");
goto err;
}
@@ -166,7 +166,7 @@ unpack_Z_stream(transformer_state_t *xstate)
if (insize < (int) (IBUFSIZ + 64) - IBUFSIZ) {
rsize = safe_read(xstate->src_fd, inbuf + insize, IBUFSIZ);
if (rsize < 0)
bb_simple_error_msg_and_die(bb_msg_read_error);
bb_error_msg_and_die(bb_msg_read_error);
insize += rsize;
}
@@ -200,7 +200,7 @@ unpack_Z_stream(transformer_state_t *xstate)
if (oldcode == -1) {
if (code >= 256)
bb_simple_error_msg_and_die("corrupted data"); /* %ld", code); */
bb_error_msg_and_die("corrupted data"); /* %ld", code); */
oldcode = code;
finchar = (int) oldcode;
outbuf[outpos++] = (unsigned char) finchar;
@@ -236,7 +236,7 @@ unpack_Z_stream(transformer_state_t *xstate)
insize, posbits, p[-1], p[0], p[1], p[2], p[3],
(posbits & 07));
*/
bb_simple_error_msg("corrupted data");
bb_error_msg("corrupted data");
goto err;
}
@@ -247,7 +247,7 @@ unpack_Z_stream(transformer_state_t *xstate)
/* Generate output characters in reverse order */
while (code >= 256) {
if (stackp <= &htabof(0))
bb_simple_error_msg_and_die("corrupted data");
bb_error_msg_and_die("corrupted data");
*--stackp = tab_suffixof(code);
code = tab_prefixof(code);
}
+11 -20
View File
@@ -59,7 +59,7 @@ static void rc_read(rc_t *rc)
//TODO: return -1 instead
//This will make unlzma delete broken unpacked file on unpack errors
if (buffer_size <= 0)
bb_simple_error_msg_and_die("unexpected EOF");
bb_error_msg_and_die("unexpected EOF");
rc->buffer_end = RC_BUFFER + buffer_size;
rc->ptr = RC_BUFFER;
}
@@ -234,7 +234,7 @@ unpack_lzma_stream(transformer_state_t *xstate)
if (full_read(xstate->src_fd, &header, sizeof(header)) != sizeof(header)
|| header.pos >= (9 * 5 * 5)
) {
bb_simple_error_msg("bad lzma header");
bb_error_msg("bad lzma header");
return -1;
}
@@ -290,11 +290,8 @@ unpack_lzma_stream(transformer_state_t *xstate)
uint32_t pos;
pos = buffer_pos - rep0;
if ((int32_t)pos < 0) {
if ((int32_t)pos < 0)
pos += header.dict_size;
if ((int32_t)pos < 0)
goto bad;
}
match_byte = buffer[pos];
do {
int bit;
@@ -356,10 +353,8 @@ unpack_lzma_stream(transformer_state_t *xstate)
if ((int32_t)pos < 0) {
pos += header.dict_size;
/* see unzip_bad_lzma_2.zip: */
if (pos >= buffer_size) {
dbg("%d pos:%d buffer_size:%d", __LINE__, pos, buffer_size);
if (pos >= buffer_size)
goto bad;
}
}
previous_byte = buffer[pos];
goto one_byte1;
@@ -435,9 +430,10 @@ unpack_lzma_stream(transformer_state_t *xstate)
for (; num_bits2 != LZMA_NUM_ALIGN_BITS; num_bits2--)
rep0 = (rep0 << 1) | rc_direct_bit(rc);
rep0 <<= LZMA_NUM_ALIGN_BITS;
// Note: (int32_t)rep0 may be < 0 here
// (I have linux-3.3.4.tar.lzma which has it).
// I moved the check after "++rep0 == 0" check below.
if ((int32_t)rep0 < 0) {
dbg("%d rep0:%d", __LINE__, rep0);
goto bad;
}
prob3 = p + LZMA_ALIGN;
}
i2 = 1;
@@ -448,13 +444,8 @@ unpack_lzma_stream(transformer_state_t *xstate)
i2 <<= 1;
}
}
rep0++;
if ((int32_t)rep0 <= 0) {
if (rep0 == 0)
break;
dbg("%d rep0:%d", __LINE__, rep0);
goto bad;
}
if (++rep0 == 0)
break;
}
len += LZMA_MATCH_MIN_LEN;
@@ -516,7 +507,7 @@ unpack_lzma_stream(transformer_state_t *xstate)
* potentially more detailed information).
* Do not fail silently.
*/
bb_simple_error_msg("corrupted data");
bb_error_msg("corrupted data");
total_written = -1; /* failure */
}
rc_free(rc);
+3 -21
View File
@@ -74,7 +74,7 @@ unpack_xz_stream(transformer_state_t *xstate)
if (iobuf.in_pos == iobuf.in_size) {
int rd = safe_read(xstate->src_fd, membuf, BUFSIZ);
if (rd < 0) {
bb_simple_error_msg(bb_msg_read_error);
bb_error_msg(bb_msg_read_error);
total = -1;
break;
}
@@ -96,24 +96,6 @@ unpack_xz_stream(transformer_state_t *xstate)
*/
do {
if (membuf[iobuf.in_pos] != 0) {
/* There is more data, but is it XZ data?
* Example: dpkg-deb -f busybox_1.30.1-4_amd64.deb
* reads control.tar.xz "control" file
* inside the ar archive, but tar.xz
* extraction code reaches end of xz data,
* reached this code and reads the beginning
* of data.tar.xz's ar header, which isn't xz data,
* and prints "corrupted data".
* The correct solution is to not read
* past nested archive (to simulate EOF).
* This is a workaround:
*/
if (membuf[iobuf.in_pos] != 0xfd) {
/* It's definitely not a xz signature
* (which is 0xfd,"7zXZ",0x00).
*/
goto end;
}
xz_dec_reset(state);
goto do_run;
}
@@ -141,12 +123,12 @@ unpack_xz_stream(transformer_state_t *xstate)
continue;
}
if (xz_result != XZ_OK && xz_result != XZ_UNSUPPORTED_CHECK) {
bb_simple_error_msg("corrupted data");
bb_error_msg("corrupted data");
total = -1;
break;
}
}
end:
xz_dec_end(state);
free(membuf);
+7 -11
View File
@@ -6,7 +6,7 @@
*/
#include "libbb.h"
#include "bb_archive.h"
#include "ar_.h"
#include "ar.h"
/* WARNING: Clobbers str[len], so fields must be read in reverse order! */
static unsigned read_num(char *str, int base, int len)
@@ -22,7 +22,7 @@ static unsigned read_num(char *str, int base, int len)
* on misformatted numbers bb_strtou returns all-ones */
err = bb_strtou(str, NULL, base);
if (err == -1)
bb_simple_error_msg_and_die("invalid ar header");
bb_error_msg_and_die("invalid ar header");
return err;
}
@@ -53,7 +53,7 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
archive_handle->offset += 60;
if (ar.formatted.magic[0] != '`' || ar.formatted.magic[1] != '\n')
bb_simple_error_msg_and_die("invalid ar header");
bb_error_msg_and_die("invalid ar header");
/*
* Note that the fields MUST be read in reverse order as
@@ -86,18 +86,14 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
return get_header_ar(archive_handle);
}
#else
bb_simple_error_msg_and_die("long filenames not supported");
bb_error_msg_and_die("long filenames not supported");
#endif
}
/* 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));
@@ -111,7 +107,7 @@ char FAST_FUNC get_header_ar(archive_handle_t *archive_handle)
long_offset = read_num(&ar.formatted.name[1], 10,
sizeof(ar.formatted.name) - 1);
if (long_offset >= archive_handle->ar__long_name_size) {
bb_simple_error_msg_and_die("can't resolve long filename");
bb_error_msg_and_die("can't resolve long filename");
}
typed->name = xstrdup(archive_handle->ar__long_names + long_offset);
} else
@@ -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;
+5 -6
View File
@@ -20,7 +20,7 @@ typedef struct hardlinks_t {
char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
{
file_header_t *file_header = archive_handle->file_header;
char cpio_header[111];
char cpio_header[110];
int namesize;
int major, minor, nlink, mode, inode;
unsigned size, uid, gid, mtime;
@@ -33,17 +33,16 @@ char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
goto create_hardlinks;
}
if (size != 110) {
bb_simple_error_msg_and_die("short read");
bb_error_msg_and_die("short read");
}
archive_handle->offset += 110;
if (!is_prefixed_with(&cpio_header[0], "07070")
|| (cpio_header[5] != '1' && cpio_header[5] != '2')
) {
bb_simple_error_msg_and_die("unsupported cpio format, use newc or crc");
bb_error_msg_and_die("unsupported cpio format, use newc or crc");
}
cpio_header[110] = '\0'; /* sscanf may call strlen which may break without this */
if (sscanf(cpio_header + 6,
"%8x" "%8x" "%8x" "%8x"
"%8x" "%8x" "%8x" /*maj,min:*/ "%*16c"
@@ -51,7 +50,7 @@ char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
&inode, &mode, &uid, &gid,
&nlink, &mtime, &size,
&major, &minor, &namesize) != 10)
bb_simple_error_msg_and_die("damaged cpio file");
bb_error_msg_and_die("damaged cpio file");
file_header->mode = mode;
/* "cpio -R USER:GRP" support: */
if (archive_handle->cpio__owner.uid != (uid_t)-1L)
@@ -125,7 +124,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);
}
+15 -31
View File
@@ -32,7 +32,7 @@ static unsigned long long getOctal(char *str, int len)
if (*end != '\0' && *end != ' ') {
int8_t first = str[0];
if (!(first & 0x80))
bb_simple_error_msg_and_die("corrupted octal value in tar header");
bb_error_msg_and_die("corrupted octal value in tar header");
/*
* GNU tar uses "base-256 encoding" for very large numbers.
* Encoding is binary, with highest bit always set as a marker
@@ -100,7 +100,7 @@ static void process_pax_hdr(archive_handle_t *archive_handle, unsigned sz, int g
|| errno != EINVAL
|| *end != ' '
) {
bb_simple_error_msg("malformed extended header, skipped");
bb_error_msg("malformed extended header, skipped");
// More verbose version:
//bb_error_msg("malformed extended header at %"OFF_FMT"d, skipped",
// archive_handle->offset - (sz + len));
@@ -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;
@@ -202,13 +194,13 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
* the very first read fails. Grrr.
*/
if (archive_handle->offset == 0)
bb_simple_error_msg("short read");
bb_error_msg("short read");
/* this merely signals end of archive, not exit(1): */
return EXIT_FAILURE;
}
if (i != 512) {
IF_FEATURE_TAR_AUTODETECT(goto autodetect;)
bb_simple_error_msg_and_die("short read");
bb_error_msg_and_die("short read");
}
#else
@@ -251,11 +243,11 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
goto err;
if (setup_unzip_on_fd(archive_handle->src_fd, /*fail_if_not_compressed:*/ 0) != 0)
err:
bb_simple_error_msg_and_die("invalid tar magic");
bb_error_msg_and_die("invalid tar magic");
archive_handle->offset = 0;
goto again_after_align;
#endif
bb_simple_error_msg_and_die("invalid tar magic");
bb_error_msg_and_die("invalid tar magic");
}
/* Do checksum on headers.
@@ -290,7 +282,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
if (sum_u != sum
IF_FEATURE_TAR_OLDSUN_COMPATIBILITY(&& sum_s != sum)
) {
bb_simple_error_msg_and_die("invalid tar header checksum");
bb_error_msg_and_die("invalid tar header checksum");
}
/* GET_OCTAL trashes subsequent field, therefore we call it
@@ -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.
@@ -358,7 +352,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
/* case 0: */
case '0':
#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
if (file_header->name && last_char_is(file_header->name, '/')) {
if (last_char_is(file_header->name, '/')) {
goto set_dir;
}
#endif
@@ -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;
@@ -422,8 +414,7 @@ char FAST_FUNC get_header_tar(archive_handle_t *archive_handle)
// case 'D': /* GNU dump dir */
// case 'M': /* Continuation of multi volume archive */
// case 'N': /* Old GNU for names > 100 characters */
case 'V': /* Volume header */
; /* Fall through to skip it */
// case 'V': /* Volume header */
#endif
}
skip_ext_hdr:
@@ -454,22 +445,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');
}
+3 -1
View File
@@ -487,7 +487,7 @@ static int find_match(lzo1x_999_t *c, lzo_swd_p s,
}
/* this is a public functions, but there is no prototype in a header file */
static int lzo1x_999_compress_internal(const uint8_t *in, unsigned in_len,
static int lzo1x_999_compress_internal(const uint8_t *in , unsigned in_len,
uint8_t *out, unsigned *out_len,
void *wrkmem,
unsigned good_length,
@@ -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;
+34 -45
View File
@@ -15,7 +15,7 @@ int FAST_FUNC check_signature16(transformer_state_t *xstate, unsigned magic16)
if (!xstate->signature_skipped) {
uint16_t magic2;
if (full_read(xstate->src_fd, &magic2, 2) != 2 || magic2 != magic16) {
bb_simple_error_msg("invalid magic");
bb_error_msg("invalid magic");
return -1;
}
xstate->signature_skipped = 2;
@@ -46,7 +46,7 @@ ssize_t FAST_FUNC transformer_write(transformer_state_t *xstate, const void *buf
} else {
nwrote = full_write(xstate->dst_fd, buf, bufsize);
if (nwrote != (ssize_t)bufsize) {
bb_simple_perror_msg("write");
bb_perror_msg("write");
nwrote = -1;
goto ret;
}
@@ -157,46 +157,49 @@ 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)
{
union {
uint8_t b[4];
uint16_t b16[2];
uint32_t b32[1];
} magic;
transformer_state_t *xstate;
xstate = xzalloc(sizeof(*xstate));
xstate->src_fd = fd;
xstate->signature_skipped = 2;
/* .gz and .bz2 both have 2-byte signature, and their
* unpack_XXX_stream wants this header skipped. */
xstate->signature_skipped = 2;
xread(fd, xstate->magic.b16, 2);
xread(fd, magic.b16, sizeof(magic.b16[0]));
if (ENABLE_FEATURE_SEAMLESS_GZ
&& xstate->magic.b16[0] == GZIP_MAGIC
&& magic.b16[0] == GZIP_MAGIC
) {
xstate->xformer = unpack_gz_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "gunzip";)
goto found_magic;
}
if (ENABLE_FEATURE_SEAMLESS_Z
&& xstate->magic.b16[0] == COMPRESS_MAGIC
&& magic.b16[0] == COMPRESS_MAGIC
) {
xstate->xformer = unpack_Z_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "uncompress";)
goto found_magic;
}
if (ENABLE_FEATURE_SEAMLESS_BZ2
&& xstate->magic.b16[0] == BZIP2_MAGIC
&& magic.b16[0] == BZIP2_MAGIC
) {
xstate->xformer = unpack_bz2_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "bunzip2";)
goto found_magic;
}
if (ENABLE_FEATURE_SEAMLESS_XZ
&& xstate->magic.b16[0] == XZ_MAGIC1
&& magic.b16[0] == XZ_MAGIC1
) {
uint32_t v32;
xstate->signature_skipped = 6;
xread(fd, &xstate->magic.b16[1], 4);
move_from_unaligned32(v32, &xstate->magic.b16[1]);
if (v32 == XZ_MAGIC2) {
xread(fd, magic.b32, sizeof(magic.b32[0]));
if (magic.b32[0] == XZ_MAGIC2) {
xstate->xformer = unpack_xz_stream;
USE_FOR_NOMMU(xstate->xformer_prog = "unxz";)
goto found_magic;
@@ -204,8 +207,8 @@ static transformer_state_t *setup_transformer_on_fd(int fd, int die_if_not_compr
}
/* No known magic seen */
if (die_if_not_compressed)
bb_simple_error_msg_and_die("no gzip"
if (fail_if_not_compressed)
bb_error_msg_and_die("no gzip"
IF_FEATURE_SEAMLESS_BZ2("/bzip2")
IF_FEATURE_SEAMLESS_XZ("/xz")
" magic");
@@ -240,15 +243,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 +267,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;
@@ -277,7 +278,8 @@ static transformer_state_t *open_transformer(const char *fname, int die_if_not_c
if (ENABLE_FEATURE_SEAMLESS_LZMA) {
/* .lzma has no header/signature, can only detect it by extension */
if (is_suffixed_with(fname, ".lzma")) {
char *sfx = strrchr(fname, '.');
if (sfx && strcmp(sfx+1, "lzma") == 0) {
xstate = xzalloc(sizeof(*xstate));
xstate->src_fd = fd;
xstate->xformer = unpack_lzma_stream;
@@ -286,18 +288,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 +330,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;
@@ -343,24 +345,11 @@ void* FAST_FUNC xmalloc_open_zipped_read_close(const char *fname, size_t *maxsz_
*maxsz_p = xstate->mem_output_size;
}
} else {
/* File is not compressed.
* We already read first few bytes, account for that.
* Example where it happens:
* "modinfo MODULE.ko" (not compressed)
* open("MODULE.ko", O_RDONLY|O_LARGEFILE) = 4
* read(4, "\177E", 2) = 2
* fstat64(4, ...)
* mmap(...)
* read(4, "LF\2\1\1\0\0\0\0"...
* ...and we avoided seeking on the fd! :)
*/
image = xmalloc_read_with_initial_buf(
xstate->src_fd,
maxsz_p,
xmemdup(&xstate->magic, xstate->signature_skipped),
xstate->signature_skipped
);
/* File is not compressed */
//FIXME: avoid seek
xlseek(xstate->src_fd, - xstate->signature_skipped, SEEK_CUR);
xstate->signature_skipped = 0;
image = xmalloc_read(xstate->src_fd, maxsz_p);
}
if (!image)
@@ -373,7 +362,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;
+1 -1
View File
@@ -13,6 +13,6 @@ void FAST_FUNC seek_by_jump(int fd, off_t amount)
if (errno == ESPIPE)
seek_by_read(fd, amount);
else
bb_simple_perror_msg_and_die("seek failure");
bb_perror_msg_and_die("seek failure");
}
}
+2 -2
View File
@@ -4,7 +4,7 @@
*/
#include "libbb.h"
#include "bb_archive.h"
#include "ar_.h"
#include "ar.h"
void FAST_FUNC unpack_ar_archive(archive_handle_t *ar_archive)
{
@@ -12,7 +12,7 @@ void FAST_FUNC unpack_ar_archive(archive_handle_t *ar_archive)
xread(ar_archive->src_fd, magic, AR_MAGIC_LEN);
if (!is_prefixed_with(magic, AR_MAGIC)) {
bb_simple_error_msg_and_die("invalid ar magic");
bb_error_msg_and_die("invalid ar magic");
}
ar_archive->offset += AR_MAGIC_LEN;
+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;
+1 -1
View File
@@ -25,7 +25,7 @@
#define STREAM_HEADER_SIZE 12
#define HEADER_MAGIC "\375""7zXZ"
#define HEADER_MAGIC "\3757zXZ"
#define HEADER_MAGIC_SIZE 6
#define FOOTER_MAGIC "YZ"
+14 -14
View File
@@ -86,7 +86,6 @@
//usage: "\n -f Force"
//usage: "\n -U Delete input files"
///////: "\n -k Keep input files" (default, so why bother documenting?)
//usage: "\n -t Test integrity"
//usage: "\n -v Verbose"
//usage: "\n -F Don't verify checksum"
@@ -154,7 +153,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 +207,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 +227,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
*litp = (unsigned char)((*litp & ~3) | lit);
/* copy over the 2 literals that replace the match */
copy2(ip-2, m_pos, pd(op, m_pos));
// o_m1_a++;
o_m1_a++;
}
/* test if a literal run follows */
else
@@ -249,7 +249,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit += 2 + t + 3;
*litp = (unsigned char)(lit - 3);
// o_m1_b++;
o_m1_b++;
*op++ = *m_pos++;
*op++ = *m_pos++;
goto copy_literal_run;
@@ -284,7 +284,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
/* set new length of previous literal run */
lit += 3 + t + 3;
*litp = (unsigned char)(lit - 3);
// o_m2++;
o_m2++;
*op++ = *m_pos++;
*op++ = *m_pos++;
*op++ = *m_pos++;
@@ -330,7 +330,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
*litp = (unsigned char)((*litp & ~3) | lit);
/* copy over the 3 literals that replace the match */
copy3(ip-3, m_pos, pd(op, m_pos));
// o_m3_a++;
o_m3_a++;
}
/* test if a literal run follows */
else if (t == 1 && lit <= 3 && nl == 0
@@ -349,7 +349,7 @@ static NOINLINE int lzo1x_optimize(uint8_t *in, unsigned in_len,
lit += 3 + t + 3;
*litp = (unsigned char)(lit - 3);
// o_m3_b++;
o_m3_b++;
*op++ = *m_pos++;
*op++ = *m_pos++;
*op++ = *m_pos++;
@@ -752,7 +752,7 @@ static FAST_FUNC void lzo_check(
*/
uint32_t c = fn(init, buf, len);
if (c != ref)
bb_simple_error_msg_and_die("checksum error");
bb_error_msg_and_die("checksum error");
}
/**********************************************************************/
@@ -785,15 +785,15 @@ static NOINLINE int lzo_decompress(uint32_t h_flags32)
/* error if split file */
if (dst_len == 0xffffffffL)
/* should not happen - not yet implemented */
bb_simple_error_msg_and_die("this file is a split lzop file");
bb_error_msg_and_die("this file is a split lzop file");
if (dst_len > MAX_BLOCK_SIZE)
bb_simple_error_msg_and_die("corrupted data");
bb_error_msg_and_die("corrupted data");
/* read compressed block size */
src_len = read32();
if (src_len <= 0 || src_len > dst_len)
bb_simple_error_msg_and_die("corrupted data");
bb_error_msg_and_die("corrupted data");
if (dst_len > block_size) {
if (b2) {
@@ -846,7 +846,7 @@ static NOINLINE int lzo_decompress(uint32_t h_flags32)
r = lzo1x_decompress_safe(b1, src_len, b2, &d /*, NULL*/);
if (r != 0 /*LZO_E_OK*/ || dst_len != d) {
bb_simple_error_msg_and_die("corrupted data");
bb_error_msg_and_die("corrupted data");
}
dst = b2;
} else {
@@ -913,7 +913,7 @@ static void check_magic(void)
unsigned char magic[sizeof(lzop_magic)];
xread(0, magic, sizeof(magic));
if (memcmp(magic, lzop_magic, sizeof(lzop_magic)) != 0)
bb_simple_error_msg_and_die("bad magic number");
bb_error_msg_and_die("bad magic number");
}
/**********************************************************************/
@@ -1049,7 +1049,7 @@ static void lzo_set_method(header_t *h)
else if (option_mask32 & OPT_8)
level = 8;
#else
bb_simple_error_msg_and_die("high compression not compiled in");
bb_error_msg_and_die("high compression not compiled in");
#endif
}
+12 -25
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config RPM
//config: bool "rpm (32 kb)"
//config: bool "rpm (33 kb)"
//config: default y
//config: help
//config: Mini RPM applet - queries and extracts RPM packages.
@@ -83,9 +83,7 @@ struct globals {
void *map;
rpm_index *mytags;
int tagcount;
unsigned mapsize;
IF_VARIABLE_ARCH_PAGESIZE(unsigned pagesize;)
#define G_pagesize cached_pagesize(G.pagesize)
unsigned mapsize, pagesize;
} FIX_ALIASING;
#define G (*(struct globals*)bb_common_bufsiz1)
#define INIT_G() do { setup_common_bufsiz(); } while (0)
@@ -116,13 +114,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 +123,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;
@@ -150,10 +141,11 @@ static int rpm_gettags(const char *filename)
G.mytags = tags;
/* Map the store */
storepos = (storepos + G_pagesize) & -(int)G_pagesize;
storepos = (storepos + G.pagesize) & -(int)G.pagesize;
/* remember size for munmap */
G.mapsize = storepos;
G.map = mmap_read(fd, storepos);
/* some NOMMU systems prefer MAP_PRIVATE over MAP_SHARED */
G.map = mmap(0, storepos, PROT_READ, MAP_PRIVATE, fd, 0);
if (G.map == MAP_FAILED)
bb_perror_msg_and_die("mmap '%s'", filename);
@@ -322,7 +314,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;
}
@@ -364,7 +356,7 @@ int rpm_main(int argc, char **argv)
int opt, func = 0;
INIT_G();
INIT_PAGESIZE(G.pagesize);
G.pagesize = getpagesize();
while ((opt = getopt(argc, argv, "iqpldc")) != -1) {
switch (opt) {
@@ -507,7 +499,7 @@ int rpm_main(int argc, char **argv)
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config RPM2CPIO
//config: bool "rpm2cpio (21 kb)"
//config: bool "rpm2cpio (20 kb)"
//config: default y
//config: help
//config: Converts a RPM file into a CPIO archive.
@@ -531,7 +523,7 @@ int rpm2cpio_main(int argc UNUSED_PARAM, char **argv)
int rpm_fd;
INIT_G();
INIT_PAGESIZE(G.pagesize);
G.pagesize = getpagesize();
rpm_fd = rpm_gettags(argv[1]);
@@ -539,24 +531,19 @@ 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)
bb_simple_error_msg_and_die("error unpacking");
bb_error_msg_and_die("error unpacking");
if (ENABLE_FEATURE_CLEAN_UP) {
close(rpm_fd);
+128 -150
View File
@@ -23,7 +23,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config TAR
//config: bool "tar (39 kb)"
//config: bool "tar (40 kb)"
//config: default y
//config: help
//config: tar is an archiving program. It's commonly used with gzip to
@@ -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
@@ -233,7 +232,7 @@ static HardLinkInfo *findHardLinkInfo(HardLinkInfo *hlInfo, struct stat *statbuf
}
/* Put an octal string into the specified buffer.
* The number is zero padded and possibly NUL terminated.
* The number is zero padded and possibly null terminated.
* Stores low-order bits only if whole value does not fit. */
static void putOctal(char *cp, int len, off_t value)
{
@@ -255,37 +254,61 @@ 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)
{
struct prefilled {
static const struct {
char mode[8]; /* 100-107 */
char uid[8]; /* 108-115 */
char gid[8]; /* 116-123 */
char size[12]; /* 124-135 */
char mtime[12]; /* 136-147 */
} prefilled = {
"0000000",
"0000000",
"0000000",
"00000000000",
"00000000000",
};
struct tar_header_t header;
int size;
memset(&header, 0, sizeof(header));
header.typeflag = type;
strcpy(header.name, "././@LongLink");
/* This sets mode/uid/gid/mtime to "00...00<NUL>" strings */
memset((char*)&header + offsetof(struct tar_header_t, mode), /* make gcc-9.x happy */
'0', sizeof(struct prefilled));
header.mode [sizeof(header.mode ) - 1] = '\0';
header.uid [sizeof(header.uid ) - 1] = '\0';
header.gid [sizeof(header.gid ) - 1] = '\0';
/* header.size is filled by '0' now, will be corrected below */
header.mtime[sizeof(header.mtime) - 1] = '\0';
dir = !!dir; /* normalize: 0/1 */
size = strlen(name) + 1 + dir; /* GNU tar uses strlen+1 */
/* + dir: account for possible '/' */
memset(&header, 0, sizeof(header));
strcpy(header.name, "././@LongLink");
memcpy(header.mode, prefilled.mode, sizeof(prefilled));
PUT_OCTAL(header.size, size);
chksum_and_xwrite_tar_header(fd, &header);
header.typeflag = type;
chksum_and_xwrite(fd, &header);
/* Write filename[/] and pad the block. */
/* dir=0: writes 'name<NUL>', pads */
@@ -346,7 +369,7 @@ static int writeTarHeader(struct TarBallInfo *tbInfo,
/* If it is larger than 100 bytes, bail out */
if (header.linkname[sizeof(header.linkname)-1]) {
free(lpath);
bb_simple_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
return FALSE;
}
# endif
@@ -416,7 +439,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 +452,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) ? "/" : "");
}
@@ -465,25 +489,21 @@ static int exclude_file(const llist_t *excluded_files, const char *file)
# define exclude_file(excluded_files, file) 0
# endif
static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
const char *fileName,
struct stat *statbuf)
static int FAST_FUNC writeFileToTarball(const char *fileName, struct stat *statbuf,
void *userData, int depth UNUSED_PARAM)
{
struct TarBallInfo *tbInfo = (struct TarBallInfo *) state->userData;
struct TarBallInfo *tbInfo = (struct TarBallInfo *) userData;
const char *header_name;
int inputFileFd = -1;
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;
if (exclude_file(tbInfo->excludeList, header_name))
return SKIP; /* "do not recurse on this directory", no error message printed */
/* It is against the rules to archive a socket */
if (S_ISSOCK(statbuf->st_mode)) {
bb_error_msg("%s: socket ignored", fileName);
@@ -517,9 +537,12 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
return TRUE;
}
if (exclude_file(tbInfo->excludeList, header_name))
return SKIP;
# if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
if (strlen(header_name) >= NAME_SIZE) {
bb_simple_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
bb_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
return TRUE;
}
# endif
@@ -529,13 +552,13 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
/* open the file we want to archive, and make sure all is well */
inputFileFd = open_or_warn(fileName, O_RDONLY);
if (inputFileFd < 0) {
return FALSE; /* make recursive_action() return FALSE */
return FALSE;
}
}
/* Add an entry to the tarball */
if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
return FALSE; /* make recursive_action() return FALSE */
return FALSE;
}
/* If it was a regular file, write out the body */
@@ -573,71 +596,56 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
/* Don't inline: vfork scares gcc and pessimizes code */
static void NOINLINE vfork_compressor(int tar_fd, const char *gzip)
{
pid_t gzipPid;
// On Linux, vfork never unpauses parent early, although standard
// allows for that. Do we want to waste bytes checking for it?
# define WAIT_FOR_CHILD 0
volatile int vfork_exec_errno = 0;
struct fd_pair data;
struct fd_pair gzipDataPipe;
# if WAIT_FOR_CHILD
struct fd_pair status;
xpiped_pair(status);
struct fd_pair gzipStatusPipe;
xpiped_pair(gzipStatusPipe);
# endif
xpiped_pair(data);
xpiped_pair(gzipDataPipe);
signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
if (xvfork() == 0) {
gzipPid = xvfork();
if (gzipPid == 0) {
/* child */
int tfd;
/* NB: close _first_, then move fds! */
close(data.wr);
close(gzipDataPipe.wr);
# if WAIT_FOR_CHILD
close(status.rd);
/* status.wr will close only on exec -
close(gzipStatusPipe.rd);
/* gzipStatusPipe.wr will close only on exec -
* parent waits for this close to happen */
fcntl(status.wr, F_SETFD, FD_CLOEXEC);
fcntl(gzipStatusPipe.wr, F_SETFD, FD_CLOEXEC);
# endif
/* copy it: parent's tar_fd variable must not change */
tfd = tar_fd;
if (tfd == 0) {
/* Output tar fd may be zero.
* xmove_fd(data.rd, 0) would destroy it.
* Reproducer:
* exec 0>&-
* exec 1>&-
* tar czf Z.tar.gz FILE
* Swapping move_fd's order wouldn't work:
* data.rd is 1 and _it_ would be destroyed.
*/
tfd = dup(tfd);
}
xmove_fd(data.rd, 0);
xmove_fd(tfd, 1);
/* exec gzip/bzip2/... program */
//BB_EXECLP(gzip, gzip, "-f", (char *)0); - WRONG for "xz",
// if xz is an enabled applet, it'll be a version which
// can only decompress. We do need to execute external
// program, not applet.
execlp(gzip, gzip, "-f", (char *)0);
xmove_fd(gzipDataPipe.rd, 0);
xmove_fd(tar_fd, 1);
/* exec gzip/bzip2 program/applet */
BB_EXECLP(gzip, gzip, "-f", (char *)0);
vfork_exec_errno = errno;
_exit_FAILURE();
_exit(EXIT_FAILURE);
}
/* parent */
xmove_fd(data.wr, tar_fd);
close(data.rd);
xmove_fd(gzipDataPipe.wr, tar_fd);
close(gzipDataPipe.rd);
# if WAIT_FOR_CHILD
close(status.wr);
close(gzipStatusPipe.wr);
while (1) {
/* Wait until child execs (or fails to) */
char buf;
int n = full_read(status.rd, &buf, 1);
int n;
/* Wait until child execs (or fails to) */
n = full_read(gzipStatusPipe.rd, &buf, 1);
if (n < 0 /* && errno == EAGAIN */)
continue; /* try it again */
}
close(status.rd);
close(gzipStatusPipe.rd);
# endif
if (vfork_exec_errno) {
errno = vfork_exec_errno;
@@ -675,7 +683,7 @@ static NOINLINE int writeTarFile(
/* Read the directory/files and iterate over them one at a time */
while (filelist) {
if (!recursive_action(filelist->data, recurseFlags,
writeFileToTarball, writeFileToTarball, tbInfo)
writeFileToTarball, writeFileToTarball, tbInfo, 0)
) {
errorFlag = TRUE;
}
@@ -698,13 +706,13 @@ static NOINLINE int writeTarFile(
freeHardLinkInfo(&tbInfo->hlInfoHead);
if (errorFlag)
bb_simple_error_msg("error exit delayed from previous errors");
bb_error_msg("error exit delayed from previous errors");
# if SEAMLESS_COMPRESSION
if (gzip) {
int status;
if (safe_waitpid(-1, &status, 0) == -1)
bb_simple_perror_msg("waitpid");
bb_perror_msg("waitpid");
else if (!WIFEXITED(status) || WEXITSTATUS(status))
/* gzip was killed or has exited with nonzero! */
errorFlag = TRUE;
@@ -713,7 +721,11 @@ static NOINLINE int writeTarFile(
return errorFlag;
}
#endif /* FEATURE_TAR_CREATE */
#else /* !FEATURE_TAR_CREATE */
# define writeTarFile(...) 0
#endif
#if ENABLE_FEATURE_TAR_FROM
static llist_t *append_file_list_to_list(llist_t *list)
@@ -744,12 +756,12 @@ static llist_t *append_file_list_to_list(llist_t *list)
//usage: IF_FEATURE_SEAMLESS_GZ("z")
//usage: IF_FEATURE_SEAMLESS_XZ("J")
//usage: IF_FEATURE_SEAMLESS_BZ2("j")
//usage: "a"
//usage: IF_FEATURE_SEAMLESS_LZMA("a")
//usage: IF_FEATURE_TAR_CREATE("h")
//usage: IF_FEATURE_TAR_NOPRESERVE_TIME("m")
//usage: "vokO] "
//usage: "[-f TARFILE] [-C DIR] "
//usage: IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[LONGOPT]... "))
//usage: IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[--exclude PATTERN]... "))
//usage: "[FILE]..."
//usage:#define tar_full_usage "\n\n"
//usage: IF_FEATURE_TAR_CREATE("Create, extract, ")
@@ -784,11 +796,8 @@ static llist_t *append_file_list_to_list(llist_t *list)
//usage: "\n -j (De)compress using bzip2"
//usage: )
//usage: IF_FEATURE_SEAMLESS_LZMA(
//usage: IF_FEATURE_TAR_LONG_OPTIONS(
//usage: "\n --lzma (De)compress using lzma"
//usage: "\n -a (De)compress using lzma"
//usage: )
//usage: )
//usage: "\n -a (De)compress based on extension"
//usage: IF_FEATURE_TAR_CREATE(
//usage: "\n -h Follow symlinks"
//usage: )
@@ -799,36 +808,34 @@ static llist_t *append_file_list_to_list(llist_t *list)
//usage: "\n --exclude PATTERN Glob pattern to exclude"
//usage: )
//usage: )
//usage: IF_FEATURE_TAR_LONG_OPTIONS(
//usage: "\n --overwrite Replace existing files"
//usage: "\n --strip-components NUM NUM of leading components to strip"
//usage: "\n --no-recursion Don't descend in directories"
//usage: "\n --numeric-owner Use numeric user:group"
//usage: "\n --no-same-permissions Don't restore access permissions"
//usage: IF_FEATURE_TAR_TO_COMMAND(
//usage: "\n --to-command COMMAND Pipe files to COMMAND"
//usage: )
//usage: )
//usage:
//usage:#define tar_example_usage
//usage: "$ zcat /tmp/tarball.tar.gz | tar -xf -\n"
//usage: "$ tar -cf /tmp/tarball.tar /usr/local\n"
// Supported but aren't in --help:
// no-recursion
// numeric-owner
// no-same-permissions
// overwrite
//IF_FEATURE_TAR_TO_COMMAND(
// to-command
//)
enum {
OPTBIT_KEEP_OLD = 8,
IF_FEATURE_TAR_CREATE( OPTBIT_CREATE ,)
IF_FEATURE_TAR_CREATE( OPTBIT_DEREFERENCE ,)
IF_FEATURE_SEAMLESS_BZ2( OPTBIT_BZIP2 ,)
IF_FEATURE_SEAMLESS_LZMA(OPTBIT_LZMA ,)
IF_FEATURE_TAR_FROM( OPTBIT_INCLUDE_FROM,)
IF_FEATURE_TAR_FROM( OPTBIT_EXCLUDE_FROM,)
IF_FEATURE_SEAMLESS_GZ( OPTBIT_GZIP ,)
IF_FEATURE_SEAMLESS_XZ( OPTBIT_XZ ,)
IF_FEATURE_SEAMLESS_Z( OPTBIT_COMPRESS ,) // 16th bit
OPTBIT_AUTOCOMPRESS_BY_EXT,
IF_FEATURE_SEAMLESS_XZ( OPTBIT_XZ ,) // 16th bit
IF_FEATURE_SEAMLESS_Z( OPTBIT_COMPRESS ,)
IF_FEATURE_TAR_NOPRESERVE_TIME(OPTBIT_NOPRESERVE_TIME,)
#if ENABLE_FEATURE_TAR_LONG_OPTIONS
OPTBIT_STRIP_COMPONENTS,
IF_FEATURE_SEAMLESS_LZMA(OPTBIT_LZMA ,)
OPTBIT_NORECURSION,
IF_FEATURE_TAR_TO_COMMAND(OPTBIT_2COMMAND ,)
OPTBIT_NUMERIC_OWNER,
@@ -847,15 +854,14 @@ enum {
OPT_CREATE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_CREATE )) + 0, // c
OPT_DEREFERENCE = IF_FEATURE_TAR_CREATE( (1 << OPTBIT_DEREFERENCE )) + 0, // h
OPT_BZIP2 = IF_FEATURE_SEAMLESS_BZ2( (1 << OPTBIT_BZIP2 )) + 0, // j
OPT_LZMA = IF_FEATURE_SEAMLESS_LZMA((1 << OPTBIT_LZMA )) + 0, // a
OPT_INCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_INCLUDE_FROM)) + 0, // T
OPT_EXCLUDE_FROM = IF_FEATURE_TAR_FROM( (1 << OPTBIT_EXCLUDE_FROM)) + 0, // X
OPT_GZIP = IF_FEATURE_SEAMLESS_GZ( (1 << OPTBIT_GZIP )) + 0, // z
OPT_XZ = IF_FEATURE_SEAMLESS_XZ( (1 << OPTBIT_XZ )) + 0, // J
OPT_COMPRESS = IF_FEATURE_SEAMLESS_Z( (1 << OPTBIT_COMPRESS )) + 0, // Z
OPT_AUTOCOMPRESS_BY_EXT = 1 << OPTBIT_AUTOCOMPRESS_BY_EXT, // a
OPT_NOPRESERVE_TIME = IF_FEATURE_TAR_NOPRESERVE_TIME((1 << OPTBIT_NOPRESERVE_TIME)) + 0, // m
OPT_STRIP_COMPONENTS = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_STRIP_COMPONENTS)) + 0, // strip-components
OPT_LZMA = IF_FEATURE_TAR_LONG_OPTIONS(IF_FEATURE_SEAMLESS_LZMA((1 << OPTBIT_LZMA))) + 0, // lzma
OPT_NORECURSION = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NORECURSION )) + 0, // no-recursion
OPT_2COMMAND = IF_FEATURE_TAR_TO_COMMAND( (1 << OPTBIT_2COMMAND )) + 0, // to-command
OPT_NUMERIC_OWNER = IF_FEATURE_TAR_LONG_OPTIONS((1 << OPTBIT_NUMERIC_OWNER )) + 0, // numeric-owner
@@ -885,6 +891,9 @@ static const char tar_longopts[] ALIGN1 =
# if ENABLE_FEATURE_SEAMLESS_BZ2
"bzip2\0" No_argument "j"
# endif
# if ENABLE_FEATURE_SEAMLESS_LZMA
"lzma\0" No_argument "a"
# endif
# if ENABLE_FEATURE_TAR_FROM
"files-from\0" Required_argument "T"
"exclude-from\0" Required_argument "X"
@@ -898,14 +907,10 @@ static const char tar_longopts[] ALIGN1 =
# if ENABLE_FEATURE_SEAMLESS_Z
"compress\0" No_argument "Z"
# endif
"auto-compress\0" No_argument "a"
# if ENABLE_FEATURE_TAR_NOPRESERVE_TIME
"touch\0" No_argument "m"
# endif
"strip-components\0" Required_argument "\xf8"
# if ENABLE_FEATURE_SEAMLESS_LZMA
"lzma\0" No_argument "\xf9"
# endif
"strip-components\0" Required_argument "\xf9"
"no-recursion\0" No_argument "\xfa"
# if ENABLE_FEATURE_TAR_TO_COMMAND
"to-command\0" Required_argument "\xfb"
@@ -994,13 +999,13 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
"txC:f:Oopvk"
IF_FEATURE_TAR_CREATE( "ch" )
IF_FEATURE_SEAMLESS_BZ2( "j" )
IF_FEATURE_SEAMLESS_LZMA("a" )
IF_FEATURE_TAR_FROM( "T:*X:*")
IF_FEATURE_SEAMLESS_GZ( "z" )
IF_FEATURE_SEAMLESS_XZ( "J" )
IF_FEATURE_SEAMLESS_Z( "Z" )
"a"
IF_FEATURE_TAR_NOPRESERVE_TIME("m")
IF_FEATURE_TAR_LONG_OPTIONS("\xf8:") // --strip-components
IF_FEATURE_TAR_LONG_OPTIONS("\xf9:") // --strip-components
"\0"
"tt:vv:" // count -t,-v
#if ENABLE_FEATURE_TAR_LONG_OPTIONS && ENABLE_FEATURE_TAR_FROM
@@ -1010,7 +1015,7 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
IF_FEATURE_TAR_CREATE("c--tx:t--cx:x--ct") // mutually exclusive
IF_NOT_FEATURE_TAR_CREATE("t--x:x--t") // mutually exclusive
#if ENABLE_FEATURE_TAR_LONG_OPTIONS
":\xf8+" // --strip-components=NUM
":\xf9+" // --strip-components=NUM
#endif
LONGOPTS
, &base_dir // -C dir
@@ -1029,7 +1034,7 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
);
#if DBG_OPTION_PARSING
bb_error_msg("opt: 0x%08x", opt);
# define showopt(o) bb_error_msg("opt & %s(%x):\t%x", #o, o, opt & o);
# define showopt(o) bb_error_msg("opt & %s(%x): %x", #o, o, opt & o);
showopt(OPT_TEST );
showopt(OPT_EXTRACT );
showopt(OPT_BASEDIR );
@@ -1042,15 +1047,14 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
showopt(OPT_CREATE );
showopt(OPT_DEREFERENCE );
showopt(OPT_BZIP2 );
showopt(OPT_LZMA );
showopt(OPT_INCLUDE_FROM );
showopt(OPT_EXCLUDE_FROM );
showopt(OPT_GZIP );
showopt(OPT_XZ );
showopt(OPT_COMPRESS );
showopt(OPT_AUTOCOMPRESS_BY_EXT);
showopt(OPT_NOPRESERVE_TIME );
showopt(OPT_STRIP_COMPONENTS);
showopt(OPT_LZMA );
showopt(OPT_NORECURSION );
showopt(OPT_2COMMAND );
showopt(OPT_NUMERIC_OWNER );
@@ -1106,15 +1110,14 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
tar_handle->ah_flags &= ~ARCHIVE_RESTORE_DATE;
#if ENABLE_FEATURE_TAR_FROM
/* Convert each -X EXCLFILE to list of to-be-rejected glob patterns */
tar_handle->reject = append_file_list_to_list(tar_handle->reject);
# if ENABLE_FEATURE_TAR_LONG_OPTIONS
/* Append --exclude=GLOBPATTERNs to reject */
if (excludes) {
llist_t **p2next = &tar_handle->reject;
while (*p2next)
p2next = &((*p2next)->link);
*p2next = excludes;
/* Append excludes to reject */
while (excludes) {
llist_t *next = excludes->link;
excludes->link = tar_handle->reject;
tar_handle->reject = excludes;
excludes = next;
}
# endif
tar_handle->accept = append_file_list_to_list(tar_handle->accept);
@@ -1134,9 +1137,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;
@@ -1145,7 +1145,7 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
if (opt & OPT_CREATE) {
/* Make sure there is at least one file to tar up */
if (tar_handle->accept == NULL)
bb_simple_error_msg_and_die("empty archive");
bb_error_msg_and_die("empty archive");
tar_fd = STDOUT_FILENO;
/* Mimicking GNU tar 1.15.1: */
@@ -1155,39 +1155,17 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
if (LONE_DASH(tar_filename)) {
tar_handle->src_fd = tar_fd;
tar_handle->seek = seek_by_read;
} else
if (ENABLE_FEATURE_TAR_AUTODETECT
&& ENABLE_FEATURE_SEAMLESS_LZMA
&& flags == O_RDONLY
&& !(opt & OPT_ANY_COMPRESS)
&& is_suffixed_with(tar_filename, ".lzma")
/* We do this only for .lzma files, they have no signature.
* All other compression formats are recognized in
* get_header_tar() when first tar block has invalid format.
* Doing it here for all filenames would falsely trigger
* on e.g. tarball with 1st file named "BZh5".
*/
) {
tar_handle->src_fd = open_zipped(tar_filename, /*die_if_not_compressed:*/ 0);
if (tar_handle->src_fd < 0)
bb_perror_msg_and_die("can't open '%s'", tar_filename);
} else {
tar_handle->src_fd = xopen(tar_filename, flags);
#if ENABLE_FEATURE_TAR_CREATE
if ((OPT_GZIP | OPT_BZIP2 | OPT_XZ | OPT_LZMA) != 0 /* at least one is config-enabled */
&& (opt & OPT_AUTOCOMPRESS_BY_EXT)
&& flags != O_RDONLY
if (ENABLE_FEATURE_TAR_AUTODETECT
&& flags == O_RDONLY
&& !(opt & OPT_ANY_COMPRESS)
) {
if (OPT_GZIP != 0 && is_suffixed_with(tar_filename, "gz"))
opt |= OPT_GZIP;
if (OPT_BZIP2 != 0 && is_suffixed_with(tar_filename, "bz2"))
opt |= OPT_BZIP2;
if (OPT_XZ != 0 && is_suffixed_with(tar_filename, "xz"))
opt |= OPT_XZ;
if (OPT_LZMA != 0 && is_suffixed_with(tar_filename, "lzma"))
opt |= OPT_LZMA;
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 {
tar_handle->src_fd = xopen(tar_filename, flags);
}
#endif
}
}
+40 -105
View File
@@ -17,7 +17,7 @@
* Zip64 + other methods
*/
//config:config UNZIP
//config: bool "unzip (26 kb)"
//config: bool "unzip (24 kb)"
//config: default y
//config: help
//config: unzip will list or extract files from a ZIP archive,
@@ -56,17 +56,15 @@
//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)"
//usage: "\n -n Never overwrite files (default: ask)"
//usage: "\n -o Overwrite"
//usage: "\n -j Do not restore paths"
//usage: "\n -p Write to stdout"
//usage: "\n -t Test"
//usage: "\n -p Print to stdout"
//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"
@@ -84,13 +82,11 @@ enum {
ZIP_FILEHEADER_MAGIC = 0x504b0304,
ZIP_CDF_MAGIC = 0x504b0102, /* CDF item */
ZIP_CDE_MAGIC = 0x504b0506, /* End of CDF */
ZIP64_CDE_MAGIC = 0x504b0606, /* End of Zip64 CDF */
ZIP_DD_MAGIC = 0x504b0708,
#else
ZIP_FILEHEADER_MAGIC = 0x04034b50,
ZIP_CDF_MAGIC = 0x02014b50,
ZIP_CDE_MAGIC = 0x06054b50,
ZIP64_CDE_MAGIC = 0x06064b50,
ZIP_DD_MAGIC = 0x08074b50,
#endif
};
@@ -119,8 +115,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 ); \
@@ -159,15 +153,15 @@ typedef union {
#define FIX_ENDIANNESS_CDF(cdf) \
do { if (BB_BIG_ENDIAN) { \
(cdf).fmt.version_made_by = SWAP_LE16((cdf).fmt.version_made_by); \
(cdf).fmt.version_needed = SWAP_LE16((cdf).fmt.version_needed ); \
(cdf).fmt.method = SWAP_LE16((cdf).fmt.method ); \
(cdf).fmt.modtime = SWAP_LE16((cdf).fmt.modtime ); \
(cdf).fmt.moddate = SWAP_LE16((cdf).fmt.moddate ); \
(cdf).fmt.crc32 = SWAP_LE32((cdf).fmt.crc32 ); \
(cdf).fmt.cmpsize = SWAP_LE32((cdf).fmt.cmpsize ); \
(cdf).fmt.ucmpsize = SWAP_LE32((cdf).fmt.ucmpsize ); \
(cdf).fmt.filename_len = SWAP_LE16((cdf).fmt.filename_len ); \
(cdf).fmt.extra_len = SWAP_LE16((cdf).fmt.extra_len ); \
(cdf).fmt.version_needed = SWAP_LE16((cdf).fmt.version_needed); \
(cdf).fmt.method = SWAP_LE16((cdf).fmt.method ); \
(cdf).fmt.modtime = SWAP_LE16((cdf).fmt.modtime ); \
(cdf).fmt.moddate = SWAP_LE16((cdf).fmt.moddate ); \
(cdf).fmt.crc32 = SWAP_LE32((cdf).fmt.crc32 ); \
(cdf).fmt.cmpsize = SWAP_LE32((cdf).fmt.cmpsize ); \
(cdf).fmt.ucmpsize = SWAP_LE32((cdf).fmt.ucmpsize ); \
(cdf).fmt.filename_len = SWAP_LE16((cdf).fmt.filename_len); \
(cdf).fmt.extra_len = SWAP_LE16((cdf).fmt.extra_len ); \
(cdf).fmt.file_comment_length = SWAP_LE16((cdf).fmt.file_comment_length); \
(cdf).fmt.external_attributes = SWAP_LE32((cdf).fmt.external_attributes); \
}} while (0)
@@ -266,12 +260,6 @@ static uint32_t find_cdf_offset(void)
continue;
/* we found CDE! */
memcpy(cde.raw, p + 1, CDE_LEN);
dbg("cde.this_disk_no:%d", cde.fmt.this_disk_no );
dbg("cde.disk_with_cdf_no:%d", cde.fmt.disk_with_cdf_no );
dbg("cde.cdf_entries_on_this_disk:%d", cde.fmt.cdf_entries_on_this_disk);
dbg("cde.cdf_entries_total:%d", cde.fmt.cdf_entries_total );
dbg("cde.cdf_size:%d", cde.fmt.cdf_size );
dbg("cde.cdf_offset:%x", cde.fmt.cdf_offset );
FIX_ENDIANNESS_CDE(cde);
/*
* I've seen .ZIP files with seemingly valid CDEs
@@ -314,27 +302,19 @@ static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf)
dbg("got ZIP_CDE_MAGIC");
return 0; /* EOF */
}
if (magic == ZIP64_CDE_MAGIC) { /* seen in .zip with >4GB files */
dbg("got ZIP64_CDE_MAGIC");
return 0; /* EOF */
}
xread(zip_fd, cdf->raw, CDF_HEADER_LEN);
FIX_ENDIANNESS_CDF(*cdf);
dbg(" magic:%08x filename_len:%u extra_len:%u file_comment_length:%u",
magic,
dbg(" filename_len:%u extra_len:%u file_comment_length:%u",
(unsigned)cdf->fmt.filename_len,
(unsigned)cdf->fmt.extra_len,
(unsigned)cdf->fmt.file_comment_length
);
//TODO: require that magic == ZIP_CDF_MAGIC?
cdf_offset += 4 + CDF_HEADER_LEN
+ cdf->fmt.filename_len
+ cdf->fmt.extra_len
+ cdf->fmt.file_comment_length;
dbg("Next cdf_offset 0x%x", cdf_offset);
return cdf_offset;
};
#endif
@@ -342,7 +322,7 @@ static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf)
static void die_if_bad_fnamesize(unsigned sz)
{
if (sz > 0xfff) /* more than 4k?! no funny business please */
bb_simple_error_msg_and_die("bad archive");
bb_error_msg_and_die("bad archive");
}
static void unzip_skip(off_t skip)
@@ -379,7 +359,7 @@ static void unzip_extract_symlink(llist_t **symlink_placeholders,
xread(zip_fd, target, zip->fmt.ucmpsize);
} else {
#if 1
bb_simple_error_msg_and_die("compressed symlink is not supported");
bb_error_msg_and_die("compressed symlink is not supported");
#else
transformer_state_t xstate;
init_transformer_state(&xstate);
@@ -419,10 +399,10 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
if (zip->fmt.method == 8) {
/* Method 8 - inflate */
if (inflate_unzip(&xstate) < 0)
bb_simple_error_msg_and_die("inflate error");
bb_error_msg_and_die("inflate error");
/* Validate decompression - crc */
if (zip->fmt.crc32 != (xstate.crc32 ^ 0xffffffffL)) {
bb_simple_error_msg_and_die("crc error");
bb_error_msg_and_die("crc error");
}
}
#if ENABLE_FEATURE_UNZIP_BZIP2
@@ -432,7 +412,7 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
*/
xstate.bytes_out = unpack_bz2_stream(&xstate);
if (xstate.bytes_out < 0)
bb_simple_error_msg_and_die("inflate error");
bb_error_msg_and_die("inflate error");
}
#endif
#if ENABLE_FEATURE_UNZIP_LZMA
@@ -440,7 +420,7 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
/* Not tested yet */
xstate.bytes_out = unpack_lzma_stream(&xstate);
if (xstate.bytes_out < 0)
bb_simple_error_msg_and_die("inflate error");
bb_error_msg_and_die("inflate error");
}
#endif
#if ENABLE_FEATURE_UNZIP_XZ
@@ -448,7 +428,7 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
/* Not tested yet */
xstate.bytes_out = unpack_xz_stream(&xstate);
if (xstate.bytes_out < 0)
bb_simple_error_msg_and_die("inflate error");
bb_error_msg_and_die("inflate error");
}
#endif
else {
@@ -456,12 +436,10 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
}
/* Validate decompression - size */
if (zip->fmt.ucmpsize != 0xffffffff /* seen on files with >4GB uncompressed data */
&& zip->fmt.ucmpsize != xstate.bytes_out
) {
if (zip->fmt.ucmpsize != xstate.bytes_out) {
/* Don't die. Who knows, maybe len calculation
* was botched somewhere. After all, crc matched! */
bb_simple_error_msg("bad length");
bb_error_msg("bad length");
}
}
@@ -469,7 +447,7 @@ static void my_fgets80(char *buf80)
{
fflush_all();
if (!fgets(buf80, 80, stdin)) {
bb_simple_perror_msg_and_die("can't read standard input");
bb_perror_msg_and_die("can't read standard input");
}
}
@@ -478,9 +456,7 @@ static int get_lstat_mode(const char *dst_fn)
struct stat stat_buf;
if (lstat(dst_fn, &stat_buf) == -1) {
if (errno != ENOENT) {
bb_perror_msg_and_die("can't stat '%s'",
dst_fn
);
bb_perror_msg_and_die("can't stat '%s'", dst_fn);
}
/* File does not exist */
return -1;
@@ -495,7 +471,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 +534,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:lnopqxjv")) != -1) {
switch (i) {
case 'd': /* Extract to base directory */
base_dir = optarg;
@@ -584,14 +554,8 @@ int unzip_main(int argc, char **argv)
overwrite = O_ALWAYS;
break;
case 't': /* Extract files to /dev/null */
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 */
case 'p': /* Extract files to stdout and fall through to set verbosity */
dst_fd = STDOUT_FILENO;
/*fallthrough*/
case 'q': /* Be quiet */
quiet++;
@@ -610,10 +574,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 */
@@ -674,9 +634,7 @@ int unzip_main(int argc, char **argv)
break;
if (++i > 2) {
*ext = '\0';
bb_error_msg_and_die("can't open %s[.zip]",
src_fn
);
bb_error_msg_and_die("can't open %s[.zip]", src_fn);
}
strcpy(ext, extn[i - 1]);
}
@@ -684,21 +642,12 @@ int unzip_main(int argc, char **argv)
}
/* Change dir if necessary */
if (base_dir) {
/* -p DIR: try to create, errors don't matter.
* UnZip 6.00 does no multi-level mkdir (-p DIR1/DIR2 syntax),
* not using bb_make_directory() here (yet?)
*/
mkdir(base_dir, 0777);
if (base_dir)
xchdir(base_dir);
}
if (quiet <= 1) { /* not -qq */
if (quiet == 0) {
printf("Archive: %s\n",
printable_string(src_fn)
);
}
if (quiet == 0)
printf("Archive: %s\n", src_fn);
if (opts & OPT_l) {
puts(verbose ?
" Length Method Size Cmpr Date Time CRC-32 Name\n"
@@ -831,10 +780,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 +805,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)
@@ -886,8 +831,7 @@ int unzip_main(int argc, char **argv)
printf( "%9u " "%s " "%s\n",
(unsigned)zip.fmt.ucmpsize,
dtbuf,
printable_string(dst_fn)
);
dst_fn);
} else {
char method6[7];
unsigned long percents;
@@ -916,8 +860,7 @@ int unzip_main(int argc, char **argv)
(unsigned)percents,
dtbuf,
zip.fmt.crc32,
printable_string(dst_fn)
);
dst_fn);
total_size += zip.fmt.cmpsize;
}
total_usize += zip.fmt.ucmpsize;
@@ -943,7 +886,7 @@ int unzip_main(int argc, char **argv)
mode = get_lstat_mode(dst_fn);
if (mode == -1) { /* ENOENT */
if (!quiet) {
printf(" creating: %s\n", printable_string(dst_fn));
printf(" creating: %s\n", dst_fn);
}
unzip_create_leading_dirs(dst_fn);
if (bb_make_directory(dst_fn, dir_mode, FILEUTILS_IGNORE_CHMOD_ERR)) {
@@ -952,9 +895,7 @@ int unzip_main(int argc, char **argv)
} else {
if (!S_ISDIR(mode)) {
bb_error_msg_and_die("'%s' exists but is not a %s",
printable_string(dst_fn),
"directory"
);
dst_fn, "directory");
}
}
goto skip_cmpsize;
@@ -973,16 +914,12 @@ int unzip_main(int argc, char **argv)
if (!S_ISREG(mode)) {
fishy:
bb_error_msg_and_die("'%s' exists but is not a %s",
printable_string(dst_fn),
"regular file"
);
dst_fn, "regular file");
}
if (overwrite == O_ALWAYS) {
goto do_open_and_extract;
}
printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ",
printable_string(dst_fn)
);
printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
my_fgets80(key_buf);
/* User input could take a long time. Is it still a regular file? */
mode = get_lstat_mode(dst_fn);
@@ -1008,14 +945,12 @@ int unzip_main(int argc, char **argv)
/* O_NOFOLLOW defends against symlink attacks */
dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
#endif
do_extract:
if (!quiet) {
printf(/* zip.fmt.method == 0
? " extracting: %s\n"
: */ " inflating: %s\n",
printable_string(dst_fn)
);
: */ " inflating: %s\n", dst_fn);
}
do_extract:
#if ENABLE_FEATURE_UNZIP_CDF
if (S_ISLNK(file_mode)) {
if (dst_fd != STDOUT_FILENO) /* not -p? */
-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
+1
View File
@@ -16,6 +16,7 @@ CONFIG_HAVE_DOT_CONFIG=y
# CONFIG_EXTRA_COMPAT is not set
# CONFIG_INCLUDE_SUSv2 is not set
# CONFIG_USE_PORTABLE_CODE is not set
CONFIG_PLATFORM_LINUX=y
CONFIG_FEATURE_BUFFERS_USE_MALLOC=y
# CONFIG_FEATURE_BUFFERS_GO_ON_STACK is not set
# CONFIG_FEATURE_BUFFERS_GO_IN_BSS is not set
+3
View File
@@ -33,6 +33,7 @@
## Assorted header problems:
## # CONFIG_HOSTID is not set
## # CONFIG_FEATURE_SYNC_FANCY is not set - syncfs()
## # CONFIG_FEATURE_TOUCH_NODEREF is not set - lutimes()
## # CONFIG_LOGNAME is not set - getlogin_r()
## # CONFIG_LOADFONT is not set
## # CONFIG_SETFONT is not set
@@ -86,6 +87,7 @@ CONFIG_DESKTOP=y
# CONFIG_EXTRA_COMPAT is not set
CONFIG_INCLUDE_SUSv2=y
# CONFIG_USE_PORTABLE_CODE is not set
CONFIG_PLATFORM_LINUX=y
CONFIG_FEATURE_BUFFERS_USE_MALLOC=y
# CONFIG_FEATURE_BUFFERS_GO_ON_STACK is not set
# CONFIG_FEATURE_BUFFERS_GO_IN_BSS is not set
@@ -268,6 +270,7 @@ CONFIG_SYNC=y
CONFIG_TEST=y
CONFIG_FEATURE_TEST_64=y
CONFIG_TOUCH=y
# CONFIG_FEATURE_TOUCH_NODEREF is not set
CONFIG_FEATURE_TOUCH_SUSV3=y
CONFIG_TR=y
CONFIG_FEATURE_TR_CLASSES=y
+1
View File
@@ -16,6 +16,7 @@ CONFIG_DESKTOP=y
# CONFIG_EXTRA_COMPAT is not set
# CONFIG_INCLUDE_SUSv2 is not set
# CONFIG_USE_PORTABLE_CODE is not set
CONFIG_PLATFORM_LINUX=y
CONFIG_FEATURE_BUFFERS_USE_MALLOC=y
# CONFIG_FEATURE_BUFFERS_GO_ON_STACK is not set
# CONFIG_FEATURE_BUFFERS_GO_IN_BSS is not set
+2
View File
@@ -16,6 +16,7 @@ CONFIG_DESKTOP=y
# CONFIG_EXTRA_COMPAT is not set
# CONFIG_INCLUDE_SUSv2 is not set
# CONFIG_USE_PORTABLE_CODE is not set
CONFIG_PLATFORM_LINUX=y
CONFIG_FEATURE_BUFFERS_USE_MALLOC=y
# CONFIG_FEATURE_BUFFERS_GO_ON_STACK is not set
# CONFIG_FEATURE_BUFFERS_GO_IN_BSS is not set
@@ -193,6 +194,7 @@ CONFIG_SYNC=y
CONFIG_TEST=y
CONFIG_FEATURE_TEST_64=y
CONFIG_TOUCH=y
# CONFIG_FEATURE_TOUCH_NODEREF is not set
CONFIG_FEATURE_TOUCH_SUSV3=y
CONFIG_TR=y
CONFIG_FEATURE_TR_CLASSES=y
+367 -604
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -16,6 +16,7 @@ CONFIG_HAVE_DOT_CONFIG=y
# CONFIG_EXTRA_COMPAT is not set
CONFIG_INCLUDE_SUSv2=y
CONFIG_USE_PORTABLE_CODE=y
# CONFIG_PLATFORM_LINUX is not set
CONFIG_FEATURE_BUFFERS_USE_MALLOC=y
# CONFIG_FEATURE_BUFFERS_GO_ON_STACK is not set
# CONFIG_FEATURE_BUFFERS_GO_IN_BSS is not set
+2 -1
View File
@@ -7,8 +7,9 @@
* 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: select PLATFORM_LINUX
//config: help
//config: This program is used to change to another terminal.
//config: Example: chvt 4 (change to terminal /dev/tty4)
+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.
+2 -1
View File
@@ -8,8 +8,9 @@
* 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: select PLATFORM_LINUX
//config: help
//config: This program deallocates unused virtual consoles.
+2 -1
View File
@@ -7,8 +7,9 @@
* 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.3 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program dumps the kernel's keyboard translation table to
//config: stdout, in binary format. You can then use loadkmap to load it.
+2 -1
View File
@@ -7,8 +7,9 @@
* 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.6 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program prints active (foreground) console number.
+2 -1
View File
@@ -9,8 +9,9 @@
* 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 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program reports and sets keyboard mode.
+14 -12
View File
@@ -12,12 +12,14 @@
//config:config LOADFONT
//config: bool "loadfont (5.4 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program loads a console font from standard input.
//config:
//config:config SETFONT
//config: bool "setfont (24 kb)"
//config: bool "setfont (26 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: Allows to load console screen map. Useful for i18n.
//config:
@@ -223,7 +225,7 @@ static void do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize,
if (unicode == PSF2_SEPARATOR) {
break;
} else if (unicode == PSF2_STARTSEQ) {
bb_simple_error_msg_and_die("unicode sequences not implemented");
bb_error_msg_and_die("unicode sequences not implemented");
} else if (unicode >= 0xC0) {
if (unicode >= 0xFC)
unicode &= 0x01, maxct = 5;
@@ -237,12 +239,12 @@ static void do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize,
unicode &= 0x1F, maxct = 1;
do {
if (tailsz <= 0 || *inbuf < 0x80 || *inbuf > 0xBF)
bb_simple_error_msg_and_die("illegal UTF-8 character");
bb_error_msg_and_die("illegal UTF-8 character");
--tailsz;
unicode = (unicode << 6) + (*inbuf++ & 0x3F);
} while (--maxct > 0);
} else if (unicode >= 0x80) {
bb_simple_error_msg_and_die("illegal UTF-8 character");
bb_error_msg_and_die("illegal UTF-8 character");
}
#else
return;
@@ -279,7 +281,7 @@ static void do_load(int fd, unsigned char *buffer, size_t len)
if (len >= sizeof(struct psf1_header) && PSF1_MAGIC_OK(psf1h(buffer))) {
if (psf1h(buffer)->mode > PSF1_MAXMODE)
bb_simple_error_msg_and_die("unsupported psf file mode");
bb_error_msg_and_die("unsupported psf file mode");
if (psf1h(buffer)->mode & PSF1_MODE512)
fontsize = 512;
if (psf1h(buffer)->mode & PSF1_MODEHASTAB)
@@ -290,7 +292,7 @@ static void do_load(int fd, unsigned char *buffer, size_t len)
#if ENABLE_FEATURE_LOADFONT_PSF2
if (len >= sizeof(struct psf2_header) && PSF2_MAGIC_OK(psf2h(buffer))) {
if (psf2h(buffer)->version > PSF2_MAXVERSION)
bb_simple_error_msg_and_die("unsupported psf file version");
bb_error_msg_and_die("unsupported psf file version");
fontsize = psf2h(buffer)->length;
if (psf2h(buffer)->flags & PSF2_HAS_UNICODE_TABLE)
has_table = 2;
@@ -309,19 +311,19 @@ static void do_load(int fd, unsigned char *buffer, size_t len)
} else
#endif
{
bb_simple_error_msg_and_die("input file: bad length or unsupported font type");
bb_error_msg_and_die("input file: bad length or unsupported font type");
}
#if !defined(PIO_FONTX) || defined(__sparc__)
if (fontsize != 256)
bb_simple_error_msg_and_die("only fontsize 256 supported");
bb_error_msg_and_die("only fontsize 256 supported");
#endif
table = font + fontsize * charsize;
buffer += len;
if (table > buffer || (!has_table && table != buffer))
bb_simple_error_msg_and_die("input file: bad length");
bb_error_msg_and_die("input file: bad length");
do_loadfont(fd, font, height, width, charsize, fontsize);
@@ -359,7 +361,7 @@ int loadfont_main(int argc UNUSED_PARAM, char **argv)
buffer = xmalloc_read(STDIN_FILENO, &len);
// xmalloc_open_zipped_read_close(filename, &len);
if (!buffer)
bb_simple_perror_msg_and_die("error reading input font");
bb_perror_msg_and_die("error reading input font");
do_load(get_console_fd_or_die(), buffer, len);
return EXIT_SUCCESS;
@@ -399,7 +401,7 @@ setfont [-O font+umap.orig] [-o font.orig] [-om cmap.orig]
-V Version
*/
//usage:#define setfont_trivial_usage
//usage: "[-m MAPFILE] [-C TTY] FILE"
//usage: "FONT [-m MAPFILE] [-C TTY]"
//usage:#define setfont_full_usage "\n\n"
//usage: "Load a console font\n"
//usage: "\n -m MAPFILE Load console screen map"
@@ -500,7 +502,7 @@ int setfont_main(int argc UNUSED_PARAM, char **argv)
if (a < 0 || a >= E_TABSZ
|| b < 0 || b > 65535
) {
bb_simple_error_msg_and_die("map format");
bb_error_msg_and_die("map format");
}
// patch map
unicodes[a] = b;
+3 -2
View File
@@ -7,8 +7,9 @@
* 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.5 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program loads a keyboard translation table from
//config: standard input.
@@ -68,7 +69,7 @@ int loadkmap_main(int argc UNUSED_PARAM, char **argv)
xread(STDIN_FILENO, flags, 7);
if (!is_prefixed_with(flags, BINARY_KEYMAP_MAGIC))
bb_simple_error_msg_and_die("not a valid binary keymap");
bb_error_msg_and_die("not a valid binary keymap");
xread(STDIN_FILENO, flags, MAX_NR_KEYMAPS);
+4 -3
View File
@@ -8,8 +8,9 @@
* 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 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program is used to start a command on an unused
//config: virtual terminal.
@@ -86,7 +87,7 @@ static int get_vt_fd(void)
fd = open(DEV_CONSOLE, O_RDONLY | O_NONBLOCK);
if (fd >= 0 && !not_vt_fd(fd))
return fd;
bb_simple_error_msg_and_die("can't find open VT");
bb_error_msg_and_die("can't find open VT");
}
static int find_free_vtno(void)
@@ -97,7 +98,7 @@ static int find_free_vtno(void)
errno = 0;
/*xfunc_error_retval = 3; - do we need compat? */
if (ioctl(fd, VT_OPENQRY, &vtno) != 0 || vtno <= 0)
bb_simple_perror_msg_and_die("can't find open VT");
bb_perror_msg_and_die("can't find open VT");
// Not really needed, grep for DAEMON_CLOSE_EXTRA_FDS
// if (fd > 2)
// close(fd);
+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 (275 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 (756 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
+2 -1
View File
@@ -8,8 +8,9 @@
* 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.7 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: Redirect writes to /dev/console to another device,
//config: like the current tty while logged in via telnet.
+2 -1
View File
@@ -9,8 +9,9 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config SETKEYCODES
//config: bool "setkeycodes (2.4 kb)"
//config: bool "setkeycodes (1.7 kb)"
//config: default y
//config: select PLATFORM_LINUX
//config: help
//config: This program loads entries into the kernel's scancode-to-keycode
//config: map, allowing unusual keyboards to generate usable keycodes.
+2 -1
View File
@@ -9,8 +9,9 @@
* 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: select PLATFORM_LINUX
//config: help
//config: This program redirects the output console of kernel messages.
+6 -5
View File
@@ -7,8 +7,9 @@
* 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: select PLATFORM_LINUX
//config: help
//config: Shows keys pressed.
@@ -55,7 +56,7 @@ static void xset1(struct termios *t)
{
int ret = tcsetattr(STDIN_FILENO, TCSAFLUSH, t);
if (ret) {
bb_simple_perror_msg("can't tcsetattr for stdin");
bb_perror_msg("can't tcsetattr for stdin");
}
}
@@ -70,8 +71,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);
@@ -106,7 +107,7 @@ int showkey_main(int argc UNUSED_PARAM, char **argv)
xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)((option_mask32 & OPT_k) ? K_MEDIUMRAW : K_RAW));
// we should exit on any signal; signals should interrupt read
bb_signals_norestart(BB_FATAL_SIGS, record_signo);
bb_signals_recursive_norestart(BB_FATAL_SIGS, record_signo);
// inform user that program ends after time of inactivity
printf(press_keys, "10s after last keypress");
+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 (371 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;
}
+5 -7
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
@@ -152,7 +152,7 @@ static int catv(unsigned opts, char **argv)
eol_seen = (c == eol_char);
#endif
visible(c, buf, opts);
fputs_stdout(buf);
fputs(buf, stdout);
}
}
if (ENABLE_FEATURE_CLEAN_UP && fd)
@@ -195,20 +195,18 @@ int cat_main(int argc UNUSED_PARAM, char **argv)
# define CAT_OPT_b (1<<1)
if (opts & (CAT_OPT_n|CAT_OPT_b)) { /* -n or -b */
struct number_state ns;
int exitcode;
ns.width = 6;
ns.start = 1;
ns.inc = 1;
ns.sep = "\t";
ns.empty_str = NULL;
ns.empty_str = "\n";
ns.all = !(opts & CAT_OPT_b); /* -n without -b */
ns.nonempty = (opts & CAT_OPT_b); /* -b (with or without -n) */
exitcode = EXIT_SUCCESS;
do {
exitcode |= print_numbered_lines(&ns, *argv);
print_numbered_lines(&ns, *argv);
} while (*++argv);
fflush_stdout_and_exit(exitcode);
fflush_stdout_and_exit(EXIT_SUCCESS);
}
/*opts >>= 2;*/
#endif
+4 -8
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CHGRP
//config: bool "chgrp (7.6 kb)"
//config: bool "chgrp (7.2 kb)"
//config: default y
//config: help
//config: chgrp is used to change the group ownership of files.
@@ -21,18 +21,14 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/chgrp.html */
//usage:#define chgrp_trivial_usage
//usage: "[-Rh"IF_DESKTOP("LHPcvf")"]... GROUP FILE..."
//usage: "[-RhLHP"IF_DESKTOP("cvf")"]... GROUP FILE..."
//usage:#define chgrp_full_usage "\n\n"
//usage: "Change the group membership of FILEs to GROUP"
//usage: "\n"
//usage: "Change the group membership of each FILE to GROUP\n"
//usage: "\n -R Recurse"
//usage: "\n -h Affect symlinks instead of symlink targets"
//usage: IF_DESKTOP(
//usage: "\n -L Traverse all symlinks to directories"
//usage: "\n -H Traverse symlinks on command line only"
//usage: "\n -P Don't traverse symlinks (default)"
//usage: )
//next 4 options are the same for chmod/chown/chgrp:
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
+12 -16
View File
@@ -10,7 +10,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CHMOD
//config: bool "chmod (5.5 kb)"
//config: bool "chmod (5.1 kb)"
//config: default y
//config: help
//config: chmod is used to change the access permission of files.
@@ -26,13 +26,12 @@
//usage:#define chmod_trivial_usage
//usage: "[-R"IF_DESKTOP("cvf")"] MODE[,MODE]... FILE..."
//usage:#define chmod_full_usage "\n\n"
//usage: "MODE is octal number (bit pattern sstrwxrwxrwx) or [ugoa]{+|-|=}[rwxXst]"
//usage: "\n"
//next 4 options are the same for chmod/chown/chgrp:
//usage: "Each MODE is one or more of the letters ugoa, one of the\n"
//usage: "symbols +-= and one or more of the letters rwxst\n"
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -v List all files"
//usage: "\n -f Hide errors"
//usage: )
//usage:
@@ -66,14 +65,12 @@
* symbolic links encountered during recursive directory traversals.
*/
static int FAST_FUNC fileAction(struct recursive_state *state,
const char *fileName,
struct stat *statbuf)
static int FAST_FUNC fileAction(const char *fileName, struct stat *statbuf, void* param, int depth)
{
mode_t newmode;
/* match coreutils behavior */
if (state->depth == 0) {
if (depth == 0) {
/* statbuf holds lstat result, but we need stat (follow link) */
if (stat(fileName, statbuf))
goto err;
@@ -82,18 +79,16 @@ static int FAST_FUNC fileAction(struct recursive_state *state,
return TRUE;
}
newmode = bb_parse_mode((char *)state->userData, statbuf->st_mode);
newmode = bb_parse_mode((char *)param, statbuf->st_mode);
if (newmode == (mode_t)-1)
bb_error_msg_and_die("invalid mode '%s'", (char *)state->userData);
bb_error_msg_and_die("invalid mode '%s'", (char *)param);
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;
}
@@ -141,7 +136,8 @@ int chmod_main(int argc UNUSED_PARAM, char **argv)
OPT_RECURSE, // recurse
fileAction, // file action
fileAction, // dir action
smode) // user data
smode, // user data
0) // depth
) {
retval = EXIT_FAILURE;
}
+9 -12
View File
@@ -7,7 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CHOWN
//config: bool "chown (7.6 kb)"
//config: bool "chown (7.2 kb)"
//config: default y
//config: help
//config: chown is used to change the user and/or group ownership
@@ -28,19 +28,15 @@
//usage:#define chown_trivial_usage
//usage: "[-Rh"IF_DESKTOP("LHPcvf")"]... USER[:[GRP]] FILE..."
//usage:#define chown_full_usage "\n\n"
//usage: "Change the owner and/or group of FILEs to USER and/or GRP"
//usage: "\n"
//usage: "Change the owner and/or group of each FILE to USER and/or GRP\n"
//usage: "\n -R Recurse"
//usage: "\n -h Affect symlinks instead of symlink targets"
//usage: IF_DESKTOP(
//usage: "\n -L Traverse all symlinks to directories"
//usage: "\n -H Traverse symlinks on command line only"
//usage: "\n -P Don't traverse symlinks (default)"
//usage: )
//next 4 options are the same for chmod/chown/chgrp:
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -v List all files"
//usage: "\n -f Hide errors"
//usage: )
//usage:
@@ -101,10 +97,10 @@ struct param_t {
chown_fptr chown_func;
};
static int FAST_FUNC fileAction(struct recursive_state *state UNUSED_PARAM,
const char *fileName, struct stat *statbuf)
static int FAST_FUNC fileAction(const char *fileName, struct stat *statbuf,
void *vparam, int depth UNUSED_PARAM)
{
#define param (*(struct param_t*)state->userData)
#define param (*(struct param_t*)vparam)
#define opt option_mask32
uid_t u = (param.ugid.uid == (uid_t)-1L) ? statbuf->st_uid : param.ugid.uid;
gid_t g = (param.ugid.gid == (gid_t)-1L) ? statbuf->st_gid : param.ugid.gid;
@@ -163,7 +159,8 @@ int chown_main(int argc UNUSED_PARAM, char **argv)
flags, /* flags */
fileAction, /* file action */
fileAction, /* dir action */
&param) /* user data */
&param, /* user data */
0) /* depth */
) {
retval = EXIT_FAILURE;
}
+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.
+18 -40
View File
@@ -7,42 +7,34 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
//config:config CKSUM
//config: bool "cksum (4.3 kb)"
//config: default y
//config:
//config:config CRC32
//config: bool "crc32 (4.2 kb)"
//config: bool "cksum (4.2 kb)"
//config: default y
//config: help
//config: cksum is used to calculate the CRC32 checksum of a file.
// APPLET_NOEXEC:name main location suid_type help
//applet:IF_CKSUM(APPLET_NOEXEC(cksum, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
//applet:IF_CRC32(APPLET_NOEXEC(crc32, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
/* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
//kbuild:lib-$(CONFIG_CKSUM) += cksum.o
//kbuild:lib-$(CONFIG_CRC32) += cksum.o
//usage:#define cksum_trivial_usage
//usage: "FILE..."
//usage:#define cksum_full_usage "\n\n"
//usage: "Calculate CRC32 checksum of FILEs"
//usage: "Calculate the CRC32 checksums of FILEs"
#include "libbb.h"
#include "common_bufsiz.h"
/* This is a NOEXEC applet. Be very careful! */
#define IS_CKSUM (ENABLE_CKSUM && (!ENABLE_CRC32 || applet_name[1] == 'k'))
#define IS_CRC32 (ENABLE_CRC32 && (!ENABLE_CKSUM || applet_name[1] == 'r'))
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;
uint32_t *crc32_table = crc32_filltable(NULL, 1);
int exit_code = EXIT_SUCCESS;
#if ENABLE_DESKTOP
getopt32(argv, ""); /* cksum coreutils 6.9 compat */
getopt32(argv, ""); /* coreutils 6.9 compat */
argv += optind;
#else
argv++;
@@ -51,55 +43,41 @@ int cksum_main(int argc UNUSED_PARAM, char **argv)
setup_common_bufsiz();
do {
uint32_t crc;
IF_CKSUM(off_t filesize;)
const char *fname = *argv ? *argv : bb_msg_standard_input;
int fd = open_or_warn_stdin(fname);
off_t filesize;
int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
if (fd < 0) {
exit_code = EXIT_FAILURE;
continue;
}
crc = IS_CKSUM ? 0 : 0xffffffff;
IF_CKSUM(filesize = 0;)
crc = 0;
filesize = 0;
#define read_buf bb_common_bufsiz1
for (;;) {
uoff_t t;
int bytes_read = safe_read(fd, read_buf, COMMON_BUFSIZE);
if (bytes_read < 0)
bb_simple_perror_msg_and_die(fname);
if (bytes_read > 0) {
IF_CKSUM(filesize += bytes_read;)
filesize += bytes_read;
} else {
IF_CKSUM(uoff_t t;)
/* Checksum filesize bytes, LSB first, and exit */
close(fd);
if (IS_CRC32)
break;
#if ENABLE_CKSUM
fd = -1; /* break flag */
/* Checksum filesize bytes, LSB first */
t = filesize;
/*bytes_read = 0; - already is */
bytes_read = 0;
while (t != 0) {
read_buf[bytes_read++] = (uint8_t)t;
t >>= 8;
}
#endif
}
crc = (IS_CKSUM ? crc32_block_endian1 : crc32_block_endian0)(crc, read_buf, bytes_read, crc32_table);
if (ENABLE_CKSUM && fd < 0)
crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
if (fd < 0)
break;
}
crc = ~crc;
#if ENABLE_CKSUM
if (IS_CKSUM)
printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
(unsigned)crc, filesize, *argv);
else
#endif
printf((*argv ? "%08x %s\n" : "%08x\n"),
(unsigned)crc, *argv);
} while (*argv && *++argv);
fflush_stdout_and_exit(exit_code);
+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 (3.9 kb)"
//config: default y
//config: help
//config: comm is used to compare two files line by line and return
+98 -164
View File
@@ -12,7 +12,7 @@
* Size reduction.
*/
//config:config CP
//config: bool "cp (10 kb)"
//config: bool "cp (9.7 kb)"
//config: default y
//config: help
//config: cp is used to copy files and directories.
@@ -24,16 +24,6 @@
//config: help
//config: Enable long options.
//config: Also add support for --parents option.
//config:
//config:config FEATURE_CP_REFLINK
//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) */
@@ -42,57 +32,10 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cp.html */
// Options of cp from GNU coreutils 6.10:
// -a, --archive
// -f, --force
// -i, --interactive
// -l, --link
// -L, --dereference
// -P, --no-dereference
// -R, -r, --recursive
// -s, --symbolic-link
// -v, --verbose
// -H follow command-line symbolic links in SOURCE
// -d same as --no-dereference --preserve=links
// -p same as --preserve=mode,ownership,timestamps
// -c same as --preserve=context
// -u, --update
// copy only when the SOURCE file is newer than the destination
// file or when the destination file is missing
// --remove-destination
// remove each existing destination file before attempting to open
// --parents
// use full source file name under DIRECTORY
// -T, --no-target-directory
// treat DEST as a normal file
// NOT SUPPORTED IN BBOX:
// --backup[=CONTROL]
// make a backup of each existing destination file
// -b like --backup but does not accept an argument
// --copy-contents
// copy contents of special files when recursive
// --preserve[=ATTR_LIST]
// preserve attributes (default: mode,ownership,timestamps),
// if possible additional attributes: security context,links,all
// --no-preserve=ATTR_LIST
// --sparse=WHEN
// control creation of sparse files
// --strip-trailing-slashes
// remove any trailing slashes from each SOURCE argument
// -S, --suffix=SUFFIX
// override the usual backup suffix
// -t, --target-directory=DIRECTORY
// copy all SOURCE arguments into DIRECTORY
// -x, --one-file-system
// stay on this file system
// -Z, --context=CONTEXT
// (SELinux) set SELinux security context of copy to CONTEXT
//usage:#define cp_trivial_usage
//usage: "[-arPLHpfinlsTu] SOURCE DEST\n"
//usage: "or: cp [-arPLHpfinlsu] SOURCE... { -t DIRECTORY | DIRECTORY }"
//usage: "[OPTIONS] SOURCE... DEST"
//usage:#define cp_full_usage "\n\n"
//usage: "Copy SOURCEs to DEST\n"
//usage: "Copy SOURCE(s) to DEST\n"
//usage: "\n -a Same as -dpR"
//usage: IF_SELINUX(
//usage: "\n -c Preserve security context"
@@ -104,17 +47,13 @@
//usage: "\n -p Preserve file attributes if possible"
//usage: "\n -f Overwrite"
//usage: "\n -i Prompt before overwrite"
//usage: "\n -n Don't overwrite"
//usage: "\n -l,-s Create (sym)links"
//usage: "\n -T Refuse to copy if DEST is a directory"
//usage: "\n -t DIR Copy all SOURCEs into DIR"
//usage: "\n -T Treat DEST as a normal file"
//usage: "\n -u Copy only newer files"
#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;
@@ -128,89 +67,92 @@ int cp_main(int argc, char **argv)
int d_flags;
int flags;
int status;
#if ENABLE_FEATURE_CP_LONG_OPTIONS
enum {
/*OPT_rmdest = FILEUTILS_RMDEST = 1 << FILEUTILS_CP_OPTBITS */
OPT_parents = 1 << (FILEUTILS_CP_OPTBITS+1),
OPT_reflink = 1 << (FILEUTILS_CP_OPTBITS+2),
FILEUTILS_CP_OPTNUM = sizeof(FILEUTILS_CP_OPTSTR)-1,
#if ENABLE_FEATURE_CP_LONG_OPTIONS
/*OPT_rmdest = FILEUTILS_RMDEST = 1 << FILEUTILS_CP_OPTNUM */
OPT_parents = 1 << (FILEUTILS_CP_OPTNUM+1),
#endif
};
# if ENABLE_FEATURE_CP_REFLINK
char *reflink = NULL;
# endif
# if ENABLE_FEATURE_CP_SPARSE
char *sparse = NULL;
# endif
#if ENABLE_FEATURE_CP_LONG_OPTIONS
flags = getopt32long(argv, "^"
FILEUTILS_CP_OPTSTR
"\0"
// Need at least one argument. (Usually two+, but -t DIR can have only one)
// Need at least two arguments
// Soft- and hardlinking doesn't mix
// -P and -d are the same (-P is POSIX, -d is GNU)
// -r and -R are the same
// -R (and therefore -r) turns on -d (coreutils does this)
// -a = -pdR
// -i overrides -n and vice versa (last wins)
"-1:l--s:s--l:Pd:rRd:Rd:apdR:i-n:n-i",
"-2:l--s:s--l:Pd:rRd:Rd:apdR",
"archive\0" No_argument "a"
"force\0" No_argument "f"
"interactive\0" No_argument "i"
"no-clobber\0" No_argument "n"
"link\0" No_argument "l"
"dereference\0" No_argument "L"
"no-dereference\0" No_argument "P"
"recursive\0" No_argument "R"
"symbolic-link\0" No_argument "s"
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
"verbose\0" No_argument "v"
"update\0" No_argument "u"
"remove-destination\0" No_argument "\xff"
"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) {
if (!reflink)
flags |= FILEUTILS_REFLINK_ALWAYS;
else if (strcmp(reflink, "always") == 0)
flags |= FILEUTILS_REFLINK_ALWAYS;
else if (strcmp(reflink, "auto") != 0)
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
"\0"
"-1:l--s:s--l:Pd:rRd:Rd:apdR"
, &last
"-2:l--s:s--l:Pd:rRd:Rd:apdR"
);
#endif
/* Options of cp from GNU coreutils 6.10:
* -a, --archive
* -f, --force
* -i, --interactive
* -l, --link
* -L, --dereference
* -P, --no-dereference
* -R, -r, --recursive
* -s, --symbolic-link
* -v, --verbose
* -H follow command-line symbolic links in SOURCE
* -d same as --no-dereference --preserve=links
* -p same as --preserve=mode,ownership,timestamps
* -c same as --preserve=context
* -u, --update
* copy only when the SOURCE file is newer than the destination
* file or when the destination file is missing
* --remove-destination
* remove each existing destination file before attempting to open
* --parents
* use full source file name under DIRECTORY
* -T, --no-target-directory
* treat DEST as a normal file
* NOT SUPPORTED IN BBOX:
* --backup[=CONTROL]
* make a backup of each existing destination file
* -b like --backup but does not accept an argument
* --copy-contents
* copy contents of special files when recursive
* --preserve[=ATTR_LIST]
* preserve attributes (default: mode,ownership,timestamps),
* if possible additional attributes: security context,links,all
* --no-preserve=ATTR_LIST
* --sparse=WHEN
* control creation of sparse files
* --strip-trailing-slashes
* remove any trailing slashes from each SOURCE argument
* -S, --suffix=SUFFIX
* override the usual backup suffix
* -t, --target-directory=DIRECTORY
* copy all SOURCE arguments into DIRECTORY
* -x, --one-file-system
* stay on this file system
* -Z, --context=CONTEXT
* (SELinux) set SELinux security context of copy to CONTEXT
*/
argc -= optind;
argv += optind;
/* Reverse this bit. If there is -d, bit is not set: */
@@ -229,57 +171,49 @@ int cp_main(int argc, char **argv)
#endif
status = EXIT_SUCCESS;
if (!(flags & FILEUTILS_TARGET_DIR)) {
last = argv[argc - 1];
if (argc < 2)
bb_show_usage();
if (argc != 2) {
if (flags & FILEUTILS_NO_TARGET_DIR)
bb_show_usage();
/* "cp A B C... DIR" - target must be dir */
} else /* argc == 2 */ {
/* "cp A B" - only case where target can be not a dir */
s_flags = cp_mv_stat2(*argv, &source_stat,
(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);
if (d_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
last = argv[argc - 1];
/* If there are only two arguments and... */
if (argc == 2) {
s_flags = cp_mv_stat2(*argv, &source_stat,
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0)
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0)
return EXIT_FAILURE;
if (flags & FILEUTILS_NO_TARGET_DIR) { /* -T */
if (!(s_flags & 2) && (d_flags & 2))
/* cp -T NOTDIR DIR */
bb_error_msg_and_die("'%s' is a directory", last);
}
if (flags & FILEUTILS_NO_TARGET_DIR) { /* -T */
if (!(s_flags & 2) && (d_flags & 2))
/* cp -T NOTDIR DIR */
bb_error_msg_and_die("'%s' is a directory", last);
}
#if ENABLE_FEATURE_CP_LONG_OPTIONS
//bb_error_msg("flags:%x FILEUTILS_RMDEST:%x OPT_parents:%x",
// flags, FILEUTILS_RMDEST, OPT_parents);
if (flags & OPT_parents) {
if (!(d_flags & 2)) {
bb_simple_error_msg_and_die("with --parents, the destination must be a directory");
}
}
if (flags & FILEUTILS_RMDEST) {
flags |= FILEUTILS_FORCE;
}
#endif
/* ...if neither is a directory... */
if (!((s_flags | d_flags) & 2)
/* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */
|| ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
|| (flags & FILEUTILS_NO_TARGET_DIR)
) {
/* Do a simple copy */
dest = last;
goto DO_COPY; /* NB: argc==2 -> *++argv==last */
//bb_error_msg("flags:%x FILEUTILS_RMDEST:%x OPT_parents:%x",
// flags, FILEUTILS_RMDEST, OPT_parents);
if (flags & OPT_parents) {
if (!(d_flags & 2)) {
bb_error_msg_and_die("with --parents, the destination must be a directory");
}
}
if (flags & FILEUTILS_RMDEST) {
flags |= FILEUTILS_FORCE;
}
#endif
/* ...if neither is a directory... */
if (!((s_flags | d_flags) & 2)
/* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */
|| ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
|| (flags & FILEUTILS_NO_TARGET_DIR)
) {
/* Do a simple copy */
dest = last;
goto DO_COPY; /* NB: argc==2 -> *++argv==last */
}
} else if (flags & FILEUTILS_NO_TARGET_DIR) {
bb_error_msg_and_die("too many arguments");
}
/* else: last is DIR from "-t DIR" */
while (1) {
#if ENABLE_FEATURE_CP_LONG_OPTIONS
@@ -301,7 +235,7 @@ int cp_main(int argc, char **argv)
if (copy_file(*argv, dest, flags) < 0) {
status = EXIT_FAILURE;
}
if (!*++argv || *argv == last) {
if (*++argv == last) {
/* possibly leaking dest... */
break;
}
+184 -302
View File
@@ -9,52 +9,26 @@
* 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.3 kb)"
//config: default y
//config: help
//config: cut is used to print selected parts of lines from
//config: each file to stdout.
//config:
//config:config FEATURE_CUT_REGEX
//config: bool "cut -F"
//config: default y
//config: depends on CUT
//config: help
//config: Allow regex based delimiters.
//applet:IF_CUT(APPLET_NOEXEC(cut, cut, BB_DIR_USR_BIN, BB_SUID_DROP, cut))
//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: "Print selected fields from each input FILE 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 -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 -d CHAR Use CHAR instead of tab as the field delimiter"
//usage: "\n -s Output only the lines containing delimiter"
//usage: "\n -f N Print only these fields"
//usage: "\n -n Ignored"
//(manpage:-n with -b: don't split multibyte characters)
//usage:
//usage:#define cut_example_usage
//usage: "$ echo \"Hello world\" | cut -f 1 -d ' '\n"
@@ -64,358 +38,266 @@
#include "libbb.h"
#if ENABLE_FEATURE_CUT_REGEX
#include "xregex.h"
#endif
/* This is a NOEXEC applet. Be very careful! */
/* 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 OPT_STR "b:c:f:d:sn"
#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_SUPPRESS_FLGS (1 << 4)
#define opt_REGEX (option_mask32 & OPT_REGEX)
struct cut_list {
int startpos;
int endpos;
};
struct cut_range {
unsigned startpos;
unsigned endpos;
enum {
BOL = 0,
EOL = INT_MAX,
NON_RANGE = -1
};
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)
static void cut_file(FILE *file, char delim, const struct cut_list *cut_lists, unsigned nlists)
{
char *line;
unsigned linenum = 0; /* keep these zero-based to be consistent */
int first_print = 1;
/* go through every line in the file */
while ((line = xmalloc_fgetline(file)) != NULL) {
/* set up a list so we can keep track of what's been printed */
unsigned linelen = strlen(line);
int linelen = strlen(line);
char *printed = xzalloc(linelen + 1);
char *orig_line = line;
unsigned cl_pos = 0;
int spos;
/* 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;
for (; cl_pos < nlists; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
while (spos < linelen) {
if (!printed[spos]) {
printed[spos] = 'X';
if (need_odelim && spos != 0 && !printed[spos-1]) {
need_odelim = 0;
fputs_stdout(odelim);
}
putchar(line[spos]);
}
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
/* NON_RANGE is -1, so if below is true,
* the above was true too (spos is >= 0) */
/* || cut_lists[cl_pos].endpos == NON_RANGE */
) {
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
|| cut_lists[cl_pos].endpos == NON_RANGE
) {
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) */
} else { /* cut by fields */
int ndelim = -1; /* zero-based / one-based problem */
int nfields_printed = 0;
char *field = NULL;
char delimiter[2];
/* Blank line? Check -s (later check for -s does not catch empty lines) */
if (linelen == 0) {
if (option_mask32 & OPT_SUPPRESS)
goto next_line;
delimiter[0] = delim;
delimiter[1] = 0;
/* does this line contain any delimiters? */
if (strchr(line, delim) == NULL) {
if (!(option_mask32 & CUT_OPT_SUPPRESS_FLGS))
puts(line);
goto next_line;
}
if (!odelim)
odelim = "\t";
first_print = 1;
/* process each list on this line, for as long as we've got
* a line to process */
for (; cl_pos < nlists && line; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
do {
/* find the field we're looking for */
while (line && ndelim < spos) {
field = strsep(&line, delimiter);
ndelim++;
}
/* 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");
}
/* 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)
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;
/* we found it, and it hasn't been printed yet */
if (field && ndelim == spos && !printed[ndelim]) {
/* if this isn't our first time through, we need to
* print the delimiter after the last field that was
* printed */
if (nfields_printed > 0)
putchar(delim);
fputs(field, stdout);
printed[ndelim] = 'X';
nfields_printed++; /* shouldn't overflow.. */
}
//bb_error_msg("End of current line: s:%d e:%d", start, end);
} else {
/* Find next delimiter */
#if ENABLE_FEATURE_CUT_REGEX
if (opt_REGEX) {
regmatch_t rr;
regex_t *reg = (void*) delim;
if (regexec(reg, line + next, 1, &rr, REG_NOTBOL|REG_NOTEOL) != 0) {
/* not found, go to "end of line" logic */
next = 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;
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 */
spos++;
/* keep going as long as we have a line to work with,
* this is a list, and we're not at the end of that
* list */
} while (spos <= cut_lists[cl_pos].endpos && line
&& cut_lists[cl_pos].endpos != NON_RANGE);
}
}
/* if we printed anything, finish with newline */
/* if we printed anything at all, we need to finish it with a
* newline cuz we were handed a chomped line */
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;
const char *delim = NULL;
const char *odelim = NULL;
/* growable array holding a series of lists */
struct cut_list *cut_lists = NULL;
unsigned nlists = 0; /* number of elements in above list */
char delim = '\t'; /* delimiter, default is tab */
char *sopt, *ltok;
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_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";
opt = getopt32(argv, "^"
OPT_STR
"\0" "b--bcf:c--bcf:f--bcf",
&sopt, &sopt, &sopt, &ltok
);
// 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)))
bb_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);
if (opt & CUT_OPT_DELIM_FLGS) {
if (ltok[0] && ltok[1]) { /* more than 1 char? */
bb_error_msg_and_die("the delimiter must be a single character");
}
delim = ltok[0];
}
/* non-field (char or byte) cutting has some special handling */
if (!(opt & CUT_OPT_FIELDS_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 (delim != '\t') {
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 = BOL;
} 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 = NON_RANGE;
} else if (!ltok[0]) {
e = EOL;
} else {
e = xatoi_positive(ltok);
/* if the user specified and end position of 0,
* that means "til the end of the line" */
if (e == 0)
e = EOL;
e--; /* again, arrays are zero based, lines are 1 based */
if (e == s)
e = NON_RANGE;
}
/* add the new list */
cut_lists = xrealloc_vector(cut_lists, 4, nlists);
/* NB: startpos is always >= 0,
* while endpos may be = NON_RANGE (-1) */
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_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
*/
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 +308,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, 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);
}
}
+67 -58
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.1 kb)"
//config: default y
//config: help
//config: date is used to set the system date or display the
@@ -33,10 +33,12 @@
//config: Enable option (-I) to output an ISO-8601 compliant
//config: date/time string.
//config:
//config:# defaults to "no": stat's nanosecond field is a bit non-portable
//config:config FEATURE_DATE_NANO
//config: bool "Support %[num]N nanosecond format specifier"
//config: default n # stat's nanosecond field is a bit non-portable
//config: default n # syscall(__NR_clock_gettime)
//config: depends on DATE
//config: select PLATFORM_LINUX
//config: help
//config: Support %[num]N format specifier. Adds ~250 bytes of code.
//config:
@@ -52,7 +54,7 @@
//config: date -s (and other commands like touch -d) use more sensible
//config: formats (for one, ISO format YYYY-MM-DD hh:mm:ss.ssssss).
//config:
//config: With this option off, 'date DATE' and 'date -s DATE' support
//config: With this option off, 'date DATE' is 'date -s DATE' support
//config: the same format. With it on, 'date DATE' additionally supports
//config: MMDDhhmm[[YY]YY][.ss] format.
@@ -93,25 +95,36 @@
*/
//usage:#define date_trivial_usage
//usage: "[OPTIONS] [+FMT] [[-s] TIME]"
//usage: "[OPTIONS] [+FMT] [TIME]"
//usage:#define date_full_usage "\n\n"
//usage: "Display time (using +FMT), or set time\n"
//usage: "\n -u Work in UTC (don't convert to local time)"
//usage: IF_NOT_LONG_OPTS(
//usage: "\n [-s] TIME Set time to TIME"
//usage: "\n -d TIME Display TIME, not 'now'"
//usage: IF_FEATURE_DATE_ISOFMT(
//usage: "\n -D FMT FMT (strptime format) for -s/-d TIME conversion"
////////^^^^^^^^^^^^^^^^^^^^^^ busybox invention, not compat
//usage: "\n -u Work in UTC (don't convert to local time)"
//usage: "\n -R Output RFC-2822 compliant date string"
//usage: ) IF_LONG_OPTS(
//usage: "\n [-s,--set] TIME Set time to TIME"
//usage: "\n -u,--utc Work in UTC (don't convert to local time)"
//usage: "\n -R,--rfc-2822 Output RFC-2822 compliant date string"
//usage: )
//usage: "\n -r FILE Display last modification time of FILE"
//usage: "\n -R Output RFC-2822 date"
//usage: IF_FEATURE_DATE_ISOFMT(
//usage: "\n -I[SPEC] Output ISO-8601 date"
//usage: "\n SPEC=date (default), hours, minutes, seconds or ns"
//usage: "\n -I[SPEC] Output ISO-8601 compliant date string"
//usage: "\n SPEC='date' (default) for date only,"
//usage: "\n 'hours', 'minutes', or 'seconds' for date and"
//usage: "\n time to the indicated precision"
//usage: )
//usage: IF_NOT_LONG_OPTS(
//usage: "\n -r FILE Display last modification time of FILE"
//usage: "\n -d TIME Display TIME, not 'now'"
//usage: ) IF_LONG_OPTS(
//usage: "\n -r,--reference FILE Display last modification time of FILE"
//usage: "\n -d,--date TIME Display TIME, not 'now'"
//usage: )
//usage: IF_FEATURE_DATE_ISOFMT(
//usage: "\n -D FMT Use FMT for -d TIME conversion"
//usage: )
//usage: "\n"
//usage: "\nRecognized TIME formats:"
//usage: "\n @seconds_since_1970"
//usage: "\n hh:mm[:ss]"
//usage: "\n [YYYY.]MM.DD-hh:mm[:ss]"
//usage: "\n YYYY-MM-DD hh:mm[:ss]"
@@ -136,8 +149,8 @@ enum {
OPT_UTC = (1 << 2), /* u */
OPT_DATE = (1 << 3), /* d */
OPT_REFERENCE = (1 << 4), /* r */
OPT_ISO8601 = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
OPT_STR2DT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
OPT_TIMESPEC = (1 << 5) * ENABLE_FEATURE_DATE_ISOFMT, /* I */
OPT_HINT = (1 << 6) * ENABLE_FEATURE_DATE_ISOFMT, /* D */
};
#if ENABLE_LONG_OPTS
@@ -159,6 +172,12 @@ static const char date_longopts[] ALIGN1 =
* - after xasprintf we use other xfuncs
*/
static void maybe_set_utc(int opt)
{
if (opt & OPT_UTC)
putenv((char*)"TZ=UTC0");
}
int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int date_main(int argc UNUSED_PARAM, char **argv)
{
@@ -166,7 +185,7 @@ int date_main(int argc UNUSED_PARAM, char **argv)
struct tm tm_time;
char buf_fmt_dt2str[64];
unsigned opt;
int isofmt = -1;
int ifmt = -1;
char *date_str;
char *fmt_dt2str;
char *fmt_str2dt;
@@ -185,16 +204,15 @@ int date_main(int argc UNUSED_PARAM, char **argv)
);
argv += optind;
if (opt & OPT_UTC)
putenv((char*)"TZ=UTC0");
maybe_set_utc(opt);
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_ISO8601)) {
isofmt = 0; /* default is date */
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_TIMESPEC)) {
ifmt = 0; /* default is date */
if (isofmt_arg) {
static const char isoformats[] ALIGN1 =
"date\0""hours\0""minutes\0""seconds\0ns\0";
isofmt = index_in_substrings(isoformats, isofmt_arg);
if (isofmt < 0)
"date\0""hours\0""minutes\0""seconds\0"; /* ns? */
ifmt = index_in_substrings(isoformats, isofmt_arg);
if (ifmt < 0)
bb_show_usage();
}
}
@@ -204,7 +222,7 @@ int date_main(int argc UNUSED_PARAM, char **argv)
fmt_dt2str = &argv[0][1]; /* skip over the '+' */
argv++;
}
if (!(opt & (OPT_SET | OPT_DATE))) { /* neither -s TIME nor -d TIME? */
if (!(opt & (OPT_SET | OPT_DATE))) {
opt |= OPT_SET;
date_str = argv[0]; /* can be NULL */
if (date_str) {
@@ -254,42 +272,39 @@ int date_main(int argc UNUSED_PARAM, char **argv)
#endif
} else {
#if ENABLE_FEATURE_DATE_NANO
clock_gettime(CLOCK_REALTIME, &ts);
/* libc has incredibly messy way of doing this,
* typically requiring -lrt. We just skip all this mess */
syscall(__NR_clock_gettime, CLOCK_REALTIME, &ts);
#else
time(&ts.tv_sec);
#endif
}
#if !ENABLE_FEATURE_DATE_NANO
ts.tv_nsec = 0;
#endif
localtime_r(&ts.tv_sec, &tm_time);
/* 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;
tm_time.tm_hour = 0;
/* Process any date input to UNIX time since 1 Jan 1970 */
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_STR2DT)) {
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & OPT_HINT)) {
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");
if ((opt & OPT_SET) && stime(&ts.tv_sec) < 0) {
bb_perror_msg("can't set date");
}
}
@@ -299,34 +314,24 @@ int date_main(int argc UNUSED_PARAM, char **argv)
if (fmt_dt2str == NULL) {
int i;
fmt_dt2str = buf_fmt_dt2str;
if (ENABLE_FEATURE_DATE_ISOFMT && isofmt >= 0) {
/* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds 4:ns*/
if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
/* -I[SPEC]: 0:date 1:hours 2:minutes 3:seconds */
strcpy(fmt_dt2str, "%Y-%m-%dT%H:%M:%S");
i = 8 + 3 * isofmt;
if (isofmt != 0) {
int n;
if (isofmt == 4) {
i -= 3;
i += sprintf(&fmt_dt2str[i], ",%09u", (unsigned)ts.tv_nsec);
}
/* %z prints "+hhmm" timezone, but coreutils-8.30 prints "+hh:mm"! */
/* ...therefore this atrocity: */
n = strftime(&fmt_dt2str[i], 8, "%z", &tm_time);
i += n;
if (n == 5 && (fmt_dt2str[i-5] == '+' || fmt_dt2str[i-5] == '-')) {
/* "mm" -> ":mm" */
fmt_dt2str[i ] = fmt_dt2str[i - 1];
fmt_dt2str[i - 1] = fmt_dt2str[i - 2];
fmt_dt2str[i - 2] = ':';
i++;
}
i = 8 + 3 * ifmt;
if (ifmt != 0) {
/* TODO: if (ifmt==4) i += sprintf(&fmt_dt2str[i], ",%09u", nanoseconds); */
format_utc:
fmt_dt2str[i++] = '%';
fmt_dt2str[i++] = (opt & OPT_UTC) ? 'Z' : 'z';
}
fmt_dt2str[i] = '\0';
} else if (opt & OPT_RFC2822) {
/* -R. undo busybox.c setlocale */
if (ENABLE_LOCALE_SUPPORT)
setlocale(LC_TIME, "C");
fmt_dt2str = (char*)"%a, %d %b %Y %H:%M:%S %z";
strcpy(fmt_dt2str, "%a, %d %b %Y %H:%M:%S ");
i = sizeof("%a, %d %b %Y %H:%M:%S ")-1;
goto format_utc;
} else { /* default case */
fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
}
@@ -378,6 +383,10 @@ int date_main(int argc UNUSED_PARAM, char **argv)
/* With no format string, just print a blank line */
date_buf[0] = '\0';
} else {
/* Handle special conversions */
if (is_prefixed_with(fmt_dt2str, "%f")) {
fmt_dt2str = (char*)"%Y.%m.%d-%H:%M:%S";
}
/* Generate output string */
strftime(date_buf, COMMON_BUFSIZE, fmt_dt2str, &tm_time);
}
+67 -166
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.1 kb)"
//config: default y
//config: help
//config: dd copies a file (from standard input to standard output,
@@ -37,7 +37,7 @@
//config: elapsed time and speed.
//config:
//config:config FEATURE_DD_IBS_OBS
//config: bool "Enable ibs, obs, iflag, oflag and conv options"
//config: bool "Enable ibs, obs, iflag and conv options"
//config: default y
//config: depends on DD
//config: help
@@ -56,11 +56,8 @@
//kbuild:lib-$(CONFIG_DD) += dd.o
//usage:#define dd_trivial_usage
//usage: "[if=FILE] [of=FILE] [" IF_FEATURE_DD_IBS_OBS("ibs=N obs=N/") "bs=N] [count=N] [skip=N] [seek=N]"
//usage: IF_FEATURE_DD_IBS_OBS("\n"
//usage: " [conv=notrunc|noerror|sync|fsync]\n"
//usage: " [iflag=skip_bytes|count_bytes|fullblock|direct] [oflag=seek_bytes|append|direct]"
//usage: )
//usage: "[if=FILE] [of=FILE] " IF_FEATURE_DD_IBS_OBS("[ibs=N] [obs=N] ") "[bs=N] [count=N] [skip=N]\n"
//usage: " [seek=N]" IF_FEATURE_DD_IBS_OBS(" [conv=notrunc|noerror|sync|fsync] [iflag=skip_bytes|fullblock]")
//usage:#define dd_full_usage "\n\n"
//usage: "Copy a file with converting and formatting\n"
//usage: "\n if=FILE Read from FILE instead of stdin"
@@ -82,12 +79,7 @@
//usage: "\n conv=fsync Physically write data out before finishing"
//usage: "\n conv=swab Swap every pair of bytes"
//usage: "\n iflag=skip_bytes skip=N is in bytes"
//usage: "\n iflag=count_bytes count=N is in bytes"
//usage: "\n oflag=seek_bytes seek=N is in bytes"
//usage: "\n iflag=direct O_DIRECT input"
//usage: "\n oflag=direct O_DIRECT output"
//usage: "\n iflag=fullblock Read full blocks"
//usage: "\n oflag=append Open output in append mode"
//usage: )
//usage: IF_FEATURE_DD_STATUS(
//usage: "\n status=noxfer Suppress rate output"
@@ -137,22 +129,14 @@ enum {
FLAG_SWAB = (1 << 4) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of conv flags */
/* start of input flags */
FLAG_IFLAG_SHIFT = 5,
FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT_BYTES = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_FULLBLOCK = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IDIRECT = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IFLAG_SHIFT = 5,
FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_FULLBLOCK = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of input flags */
/* start of output flags */
FLAG_OFLAG_SHIFT = 9,
FLAG_SEEK_BYTES = (1 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_APPEND = (1 << 10) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_ODIRECT = (1 << 11) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of output flags */
FLAG_TWOBUFS = (1 << 12) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 13,
FLAG_STATUS_NONE = 1 << 14,
FLAG_STATUS_NOXFER = 1 << 15,
FLAG_TWOBUFS = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 8,
FLAG_STATUS_NONE = 1 << 9,
FLAG_STATUS_NOXFER = 1 << 10,
};
static void dd_output_status(int UNUSED_PARAM cur_signal)
@@ -177,9 +161,8 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
//So far we react to it (we print the stats),
//status=none only suppresses final, non-USR1 generated status message.
# endif
fprintf(stderr, /*G.total_bytes < 1024
? "%llu bytes copied, " : */ "%llu bytes (%sB) copied, "
, G.total_bytes,
fprintf(stderr, "%llu bytes (%sB) copied, ",
G.total_bytes,
/* show fractional digit, use suffixes */
make_human_readable_str(G.total_bytes, 1, 0)
);
@@ -199,59 +182,23 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
#endif
}
#if ENABLE_FEATURE_DD_IBS_OBS
# ifdef O_DIRECT
static int clear_O_DIRECT(int fd)
static ssize_t full_write_or_warn(const void *buf, size_t len,
const char *const filename)
{
if (errno == EINVAL) {
int fl = fcntl(fd, F_GETFL);
if (fl & O_DIRECT) {
fcntl(fd, F_SETFL, fl & ~O_DIRECT);
return 1;
}
}
return 0;
}
# endif
#endif
static ssize_t dd_read(void *ibuf, size_t ibs)
{
ssize_t n;
#if ENABLE_FEATURE_DD_IBS_OBS
read_again:
if (G.flags & FLAG_FULLBLOCK)
n = full_read(ifd, ibuf, ibs);
else
#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
ssize_t n = full_write(ofd, buf, len);
if (n < 0)
bb_perror_msg("writing '%s'", filename);
return n;
}
static bool write_and_stats(const void *buf, size_t len, size_t obs,
const char *filename)
{
ssize_t n;
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
ssize_t n = full_write_or_warn(buf, len, filename);
if (n < 0)
return 1;
#if ENABLE_FEATURE_DD_THIRD_STATUS_LINE
if (n > 0)
G.total_bytes += n;
G.total_bytes += n;
#endif
if ((size_t)n == obs) {
G.out_full++;
@@ -261,17 +208,15 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
G.out_part++;
return 0;
}
/* n is < len (and possibly is -1).
* Even if n >= 0, errno is usually set correctly.
* For example, if writing to block device and getting ENOSPC,
* full_write() first sees a short write, then tries to write
* the remainder and gets errno set to ENOSPC.
* It returns n > 0 (the amount which it did write).
*/
bb_perror_msg("error writing '%s'", filename);
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)
{
@@ -299,30 +244,20 @@ static int parse_comma_flags(char *val, const char *words, const char *error_in)
}
#endif
static void *alloc_buf(size_t size)
{
/* Important for "{i,o}flag=direct" - buffers must be page aligned */
if (size >= bb_getpagesize())
return xmmap_anon(size);
return xmalloc(size);
}
int dd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int dd_main(int argc UNUSED_PARAM, char **argv)
{
static const char keywords[] ALIGN1 =
"bs\0""count\0""seek\0""skip\0""if\0""of\0"IF_FEATURE_DD_STATUS("status\0")
#if ENABLE_FEATURE_DD_IBS_OBS
"ibs\0""obs\0""conv\0""iflag\0""oflag\0"
"ibs\0""obs\0""conv\0""iflag\0"
#endif
;
#if ENABLE_FEATURE_DD_IBS_OBS
static const char conv_words[] ALIGN1 =
"notrunc\0""sync\0""noerror\0""fsync\0""swab\0";
static const char iflag_words[] ALIGN1 =
"skip_bytes\0""count_bytes\0""fullblock\0""direct\0";
static const char oflag_words[] ALIGN1 =
"seek_bytes\0append\0""direct\0";
"skip_bytes\0""fullblock\0";
#endif
#if ENABLE_FEATURE_DD_STATUS
static const char status_words[] ALIGN1 =
@@ -341,7 +276,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
OP_obs,
OP_conv,
OP_iflag,
OP_oflag,
/* Must be in the same order as FLAG_XXX! */
OP_conv_notrunc = 0,
OP_conv_sync,
@@ -362,14 +296,10 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
/* Partially implemented: */
//swab swap every pair of input bytes: will abort on non-even reads
OP_iflag_skip_bytes,
OP_iflag_count_bytes,
OP_iflag_fullblock,
OP_iflag_direct,
OP_oflag_seek_bytes,
OP_oflag_direct,
#endif
};
exitcode_t exitcode = EXIT_FAILURE;
smallint exitcode = EXIT_FAILURE;
int i;
size_t ibs = 512;
char *ibuf;
@@ -382,13 +312,13 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
#endif
/* These are all zeroed at once! */
struct {
IF_FEATURE_DD_IBS_OBS(size_t ocount;)
size_t oc;
ssize_t prev_read_size; /* for detecting swab failure */
off_t count;
off_t seek, skip;
const char *infile, *outfile;
} Z;
#define ocount (Z.ocount )
#define oc (Z.oc )
#define prev_read_size (Z.prev_read_size)
#define count (Z.count )
#define seek (Z.seek )
@@ -438,10 +368,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
G.flags |= parse_comma_flags(val, iflag_words, "iflag") << FLAG_IFLAG_SHIFT;
/*continue;*/
}
if (what == OP_oflag) {
G.flags |= parse_comma_flags(val, oflag_words, "oflag") << FLAG_OFLAG_SHIFT;
/*continue;*/
}
#endif
if (what == OP_bs) {
ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, cwbkMG_suffixes);
@@ -451,15 +377,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) {
@@ -482,12 +408,13 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
#endif
} /* end of "for (argv[i])" */
ibuf = alloc_buf(ibs);
//XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
ibuf = xmalloc(ibs);
obuf = ibuf;
#if ENABLE_FEATURE_DD_IBS_OBS
if (ibs != obs) {
G.flags |= FLAG_TWOBUFS;
obuf = alloc_buf(obs);
obuf = xmalloc(obs);
}
#endif
@@ -499,17 +426,7 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
#endif
if (infile) {
int iflag = O_RDONLY;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_IDIRECT) {
# ifdef O_DIRECT
iflag |= O_DIRECT;
# else
bb_error_msg_and_die("O_DIRECT not supported on this platform");
# endif
}
#endif
xmove_fd(xopen(infile, iflag), ifd);
xmove_fd(xopen(infile, O_RDONLY), ifd);
} else {
infile = bb_msg_standard_input;
}
@@ -518,22 +435,11 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (!seek && !(G.flags & FLAG_NOTRUNC))
oflag |= O_TRUNC;
if (G.flags & FLAG_APPEND)
oflag |= O_APPEND;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_ODIRECT) {
# ifdef O_DIRECT
oflag |= O_DIRECT;
# else
bb_error_msg_and_die("O_DIRECT not supported on this platform");
# endif
}
#endif
xmove_fd(xopen(outfile, oflag), ofd);
if (seek && !(G.flags & FLAG_NOTRUNC)) {
size_t blocksz = (G.flags & FLAG_SEEK_BYTES) ? 1 : obs;
if (ftruncate(ofd, seek * blocksz) < 0) {
if (ftruncate(ofd, seek * obs) < 0) {
struct stat st;
if (fstat(ofd, &st) < 0
@@ -551,7 +457,13 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
size_t blocksz = (G.flags & FLAG_SKIP_BYTES) ? 1 : ibs;
if (lseek(ifd, skip * blocksz, SEEK_CUR) < 0) {
do {
ssize_t n = dd_read(ibuf, blocksz);
ssize_t n;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_FULLBLOCK)
n = full_read(ifd, ibuf, blocksz);
else
#endif
n = safe_read(ifd, ibuf, blocksz);
if (n < 0)
goto die_infile;
if (n == 0)
@@ -560,22 +472,18 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
}
}
if (seek) {
size_t blocksz = (G.flags & FLAG_SEEK_BYTES) ? 1 : obs;
if (lseek(ofd, seek * blocksz, SEEK_CUR) < 0)
if (lseek(ofd, seek * obs, SEEK_CUR) < 0)
goto die_outfile;
}
while (1) {
ssize_t n = ibs;
if (G.flags & FLAG_COUNT) {
if (count == 0)
break;
if ((G.flags & FLAG_COUNT_BYTES) && count < ibs)
n = count;
}
n = dd_read(ibuf, n);
while (!(G.flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
ssize_t n;
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_FULLBLOCK)
n = full_read(ifd, ibuf, ibs);
else
#endif
n = safe_read(ifd, ibuf, ibs);
if (n == 0)
break;
if (n < 0) {
@@ -610,7 +518,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
p16++;
}
}
count -= (G.flags & FLAG_COUNT_BYTES) ? n : 1;
if ((size_t)n == ibs)
G.in_full++;
else {
@@ -620,26 +527,24 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
n = ibs;
}
}
#if ENABLE_FEATURE_DD_IBS_OBS
if (G.flags & FLAG_TWOBUFS) {
char *tmp = ibuf;
while (n) {
size_t d = obs - ocount;
size_t d = obs - oc;
if (d > (size_t)n)
d = n;
memcpy(obuf + ocount, tmp, d);
memcpy(obuf + oc, tmp, d);
n -= d;
tmp += d;
ocount += d;
if (ocount == obs) {
oc += d;
if (oc == obs) {
if (write_and_stats(obuf, obs, obs, outfile))
goto out_status;
ocount = 0;
oc = 0;
}
}
} else
#endif
{
} else {
if (write_and_stats(ibuf, n, obs, outfile))
goto out_status;
}
@@ -650,12 +555,10 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
goto die_outfile;
}
#if ENABLE_FEATURE_DD_IBS_OBS
if (ocount != 0) {
if (write_and_stats(obuf, ocount, obs, outfile))
if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
if (write_and_stats(obuf, oc, obs, outfile))
goto out_status;
}
#endif
if (close(ifd) < 0) {
die_infile:
bb_simple_perror_msg_and_die(infile);
@@ -671,13 +574,11 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
if (!ENABLE_FEATURE_DD_STATUS || !(G.flags & FLAG_STATUS_NONE))
dd_output_status(0);
#if 0 /* can't just free(), they can be mmap()ed */
if (ENABLE_FEATURE_CLEAN_UP) {
free(obuf);
if (G.flags & FLAG_TWOBUFS)
free(ibuf);
}
#endif
return exitcode;
}
+26 -60
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 (7.5 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))
@@ -65,7 +45,7 @@
//usage: IF_FEATURE_HUMAN_READABLE("mh")
//usage: "T"
//usage: IF_FEATURE_DF_FANCY("ai] [-B SIZE")
//usage: "] [-t TYPE] [FILESYSTEM]..."
//usage: "] [FILESYSTEM]..."
//usage:#define df_full_usage "\n\n"
//usage: "Print filesystem usage statistics\n"
//usage: "\n -P POSIX output format"
@@ -75,7 +55,6 @@
//usage: "\n -h Human readable (e.g. 1K 243M 2G)"
//usage: )
//usage: "\n -T Print filesystem type"
//usage: "\n -t TYPE Print only mounts of this type"
//usage: IF_FEATURE_DF_FANCY(
//usage: "\n -a Show all filesystems"
//usage: "\n -i Inodes"
@@ -113,51 +92,39 @@ 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_ALL = (1 << 3) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (3 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
char *chp;
init_unicode();
/* From the manpage of df from coreutils-6.10:
* Disk space is shown in 1K blocks by default, unless the environment
* variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
*/
if (getenv("POSIXLY_CORRECT")) /* TODO - a new libbb function? */
df_disp_hr = 512;
opt = getopt32(argv, "^"
"kPTt:"
"kPT"
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"
#elif ENABLE_FEATURE_HUMAN_READABLE
"k-m:m-k"
#endif
, &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 +142,15 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
if (opt & (OPT_HUMAN|OPT_HUMANDEC)) {
/* From the manpage of df from coreutils-6.10:
* Disk space is shown in 1K blocks by default, unless the environment
* variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
*/
if (getenv("POSIXLY_CORRECT")) /* TODO - a new libbb function? */
df_disp_hr = 512;
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 +159,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
@@ -207,7 +178,7 @@ int df_main(int argc UNUSED_PARAM, char **argv)
if (!argv[0]) {
mount_table = setmntent(bb_path_mtab_file, "r");
if (!mount_table)
bb_simple_perror_msg_and_die(bb_path_mtab_file);
bb_perror_msg_and_die(bb_path_mtab_file);
}
while (1) {
@@ -243,11 +214,6 @@ int df_main(int argc UNUSED_PARAM, char **argv)
mount_point = mount_entry->mnt_dir;
fs_type = mount_entry->mnt_type;
if (opt & OPT_t) {
if (strcmp(fs_type, opt_t) != 0)
continue;
}
if (statvfs(mount_point, &s) != 0) {
bb_simple_perror_msg(mount_point);
goto set_error;
+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 (289 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.1 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.1 kb)"
//config: default y
//config: help
//config: unix2dos is used to convert a text file from UNIX format to
+19 -26
View File
@@ -19,16 +19,18 @@
* 4) Fixed busybox bug #1284 involving long overflow with human_readable.
*/
//config:config DU
//config: bool "du (6.5 kb)"
//config: bool "du (default blocksize of 512 bytes)"
//config: default y
//config: help
//config: du is used to report the amount of disk space used
//config: for specified files.
//config:
//config:config FEATURE_DU_DEFAULT_BLOCKSIZE_1K
//config: bool "Use default blocksize of 1024 bytes (else it's 512 bytes)"
//config: bool "Use a default blocksize of 1024 bytes (1K)"
//config: default y
//config: depends on DU
//config: help
//config: Use a blocksize of (1K) instead of the default 512b.
//applet:IF_DU(APPLET(du, BB_DIR_USR_BIN, BB_SUID_DROP))
@@ -40,9 +42,8 @@
//usage:#define du_trivial_usage
//usage: "[-aHLdclsx" IF_FEATURE_HUMAN_READABLE("hm") "k] [FILE]..."
//usage:#define du_full_usage "\n\n"
//usage: "Summarize disk space used for FILEs (or directories)\n"
//usage: "Summarize disk space used for each FILE and/or directory\n"
//usage: "\n -a Show file sizes too"
//usage: "\n -b Apparent size (including holes)"
//usage: "\n -L Follow all symlinks"
//usage: "\n -H Follow symlinks on command line"
//usage: "\n -d N Limit output to directories (and files with -a) of depth < N"
@@ -85,9 +86,8 @@ enum {
OPT_d_maxdepth = (1 << 6),
OPT_l_hardlinks = (1 << 7),
OPT_c_total = (1 << 8),
OPT_b = (1 << 9),
OPT_h_for_humans = (1 << 10),
OPT_m_mbytes = (1 << 11),
OPT_h_for_humans = (1 << 9),
OPT_m_mbytes = (1 << 10),
};
struct globals {
@@ -111,7 +111,7 @@ static void print(unsigned long long size, const char *filename)
/* TODO - May not want to defer error checking here. */
#if ENABLE_FEATURE_HUMAN_READABLE
# if ENABLE_DESKTOP
/* ~30 bytes of code for extra compat:
/* ~30 bytes of code for extra comtat:
* coreutils' du rounds sizes up:
* for example, 1025k file is shown as "2" by du -m.
* We round to nearest if human-readable [too hard to fix],
@@ -126,16 +126,12 @@ static void print(unsigned long long size, const char *filename)
* If G.disp_unit == 0, show one fractional
* and use suffixes
*/
make_human_readable_str(size, (option_mask32 & OPT_b) ? 1 : 512, G.disp_unit),
make_human_readable_str(size, 512, G.disp_unit),
filename);
#else
if (G.disp_k) {
if (!(option_mask32 & OPT_b)) {
size++;
size >>= 1;
} else {
size >>= 10;
}
size++;
size >>= 1;
}
printf("%llu\t%s\n", size, filename);
#endif
@@ -161,7 +157,7 @@ static unsigned long long du(const char *filename)
}
}
sum = ((option_mask32 & OPT_b) ? statbuf.st_size : statbuf.st_blocks);
sum = statbuf.st_blocks;
if (S_ISLNK(statbuf.st_mode)) {
if (G.slink_depth > G.du_depth) { /* -H or -L */
@@ -170,7 +166,7 @@ static unsigned long long du(const char *filename)
G.status = EXIT_FAILURE;
return 0;
}
sum = ((option_mask32 & OPT_b) ? statbuf.st_size : statbuf.st_blocks);
sum = statbuf.st_blocks;
if (G.slink_depth == 1) {
/* Convert -H to -L */
G.slink_depth = INT_MAX;
@@ -247,14 +243,11 @@ int du_main(int argc UNUSED_PARAM, char **argv)
*/
#if ENABLE_FEATURE_HUMAN_READABLE
opt = getopt32(argv, "^"
"aHkLsxd:+lcbhm"
"aHkLsxd:+lchm"
"\0" "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s",
&G.max_print_depth
);
argv += optind;
if (opt & OPT_b) {
G.disp_unit = 1;
}
if (opt & OPT_h_for_humans) {
G.disp_unit = 0;
}
@@ -266,16 +259,16 @@ int du_main(int argc UNUSED_PARAM, char **argv)
}
#else
opt = getopt32(argv, "^"
"aHkLsxd:+lcb"
"aHkLsxd:+lc"
"\0" "H-L:L-H:s-d:d-s",
&G.max_print_depth
);
argv += optind;
# if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
#if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
if (opt & OPT_k_kbytes) {
G.disp_k = 1;
}
# endif
#endif
#endif
if (opt & OPT_H_follow_links) {
G.slink_depth = 1;
@@ -299,11 +292,11 @@ int du_main(int argc UNUSED_PARAM, char **argv)
total = 0;
do {
total += du(*argv);
/* otherwise du /dir /dir won't show /dir twice: */
reset_ino_dev_hashtable();
G.slink_depth = slink_depth_save;
} while (*++argv);
if (ENABLE_FEATURE_CLEAN_UP)
reset_ino_dev_hashtable();
if (opt & OPT_c_total)
print(total, "total");
+11 -13
View File
@@ -19,10 +19,10 @@
* The previous version did not allow 4-digit octals.
*/
//config:config ECHO
//config: bool "echo (2 kb)"
//config: bool "echo (basic SuSv3 version taking no options)"
//config: default y
//config: help
//config: echo prints a specified string to stdout.
//config: echo is used to print a specified string to stdout.
//config:
//config:# this entry also appears in shell/Config.in, next to the echo builtin
//config:config FEATURE_FANCY_ECHO
@@ -43,10 +43,10 @@
//usage:#define echo_trivial_usage
//usage: IF_FEATURE_FANCY_ECHO("[-neE] ") "[ARG]..."
//usage:#define echo_full_usage "\n\n"
//usage: "Print ARGs to stdout"
//usage: "Print the specified ARGs to stdout"
//usage: IF_FEATURE_FANCY_ECHO( "\n"
//usage: "\n -n No trailing newline"
//usage: "\n -e Interpret backslash escapes (\\t=tab etc)"
//usage: "\n -n Suppress trailing newline"
//usage: "\n -e Interpret backslash escapes (i.e., \\t=tab)"
//usage: "\n -E Don't interpret backslash escapes (default)"
//usage: )
//usage:
@@ -87,7 +87,6 @@ int echo_main(int argc UNUSED_PARAM, char **argv)
char *out;
char *buffer;
unsigned buflen;
int err;
#if !ENABLE_FEATURE_FANCY_ECHO
enum {
eflag = 0, /* 0 -- disable escape sequences */
@@ -186,12 +185,13 @@ int echo_main(int argc UNUSED_PARAM, char **argv)
do_write:
/* Careful to error out on partial writes too (think ENOSPC!) */
errno = 0;
err = full_write(STDOUT_FILENO, buffer, out - buffer) != out - buffer;
if (err) {
bb_simple_perror_msg(bb_msg_write_error);
}
/*r =*/ full_write(STDOUT_FILENO, buffer, out - buffer);
free(buffer);
return err;
if (/*WRONG:r < 0*/ errno) {
bb_perror_msg(bb_msg_write_error);
return 1;
}
return 0;
}
/*
@@ -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);
}
Loaded 100 of 1385 files, more files were not shown because too many files have changed in this diff. Show more