Compare commits

..
661 changed files with 17574 additions and 35673 deletions

No files matched your search

+33 -57
View File
@@ -13,6 +13,22 @@ menu "Busybox Settings"
menu "General Configuration"
config NITPICK
bool "See lots more (probably unnecessary) configuration options."
default n
help
Some BusyBox applets have more configuration options than anyone
will ever care about. To avoid drowining people in complexity, most
of the applet features that can be set to a sane default value are
hidden, unless you hit the above switch.
This is better than to telling people to edit the busybox source
code, but not by much.
See http://en.wikipedia.org/wiki/Fibber_McGee_and_Molly#The_Closet
You have been warned.
config DESKTOP
bool "Enable options for full-blown desktop systems"
default n
@@ -21,21 +37,10 @@ config DESKTOP
Select this only if you plan to use busybox on full-blown
desktop machine with common Linux distro, not on an embedded box.
config FEATURE_ASSUME_UNICODE
bool "Assume that 1:1 char/glyph correspondence is not true"
default n
help
This makes various applets aware that one byte is not
one character on screen.
Busybox aims to eventually work correctly with Unicode displays.
Any older encodings are not guaranteed to work.
Probably by the time when busybox will be fully Unicode-clean,
other encodings will be mainly of historic interest.
choice
prompt "Buffer allocation policy"
default FEATURE_BUFFERS_USE_MALLOC
depends on NITPICK
help
There are 3 ways BusyBox can handle buffer allocations:
- Use malloc. This costs code size for the call to xmalloc.
@@ -106,7 +111,7 @@ config LOCALE_SUPPORT
busybox to support locale settings.
config GETOPT_LONG
bool "Support for --long-options"
bool "Enable support for --long-options"
default y
help
Enable this if you want busybox applets to use the gnu --long-option
@@ -125,6 +130,7 @@ config FEATURE_DEVPTS
config FEATURE_CLEAN_UP
bool "Clean up all memory before exiting (usually not needed)"
default n
depends on NITPICK
help
As a size optimization, busybox normally exits without explicitly
freeing dynamically allocated memory or closing files. This saves
@@ -274,31 +280,10 @@ config STATIC
Most people will leave this set to 'N'.
config PIE
bool "Build BusyBox as a position independent executable"
default n
depends on !STATIC
help
(TODO: what is it and why/when is it useful?)
Most people will leave this set to 'N'.
config NOMMU
bool "Force NOMMU build"
default n
help
Busybox tries to detect whether architecture it is being
built against supports MMU or not. If this detection fails,
or if you want to build NOMMU version of busybox for testing,
you may force NOMMU build here.
Most people will leave this set to 'N'.
# PIE can be made to work with BUILD_LIBBUSYBOX, but currently
# build system does not support that
config BUILD_LIBBUSYBOX
bool "Build shared libbusybox"
default n
depends on !FEATURE_PREFER_APPLETS && !PIE && !STATIC
depends on !FEATURE_PREFER_APPLETS
help
Build a shared library libbusybox.so.N.N.N which contains all
busybox code.
@@ -385,16 +370,6 @@ config LFS
cp, mount, tar, and many others. If you want to access files larger
than 2 Gigabytes, enable this option. Otherwise, leave it set to 'N'.
config CROSS_COMPILER_PREFIX
string "Cross Compiler prefix"
default ""
help
If you want to build BusyBox with a cross compiler, then you
will need to set this to the cross-compiler prefix, for example,
"i386-uclibc-". Note that CROSS_COMPILE environment variable
or "make CROSS_COMPILE=xxx ..." will override this selection.
For native build leave it empty.
endmenu
menu 'Debugging Options'
@@ -410,17 +385,6 @@ config DEBUG
Most people should answer N.
config DEBUG_PESSIMIZE
bool "Disable compiler optimizations."
default n
depends on DEBUG
help
The compiler's optimization of source code can eliminate and reorder
code, resulting in an executable that's hard to understand when
stepping through it with a debugger. This switches it off, resulting
in a much bigger executable that more closely matches the source
code.
config WERROR
bool "Abort compilation on any warning"
default n
@@ -429,6 +393,18 @@ config WERROR
Most people should answer N.
# Seems to be unused
#config DEBUG_PESSIMIZE
# bool "Disable compiler optimizations."
# default n
# depends on DEBUG
# help
# The compiler's optimization of source code can eliminate and reorder
# code, resulting in an executable that's hard to understand when
# stepping through it with a debugger. This switches it off, resulting
# in a much bigger executable that more closely matches the source
# code.
choice
prompt "Additional debugging library"
default NO_DEBUG_LIB
@@ -579,4 +555,4 @@ source shell/Config.in
source sysklogd/Config.in
source runit/Config.in
source selinux/Config.in
source printutils/Config.in
source ipsvd/Config.in
+26 -40
View File
@@ -1,6 +1,6 @@
VERSION = 1
PATCHLEVEL = 11
SUBLEVEL = 3
PATCHLEVEL = 9
SUBLEVEL = 2
EXTRAVERSION =
NAME = Unnamed
@@ -142,6 +142,17 @@ VPATH := $(srctree)$(if $(KBUILD_EXTMOD),:$(KBUILD_EXTMOD))
export srctree objtree VPATH TOPDIR
# SUBARCH tells the usermode build what the underlying arch is. That is set
# first, and if a usermode build is happening, the "ARCH=um" on the command
# line overrides the setting of ARCH below. If a native build is happening,
# then ARCH is assigned, getting whatever value it gets normally, and
# SUBARCH is subsequently ignored.
SUBARCH := $(shell uname -m | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ \
-e s/arm.*/arm/ -e s/sa110/arm/ \
-e s/s390x/s390/ -e s/parisc64/parisc/ \
-e s/ppc.*/powerpc/ -e s/mips.*/mips/ )
# Cross compiling and selecting different set of gcc/bin-utils
# ---------------------------------------------------------------------------
#
@@ -161,32 +172,8 @@ export srctree objtree VPATH TOPDIR
# Default value for CROSS_COMPILE is not to prefix executables
# Note: Some architectures assign CROSS_COMPILE in their arch/*/Makefile
CROSS_COMPILE ?=
# bbox: we may have CONFIG_CROSS_COMPILER_PREFIX in .config,
# and it has not been included yet... thus using an awkward syntax.
ifeq ($(CROSS_COMPILE),)
CROSS_COMPILE := $(shell grep ^CONFIG_CROSS_COMPILER_PREFIX .config 2>/dev/null)
CROSS_COMPILE := $(subst CONFIG_CROSS_COMPILER_PREFIX=,,$(CROSS_COMPILE))
CROSS_COMPILE := $(subst ",,$(CROSS_COMPILE))
endif
# SUBARCH tells the usermode build what the underlying arch is. That is set
# first, and if a usermode build is happening, the "ARCH=um" on the command
# line overrides the setting of ARCH below. If a native build is happening,
# then ARCH is assigned, getting whatever value it gets normally, and
# SUBARCH is subsequently ignored.
ifneq ($(CROSS_COMPILE),)
SUBARCH := $(shell echo $(CROSS_COMPILE) | cut -d- -f1)
else
SUBARCH := $(shell uname -m)
endif
SUBARCH := $(shell echo $(SUBARCH) | sed -e s/i.86/i386/ -e s/sun4u/sparc64/ \
-e s/arm.*/arm/ -e s/sa110/arm/ \
-e s/s390x/s390/ -e s/parisc64/parisc/ \
-e s/ppc.*/powerpc/ -e s/mips.*/mips/ )
ARCH ?= $(SUBARCH)
ARCH ?= $(SUBARCH)
CROSS_COMPILE ?=
# Architecture as present in compile.h
UTS_MACHINE := $(ARCH)
@@ -315,8 +302,6 @@ AFLAGS_KERNEL =
# Use LINUXINCLUDE when you must reference the include/ directory.
# Needed to be compatible with the O= option
CFLAGS := $(CFLAGS)
# Added only to final link stage of busybox binary
CFLAGS_busybox := $(CFLAGS_busybox)
CPPFLAGS := $(CPPFLAGS)
AFLAGS := $(AFLAGS)
LDFLAGS := $(LDFLAGS)
@@ -376,8 +361,7 @@ endif
# of make so .config is not included in this case either (for *config).
no-dot-config-targets := clean mrproper distclean \
cscope TAGS tags help %docs
#bbox# check% is removed from above
cscope TAGS tags help %docs check%
config-targets := 0
mixed-targets := 0
@@ -453,6 +437,7 @@ libs-y := \
editors/ \
findutils/ \
init/ \
ipsvd/ \
libbb/ \
libpwdgrp/ \
loginutils/ \
@@ -461,14 +446,12 @@ libs-y := \
networking/ \
networking/libiproute/ \
networking/udhcp/ \
printutils/ \
procps/ \
runit/ \
selinux/ \
shell/ \
sysklogd/ \
util-linux/ \
util-linux/volume_id/ \
endif # KBUILD_EXTMOD
@@ -513,6 +496,12 @@ all: busybox
#bbox# NOSTDINC_FLAGS += -nostdinc -isystem $(shell $(CC) -print-file-name=include)
CHECKFLAGS += $(NOSTDINC_FLAGS)
# warn about C99 declaration after statement
CFLAGS += $(call cc-option,-Wdeclaration-after-statement,)
# disable pointer signedness warnings in gcc 4.0
CFLAGS += $(call cc-option,-Wno-pointer-sign,)
# Default kernel image to build when no specific target is given.
# KBUILD_IMAGE may be overruled on the commandline or
# set in the environment
@@ -582,7 +571,6 @@ quiet_cmd_busybox__ ?= LINK $@
cmd_busybox__ ?= $(srctree)/scripts/trylink \
"$@" \
"$(CC)" \
"$(CFLAGS) $(CFLAGS_busybox)" \
"$(LDFLAGS) $(EXTRA_LDFLAGS)" \
"$(core-y)" \
"$(libs-y)" \
@@ -698,8 +686,6 @@ ifeq ($(SKIP_STRIP),y)
else
$(Q)$(STRIP) -s --remove-section=.note --remove-section=.comment \
busybox_unstripped -o $@
# strip is confused by PIE executable and does not set exec bits
$(Q)chmod a+x $@
endif
# The actual objects are generated when descending,
@@ -743,7 +729,7 @@ localver = $(subst $(space),, \
# Currently, only git is supported.
# Other SCMs can edit scripts/setlocalversion and add the appropriate
# checks as needed.
ifdef _BB_DISABLED_CONFIG_LOCALVERSION_AUTO
ifdef CONFIG_LOCALVERSION_AUTO
_localver-auto = $(shell $(CONFIG_SHELL) \
$(srctree)/scripts/setlocalversion $(srctree))
localver-auto = $(LOCALVERSION)$(_localver-auto)
@@ -856,7 +842,7 @@ depend dep:
# ---------------------------------------------------------------------------
# Modules
ifdef _BB_DISABLED_CONFIG_MODULES
ifdef CONFIG_MODULES
# By default, build modules as well
@@ -933,7 +919,7 @@ endif # CONFIG_MODULES
# Directories & files removed with 'make clean'
CLEAN_DIRS += $(MODVERDIR)
CLEAN_FILES += busybox busybox_unstripped* System.map .kernelrelease \
CLEAN_FILES += busybox* System.map .kernelrelease \
.tmp_kallsyms* .tmp_version .tmp_busybox* .tmp_System.map
# Directories & files removed with 'make mrproper'
+4 -9
View File
@@ -46,20 +46,15 @@ ifneq ($(strip $(DO_INSTALL_LIBS)),n)
done
endif
# Not very elegant: copies testsuite to objdir...
# (cp -pPR is POSIX-compliant (cp -dpR or cp -a would not be))
.PHONY: check
.PHONY: test
check test: busybox busybox.links
test -d $(objtree)/testsuite || cp -pPR $(srctree)/testsuite $(objtree)
bindir=$(objtree) srcdir=$(srctree)/testsuite \
$(SHELL) -c "cd $(objtree)/testsuite && $(srctree)/testsuite/runtest $(if $(KBUILD_VERBOSE:0=),-v)"
bindir=$(objtree) srcdir=$(srctree)/testsuite SED="$(SED)" \
$(SHELL) $(srctree)/testsuite/runtest $(if $(KBUILD_VERBOSE:0=),-v)
.PHONY: release
release: distclean
cd ..; \
rm -r -f busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION); \
cp -pPR busybox busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION) && { \
cp -a busybox busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION) && { \
find busybox-$(VERSION).$(PATCHLEVEL).$(SUBLEVEL)$(EXTRAVERSION)/ -type d \
-name .svn \
-print \
@@ -99,7 +94,7 @@ stksizes: busybox_unstripped
.PHONY: bigdata
bigdata: busybox_unstripped
$(CROSS_COMPILE)nm --size-sort busybox_unstripped | grep -vi ' [trw] '
$(CROSS_COMPILE)nm --size-sort busybox_unstripped | grep -vi ' [tr] '
# Documentation Targets
.PHONY: doc
+27 -41
View File
@@ -11,31 +11,37 @@ CPPFLAGS += $(call cc-option,-std=gnu99,)
CPPFLAGS += \
-Iinclude -Ilibbb \
$(if $(KBUILD_SRC),-Iinclude2 -I$(srctree)/include -I$(srctree)/libbb) \
$(if $(KBUILD_SRC),-Iinclude2 -I$(srctree)/include) -I$(srctree)/libbb \
-include include/autoconf.h \
-D_GNU_SOURCE -DNDEBUG \
$(if $(CONFIG_LFS),-D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE -D_FILE_OFFSET_BITS=64) \
-D"BB_VER=KBUILD_STR($(BB_VER))" -DBB_BT=AUTOCONF_TIMESTAMP
CFLAGS += $(call cc-option,-Wall,)
CFLAGS += $(call cc-option,-Wshadow,)
CFLAGS += $(call cc-option,-Wwrite-strings,)
CFLAGS += $(call cc-option,-Wundef,)
CFLAGS += $(call cc-option,-Wstrict-prototypes,)
CFLAGS += $(call cc-option,-Wunused -Wunused-parameter,)
CFLAGS += $(call cc-option,-Wmissing-prototypes -Wmissing-declarations,)
# 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
# still possible to build bbox without warnings.
# flag checks are grouped together to speed the checks up a bit..
CFLAGS += $(call cc-option,-Wall -Wshadow -Wwrite-strings,)
CFLAGS += $(call cc-option,-Wundef -Wstrict-prototypes,)
# If you want to add "-Wmissing-prototypes -Wmissing-declarations" above
# (or anything else for that matter) make sure that it is still possible
# to build bbox without warnings. Current offender: find.c:alloc_action().
# Looks more like gcc bug: gcc will warn on it with or without prototype.
# But still, warning-free compile is a must, or else we will drown
# in warnings pretty soon.
ifeq ($(CONFIG_WERROR),y)
CFLAGS += $(call cc-option,-Werror,)
else
# for development, warn a little bit about unused results..
CPPFLAGS += -D_FORTIFY_SOURCE=2
endif
# gcc 3.x emits bogus "old style proto" warning on find.c:alloc_action()
CFLAGS += $(call cc-ifversion, -ge, 0400, -Wold-style-definition)
CFLAGS += $(call cc-option,-fno-builtin-strlen -finline-limit=0 -fomit-frame-pointer -ffunction-sections -fdata-sections,)
# gcc emits bogus "no prev proto" warning on find.c:alloc_action()
ifneq ($(CONFIG_WERROR),y)
CFLAGS += $(call cc-option,-Wmissing-prototypes -Wmissing-declarations,)
endif
CFLAGS += $(call cc-option,-Os -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,)
@@ -46,38 +52,21 @@ CFLAGS += $(call cc-option,-falign-functions=1 -falign-jumps=1 -falign-labels=1
# be fixed..
#CFLAGS+=$(call cc-option,-Wconversion,)
ifneq ($(CONFIG_DEBUG),y)
CFLAGS += $(call cc-option,-Os,)
else
CFLAGS += $(call cc-option,-g,)
ifeq ($(CONFIG_DEBUG_PESSIMIZE),y)
CFLAGS += $(call cc-option,-O0,)
else
CFLAGS += $(call cc-option,-Os,)
ifeq ($(CONFIG_DEBUG),y)
CFLAGS += $(call cc-option,-g)
endif
endif
# If arch/$(ARCH)/Makefile did not override it (with, say, -fPIC)...
ARCH_FPIC ?= -fpic
ARCH_FPIE ?= -fpie
ARCH_PIE ?= -pie
ifeq ($(CONFIG_BUILD_LIBBUSYBOX),y)
# on i386: 14% smaller libbusybox.so
# (code itself is 9% bigger, we save on relocs/PLT/GOT)
CFLAGS += $(ARCH_FPIC)
CFLAGS += -fpic
# and another 4% reduction of libbusybox.so:
# (external entry points must be marked EXTERNALLY_VISIBLE)
CFLAGS += $(call cc-option,-fvisibility=hidden)
endif
ifeq ($(CONFIG_STATIC),y)
CFLAGS_busybox += -static
endif
ifeq ($(CONFIG_PIE),y)
CFLAGS_busybox += $(ARCH_PIE)
CFLAGS += $(ARCH_FPIE)
LDFLAGS += -static
endif
LDLIBS += m crypt
@@ -98,13 +87,10 @@ ifeq ($(CONFIG_DMALLOC),y)
LDLIBS += dmalloc
endif
# If a flat binary should be built, CFLAGS_busybox="-Wl,-elf2flt"
# env var should be set for make invocation.
# Here we check whether CFLAGS_busybox indeed contains that flag.
# (For historical reasons, we also check LDFLAGS, which doesn't
# seem to be entirely correct variable to put "-Wl,-elf2flt" into).
W_ELF2FLT = -Wl,-elf2flt
ifneq (,$(findstring $(W_ELF2FLT),$(LDFLAGS) $(CFLAGS_busybox)))
#LDFLAGS += -nostdlib
LDFLAGS_ELF2FLT = -Wl,-elf2flt
ifneq (,$(findstring $(LDFLAGS_ELF2FLT),$(LDFLAGS)))
SKIP_STRIP = y
endif
-3
View File
@@ -82,9 +82,6 @@ Downloading the current source code:
is generally a faster way of getting it fixed, and the complete archive of
what happened is the subversion changelog.
Note: if you want to compile busybox in a busybox environment you must
select ENABLE_DESKTOP.
----------------
getting help:
+25 -8
View File
@@ -6,17 +6,20 @@ do one of these bounce an email off the person it's listed under to see if they
have any suggestions how they plan to go about it, and to minimize conflicts
between your work and theirs. But otherwise, all of these are fair game.
Rob Landley suggested these:
Rob Landley <rob@landley.net>:
Add BB_NOMMU to platform.h and migrate __uClinux__ tests to that.
#if defined __UCLIBC__ && !defined __ARCH_USE_MMU__
Add a libbb/platform.c
Implement fdprintf() for platforms that haven't got one.
Implement bb_realpath() that can handle NULL on non-glibc.
Cleanup bb_asprintf()
Migrate calloc() and bb_calloc() occurrences to bb_xzalloc().
Remove obsolete _() wrapper crud for internationalization we don't do.
Figure out where we need utf8 support, and add it.
sh
The command shell situation is a big mess. We have three different
The command shell situation is a big mess. We have three or four different
shells that don't really share any code, and the "standalone shell" doesn't
work all that well (especially not in a chroot environment), due to apps not
being reentrant.
@@ -24,6 +27,11 @@ Rob Landley suggested these:
but less buggy :)
init
General cleanup (should use ENABLE_FEATURE_INIT_SYSLOG and ENABLE_FEATURE_INIT_DEBUG).
depmod
busybox lacks a way to update module deps when running from firmware without the
use of the depmod.pl (perl is to bloated for most embedded setups) and or orig
modutils. The orig depmod is rather pointless to have to add to a firmware image
in when we already have a insmod/rmmod and friends.
Do a SUSv3 audit
Look at the full Single Unix Specification version 3 (available online at
"http://www.opengroup.org/onlinepubs/009695399/nfindex.html") and
@@ -115,6 +123,9 @@ Bernhard Fischer <busybox@busybox.net> suggests to look at these:
As yet unclaimed:
----
find
doesn't understand (), lots of susv3 stuff.
----
diff
Make sure we handle empty files properly:
@@ -132,6 +143,10 @@ patch
And while we're at it, a new patch filename quoting format is apparently
coming soon: http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2
---
ps / top
Add support for both RSS and VSIZE rather than just one or the other.
Or make it a build option.
---
man
It would be nice to have a man command. Not one that handles troff or
anything, just one that can handle preformatted ascii man pages, possibly
@@ -141,7 +156,7 @@ man
(How doclifter might work into this is anybody's guess.)
---
ar
Write support!
Write support?
---
stty / catv
stty's visible() function and catv's guts are identical. Merge them into
@@ -277,22 +292,24 @@ Minor stuff:
---
use bb_perror_msg where appropriate: See
egrep "[^_]perror"
---
Remove superfluous fmt occurances: e.g.
fprintf(stderr, "%s: %s not found\n", "unalias", *argptr);
-> fprintf(stderr, "unalias: %s not found\n", *argptr);
---
possible code duplication ingroup() and is_a_group_member()
---
Move __get_hz() to a better place and (re)use it in route.c, ash.c, msh.c
---
See grep -r strtod
Alot of duplication that wants cleanup.
---
in_ether duplicated in network/{interface,ifconfig}.c
---
Code cleanup:
Replace deprecated functions.
bzero() -> memset()
---
sigblock(), siggetmask(), sigsetmask(), sigmask() -> sigprocmask et al
---
vdprintf() -> similar sized functionality
---
+69 -136
View File
@@ -1,7 +1,7 @@
#
# Automatically generated make config: don't edit
# Busybox version: 1.11.0.svn
# Mon Apr 21 23:20:35 2008
# Busybox version: 1.9.0.svn
# Mon Dec 24 14:21:28 2007
#
CONFIG_HAVE_DOT_CONFIG=y
@@ -12,6 +12,7 @@ CONFIG_HAVE_DOT_CONFIG=y
#
# General Configuration
#
CONFIG_NITPICK=y
CONFIG_DESKTOP=y
CONFIG_FEATURE_BUFFERS_USE_MALLOC=y
# CONFIG_FEATURE_BUFFERS_GO_ON_STACK is not set
@@ -28,7 +29,7 @@ CONFIG_FEATURE_PIDFILE=y
CONFIG_FEATURE_SUID=y
CONFIG_FEATURE_SUID_CONFIG=y
CONFIG_FEATURE_SUID_CONFIG_QUIET=y
CONFIG_SELINUX=y
# CONFIG_SELINUX is not set
CONFIG_FEATURE_PREFER_APPLETS=y
CONFIG_BUSYBOX_EXEC_PATH="/proc/self/exe"
CONFIG_FEATURE_SYSLOG=y
@@ -38,7 +39,6 @@ CONFIG_FEATURE_HAVE_RPC=y
# Build Options
#
# CONFIG_STATIC is not set
CONFIG_NOMMU=y
# CONFIG_BUILD_LIBBUSYBOX is not set
# CONFIG_FEATURE_INDIVIDUAL is not set
# CONFIG_FEATURE_SHARED_BUSYBOX is not set
@@ -48,7 +48,7 @@ CONFIG_LFS=y
# Debugging Options
#
# CONFIG_DEBUG is not set
# CONFIG_WERROR is not set
CONFIG_WERROR=y
CONFIG_NO_DEBUG_LIB=y
# CONFIG_DMALLOC is not set
# CONFIG_EFENCE is not set
@@ -72,17 +72,17 @@ CONFIG_PREFIX="./_install"
#
CONFIG_PASSWORD_MINLEN=6
CONFIG_MD5_SIZE_VS_SPEED=2
CONFIG_FEATURE_FAST_TOP=y
CONFIG_FEATURE_ETC_NETWORKS=y
# CONFIG_FEATURE_FAST_TOP is not set
# CONFIG_FEATURE_ETC_NETWORKS is not set
CONFIG_FEATURE_EDITING=y
CONFIG_FEATURE_EDITING_MAX_LEN=1024
CONFIG_FEATURE_EDITING_VI=y
# CONFIG_FEATURE_EDITING_FANCY_KEYS is not set
# CONFIG_FEATURE_EDITING_VI is not set
CONFIG_FEATURE_EDITING_HISTORY=15
# CONFIG_FEATURE_EDITING_SAVEHISTORY is not set
CONFIG_FEATURE_TAB_COMPLETION=y
CONFIG_FEATURE_USERNAME_COMPLETION=y
CONFIG_FEATURE_EDITING_FANCY_PROMPT=y
CONFIG_FEATURE_VERBOSE_CP_MESSAGE=y
CONFIG_FEATURE_COPYBUF_KB=4
CONFIG_MONOTONIC_SYSCALL=y
CONFIG_IOCTL_HEX2STR_ERROR=y
@@ -99,10 +99,9 @@ CONFIG_FEATURE_AR_LONG_FILENAMES=y
CONFIG_BUNZIP2=y
CONFIG_BZIP2=y
CONFIG_CPIO=y
CONFIG_FEATURE_CPIO_O=y
CONFIG_DPKG=y
CONFIG_DPKG_DEB=y
CONFIG_FEATURE_DPKG_DEB_EXTRACT_ONLY=y
# CONFIG_FEATURE_DPKG_DEB_EXTRACT_ONLY is not set
CONFIG_GUNZIP=y
CONFIG_FEATURE_GUNZIP_UNCOMPRESS=y
CONFIG_GZIP=y
@@ -111,17 +110,15 @@ CONFIG_RPM=y
CONFIG_FEATURE_RPM_BZ2=y
CONFIG_TAR=y
CONFIG_FEATURE_TAR_CREATE=y
CONFIG_FEATURE_TAR_GZIP=y
CONFIG_FEATURE_TAR_BZIP2=y
CONFIG_FEATURE_TAR_LZMA=y
CONFIG_FEATURE_TAR_COMPRESS=y
CONFIG_FEATURE_TAR_AUTODETECT=y
CONFIG_FEATURE_TAR_FROM=y
CONFIG_FEATURE_TAR_GZIP=y
CONFIG_FEATURE_TAR_COMPRESS=y
CONFIG_FEATURE_TAR_OLDGNU_COMPATIBILITY=y
CONFIG_FEATURE_TAR_OLDSUN_COMPATIBILITY=y
CONFIG_FEATURE_TAR_GNU_EXTENSIONS=y
CONFIG_FEATURE_TAR_LONG_OPTIONS=y
CONFIG_FEATURE_TAR_UNAME_GNAME=y
CONFIG_UNCOMPRESS=y
CONFIG_UNLZMA=y
CONFIG_FEATURE_LZMA_FAST=y
@@ -130,6 +127,7 @@ CONFIG_UNZIP=y
#
# Common options for cpio and tar
#
CONFIG_FEATURE_UNARCHIVE_TAPE=y
#
# Common options for dpkg and dpkg_deb
@@ -211,7 +209,6 @@ CONFIG_FEATURE_READLINK_FOLLOW=y
CONFIG_REALPATH=y
CONFIG_RM=y
CONFIG_RMDIR=y
CONFIG_FEATURE_RMDIR_LONG_OPTIONS=y
CONFIG_SEQ=y
CONFIG_SHA1SUM=y
CONFIG_SLEEP=y
@@ -225,7 +222,6 @@ CONFIG_FEATURE_STAT_FORMAT=y
CONFIG_STTY=y
CONFIG_SUM=y
CONFIG_SYNC=y
CONFIG_TAC=y
CONFIG_TAIL=y
CONFIG_FEATURE_FANCY_TAIL=y
CONFIG_TEE=y
@@ -318,7 +314,7 @@ CONFIG_PATCH=y
CONFIG_SED=y
CONFIG_VI=y
CONFIG_FEATURE_VI_MAX_LEN=4096
CONFIG_FEATURE_VI_8BIT=y
# CONFIG_FEATURE_VI_8BIT is not set
CONFIG_FEATURE_VI_COLON=y
CONFIG_FEATURE_VI_YANKMARK=y
CONFIG_FEATURE_VI_SEARCH=y
@@ -355,7 +351,7 @@ CONFIG_FEATURE_FIND_PRUNE=y
CONFIG_FEATURE_FIND_DELETE=y
CONFIG_FEATURE_FIND_PATH=y
CONFIG_FEATURE_FIND_REGEX=y
CONFIG_FEATURE_FIND_CONTEXT=y
# CONFIG_FEATURE_FIND_CONTEXT is not set
CONFIG_GREP=y
CONFIG_FEATURE_GREP_EGREP_ALIAS=y
CONFIG_FEATURE_GREP_FGREP_ALIAS=y
@@ -369,16 +365,14 @@ CONFIG_FEATURE_XARGS_SUPPORT_ZERO_TERM=y
#
# Init Utilities
#
CONFIG_INIT=y
# CONFIG_INIT is not set
# CONFIG_DEBUG_INIT is not set
CONFIG_FEATURE_USE_INITTAB=y
CONFIG_FEATURE_KILL_REMOVED=y
CONFIG_FEATURE_KILL_DELAY=1
CONFIG_FEATURE_INIT_SCTTY=y
CONFIG_FEATURE_INIT_SYSLOG=y
CONFIG_FEATURE_EXTRA_QUIET=y
CONFIG_FEATURE_INIT_COREDUMPS=y
CONFIG_FEATURE_INITRD=y
# CONFIG_FEATURE_USE_INITTAB is not set
# CONFIG_FEATURE_INIT_SCTTY is not set
# CONFIG_FEATURE_INIT_SYSLOG is not set
# CONFIG_FEATURE_EXTRA_QUIET is not set
# CONFIG_FEATURE_INIT_COREDUMPS is not set
# CONFIG_FEATURE_INITRD is not set
CONFIG_HALT=y
CONFIG_MESG=y
@@ -392,9 +386,7 @@ CONFIG_ADDGROUP=y
CONFIG_FEATURE_ADDUSER_TO_GROUP=y
CONFIG_DELGROUP=y
CONFIG_FEATURE_DEL_USER_FROM_GROUP=y
CONFIG_FEATURE_CHECK_NAMES=y
CONFIG_ADDUSER=y
CONFIG_FEATURE_ADDUSER_LONG_OPTIONS=y
CONFIG_DELUSER=y
CONFIG_GETTY=y
CONFIG_FEATURE_UTMP=y
@@ -402,7 +394,7 @@ CONFIG_FEATURE_WTMP=y
CONFIG_LOGIN=y
# CONFIG_PAM is not set
CONFIG_LOGIN_SCRIPTS=y
CONFIG_FEATURE_NOLOGIN=y
# CONFIG_FEATURE_NOLOGIN is not set
CONFIG_FEATURE_SECURETTY=y
CONFIG_PASSWD=y
CONFIG_FEATURE_PASSWD_WEAK_CHECK=y
@@ -463,7 +455,6 @@ CONFIG_FEATURE_SGI_LABEL=y
CONFIG_FEATURE_SUN_LABEL=y
CONFIG_FEATURE_OSF_LABEL=y
CONFIG_FEATURE_FDISK_ADVANCED=y
CONFIG_FINDFS=y
CONFIG_FREERAMDISK=y
CONFIG_FSCK_MINIX=y
CONFIG_MKFS_MINIX=y
@@ -474,8 +465,8 @@ CONFIG_MKFS_MINIX=y
CONFIG_FEATURE_MINIX2=y
CONFIG_GETOPT=y
CONFIG_HEXDUMP=y
CONFIG_FEATURE_HEXDUMP_REVERSE=y
CONFIG_HD=y
CONFIG_FEATURE_HEXDUMP_REVERSE=y
CONFIG_HWCLOCK=y
CONFIG_FEATURE_HWCLOCK_LONG_OPTIONS=y
CONFIG_FEATURE_HWCLOCK_ADJTIME_FHS=y
@@ -484,36 +475,14 @@ CONFIG_IPCS=y
CONFIG_LOSETUP=y
CONFIG_MDEV=y
CONFIG_FEATURE_MDEV_CONF=y
CONFIG_FEATURE_MDEV_RENAME=y
CONFIG_FEATURE_MDEV_RENAME_REGEXP=y
CONFIG_FEATURE_MDEV_EXEC=y
CONFIG_FEATURE_MDEV_LOAD_FIRMWARE=y
CONFIG_MKSWAP=y
CONFIG_FEATURE_MKSWAP_V0=y
CONFIG_MORE=y
CONFIG_FEATURE_USE_TERMIOS=y
CONFIG_VOLUMEID=y
CONFIG_FEATURE_VOLUMEID_EXT=y
CONFIG_FEATURE_VOLUMEID_REISERFS=y
CONFIG_FEATURE_VOLUMEID_FAT=y
CONFIG_FEATURE_VOLUMEID_HFS=y
CONFIG_FEATURE_VOLUMEID_JFS=y
CONFIG_FEATURE_VOLUMEID_XFS=y
CONFIG_FEATURE_VOLUMEID_NTFS=y
CONFIG_FEATURE_VOLUMEID_ISO9660=y
CONFIG_FEATURE_VOLUMEID_UDF=y
CONFIG_FEATURE_VOLUMEID_LUKS=y
CONFIG_FEATURE_VOLUMEID_LINUXSWAP=y
CONFIG_FEATURE_VOLUMEID_CRAMFS=y
CONFIG_FEATURE_VOLUMEID_ROMFS=y
CONFIG_FEATURE_VOLUMEID_SYSV=y
CONFIG_FEATURE_VOLUMEID_OCFS2=y
CONFIG_FEATURE_VOLUMEID_LINUXRAID=y
CONFIG_MOUNT=y
CONFIG_FEATURE_MOUNT_FAKE=y
CONFIG_FEATURE_MOUNT_VERBOSE=y
CONFIG_FEATURE_MOUNT_HELPERS=y
CONFIG_FEATURE_MOUNT_LABEL=y
CONFIG_FEATURE_MOUNT_NFS=y
CONFIG_FEATURE_MOUNT_CIFS=y
CONFIG_FEATURE_MOUNT_FLAGS=y
@@ -521,8 +490,6 @@ CONFIG_FEATURE_MOUNT_FSTAB=y
CONFIG_PIVOT_ROOT=y
CONFIG_RDATE=y
CONFIG_READPROFILE=y
CONFIG_RTCWAKE=y
CONFIG_SCRIPT=y
CONFIG_SETARCH=y
CONFIG_SWAPONOFF=y
CONFIG_SWITCH_ROOT=y
@@ -539,20 +506,12 @@ CONFIG_FEATURE_MOUNT_LOOP=y
# Miscellaneous Utilities
#
CONFIG_ADJTIMEX=y
CONFIG_BBCONFIG=y
CONFIG_CHAT=y
CONFIG_FEATURE_CHAT_NOFAIL=y
CONFIG_FEATURE_CHAT_TTY_HIFI=y
CONFIG_FEATURE_CHAT_IMPLICIT_CR=y
CONFIG_FEATURE_CHAT_SWALLOW_OPTS=y
CONFIG_FEATURE_CHAT_SEND_ESCAPES=y
CONFIG_FEATURE_CHAT_VAR_ABORT_LEN=y
CONFIG_FEATURE_CHAT_CLR_ABORT=y
# CONFIG_BBCONFIG is not set
CONFIG_CHRT=y
CONFIG_CROND=y
CONFIG_DEBUG_CROND_OPTION=y
CONFIG_FEATURE_CROND_CALL_SENDMAIL=y
CONFIG_CRONTAB=y
# CONFIG_CROND is not set
# CONFIG_DEBUG_CROND_OPTION is not set
# CONFIG_FEATURE_CROND_CALL_SENDMAIL is not set
# CONFIG_CRONTAB is not set
CONFIG_DC=y
# CONFIG_DEVFSD is not set
# CONFIG_DEVFSD_MODLOAD is not set
@@ -560,8 +519,6 @@ CONFIG_DC=y
# CONFIG_DEVFSD_VERBOSE is not set
# CONFIG_FEATURE_DEVFS is not set
CONFIG_EJECT=y
CONFIG_FEATURE_EJECT_SCSI=y
CONFIG_FBSPLASH=y
CONFIG_LAST=y
CONFIG_LESS=y
CONFIG_FEATURE_LESS_MAXLINES=9999999
@@ -580,7 +537,6 @@ CONFIG_FEATURE_HDPARM_HDIO_GETSET_DMA=y
CONFIG_MAKEDEVS=y
# CONFIG_FEATURE_MAKEDEVS_LEAF is not set
CONFIG_FEATURE_MAKEDEVS_TABLE=y
CONFIG_MAN=y
CONFIG_MICROCOM=y
CONFIG_MOUNTPOINT=y
CONFIG_MT=y
@@ -588,9 +544,8 @@ CONFIG_RAIDAUTORUN=y
CONFIG_READAHEAD=y
CONFIG_RUNLEVEL=y
CONFIG_RX=y
CONFIG_SETSID=y
CONFIG_STRINGS=y
CONFIG_SYMLINKS=y
CONFIG_SETSID=y
CONFIG_TASKSET=y
CONFIG_FEATURE_TASKSET_FANCY=y
CONFIG_TIME=y
@@ -605,9 +560,6 @@ CONFIG_FEATURE_PREFER_IPV4_ADDRESS=y
CONFIG_VERBOSE_RESOLUTION_ERRORS=y
CONFIG_ARP=y
CONFIG_ARPING=y
CONFIG_BRCTL=y
CONFIG_FEATURE_BRCTL_FANCY=y
CONFIG_FEATURE_BRCTL_SHOW=y
CONFIG_DNSD=y
CONFIG_ETHER_WAKE=y
CONFIG_FAKEIDENTD=y
@@ -635,23 +587,22 @@ CONFIG_FEATURE_IFCONFIG_SLIP=y
CONFIG_FEATURE_IFCONFIG_MEMSTART_IOADDR_IRQ=y
CONFIG_FEATURE_IFCONFIG_HW=y
CONFIG_FEATURE_IFCONFIG_BROADCAST_PLUS=y
CONFIG_IFENSLAVE=y
CONFIG_IFUPDOWN=y
CONFIG_IFUPDOWN_IFSTATE_PATH="/var/run/ifstate"
CONFIG_FEATURE_IFUPDOWN_IP=y
CONFIG_FEATURE_IFUPDOWN_IP_BUILTIN=y
# CONFIG_IFUPDOWN is not set
CONFIG_IFUPDOWN_IFSTATE_PATH=""
# CONFIG_FEATURE_IFUPDOWN_IP is not set
# CONFIG_FEATURE_IFUPDOWN_IP_BUILTIN is not set
# CONFIG_FEATURE_IFUPDOWN_IFCONFIG_BUILTIN is not set
CONFIG_FEATURE_IFUPDOWN_IPV4=y
CONFIG_FEATURE_IFUPDOWN_IPV6=y
CONFIG_FEATURE_IFUPDOWN_MAPPING=y
CONFIG_FEATURE_IFUPDOWN_EXTERNAL_DHCP=y
CONFIG_INETD=y
CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO=y
CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD=y
CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME=y
CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME=y
CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN=y
CONFIG_FEATURE_INETD_RPC=y
# CONFIG_FEATURE_IFUPDOWN_IPV4 is not set
# CONFIG_FEATURE_IFUPDOWN_IPV6 is not set
# CONFIG_FEATURE_IFUPDOWN_MAPPING is not set
# CONFIG_FEATURE_IFUPDOWN_EXTERNAL_DHCP is not set
# CONFIG_INETD is not set
# CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_ECHO is not set
# CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DISCARD is not set
# CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_TIME is not set
# CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_DAYTIME is not set
# CONFIG_FEATURE_INETD_SUPPORT_BUILTIN_CHARGEN is not set
# CONFIG_FEATURE_INETD_RPC is not set
CONFIG_IP=y
CONFIG_FEATURE_IP_ADDRESS=y
CONFIG_FEATURE_IP_LINK=y
@@ -678,11 +629,9 @@ CONFIG_FEATURE_NETSTAT_WIDE=y
CONFIG_NSLOOKUP=y
CONFIG_PING=y
CONFIG_PING6=y
CONFIG_FEATURE_FANCY_PING=y
CONFIG_PSCAN=y
CONFIG_FEATURE_FANCY_PING=y
CONFIG_ROUTE=y
CONFIG_SENDMAIL=y
CONFIG_FETCHMAIL=y
CONFIG_SLATTACH=y
CONFIG_TELNET=y
CONFIG_FEATURE_TELNET_TTYPE=y
@@ -690,11 +639,10 @@ CONFIG_FEATURE_TELNET_AUTOLOGIN=y
CONFIG_TELNETD=y
CONFIG_FEATURE_TELNETD_STANDALONE=y
CONFIG_TFTP=y
CONFIG_TFTPD=y
CONFIG_FEATURE_TFTP_GET=y
CONFIG_FEATURE_TFTP_PUT=y
CONFIG_FEATURE_TFTP_BLOCKSIZE=y
CONFIG_DEBUG_TFTP=y
# CONFIG_DEBUG_TFTP is not set
CONFIG_TRACEROUTE=y
CONFIG_FEATURE_TRACEROUTE_VERBOSE=y
CONFIG_FEATURE_TRACEROUTE_SOURCE_ROUTE=y
@@ -703,13 +651,10 @@ CONFIG_APP_UDHCPD=y
CONFIG_APP_DHCPRELAY=y
CONFIG_APP_DUMPLEASES=y
CONFIG_FEATURE_UDHCPD_WRITE_LEASES_EARLY=y
CONFIG_DHCPD_LEASES_FILE="/var/lib/misc/udhcpd.leases"
CONFIG_APP_UDHCPC=y
CONFIG_FEATURE_UDHCPC_ARPING=y
CONFIG_FEATURE_UDHCP_PORT=y
CONFIG_FEATURE_UDHCP_DEBUG=y
CONFIG_FEATURE_RFC3397=y
CONFIG_DHCPC_DEFAULT_SCRIPT="/usr/share/udhcpc/default.script"
CONFIG_UDHCPC_SLACK_FOR_BUGGY_SERVERS=80
CONFIG_VCONFIG=y
CONFIG_WGET=y
@@ -717,8 +662,6 @@ CONFIG_FEATURE_WGET_STATUSBAR=y
CONFIG_FEATURE_WGET_AUTHENTICATION=y
CONFIG_FEATURE_WGET_LONG_OPTIONS=y
CONFIG_ZCIP=y
CONFIG_TCPSVD=y
CONFIG_UDPSVD=y
#
# Process Utilities
@@ -736,8 +679,6 @@ CONFIG_FEATURE_PIDOF_OMIT=y
CONFIG_PKILL=y
CONFIG_PS=y
CONFIG_FEATURE_PS_WIDE=y
CONFIG_FEATURE_PS_TIME=y
CONFIG_FEATURE_PS_UNUSUAL_SYSTEMS=y
CONFIG_RENICE=y
CONFIG_BB_SYSCTL=y
CONFIG_TOP=y
@@ -756,7 +697,6 @@ CONFIG_WATCH=y
# CONFIG_FEATURE_SH_IS_MSH is not set
CONFIG_FEATURE_SH_IS_NONE=y
# CONFIG_ASH is not set
# CONFIG_ASH_BASH_COMPAT is not set
# CONFIG_ASH_JOB_CONTROL is not set
# CONFIG_ASH_READ_NCHARS is not set
# CONFIG_ASH_READ_TIMEOUT is not set
@@ -773,8 +713,8 @@ CONFIG_FEATURE_SH_IS_NONE=y
# CONFIG_ASH_EXPAND_PRMT is not set
CONFIG_HUSH=y
CONFIG_HUSH_HELP=y
CONFIG_HUSH_INTERACTIVE=y
CONFIG_HUSH_JOB=y
# CONFIG_HUSH_INTERACTIVE is not set
# CONFIG_HUSH_JOB is not set
CONFIG_HUSH_TICK=y
CONFIG_HUSH_IF=y
CONFIG_HUSH_LOOPS=y
@@ -786,7 +726,6 @@ CONFIG_MSH=y
#
CONFIG_FEATURE_SH_EXTRA_QUIET=y
CONFIG_FEATURE_SH_STANDALONE=y
CONFIG_FEATURE_SH_NOFORK=y
CONFIG_CTTYHACK=y
#
@@ -795,7 +734,6 @@ CONFIG_CTTYHACK=y
CONFIG_SYSLOGD=y
CONFIG_FEATURE_ROTATE_LOGFILE=y
CONFIG_FEATURE_REMOTE_LOG=y
CONFIG_FEATURE_SYSLOGD_DUP=y
CONFIG_FEATURE_IPC_SYSLOG=y
CONFIG_FEATURE_IPC_SYSLOG_BUFFER_SIZE=16
CONFIG_LOGREAD=y
@@ -806,38 +744,33 @@ CONFIG_LOGGER=y
#
# Runit Utilities
#
CONFIG_RUNSV=y
# CONFIG_RUNSV is not set
CONFIG_RUNSVDIR=y
CONFIG_SV=y
CONFIG_SVLOGD=y
# CONFIG_SVLOGD is not set
CONFIG_CHPST=y
CONFIG_SETUIDGID=y
CONFIG_ENVUIDGID=y
CONFIG_ENVDIR=y
CONFIG_SOFTLIMIT=y
# CONFIG_CHCON is not set
# CONFIG_FEATURE_CHCON_LONG_OPTIONS is not set
# CONFIG_GETENFORCE is not set
# CONFIG_GETSEBOOL is not set
# CONFIG_LOAD_POLICY is not set
# CONFIG_MATCHPATHCON is not set
# CONFIG_RESTORECON is not set
# CONFIG_RUNCON is not set
# CONFIG_FEATURE_RUNCON_LONG_OPTIONS is not set
# CONFIG_SELINUXENABLED is not set
# CONFIG_SETENFORCE is not set
# CONFIG_SETFILES is not set
# CONFIG_FEATURE_SETFILES_CHECK_OPTION is not set
# CONFIG_SETSEBOOL is not set
# CONFIG_SESTATUS is not set
#
# Selinux Utilities
# ipsvd utilities
#
CONFIG_CHCON=y
CONFIG_FEATURE_CHCON_LONG_OPTIONS=y
CONFIG_GETENFORCE=y
CONFIG_GETSEBOOL=y
CONFIG_LOAD_POLICY=y
CONFIG_MATCHPATHCON=y
CONFIG_RESTORECON=y
CONFIG_RUNCON=y
CONFIG_FEATURE_RUNCON_LONG_OPTIONS=y
CONFIG_SELINUXENABLED=y
CONFIG_SETENFORCE=y
CONFIG_SETFILES=y
CONFIG_FEATURE_SETFILES_CHECK_OPTION=y
CONFIG_SETSEBOOL=y
CONFIG_SESTATUS=y
#
# Print Utilities
#
CONFIG_LPD=y
CONFIG_LPR=y
CONFIG_LPQ=y
# CONFIG_TCPSVD is not set
# CONFIG_UDPSVD is not set
+6 -17
View File
@@ -32,7 +32,7 @@ struct bb_applet {
/* Define struct bb_applet applets[] */
#include "../include/applets.h"
enum { NUM_APPLETS = ARRAY_SIZE(applets) };
enum { NUM_APPLETS = sizeof(applets)/sizeof(applets[0]) };
static int offset[NUM_APPLETS];
@@ -47,7 +47,6 @@ int main(int argc, char **argv)
{
int i;
int ofs;
unsigned MAX_APPLET_NAME_LEN = 1;
qsort(applets, NUM_APPLETS, sizeof(applets[0]), cmp_name);
@@ -70,23 +69,15 @@ int main(int argc, char **argv)
/* Keep in sync with include/busybox.h! */
puts("/* This is a generated file, don't edit */\n");
puts("/* This is a generated file, don't edit */");
printf("#define NUM_APPLETS %u\n", NUM_APPLETS);
if (NUM_APPLETS == 1) {
printf("#define SINGLE_APPLET_STR \"%s\"\n", applets[0].name);
printf("#define SINGLE_APPLET_MAIN %s_main\n", applets[0].name);
}
puts("\nconst char applet_names[] ALIGN1 = \"\"");
puts("const char applet_names[] ALIGN1 = \"\" \n");
for (i = 0; i < NUM_APPLETS; i++) {
printf("\"%s\" \"\\0\"\n", applets[i].name);
if (MAX_APPLET_NAME_LEN < strlen(applets[i].name))
MAX_APPLET_NAME_LEN = strlen(applets[i].name);
}
puts(";");
puts("\nint (*const applet_main[])(int argc, char **argv) = {");
puts("int (*const applet_main[])(int argc, char **argv) = {");
for (i = 0; i < NUM_APPLETS; i++) {
printf("%s_main,\n", applets[i].main);
}
@@ -101,7 +92,7 @@ int main(int argc, char **argv)
+ (applets[i].noexec << 13)
#endif
#if ENABLE_FEATURE_SUID
+ (applets[i].need_suid << 14) /* 2 bits */
+ (applets[i].need_suid << 14) /* 2 bits */
#endif
);
}
@@ -117,10 +108,8 @@ int main(int argc, char **argv)
printf("0x%02x,\n", v);
i++;
}
puts("};\n");
puts("};");
#endif
printf("#define MAX_APPLET_NAME_LEN %u\n", MAX_APPLET_NAME_LEN);
return 0;
}
+13 -2
View File
@@ -10,9 +10,20 @@
#include <assert.h>
#include "busybox.h"
/* Apparently uclibc defines __GLIBC__ (compat trick?). Oh well. */
#if ENABLE_STATIC && defined(__GLIBC__) && !defined(__UCLIBC__)
#warning Static linking against glibc produces buggy executables
#warning (glibc does not cope well with ld --gc-sections).
#warning See sources.redhat.com/bugzilla/show_bug.cgi?id=3400
#warning Note that glibc is unsuitable for static linking anyway.
#warning If you still want to do it, remove -Wl,--gc-sections
#warning from scripts/trylink and remove this warning.
#error Aborting compilation.
#endif
#if ENABLE_BUILD_LIBBUSYBOX
int main(int argc ATTRIBUTE_UNUSED, char **argv)
int main(int argc, char **argv)
{
return lbb_main(argv);
return lbb_main(argc, argv);
}
#endif
+4 -2
View File
@@ -14,11 +14,13 @@ const char *applet_name;
int main(int argc, char **argv)
{
applet_name = argv[0];
return APPLET_main(argc,argv);
}
void bb_show_usage(void)
{
fputs(APPLET_full_usage "\n", stdout);
exit(EXIT_FAILURE);
printf(APPLET_full_usage "\n");
exit(1);
}
+1 -1
View File
@@ -37,7 +37,7 @@ if [ -n "$DO_INSTALL_LIBS" ] && [ "$DO_INSTALL_LIBS" != "n" ]; then
for i in $DO_INSTALL_LIBS; do
rm -f $prefix/$libdir/$i || exit 1
if [ -f $i ]; then
cp -pPR $i $prefix/$libdir/ || exit 1
cp -a $i $prefix/$libdir/ || exit 1
chmod 0644 $prefix/$libdir/$i || exit 1
fi
done
+1 -12
View File
@@ -5,17 +5,6 @@
* object directory */
#include "../include/autoconf.h"
/* Since we can't use platform.h, have to do this again by hand: */
#if ENABLE_NOMMU
#define BB_MMU 0
#define USE_FOR_NOMMU(...) __VA_ARGS__
#define USE_FOR_MMU(...)
#else
#define BB_MMU 1
#define USE_FOR_NOMMU(...)
#define USE_FOR_MMU(...) __VA_ARGS__
#endif
static const char usage_messages[] = ""
#define MAKE_USAGE
#include "usage.h"
@@ -24,6 +13,6 @@ static const char usage_messages[] = ""
int main(void)
{
write(STDOUT_FILENO, usage_messages, sizeof(usage_messages));
write(1, usage_messages, sizeof(usage_messages));
return 0;
}
+3 -18
View File
@@ -12,23 +12,8 @@ sz=`"$loc/usage" | wc -c` || exit 1
exec >"$target"
echo 'static const char packed_usage[] ALIGN1 = {'
## Breaks on big-endian systems!
## # Extra effort to avoid using "od -t x1": -t is not available
## # in non-CONFIG_DESKTOPed busybox od
##
## "$loc/usage" | bzip2 -1 | od -v -x \
## | $SED -e 's/^[^ ]*//' \
## | $SED -e 's/ //g' \
## | grep -v '^$' \
## | $SED -e 's/\(..\)\(..\)/0x\2,0x\1,/g'
echo 'static const char packed_usage[] ALIGN1 = '
"$loc/usage" | bzip2 -1 | od -v -t x1 \
| $SED -e 's/^[^ ]*//' \
| $SED -e 's/ //g' \
| grep -v '^$' \
| $SED -e 's/\(..\)/0x\1,/g'
echo '};'
| $SED -e 's/^[^ ]*//' -e 's/ *\(..\)/\\x\1/g' -e 's/^\(.*\)$/"\1"/'
echo ';'
echo '#define SIZEOF_usage_messages' `expr 0 + $sz`
+29 -47
View File
@@ -29,7 +29,7 @@ config AR
probably say N here.
config FEATURE_AR_LONG_FILENAMES
bool "Support for long filenames (not need for debs)"
bool "Enable support for long filenames (not need for debs)"
default n
depends on AR
help
@@ -78,14 +78,6 @@ config CPIO
Unless you have a specific application which requires cpio, you should
probably say N here.
config FEATURE_CPIO_O
bool "Support for archive creation"
default n
depends on CPIO
help
This implementation of cpio can create cpio archives in the "newc"
format only.
config DPKG
bool "dpkg"
default n
@@ -107,7 +99,7 @@ config DPKG_DEB
probably say N here.
config FEATURE_DPKG_DEB_EXTRACT_ONLY
bool "Extract only (-x)"
bool "extract only (-x)"
default n
depends on DPKG_DEB
help
@@ -174,14 +166,6 @@ config FEATURE_TAR_CREATE
If you enable this option you'll be able to create
tar archives using the `-c' option.
config FEATURE_TAR_GZIP
bool "Enable -z option"
default y
depends on TAR
help
If you enable this option tar will be able to call gzip,
when creating or extracting tar gziped archives.
config FEATURE_TAR_BZIP2
bool "Enable -j option to handle .tar.bz2 files"
default n
@@ -198,22 +182,6 @@ config FEATURE_TAR_LZMA
If you enable this option you'll be able to extract
archives compressed with lzma.
config FEATURE_TAR_COMPRESS
bool "Enable -Z option"
default n
depends on TAR
help
If you enable this option tar will be able to call uncompress,
when extracting .tar.Z archives.
config FEATURE_TAR_AUTODETECT
bool "Let tar autodetect gz/bz2 compresses tarballs"
default n
depends on FEATURE_TAR_GZIP || FEATURE_TAR_BZIP2
help
With this option tar can automatically detect gzip/bzip2 compressed
tarballs. Currently it works only on seekable streams.
config FEATURE_TAR_FROM
bool "Enable -X (exclude from) and -T (include from) options)"
default n
@@ -222,8 +190,24 @@ config FEATURE_TAR_FROM
If you enable this option you'll be able to specify
a list of files to include or exclude from an archive.
config FEATURE_TAR_GZIP
bool "Enable -z option"
default y
depends on TAR
help
If you enable this option tar will be able to call gzip,
when creating or extracting tar gziped archives.
config FEATURE_TAR_COMPRESS
bool "Enable -Z option"
default n
depends on TAR
help
If you enable this option tar will be able to call uncompress,
when extracting .tar.Z archives.
config FEATURE_TAR_OLDGNU_COMPATIBILITY
bool "Support for old tar header format"
bool "Enable support for old tar header format"
default N
depends on TAR
help
@@ -241,7 +225,7 @@ config FEATURE_TAR_OLDSUN_COMPATIBILITY
It is said to be fixed in newer Sun tar, but "old" tarballs still exist.
config FEATURE_TAR_GNU_EXTENSIONS
bool "Support for GNU tar extensions (long filenames)"
bool "Enable support for some GNU tar extensions"
default y
depends on TAR
help
@@ -253,16 +237,7 @@ config FEATURE_TAR_LONG_OPTIONS
default n
depends on TAR && GETOPT_LONG
help
Enable use of long options, increases size by about 400 Bytes
config FEATURE_TAR_UNAME_GNAME
bool "Enable use of user and group names"
default n
depends on TAR
help
Enables use of user and group names in tar. This affects contents
listings (-t) and preserving permissions when unpacking (-p).
+200 bytes.
Enable use of long options, increases size by about 400 Bytes
config UNCOMPRESS
bool "uncompress"
@@ -287,7 +262,7 @@ config UNLZMA
should probably say N here.
config FEATURE_LZMA_FAST
bool "Optimize unlzma for speed"
bool "Optimze unlzma for speed"
default n
depends on UNLZMA
help
@@ -307,6 +282,13 @@ config UNZIP
comment "Common options for cpio and tar"
depends on CPIO || TAR
config FEATURE_UNARCHIVE_TAPE
bool "Enable tape drive support"
default n
depends on CPIO || TAR
help
I don't think this is needed anymore.
comment "Common options for dpkg and dpkg_deb"
depends on DPKG || DPKG_DEB
+5 -19
View File
@@ -159,7 +159,7 @@ USE_DESKTOP(long long) int unpack_bunzip2(void)
}
int bunzip2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int bunzip2_main(int argc ATTRIBUTE_UNUSED, char **argv)
int bunzip2_main(int argc, char **argv)
{
getopt32(argv, "cfvdt");
argv += optind;
@@ -256,24 +256,10 @@ USE_DESKTOP(long long) int unpack_gunzip(void)
return status;
}
/*
* Linux kernel build uses gzip -d -n. We accept and ignore it.
* Man page says:
* -n --no-name
* gzip: do not save the original file name and time stamp.
* (The original name is always saved if the name had to be truncated.)
* gunzip: do not restore the original file name/time even if present
* (remove only the gzip suffix from the compressed file name).
* This option is the default when decompressing.
* -N --name
* gzip: always save the original file name and time stamp (this is the default)
* gunzip: restore the original file name and time stamp if present.
*/
int gunzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int gunzip_main(int argc ATTRIBUTE_UNUSED, char **argv)
int gunzip_main(int argc, char **argv)
{
getopt32(argv, "cfvdtn");
getopt32(argv, "cfvdt");
argv += optind;
/* if called as zcat */
if (applet_name[1] == 'c')
@@ -309,7 +295,7 @@ USE_DESKTOP(long long) int unpack_unlzma(void)
}
int unlzma_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int unlzma_main(int argc ATTRIBUTE_UNUSED, char **argv)
int unlzma_main(int argc, char **argv)
{
getopt32(argv, "cf");
argv += optind;
@@ -351,7 +337,7 @@ USE_DESKTOP(long long) int unpack_uncompress(void)
}
int uncompress_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int uncompress_main(int argc ATTRIBUTE_UNUSED, char **argv)
int uncompress_main(int argc, char **argv)
{
getopt32(argv, "cf");
argv += optind;
+1 -1
View File
@@ -141,7 +141,7 @@ char* make_new_name_bzip2(char *filename)
}
int bzip2_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int bzip2_main(int argc ATTRIBUTE_UNUSED, char **argv)
int bzip2_main(int argc, char **argv)
{
unsigned opt;
+18 -285
View File
@@ -7,298 +7,35 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*
* Limitations:
* Doesn't check CRC's
* Only supports new ASCII and CRC formats
* Doesn't check CRC's
* Only supports new ASCII and CRC formats
*
*/
#include "libbb.h"
#include "unarchive.h"
#if ENABLE_FEATURE_CPIO_O
static off_t cpio_pad4(off_t size)
{
int i;
i = (- size) & 3;
size += i;
while (--i >= 0)
bb_putchar('\0');
return size;
}
/* Return value will become exit code.
* It's ok to exit instead of return. */
static int cpio_o(void)
{
struct name_s {
struct name_s *next;
char name[1];
};
struct inodes_s {
struct inodes_s *next;
struct name_s *names;
struct stat st;
};
struct inodes_s *links = NULL;
off_t bytes = 0; /* output bytes count */
while (1) {
const char *name;
char *line;
struct stat st;
line = xmalloc_fgetline(stdin);
if (line) {
/* Strip leading "./[./]..." from the filename */
name = line;
while (name[0] == '.' && name[1] == '/') {
while (*++name == '/')
continue;
}
if (!*name) { /* line is empty */
free(line);
continue;
}
if (lstat(name, &st)) {
abort_cpio_o:
bb_simple_perror_msg_and_die(name);
}
if (!(S_ISLNK(st.st_mode) || S_ISREG(st.st_mode)))
st.st_size = 0; /* paranoia */
/* Store hardlinks for later processing, dont output them */
if (!S_ISDIR(st.st_mode) && st.st_nlink > 1) {
struct name_s *n;
struct inodes_s *l;
/* Do we have this hardlink remembered? */
l = links;
while (1) {
if (l == NULL) {
/* Not found: add new item to "links" list */
l = xzalloc(sizeof(*l));
l->st = st;
l->next = links;
links = l;
break;
}
if (l->st.st_ino == st.st_ino) {
/* found */
break;
}
l = l->next;
}
/* Add new name to "l->names" list */
n = xmalloc(sizeof(*n) + strlen(name));
strcpy(n->name, name);
n->next = l->names;
l->names = n;
free(line);
continue;
}
} else { /* line == NULL: EOF */
next_link:
if (links) {
/* Output hardlink's data */
st = links->st;
name = links->names->name;
links->names = links->names->next;
/* GNU cpio is reported to emit file data
* only for the last instance. Mimic that. */
if (links->names == NULL)
links = links->next;
else
st.st_size = 0;
/* NB: we leak links->names and/or links,
* this is intended (we exit soon anyway) */
} else {
/* If no (more) hardlinks to output,
* output "trailer" entry */
name = "TRAILER!!!";
/* st.st_size == 0 is a must, but for uniformity
* in the output, we zero out everything */
memset(&st, 0, sizeof(st));
/* st.st_nlink = 1; - GNU cpio does this */
}
}
bytes += printf("070701"
"%08X%08X%08X%08X%08X%08X%08X"
"%08X%08X%08X%08X" /* GNU cpio uses uppercase hex */
/* strlen+1: */ "%08X"
/* chksum: */ "00000000" /* (only for "070702" files) */
/* name,NUL: */ "%s%c",
(unsigned)(uint32_t) st.st_ino,
(unsigned)(uint32_t) st.st_mode,
(unsigned)(uint32_t) st.st_uid,
(unsigned)(uint32_t) st.st_gid,
(unsigned)(uint32_t) st.st_nlink,
(unsigned)(uint32_t) st.st_mtime,
(unsigned)(uint32_t) st.st_size,
(unsigned)(uint32_t) major(st.st_dev),
(unsigned)(uint32_t) minor(st.st_dev),
(unsigned)(uint32_t) major(st.st_rdev),
(unsigned)(uint32_t) minor(st.st_rdev),
(unsigned)(strlen(name) + 1),
name, '\0');
bytes = cpio_pad4(bytes);
if (st.st_size) {
if (S_ISLNK(st.st_mode)) {
char *lpath = xmalloc_readlink_or_warn(name);
if (!lpath)
goto abort_cpio_o;
bytes += printf("%s", lpath);
free(lpath);
} else { /* S_ISREG */
int fd = xopen(name, O_RDONLY);
fflush(stdout);
/* We must abort if file got shorter too! */
bb_copyfd_exact_size(fd, STDOUT_FILENO, st.st_size);
bytes += st.st_size;
close(fd);
}
bytes = cpio_pad4(bytes);
}
if (!line) {
if (links)
goto next_link;
/* TODO: GNU cpio pads trailer to 512 bytes, do we want that? */
return EXIT_SUCCESS;
}
free(line);
} /* end of "while (1)" */
}
#endif
/* GNU cpio (GNU cpio) 2.9 help (abridged):
Main operation mode:
-i, --extract Extract files from an archive
-o, --create Create the archive
-p, --pass-through Copy-pass mode (was ist das?!)
-t, --list List the archive
Operation modifiers valid in any mode:
--block-size=SIZE I/O block size = SIZE * 512 bytes
-B I/O block size = 5120 bytes
-c Use the old portable (ASCII) archive format
-C, --io-size=NUMBER I/O block size to the given NUMBER bytes
-f, --nonmatching Only copy files that do not match given pattern
-F, --file=FILE Use FILE instead of standard input or output
-H, --format=FORMAT Use given archive FORMAT
-M, --message=STRING Print STRING when the end of a volume of the
backup media is reached
-n, --numeric-uid-gid If -v, show numeric UID and GID
--quiet Do not print the number of blocks copied
--rsh-command=COMMAND Use remote COMMAND instead of rsh
-v, --verbose Verbosely list the files processed
-V, --dot Print a "." for each file processed
-W, --warning=FLAG Control warning display: 'none','truncate','all';
multiple options accumulate
Operation modifiers valid only in --extract mode:
-b, --swap Swap both halfwords of words and bytes of
halfwords in the data (equivalent to -sS)
-r, --rename Interactively rename files
-s, --swap-bytes Swap the bytes of each halfword in the files
-S, --swap-halfwords Swap the halfwords of each word (4 bytes)
--to-stdout Extract files to standard output
-E, --pattern-file=FILE Read additional patterns specifying filenames to
extract or list from FILE
--only-verify-crc Verify CRC's, don't actually extract the files
Operation modifiers valid only in --create mode:
-A, --append Append to an existing archive
-O FILE File to use instead of standard output
Operation modifiers valid only in --pass-through mode:
-l, --link Link files instead of copying them, when possible
Operation modifiers valid in --extract and --create modes:
--absolute-filenames Do not strip file system prefix components from
the file names
--no-absolute-filenames Create all files relative to the current dir
Operation modifiers valid in --create and --pass-through modes:
-0, --null A list of filenames is terminated by a NUL
-a, --reset-access-time Reset the access times of files after reading them
-I FILE File to use instead of standard input
-L, --dereference Dereference symbolic links (copy the files
that they point to instead of copying the links)
-R, --owner=[USER][:.][GROUP] Set owner of created files
Operation modifiers valid in --extract and --pass-through modes:
-d, --make-directories Create leading directories where needed
-m, --preserve-modification-time
Retain previous file modification times when
creating files
--no-preserve-owner Do not change the ownership of the files
--sparse Write files with blocks of zeros as sparse files
-u, --unconditional Replace all files unconditionally
*/
#define CPIO_OPT_EXTRACT 0x01
#define CPIO_OPT_TEST 0x02
#define CPIO_OPT_UNCONDITIONAL 0x04
#define CPIO_OPT_VERBOSE 0x08
#define CPIO_OPT_FILE 0x10
#define CPIO_OPT_CREATE_LEADING_DIR 0x20
#define CPIO_OPT_PRESERVE_MTIME 0x40
int cpio_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cpio_main(int argc ATTRIBUTE_UNUSED, char **argv)
int cpio_main(int argc, char **argv)
{
archive_handle_t *archive_handle;
char *cpio_filename;
USE_FEATURE_CPIO_O(const char *cpio_fmt = "";)
char *cpio_filename = NULL;
unsigned opt;
enum {
CPIO_OPT_EXTRACT = (1 << 0),
CPIO_OPT_TEST = (1 << 1),
CPIO_OPT_UNCONDITIONAL = (1 << 2),
CPIO_OPT_VERBOSE = (1 << 3),
CPIO_OPT_FILE = (1 << 4),
CPIO_OPT_CREATE_LEADING_DIR = (1 << 5),
CPIO_OPT_PRESERVE_MTIME = (1 << 6),
CPIO_OPT_CREATE = (1 << 7),
CPIO_OPT_FORMAT = (1 << 8),
};
#if ENABLE_GETOPT_LONG && ENABLE_DESKTOP
applet_long_options =
"extract\0" No_argument "i"
"list\0" No_argument "t"
#if ENABLE_FEATURE_CPIO_O
"create\0" No_argument "o"
"format\0" Required_argument "H"
#endif
;
#endif
/* Initialize */
/* Initialise */
archive_handle = init_handle();
archive_handle->src_fd = STDIN_FILENO;
archive_handle->seek = seek_by_read;
archive_handle->flags = ARCHIVE_EXTRACT_NEWER;
archive_handle->flags = ARCHIVE_EXTRACT_NEWER | ARCHIVE_PRESERVE_DATE;
#if ENABLE_FEATURE_CPIO_O
opt = getopt32(argv, "ituvF:dmoH:", &cpio_filename, &cpio_fmt);
if (opt & CPIO_OPT_CREATE) {
if (*cpio_fmt != 'n')
bb_show_usage();
if (opt & CPIO_OPT_FILE) {
fclose(stdout);
stdout = fopen(cpio_filename, "w");
/* Paranoia: I don't trust libc that much */
xdup2(fileno(stdout), STDOUT_FILENO);
}
return cpio_o();
}
#else
opt = getopt32(argv, "ituvF:dm", &cpio_filename);
#endif
argv += optind;
/* One of either extract or test options must be given */
if ((opt & (CPIO_OPT_TEST | CPIO_OPT_EXTRACT)) == 0) {
@@ -326,25 +63,21 @@ int cpio_main(int argc ATTRIBUTE_UNUSED, char **argv)
archive_handle->action_header = header_list;
}
}
if (opt & CPIO_OPT_FILE) { /* -F */
if (cpio_filename) { /* CPIO_OPT_FILE */
archive_handle->src_fd = xopen(cpio_filename, O_RDONLY);
archive_handle->seek = seek_by_jump;
}
if (opt & CPIO_OPT_CREATE_LEADING_DIR) {
archive_handle->flags |= ARCHIVE_CREATE_LEADING_DIRS;
}
if (opt & CPIO_OPT_PRESERVE_MTIME) {
archive_handle->flags |= ARCHIVE_PRESERVE_DATE;
}
while (*argv) {
while (optind < argc) {
archive_handle->filter = filter_accept_list;
llist_add_to(&(archive_handle->accept), *argv);
argv++;
llist_add_to(&(archive_handle->accept), argv[optind]);
optind++;
}
while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
continue;
while (get_header_cpio(archive_handle) == EXIT_SUCCESS);
return EXIT_SUCCESS;
}
+92 -114
View File
@@ -75,21 +75,10 @@ typedef struct status_node_s {
unsigned status:16; /* was:14 */ /* has to fit STATUS_HASH_PRIME */
} status_node_t;
/* Globals */
struct globals {
char *name_hashtable[NAME_HASH_PRIME + 1];
common_node_t *package_hashtable[PACKAGE_HASH_PRIME + 1];
status_node_t *status_hashtable[STATUS_HASH_PRIME + 1];
};
#define G (*ptr_to_globals)
#define name_hashtable (G.name_hashtable )
#define package_hashtable (G.package_hashtable)
#define status_hashtable (G.status_hashtable )
#define INIT_G() do { \
SET_PTR_TO_GLOBALS(xzalloc(sizeof(G))); \
} while (0)
/* Were statically declared here, but such a big bss is nommu-unfriendly */
static char **name_hashtable; /* [NAME_HASH_PRIME + 1] */
static common_node_t **package_hashtable; /* [PACKAGE_HASH_PRIME + 1] */
static status_node_t **status_hashtable; /* [STATUS_HASH_PRIME + 1] */
/* Even numbers are for 'extras', like ored dependencies or null */
enum edge_type_e {
@@ -135,7 +124,7 @@ static void make_hash(const char *key, unsigned *start, unsigned *decrement, con
* shift amount is mod 24 because long int is 32 bit and data
* to be shifted is 8, don't want to shift data to where it has
* no effect*/
hash_num += (key[i] + key[i-1]) << ((key[i] * i) % 24);
hash_num += ((key[i] + key[i-1]) << ((key[i] * i) % 24));
}
*start = (unsigned) hash_num % hash_prime;
*decrement = (unsigned) 1 + (hash_num % (hash_prime - 1));
@@ -144,8 +133,8 @@ static void make_hash(const char *key, unsigned *start, unsigned *decrement, con
/* this adds the key to the hash table */
static int search_name_hashtable(const char *key)
{
unsigned probe_address;
unsigned probe_decrement;
unsigned probe_address = 0;
unsigned probe_decrement = 0;
make_hash(key, &probe_address, &probe_decrement, NAME_HASH_PRIME);
while (name_hashtable[probe_address] != NULL) {
@@ -166,8 +155,8 @@ static int search_name_hashtable(const char *key)
*/
static unsigned search_status_hashtable(const char *key)
{
unsigned probe_address;
unsigned probe_decrement;
unsigned probe_address = 0;
unsigned probe_decrement = 0;
make_hash(key, &probe_address, &probe_decrement, STATUS_HASH_PRIME);
while (status_hashtable[probe_address] != NULL) {
@@ -323,10 +312,11 @@ static int test_version(const unsigned version1, const unsigned version2, const
return FALSE;
}
static int search_package_hashtable(const unsigned name, const unsigned version, const unsigned operator)
{
unsigned probe_address;
unsigned probe_decrement;
unsigned probe_address = 0;
unsigned probe_decrement = 0;
make_hash(name_hashtable[name], &probe_address, &probe_decrement, PACKAGE_HASH_PRIME);
while (package_hashtable[probe_address] != NULL) {
@@ -420,10 +410,10 @@ static void add_split_dependencies(common_node_t *parent_node, const char *whole
if ((edge_type == EDGE_DEPENDS || edge_type == EDGE_PRE_DEPENDS)
&& (strcmp(field, field2) != 0)
) {
or_edge = xzalloc(sizeof(edge_t));
or_edge = xmalloc(sizeof(edge_t));
or_edge->type = edge_type + 1;
or_edge->name = search_name_hashtable(field);
//or_edge->version = 0; // tracks the number of alternatives
or_edge->version = 0; // tracks the number of alternatives
add_edge_to_node(parent_node, or_edge);
}
@@ -449,13 +439,17 @@ static void add_split_dependencies(common_node_t *parent_node, const char *whole
if (offset_ch > 0) {
if (strncmp(version, "=", offset_ch) == 0) {
edge->operator = VER_EQUAL;
} else if (strncmp(version, "<<", offset_ch) == 0) {
}
else if (strncmp(version, "<<", offset_ch) == 0) {
edge->operator = VER_LESS;
} else if (strncmp(version, "<=", offset_ch) == 0) {
}
else if (strncmp(version, "<=", offset_ch) == 0) {
edge->operator = VER_LESS_EQUAL;
} else if (strncmp(version, ">>", offset_ch) == 0) {
}
else if (strncmp(version, ">>", offset_ch) == 0) {
edge->operator = VER_MORE;
} else if (strncmp(version, ">=", offset_ch) == 0) {
}
else if (strncmp(version, ">=", offset_ch) == 0) {
edge->operator = VER_MORE_EQUAL;
} else {
bb_error_msg_and_die("illegal operator");
@@ -608,7 +602,7 @@ static unsigned fill_package_struct(char *control_buffer)
&field_name, &field_value);
if (field_name == NULL) {
goto fill_package_struct_cleanup;
goto fill_package_struct_cleanup; /* Oh no, the dreaded goto statement! */
}
field_num = index_in_strings(field_names, field_name);
@@ -741,6 +735,7 @@ static const char *describe_status(int status_num)
return "is not installed or flagged to be installed";
}
static void index_status_file(const char *filename)
{
FILE *status_file;
@@ -750,7 +745,7 @@ static void index_status_file(const char *filename)
unsigned status_num;
status_file = xfopen(filename, "r");
while ((control_buffer = xmalloc_fgetline_str(status_file, "\n\n")) != NULL) {
while ((control_buffer = xmalloc_fgets_str(status_file, "\n\n")) != NULL) {
const unsigned package_num = fill_package_struct(control_buffer);
if (package_num != -1) {
status_node = xmalloc(sizeof(status_node_t));
@@ -803,7 +798,7 @@ static void write_status_file(deb_file_t **deb_file)
int i = 0;
/* Update previously known packages */
while ((control_buffer = xmalloc_fgetline_str(old_status_file, "\n\n")) != NULL) {
while ((control_buffer = xmalloc_fgets_str(old_status_file, "\n\n")) != NULL) {
tmp_string = strstr(control_buffer, "Package:");
if (tmp_string == NULL) {
continue;
@@ -918,16 +913,20 @@ static void write_status_file(deb_file_t **deb_file)
fclose(old_status_file);
fclose(new_status_file);
/* Create a separate backfile to dpkg */
if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) {
if (errno != ENOENT)
bb_error_msg_and_die("cannot create backup status file");
struct stat stat_buf;
xstat("/var/lib/dpkg/status", &stat_buf);
/* Its ok if renaming the status file fails because status
* file doesnt exist, maybe we are starting from scratch */
bb_error_msg("no status file found, creating new one");
}
xrename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status");
if (rename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status") == -1) {
bb_error_msg_and_die("DANGER: cannot create status file, "
"you need to manually repair your status file");
}
}
/* This function returns TRUE if the given package can satisfy a
@@ -954,7 +953,7 @@ static int package_satisfies_dependency(int package, int depend_type)
return 0;
}
static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count - ?? */)
static int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
{
int *conflicts = NULL;
int conflicts_num = 0;
@@ -1157,9 +1156,9 @@ static int check_deps(deb_file_t **deb_file, int deb_start /*, int dep_max_count
static char **create_list(const char *filename)
{
FILE *list_stream;
char **file_list;
char *line;
int count;
char **file_list = NULL;
char *line = NULL;
int count = 0;
/* don't use [xw]fopen here, handle error ourself */
list_stream = fopen(filename, "r");
@@ -1167,15 +1166,17 @@ static char **create_list(const char *filename)
return NULL;
}
file_list = NULL;
count = 0;
while ((line = xmalloc_fgetline(list_stream)) != NULL) {
while ((line = xmalloc_getline(list_stream)) != NULL) {
file_list = xrealloc(file_list, sizeof(char *) * (count + 2));
file_list[count++] = line;
file_list[count] = NULL;
file_list[count] = line;
count++;
}
fclose(list_stream);
if (count == 0) {
return NULL;
}
file_list[count] = NULL;
return file_list;
}
@@ -1212,54 +1213,24 @@ static int remove_file_array(char **remove_names, char **exclude_names)
return (remove_flag == 0);
}
static void run_package_script_or_die(const char *package_name, const char *script_type)
static int run_package_script(const char *package_name, const char *script_type)
{
struct stat path_stat;
char *script_path;
int result;
script_path = xasprintf("/var/lib/dpkg/info/%s.%s", package_name, script_type);
/* If the file doesnt exist is isnt fatal */
result = access(script_path, F_OK) ? EXIT_SUCCESS : system(script_path);
/* If the file doesnt exist is isnt a fatal */
result = lstat(script_path, &path_stat) < 0 ? EXIT_SUCCESS : system(script_path);
free(script_path);
if (result)
bb_error_msg_and_die("%s failed, exit code %d", script_type, result);
return result;
}
/*
The policy manual defines what scripts get called when and with
what arguments. I realize that busybox does not support all of
these scenarios, but it does support some of them; it does not,
however, run them with any parameters in run_package_script_or_die().
Here are the scripts:
preinst install
preinst install <old_version>
preinst upgrade <old_version>
preinst abort_upgrade <new_version>
postinst configure <most_recent_version>
postinst abort-upgade <new_version>
postinst abort-remove
postinst abort-remove in-favour <package> <version>
postinst abort-deconfigure in-favor <failed_install_package> removing <conflicting_package> <version>
prerm remove
prerm upgrade <new_version>
prerm failed-upgrade <old_version>
prerm remove in-favor <package> <new_version>
prerm deconfigure in-favour <package> <version> removing <package> <version>
postrm remove
postrm purge
postrm upgrade <new_version>
postrm failed-upgrade <old_version>
postrm abort-install
postrm abort-install <old_version>
postrm abort-upgrade <old_version>
postrm disappear <overwriter> <version>
*/
static const char *const all_control_files[] = {
"preinst", "postinst", "prerm", "postrm",
"list", "md5sums", "shlibs", "conffiles",
"config", "templates"
"config", "templates", NULL
};
static char **all_control_list(const char *package_name)
@@ -1268,10 +1239,9 @@ static char **all_control_list(const char *package_name)
char **remove_files;
/* Create a list of all /var/lib/dpkg/info/<package> files */
remove_files = xzalloc(sizeof(all_control_files) + sizeof(char*));
while (i < ARRAY_SIZE(all_control_files)) {
remove_files[i] = xasprintf("/var/lib/dpkg/info/%s.%s",
package_name, all_control_files[i]);
remove_files = xzalloc(sizeof(all_control_files));
while (all_control_files[i]) {
remove_files[i] = xasprintf("/var/lib/dpkg/info/%s.%s", package_name, all_control_files[i]);
i++;
}
@@ -1344,26 +1314,27 @@ static void remove_package(const unsigned package_num, int noisy)
if (noisy)
printf("Removing %s (%s)...\n", package_name, package_version);
/* Run prerm script */
run_package_script_or_die(package_name, "prerm");
/* run prerm script */
if (run_package_script(package_name, "prerm") != 0) {
bb_error_msg_and_die("script failed, prerm failure");
}
/* Create a list of files to remove, and a separate list of those to keep */
sprintf(list_name, "/var/lib/dpkg/info/%s.%s", package_name, "list");
sprintf(list_name, "/var/lib/dpkg/info/%s.list", package_name);
remove_files = create_list(list_name);
sprintf(conffile_name, "/var/lib/dpkg/info/%s.%s", package_name, "conffiles");
sprintf(conffile_name, "/var/lib/dpkg/info/%s.conffiles", package_name);
exclude_files = create_list(conffile_name);
/* Some directories can't be removed straight away, so do multiple passes */
while (remove_file_array(remove_files, exclude_files))
continue;
while (remove_file_array(remove_files, exclude_files)) /*repeat */;
free_array(exclude_files);
free_array(remove_files);
/* Create a list of files in /var/lib/dpkg/info/<package>.* to keep */
exclude_files = xzalloc(sizeof(char*) * 3);
exclude_files[0] = xstrdup(conffile_name);
exclude_files[1] = xasprintf("/var/lib/dpkg/info/%s.%s", package_name, "postrm");
exclude_files[1] = xasprintf("/var/lib/dpkg/info/%s.postrm", package_name);
/* Create a list of all /var/lib/dpkg/info/<package> files */
remove_files = all_control_list(package_name);
@@ -1372,9 +1343,7 @@ static void remove_package(const unsigned package_num, int noisy)
free_array(remove_files);
free_array(exclude_files);
/* rename <package>.conffiles to <package>.list
* The conffiles control file isn't required in Debian packages, so don't
* error out if it's missing. */
/* rename <package>.conffile to <package>.list */
rename(conffile_name, list_name);
/* Change package status */
@@ -1392,11 +1361,13 @@ static void purge_package(const unsigned package_num)
printf("Purging %s (%s)...\n", package_name, package_version);
/* Run prerm script */
run_package_script_or_die(package_name, "prerm");
/* run prerm script */
if (run_package_script(package_name, "prerm") != 0) {
bb_error_msg_and_die("script failed, prerm failure");
}
/* Create a list of files to remove */
sprintf(list_name, "/var/lib/dpkg/info/%s.%s", package_name, "list");
sprintf(list_name, "/var/lib/dpkg/info/%s.list", package_name);
remove_files = create_list(list_name);
exclude_files = xzalloc(sizeof(char*));
@@ -1411,8 +1382,10 @@ static void purge_package(const unsigned package_num)
free_array(remove_files);
free(exclude_files);
/* Run postrm script */
run_package_script_or_die(package_name, "postrm");
/* run postrm script */
if (run_package_script(package_name, "postrm") != 0) {
bb_error_msg_and_die("postrm failure.. set status to what?");
}
/* Change package status */
set_status(status_num, "not-installed", 3);
@@ -1502,8 +1475,8 @@ static void unpack_package(deb_file_t *deb_file)
char *list_filename;
archive_handle_t *archive_handle;
FILE *out_stream;
llist_t *accept_list;
int i;
llist_t *accept_list = NULL;
int i = 0;
/* If existing version, remove it first */
if (strcmp(name_hashtable[get_status(status_num, 3)], "installed") == 0) {
@@ -1517,13 +1490,11 @@ static void unpack_package(deb_file_t *deb_file)
}
/* Extract control.tar.gz to /var/lib/dpkg/info/<package>.filename */
info_prefix = xasprintf("/var/lib/dpkg/info/%s.%s", package_name, "");
info_prefix = xasprintf("/var/lib/dpkg/info/%s.", package_name);
archive_handle = init_archive_deb_ar(deb_file->filename);
init_archive_deb_control(archive_handle);
accept_list = NULL;
i = 0;
while (i < ARRAY_SIZE(all_control_files)) {
while (all_control_files[i]) {
char *c = xasprintf("./%s", all_control_files[i]);
llist_add_to(&accept_list, c);
i++;
@@ -1536,7 +1507,10 @@ static void unpack_package(deb_file_t *deb_file)
unpack_ar_archive(archive_handle);
/* Run the preinst prior to extracting */
run_package_script_or_die(package_name, "preinst");
if (run_package_script(package_name, "preinst") != 0) {
/* when preinst returns exit code != 0 then quit installation process */
bb_error_msg_and_die("subprocess pre-installation script returned error");
}
/* Extract data.tar.gz to the root directory */
archive_handle = init_archive_deb_ar(deb_file->filename);
@@ -1547,7 +1521,7 @@ static void unpack_package(deb_file_t *deb_file)
unpack_ar_archive(archive_handle);
/* Create the list file */
list_filename = xasprintf("/var/lib/dpkg/info/%s.%s", package_name, "list");
list_filename = xasprintf("/var/lib/dpkg/info/%s.list", package_name);
out_stream = xfopen(list_filename, "w");
while (archive_handle->sub_archive->passed) {
/* the leading . has been stripped by data_extract_all_prefix already */
@@ -1574,16 +1548,17 @@ static void configure_package(deb_file_t *deb_file)
printf("Setting up %s (%s)...\n", package_name, package_version);
/* Run the postinst script */
/* TODO: handle failure gracefully */
run_package_script_or_die(package_name, "postinst");
if (run_package_script(package_name, "postinst") != 0) {
/* TODO: handle failure gracefully */
bb_error_msg_and_die("postinst failure.. set status to what?");
}
/* Change status to reflect success */
set_status(status_num, "install", 1);
set_status(status_num, "installed", 3);
}
int dpkg_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int dpkg_main(int argc ATTRIBUTE_UNUSED, char **argv)
int dpkg_main(int argc, char **argv)
{
deb_file_t **deb_file = NULL;
status_node_t *status_node;
@@ -1604,8 +1579,6 @@ int dpkg_main(int argc ATTRIBUTE_UNUSED, char **argv)
OPT_unpack = 0x40,
};
INIT_G();
opt = getopt32(argv, "CF:ilPru", &str_f);
//if (opt & OPT_configure) ... // -C
if (opt & OPT_force_ignore_depends) { // -F (--force in official dpkg)
@@ -1617,11 +1590,16 @@ int dpkg_main(int argc ATTRIBUTE_UNUSED, char **argv)
//if (opt & OPT_purge) ... // -P
//if (opt & OPT_remove) ... // -r
//if (opt & OPT_unpack) ... // -u (--unpack in official dpkg)
argc -= optind;
argv += optind;
/* check for non-option argument if expected */
if (!opt || (!argv[0] && !(opt && OPT_list_installed)))
if (!opt || (!argc && !(opt && OPT_list_installed)))
bb_show_usage();
name_hashtable = xzalloc(sizeof(name_hashtable[0]) * (NAME_HASH_PRIME + 1));
package_hashtable = xzalloc(sizeof(package_hashtable[0]) * (PACKAGE_HASH_PRIME + 1));
status_hashtable = xzalloc(sizeof(status_hashtable[0]) * (STATUS_HASH_PRIME + 1));
/* puts("(Reading database ... xxxxx files and directories installed.)"); */
index_status_file("/var/lib/dpkg/status");
@@ -1715,7 +1693,7 @@ int dpkg_main(int argc ATTRIBUTE_UNUSED, char **argv)
/* Check that the deb file arguments are installable */
if (!(opt & OPT_force_ignore_depends)) {
if (!check_deps(deb_file, 0 /*, deb_count*/)) {
if (!check_deps(deb_file, 0, deb_count)) {
bb_error_msg_and_die("dependency check failed");
}
}
+3 -21
View File
@@ -2025,31 +2025,13 @@ USE_DESKTOP(long long) int pack_gzip(void)
return 0;
}
/*
* Linux kernel build uses gzip -d -n. We accept and ignore it.
* Man page says:
* -n --no-name
* gzip: do not save the original file name and time stamp.
* (The original name is always saved if the name had to be truncated.)
* gunzip: do not restore the original file name/time even if present
* (remove only the gzip suffix from the compressed file name).
* This option is the default when decompressing.
* -N --name
* gzip: always save the original file name and time stamp (this is the default)
* gunzip: restore the original file name and time stamp if present.
*/
int gzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
#if ENABLE_GUNZIP
int gzip_main(int argc, char **argv)
#else
int gzip_main(int argc ATTRIBUTE_UNUSED, char **argv)
#endif
{
unsigned opt;
/* Must match bbunzip's constants OPT_STDOUT, OPT_FORCE! */
opt = getopt32(argv, "cfv" USE_GUNZIP("d") "q123456789n" );
opt = getopt32(argv, "cfv" USE_GUNZIP("d") "q123456789" );
#if ENABLE_GUNZIP /* gunzip_main may not be visible... */
if (opt & 0x8) // -d
return gunzip_main(argc, argv);
@@ -2060,8 +2042,8 @@ int gzip_main(int argc ATTRIBUTE_UNUSED, char **argv)
//if (opt & 0x4) // -v
argv += optind;
SET_PTR_TO_GLOBALS(xzalloc(sizeof(struct globals) + sizeof(struct globals2))
+ sizeof(struct globals));
PTR_TO_GLOBALS = xzalloc(sizeof(struct globals) + sizeof(struct globals2))
+ sizeof(struct globals);
G2.l_desc.dyn_tree = G2.dyn_ltree;
G2.l_desc.static_tree = G2.static_ltree;
G2.l_desc.extra_bits = extra_lbits;
@@ -12,7 +12,7 @@ ssize_t archive_xread_all_eof(archive_handle_t *archive_handle,
ssize_t size;
size = full_read(archive_handle->src_fd, buf, count);
if (size != 0 && size != (ssize_t)count) {
if (size != 0 && size != count) {
bb_error_msg_and_die("short read: %u of %u",
(unsigned)size, (unsigned)count);
}
+4 -2
View File
@@ -3,12 +3,14 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
//#include <sys/types.h>
#include "libbb.h"
#include "unarchive.h"
void data_align(archive_handle_t *archive_handle, unsigned boundary)
void data_align(archive_handle_t *archive_handle, const unsigned short boundary)
{
unsigned skip_amount = (boundary - (archive_handle->offset % boundary)) % boundary;
const unsigned short skip_amount = (boundary - (archive_handle->offset % boundary)) % boundary;
archive_handle->seek(archive_handle, skip_amount);
archive_handle->offset += skip_amount;
+1 -16
View File
@@ -20,7 +20,7 @@ void data_extract_all(archive_handle_t *archive_handle)
/* Check if the file already exists */
if (archive_handle->flags & ARCHIVE_EXTRACT_UNCONDITIONAL) {
/* Remove the entry if it exists */
/* Remove the existing entry if it exists */
if (((file_header->mode & S_IFMT) != S_IFDIR)
&& (unlink(file_header->name) == -1)
&& (errno != ENOENT)
@@ -112,22 +112,7 @@ void data_extract_all(archive_handle_t *archive_handle)
}
if (!(archive_handle->flags & ARCHIVE_NOPRESERVE_OWN)) {
#if ENABLE_FEATURE_TAR_UNAME_GNAME
uid_t uid = file_header->uid;
gid_t gid = file_header->gid;
if (file_header->uname) {
struct passwd *pwd = getpwnam(file_header->uname);
if (pwd) uid = pwd->pw_uid;
}
if (file_header->gname) {
struct group *grp = getgrnam(file_header->gname);
if (grp) gid = grp->gr_gid;
}
lchown(file_header->name, uid, gid);
#else
lchown(file_header->name, file_header->uid, file_header->gid);
#endif
}
if ((file_header->mode & S_IFMT) != S_IFLNK) {
/* uclibc has no lchmod, glibc is even stranger -
+80 -16
View File
@@ -66,6 +66,7 @@ struct group_data {
* | grep 'bd->' | sed 's/^.*bd->/bd->/' | sort | $PAGER
* and moved it (inbufBitCount) to offset 0.
*/
struct bunzip_data {
/* I/O tracking data (file handles, buffers, positions, etc.) */
unsigned inbufBitCount, inbufBits;
@@ -101,9 +102,11 @@ static unsigned get_bits(bunzip_data *bd, int bits_wanted)
/* If we need to get more data from the byte buffer, do so. (Loop getting
one byte at a time to enforce endianness and avoid unaligned access.) */
while ((int)(bd->inbufBitCount) < bits_wanted) {
while (bd->inbufBitCount < bits_wanted) {
/* If we need to read more data from file into byte buffer, do so */
if (bd->inbufPos == bd->inbufCount) {
/* if "no input fd" case: in_fd == -1, read fails, we jump */
bd->inbufCount = read(bd->in_fd, bd->inbuf, IOBUF_SIZE);
@@ -113,6 +116,7 @@ static unsigned get_bits(bunzip_data *bd, int bits_wanted)
}
/* Avoid 32-bit overflow (dump bit buffer to top of output) */
if (bd->inbufBitCount >= 24) {
bits = bd->inbufBits & ((1 << bd->inbufBitCount) - 1);
bits_wanted -= bd->inbufBitCount;
@@ -121,11 +125,13 @@ static unsigned get_bits(bunzip_data *bd, int bits_wanted)
}
/* Grab next 8 bits of input from buffer. */
bd->inbufBits = (bd->inbufBits << 8) | bd->inbuf[bd->inbufPos++];
bd->inbufBitCount += 8;
}
/* Calculate result */
bd->inbufBitCount -= bits_wanted;
bits |= (bd->inbufBits >> bd->inbufBitCount) & ((1 << bits_wanted) - 1);
@@ -133,6 +139,7 @@ static unsigned get_bits(bunzip_data *bd, int bits_wanted)
}
/* Unpacks the next block and sets up for the inverse burrows-wheeler step. */
static int get_next_block(bunzip_data *bd)
{
struct group_data *hufGroup;
@@ -146,11 +153,13 @@ static int get_next_block(bunzip_data *bd)
selectors = bd->selectors;
/* Reset longjmp I/O error handling */
i = setjmp(bd->jmpbuf);
if (i) return i;
/* Read in header signature and CRC, then validate signature.
(last block signature means CRC is for whole file, return now) */
i = get_bits(bd, 24);
j = get_bits(bd, 24);
bd->headerCRC = get_bits(bd, 32);
@@ -160,15 +169,17 @@ static int get_next_block(bunzip_data *bd)
/* We can add support for blockRandomised if anybody complains. There was
some code for this in busybox 1.0.0-pre3, but nobody ever noticed that
it didn't actually work. */
if (get_bits(bd, 1)) return RETVAL_OBSOLETE_INPUT;
origPtr = get_bits(bd, 24);
if ((int)origPtr > dbufSize) return RETVAL_DATA_ERROR;
if (origPtr > dbufSize) return RETVAL_DATA_ERROR;
/* mapping table: if some byte values are never used (encoding things
like ascii text), the compression code removes the gaps to have fewer
symbols to deal with, and writes a sparse bitfield indicating which
values were present. We make a translation table to convert the symbols
back to the corresponding bytes. */
t = get_bits(bd, 16);
symTotal = 0;
for (i = 0; i < 16; i++) {
@@ -181,6 +192,7 @@ static int get_next_block(bunzip_data *bd)
}
/* How many different Huffman coding groups does this block use? */
groupCount = get_bits(bd, 3);
if (groupCount < 2 || groupCount > MAX_GROUPS)
return RETVAL_DATA_ERROR;
@@ -189,16 +201,19 @@ static int get_next_block(bunzip_data *bd)
group. Read in the group selector list, which is stored as MTF encoded
bit runs. (MTF=Move To Front, as each value is used it's moved to the
start of the list.) */
nSelectors = get_bits(bd, 15);
if (!nSelectors) return RETVAL_DATA_ERROR;
for (i = 0; i < groupCount; i++) mtfSymbol[i] = i;
for (i = 0; i < nSelectors; i++) {
/* Get next value */
for (j = 0; get_bits(bd, 1); j++)
if (j >= groupCount) return RETVAL_DATA_ERROR;
/* Decode MTF to get the next selector */
uc = mtfSymbol[j];
for (;j;j--) mtfSymbol[j] = mtfSymbol[j-1];
mtfSymbol[0] = selectors[i] = uc;
@@ -206,11 +221,10 @@ static int get_next_block(bunzip_data *bd)
/* Read the Huffman coding tables for each group, which code for symTotal
literal symbols, plus two run symbols (RUNA, RUNB) */
symCount = symTotal + 2;
for (j = 0; j < groupCount; j++) {
unsigned char length[MAX_SYMBOLS];
/* 8 bits is ALMOST enough for temp[], see below */
unsigned temp[MAX_HUFCODE_BITS+1];
unsigned char length[MAX_SYMBOLS], temp[MAX_HUFCODE_BITS+1];
int minLen, maxLen, pp;
/* Read Huffman code lengths for each symbol. They're stored in
@@ -219,6 +233,7 @@ static int get_next_block(bunzip_data *bd)
(Subtracting 1 before the loop and then adding it back at the end is
an optimization that makes the test inside the loop simpler: symbol
length 0 becomes negative, so an unsigned inequality catches it.) */
t = get_bits(bd, 5) - 1;
for (i = 0; i < symCount; i++) {
for (;;) {
@@ -228,6 +243,7 @@ static int get_next_block(bunzip_data *bd)
/* If first bit is 0, stop. Else second bit indicates whether
to increment or decrement the value. Optimization: grab 2
bits and unget the second if the first was 0. */
k = get_bits(bd, 2);
if (k < 2) {
bd->inbufBitCount++;
@@ -235,14 +251,17 @@ static int get_next_block(bunzip_data *bd)
}
/* Add one if second bit 1, else subtract 1. Avoids if/else */
t += (((k+1) & 2) - 1);
}
/* Correct for the initial -1, to get the final symbol length */
length[i] = t + 1;
}
/* Find largest and smallest lengths in this group */
minLen = maxLen = length[0];
for (i = 1; i < symCount; i++) {
if (length[i] > maxLen) maxLen = length[i];
@@ -259,6 +278,7 @@ static int get_next_block(bunzip_data *bd)
* number of bits can have. This is how the Huffman codes can vary in
* length: each code with a value>limit[length] needs another bit.
*/
hufGroup = bd->groups + j;
hufGroup->minLen = minLen;
hufGroup->maxLen = maxLen;
@@ -266,10 +286,12 @@ static int get_next_block(bunzip_data *bd)
/* Note that minLen can't be smaller than 1, so we adjust the base
and limit array pointers so we're not always wasting the first
entry. We do this again when using them (during symbol decoding).*/
base = hufGroup->base - 1;
limit = hufGroup->limit - 1;
/* Calculate permute[]. Concurently, initialize temp[] and limit[]. */
pp = 0;
for (i = minLen; i <= maxLen; i++) {
temp[i] = limit[i] = 0;
@@ -279,14 +301,14 @@ static int get_next_block(bunzip_data *bd)
}
/* Count symbols coded for at each bit length */
/* NB: in pathological cases, temp[8] can end ip being 256.
* That's why uint8_t is too small for temp[]. */
for (i = 0; i < symCount; i++) temp[length[i]]++;
/* Calculate limit[] (the largest symbol-coding value at each bit
* length, which is (previous limit<<1)+symbols at this level), and
* base[] (number of symbols to ignore at each bit length, which is
* limit minus the cumulative count of symbols coded for already). */
pp = t = 0;
for (i = minLen; i < maxLen; i++) {
pp += temp[i];
@@ -297,6 +319,7 @@ static int get_next_block(bunzip_data *bd)
each level we're really only interested in the first few bits,
so here we set all the trailing to-be-ignored bits to 1 so they
don't affect the value>limit[length] comparison. */
limit[i] = (pp << (maxLen - i)) - 1;
pp <<= 1;
t += temp[i];
@@ -312,6 +335,7 @@ static int get_next_block(bunzip_data *bd)
and run length encoding, saving the result into dbuf[dbufCount++] = uc */
/* Initialize symbol occurrence counters and symbol Move To Front table */
memset(byteCount, 0, sizeof(byteCount)); /* smaller, maybe slower? */
for (i = 0; i < 256; i++) {
//byteCount[i] = 0;
@@ -323,7 +347,8 @@ static int get_next_block(bunzip_data *bd)
runPos = dbufCount = selector = 0;
for (;;) {
/* Fetch next Huffman coding group from list. */
/* fetch next Huffman coding group from list. */
symCount = GROUP_SIZE - 1;
if (selector >= nSelectors) return RETVAL_DATA_ERROR;
hufGroup = bd->groups + selectors[selector++];
@@ -342,7 +367,8 @@ static int get_next_block(bunzip_data *bd)
dry). The following (up to got_huff_bits:) is equivalent to
j = get_bits(bd, hufGroup->maxLen);
*/
while ((int)(bd->inbufBitCount) < hufGroup->maxLen) {
while (bd->inbufBitCount < hufGroup->maxLen) {
if (bd->inbufPos == bd->inbufCount) {
j = get_bits(bd, hufGroup->maxLen);
goto got_huff_bits;
@@ -356,11 +382,13 @@ static int get_next_block(bunzip_data *bd)
got_huff_bits:
/* Figure how how many bits are in next symbol and unget extras */
i = hufGroup->minLen;
while (j > limit[i]) ++i;
bd->inbufBitCount += (hufGroup->maxLen - i);
/* Huffman decode value to get nextSym (with bounds checking) */
if (i > hufGroup->maxLen)
return RETVAL_DATA_ERROR;
j = (j >> (hufGroup->maxLen - i)) - base[i];
@@ -372,9 +400,11 @@ static int get_next_block(bunzip_data *bd)
byte, or a repeated run of the most recent literal byte. First,
check if nextSym indicates a repeated run, and if so loop collecting
how many times to repeat the last literal. */
if ((unsigned)nextSym <= SYMBOL_RUNB) { /* RUNA or RUNB */
/* If this is the start of a new run, zero out counter */
if (!runPos) {
runPos = 1;
t = 0;
@@ -387,6 +417,7 @@ static int get_next_block(bunzip_data *bd)
the basic or 0/1 method (except all bits 0, which would use no
symbols, but a run of length 0 doesn't mean anything in this
context). Thus space is saved. */
t += (runPos << nextSym); /* +runPos if RUNA; +2*runPos if RUNB */
if (runPos < dbufSize) runPos <<= 1;
goto end_of_huffman_loop;
@@ -396,6 +427,7 @@ static int get_next_block(bunzip_data *bd)
how many times to repeat the last literal, so append that many
copies to our buffer of decoded symbols (dbuf) now. (The last
literal used is the one at the head of the mtfSymbol array.) */
if (runPos) {
runPos = 0;
if (dbufCount + t >= dbufSize) return RETVAL_DATA_ERROR;
@@ -406,6 +438,7 @@ static int get_next_block(bunzip_data *bd)
}
/* Is this the terminating symbol? */
if (nextSym > symTotal) break;
/* At this point, nextSym indicates a new literal character. Subtract
@@ -415,6 +448,7 @@ static int get_next_block(bunzip_data *bd)
first symbol in the mtf array, position 0, would have been handled
as part of a run above. Therefore 1 unused mtf position minus
2 non-literal nextSym values equals -1.) */
if (dbufCount >= dbufSize) return RETVAL_DATA_ERROR;
i = nextSym - 1;
uc = mtfSymbol[i];
@@ -423,6 +457,7 @@ static int get_next_block(bunzip_data *bd)
* small number of symbols, and are bound by 256 in any case, using
* memmove here would typically be bigger and slower due to function
* call overhead and other assorted setup costs. */
do {
mtfSymbol[i] = mtfSymbol[i-1];
} while (--i);
@@ -430,11 +465,13 @@ static int get_next_block(bunzip_data *bd)
uc = symToByte[uc];
/* We have our literal byte. Save it into dbuf. */
byteCount[uc]++;
dbuf[dbufCount++] = (unsigned)uc;
/* Skip group initialization if we're not done with this group. Done
* this way to avoid compiler warning. */
end_of_huffman_loop:
if (symCount--) goto continue_this_group;
}
@@ -447,6 +484,7 @@ static int get_next_block(bunzip_data *bd)
*/
/* Turn byteCount into cumulative occurrence counts of 0 to n-1. */
j = 0;
for (i = 0; i < 256; i++) {
k = j + byteCount[i];
@@ -455,6 +493,7 @@ static int get_next_block(bunzip_data *bd)
}
/* Figure out what order dbuf would be in if we sorted it. */
for (i = 0; i < dbufCount; i++) {
uc = (unsigned char)(dbuf[i] & 0xff);
dbuf[byteCount[uc]] |= (i << 8);
@@ -464,10 +503,11 @@ static int get_next_block(bunzip_data *bd)
/* Decode first byte by hand to initialize "previous" byte. Note that it
doesn't get output, and if the first three characters are identical
it doesn't qualify as a run (hence writeRunCountdown=5). */
if (dbufCount) {
if ((int)origPtr >= dbufCount) return RETVAL_DATA_ERROR;
if (origPtr >= dbufCount) return RETVAL_DATA_ERROR;
bd->writePos = dbuf[origPtr];
bd->writeCurrent = (unsigned char)(bd->writePos & 0xff);
bd->writeCurrent = (unsigned char)(bd->writePos & 0xff);
bd->writePos >>= 8;
bd->writeRunCountdown = 5;
}
@@ -482,6 +522,7 @@ static int get_next_block(bunzip_data *bd)
error (all errors are negative numbers). If out_fd!=-1, outbuf and len
are ignored, data is written to out_fd and return is RETVAL_OK or error.
*/
int read_bunzip(bunzip_data *bd, char *outbuf, int len)
{
const unsigned *dbuf;
@@ -498,15 +539,19 @@ int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* We will always have pending decoded data to write into the output
buffer unless this is the very first call (in which case we haven't
Huffman-decoded a block into the intermediate buffer yet). */
if (bd->writeCopies) {
/* Inside the loop, writeCopies means extra copies (beyond 1) */
--bd->writeCopies;
/* Loop outputting bytes */
for (;;) {
/* If the output buffer is full, snapshot state and return */
if (gotcount >= len) {
bd->writePos = pos;
bd->writeCurrent = current;
@@ -515,11 +560,13 @@ int read_bunzip(bunzip_data *bd, char *outbuf, int len)
}
/* Write next byte into output buffer, updating CRC */
outbuf[gotcount++] = current;
bd->writeCRC = (bd->writeCRC << 8)
^ bd->crc32Table[(bd->writeCRC >> 24) ^ current];
^ bd->crc32Table[(bd->writeCRC >> 24) ^ current];
/* Loop now if we're outputting multiple copies of this byte */
if (bd->writeCopies) {
--bd->writeCopies;
continue;
@@ -535,29 +582,35 @@ int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* After 3 consecutive copies of the same byte, the 4th
* is a repeat count. We count down from 4 instead
* of counting up because testing for non-zero is faster */
if (--bd->writeRunCountdown) {
if (current != previous)
bd->writeRunCountdown = 4;
} else {
/* We have a repeated run, this byte indicates the count */
bd->writeCopies = current;
current = previous;
bd->writeRunCountdown = 5;
/* Sometimes there are just 3 bytes (run length 0) */
if (!bd->writeCopies) goto decode_next_byte;
/* Subtract the 1 copy we'd output anyway to get extras */
--bd->writeCopies;
}
}
/* Decompression of this block completed successfully */
bd->writeCRC = ~bd->writeCRC;
bd->totalCRC = ((bd->totalCRC << 1) | (bd->totalCRC >> 31)) ^ bd->writeCRC;
/* If this block had a CRC error, force file level CRC error. */
if (bd->writeCRC != bd->headerCRC) {
bd->totalCRC = bd->headerCRC + 1;
return RETVAL_LAST_BLOCK;
@@ -566,6 +619,7 @@ int read_bunzip(bunzip_data *bd, char *outbuf, int len)
/* Refill the intermediate buffer by Huffman-decoding next block of input */
/* (previous is just a convenient unused temp variable here) */
previous = get_next_block(bd);
if (previous) {
bd->writeCount = previous;
@@ -577,6 +631,7 @@ int read_bunzip(bunzip_data *bd, char *outbuf, int len)
goto decode_next_byte;
}
/* Allocate the structure, read file header. If in_fd==-1, inbuf must contain
a complete bunzip file (len bytes long). If in_fd!=-1, inbuf and len are
ignored, and data is read from file handle into temporary buffer. */
@@ -584,6 +639,7 @@ 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! */
int start_bunzip(bunzip_data **bdp, int in_fd, const unsigned char *inbuf,
int len)
{
@@ -594,13 +650,16 @@ int start_bunzip(bunzip_data **bdp, int in_fd, const unsigned char *inbuf,
};
/* Figure out how much data to allocate */
i = sizeof(bunzip_data);
if (in_fd != -1) i += IOBUF_SIZE;
/* Allocate bunzip_data. Most fields initialize to zero. */
bd = *bdp = xzalloc(i);
/* Setup input buffer */
bd->in_fd = in_fd;
if (-1 == in_fd) {
/* in this case, bd->inbuf is read-only */
@@ -610,18 +669,22 @@ int start_bunzip(bunzip_data **bdp, int in_fd, const unsigned char *inbuf,
bd->inbuf = (unsigned char *)(bd + 1);
/* Init the CRC32 table (big endian) */
crc32_filltable(bd->crc32Table, 1);
/* Setup for I/O error handling via longjmp */
i = setjmp(bd->jmpbuf);
if (i) return i;
/* Ensure that file starts with "BZh['1'-'9']." */
i = get_bits(bd, 32);
if ((unsigned)(i - BZh0 - 1) >= 9) return RETVAL_NOT_BZIP_DATA;
/* Fourth byte (ascii '1'-'9') indicates block size in units of 100k of
/* Fourth byte (ascii '1'-'9'), indicates block size in units of 100k of
uncompressed data. Allocate intermediate buffer for block. */
bd->dbufSize = 100000 * (i - BZh0);
/* Cannot use xmalloc - may leak bd in NOFORK case! */
@@ -641,6 +704,7 @@ void dealloc_bunzip(bunzip_data *bd)
/* Decompress src_fd to dst_fd. Stops at end of bzip data, not end of file. */
USE_DESKTOP(long long) int
unpack_bz2_stream(int src_fd, int dst_fd)
{
@@ -697,9 +761,9 @@ int main(int argc, char **argv)
char c;
if (i < 0)
fprintf(stderr, "%s\n", bunzip_errors[-i]);
else if (read(STDIN_FILENO, &c, 1))
fprintf(stderr, "Trailing garbage ignored\n");
fprintf(stderr,"%s\n", bunzip_errors[-i]);
else if (read(0, &c, 1))
fprintf(stderr,"Trailing garbage ignored\n");
return -i;
}
#endif
+43 -44
View File
@@ -282,16 +282,14 @@ unpack_lzma_stream(int src_fd, int dst_fd)
while (global_pos + buffer_pos < header.dst_size) {
int pos_state = (buffer_pos + global_pos) & pos_state_mask;
prob = p + LZMA_IS_MATCH + (state << LZMA_NUM_POS_BITS_MAX) + pos_state;
prob =
p + LZMA_IS_MATCH + (state << LZMA_NUM_POS_BITS_MAX) + pos_state;
if (rc_is_bit_0(rc, prob)) {
mi = 1;
rc_update_bit_0(rc, prob);
prob = (p + LZMA_LITERAL
+ (LZMA_LIT_SIZE * ((((buffer_pos + global_pos) & literal_pos_mask) << lc)
+ (previous_byte >> (8 - lc))
)
)
);
prob = (p + LZMA_LITERAL + (LZMA_LIT_SIZE
* ((((buffer_pos + global_pos) & literal_pos_mask) << lc)
+ (previous_byte >> (8 - lc)))));
if (state >= LZMA_NUM_LIT_STATES) {
int match_byte;
@@ -306,37 +304,35 @@ unpack_lzma_stream(int src_fd, int dst_fd)
match_byte <<= 1;
bit = match_byte & 0x100;
prob_lit = prob + 0x100 + bit + mi;
bit ^= (rc_get_bit(rc, prob_lit, &mi) << 8); /* 0x100 or 0 */
if (bit)
break;
if (rc_get_bit(rc, prob_lit, &mi)) {
if (!bit)
break;
} else {
if (bit)
break;
}
} while (mi < 0x100);
}
while (mi < 0x100) {
prob_lit = prob + mi;
rc_get_bit(rc, prob_lit, &mi);
}
state -= 3;
if (state < 4-3)
state = 0;
if (state >= 10-3)
state -= 6-3;
previous_byte = (uint8_t) mi;
#if ENABLE_FEATURE_LZMA_FAST
one_byte1:
buffer[buffer_pos++] = previous_byte;
if (buffer_pos == header.dict_size) {
buffer_pos = 0;
global_pos += header.dict_size;
if (full_write(dst_fd, buffer, header.dict_size) != (ssize_t)header.dict_size)
if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
goto bad;
USE_DESKTOP(total_written += header.dict_size;)
}
#else
len = 1;
goto one_byte2;
#endif
if (state < 4)
state = 0;
else if (state < 10)
state -= 3;
else
state -= 6;
} else {
int offset;
uint16_t *prob_len;
@@ -356,23 +352,24 @@ unpack_lzma_stream(int src_fd, int dst_fd)
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
prob = (p + LZMA_IS_REP_0_LONG
+ (state << LZMA_NUM_POS_BITS_MAX)
+ pos_state
);
+ (state << LZMA_NUM_POS_BITS_MAX) + pos_state);
if (rc_is_bit_0(rc, prob)) {
rc_update_bit_0(rc, prob);
state = state < LZMA_NUM_LIT_STATES ? 9 : 11;
#if ENABLE_FEATURE_LZMA_FAST
pos = buffer_pos - rep0;
while (pos >= header.dict_size)
pos += header.dict_size;
previous_byte = buffer[pos];
goto one_byte1;
#else
len = 1;
goto string;
#endif
buffer[buffer_pos++] = previous_byte;
if (buffer_pos == header.dict_size) {
buffer_pos = 0;
global_pos += header.dict_size;
if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
goto bad;
USE_DESKTOP(total_written += header.dict_size;)
}
continue;
} else {
rc_update_bit_1(rc, prob);
}
@@ -408,7 +405,7 @@ unpack_lzma_stream(int src_fd, int dst_fd)
if (rc_is_bit_0(rc, prob_len)) {
rc_update_bit_0(rc, prob_len);
prob_len = (prob + LZMA_LEN_LOW
+ (pos_state << LZMA_LEN_NUM_LOW_BITS));
+ (pos_state << LZMA_LEN_NUM_LOW_BITS));
offset = 0;
num_bits = LZMA_LEN_NUM_LOW_BITS;
} else {
@@ -417,14 +414,14 @@ unpack_lzma_stream(int src_fd, int dst_fd)
if (rc_is_bit_0(rc, prob_len)) {
rc_update_bit_0(rc, prob_len);
prob_len = (prob + LZMA_LEN_MID
+ (pos_state << LZMA_LEN_NUM_MID_BITS));
+ (pos_state << LZMA_LEN_NUM_MID_BITS));
offset = 1 << LZMA_LEN_NUM_LOW_BITS;
num_bits = LZMA_LEN_NUM_MID_BITS;
} else {
rc_update_bit_1(rc, prob_len);
prob_len = prob + LZMA_LEN_HIGH;
offset = ((1 << LZMA_LEN_NUM_LOW_BITS)
+ (1 << LZMA_LEN_NUM_MID_BITS));
+ (1 << LZMA_LEN_NUM_MID_BITS));
num_bits = LZMA_LEN_NUM_HIGH_BITS;
}
}
@@ -435,10 +432,12 @@ unpack_lzma_stream(int src_fd, int dst_fd)
int pos_slot;
state += LZMA_NUM_LIT_STATES;
prob = p + LZMA_POS_SLOT +
((len < LZMA_NUM_LEN_TO_POS_STATES ? len :
LZMA_NUM_LEN_TO_POS_STATES - 1)
<< LZMA_NUM_POS_SLOT_BITS);
prob =
p + LZMA_POS_SLOT +
((len <
LZMA_NUM_LEN_TO_POS_STATES ? len :
LZMA_NUM_LEN_TO_POS_STATES - 1)
<< LZMA_NUM_POS_SLOT_BITS);
rc_bit_tree_decode(rc, prob, LZMA_NUM_POS_SLOT_BITS,
&pos_slot);
if (pos_slot >= LZMA_START_POS_MODEL_INDEX) {
@@ -469,18 +468,17 @@ unpack_lzma_stream(int src_fd, int dst_fd)
}
len += LZMA_MATCH_MIN_LEN;
SKIP_FEATURE_LZMA_FAST(string:)
do {
pos = buffer_pos - rep0;
while (pos >= header.dict_size)
pos += header.dict_size;
previous_byte = buffer[pos];
SKIP_FEATURE_LZMA_FAST(one_byte2:)
buffer[buffer_pos++] = previous_byte;
if (buffer_pos == header.dict_size) {
buffer_pos = 0;
global_pos += header.dict_size;
if (full_write(dst_fd, buffer, header.dict_size) != (ssize_t)header.dict_size)
if (full_write(dst_fd, buffer, header.dict_size) != header.dict_size)
goto bad;
USE_DESKTOP(total_written += header.dict_size;)
}
@@ -489,7 +487,8 @@ unpack_lzma_stream(int src_fd, int dst_fd)
}
}
if (full_write(dst_fd, buffer, buffer_pos) != (ssize_t)buffer_pos) {
if (full_write(dst_fd, buffer, buffer_pos) != buffer_pos) {
bad:
rc_free(rc);
return -1;
+9 -20
View File
@@ -85,8 +85,7 @@ typedef struct state_t {
/* input (compressed) data */
unsigned char *bytebuffer; /* buffer itself */
off_t to_read; /* compressed bytes to read (unzip only, -1 for gunzip) */
// unsigned bytebuffer_max; /* buffer size */
unsigned bytebuffer_max; /* buffer size */
unsigned bytebuffer_offset; /* buffer position */
unsigned bytebuffer_size; /* how much data is there (size <= max) */
@@ -127,10 +126,7 @@ typedef struct state_t {
#define gunzip_crc_table (S()gunzip_crc_table )
#define gunzip_bb (S()gunzip_bb )
#define gunzip_bk (S()gunzip_bk )
#define to_read (S()to_read )
// #define bytebuffer_max (S()bytebuffer_max )
// Both gunzip and unzip can use constant buffer size now (16k):
#define bytebuffer_max 0x4000
#define bytebuffer_max (S()bytebuffer_max )
#define bytebuffer (S()bytebuffer )
#define bytebuffer_offset (S()bytebuffer_offset )
#define bytebuffer_size (S()bytebuffer_size )
@@ -255,18 +251,13 @@ static unsigned fill_bitbuffer(STATE_PARAM unsigned bitbuffer, unsigned *current
{
while (*current < required) {
if (bytebuffer_offset >= bytebuffer_size) {
unsigned sz = bytebuffer_max - 4;
if (to_read >= 0 && to_read < sz) /* unzip only */
sz = to_read;
/* Leave the first 4 bytes empty so we can always unwind the bitbuffer
* to the front of the bytebuffer */
bytebuffer_size = safe_read(gunzip_src_fd, &bytebuffer[4], sz);
bytebuffer_size = safe_read(gunzip_src_fd, &bytebuffer[4], bytebuffer_max - 4);
if ((int)bytebuffer_size < 1) {
error_msg = "unexpected end of file";
abort_unzip(PASS_STATE_ONLY);
}
if (to_read >= 0) /* unzip only */
to_read -= bytebuffer_size;
bytebuffer_size += 4;
bytebuffer_offset = 4;
}
@@ -922,7 +913,7 @@ static int inflate_block(STATE_PARAM smallint *e)
/* Two callsites, both in inflate_get_next_window */
static void calculate_gunzip_crc(STATE_PARAM_ONLY)
{
unsigned n;
int n;
for (n = 0; n < gunzip_outbuf_count; n++) {
gunzip_crc = gunzip_crc_table[((int) gunzip_crc ^ (gunzip_window[n])) & 0xff] ^ (gunzip_crc >> 8);
}
@@ -1003,7 +994,7 @@ inflate_unzip_internal(STATE_PARAM int in, int out)
while (1) {
int r = inflate_get_next_window(PASS_STATE_ONLY);
nwrote = full_write(out, gunzip_window, gunzip_outbuf_count);
if (nwrote != (ssize_t)gunzip_outbuf_count) {
if (nwrote != gunzip_outbuf_count) {
bb_perror_msg("write");
n = -1;
goto ret;
@@ -1034,15 +1025,14 @@ inflate_unzip_internal(STATE_PARAM int in, int out)
/* For unzip */
USE_DESKTOP(long long) int
inflate_unzip(inflate_unzip_result *res, off_t compr_size, int in, int out)
inflate_unzip(inflate_unzip_result *res, unsigned bufsize, int in, int out)
{
USE_DESKTOP(long long) int n;
DECLARE_STATE;
ALLOC_STATE;
to_read = compr_size;
// bytebuffer_max = 0x8000;
bytebuffer_max = bufsize + 4;
bytebuffer_offset = 4;
bytebuffer = xmalloc(bytebuffer_max);
n = inflate_unzip_internal(PASS_STATE in, out);
@@ -1064,7 +1054,7 @@ static int top_up(STATE_PARAM unsigned n)
{
int count = bytebuffer_size - bytebuffer_offset;
if (count < (int)n) {
if (count < n) {
memmove(bytebuffer, &bytebuffer[bytebuffer_offset], count);
bytebuffer_offset = 0;
bytebuffer_size = full_read(gunzip_src_fd, &bytebuffer[count], bytebuffer_max - count);
@@ -1186,8 +1176,7 @@ unpack_gz_stream(int in, int out)
n = 0;
ALLOC_STATE;
to_read = -1;
// bytebuffer_max = 0x8000;
bytebuffer_max = 0x8000;
bytebuffer = xmalloc(bytebuffer_max);
gunzip_src_fd = in;
@@ -13,14 +13,11 @@
*/
char filter_accept_reject_list(archive_handle_t *archive_handle)
{
const char *key;
const llist_t *reject_entry;
const char *key = archive_handle->file_header->name;
const llist_t *reject_entry = find_list_entry2(archive_handle->reject, key);
const llist_t *accept_entry;
key = archive_handle->file_header->name;
/* If the key is in a reject list fail */
reject_entry = find_list_entry2(archive_handle->reject, key);
if (reject_entry) {
return EXIT_FAILURE;
}
+1 -1
View File
@@ -38,7 +38,7 @@ const llist_t *find_list_entry2(const llist_t *list, const char *filename)
if (*c++ == '/') pattern_slash_cnt++;
c = filename;
d = buf;
/* paranoia is better than buffer overflows */
/* paranoia is better that buffer overflows */
while (*c && d != buf + sizeof(buf)-1) {
if (*c == '/' && --pattern_slash_cnt < 0)
break;
+90 -98
View File
@@ -7,33 +7,71 @@
#include "libbb.h"
#include "unarchive.h"
typedef struct hardlinks_t {
struct hardlinks_t *next;
int inode; /* TODO: must match maj/min too! */
int mode ;
int mtime; /* These three are useful only in corner case */
int uid ; /* of hardlinks with zero size body */
int gid ;
char name[1];
typedef struct hardlinks_s {
char *name;
int inode;
struct hardlinks_s *next;
} hardlinks_t;
char get_header_cpio(archive_handle_t *archive_handle)
{
static hardlinks_t *saved_hardlinks = NULL;
static hardlinks_t *saved_hardlinks_created = NULL;
static unsigned pending_hardlinks = 0;
static int inode;
file_header_t *file_header = archive_handle->file_header;
char cpio_header[110];
char dummy[16];
int namesize;
int major, minor, nlink, mode, inode;
unsigned size, uid, gid, mtime;
char dummy[16];
int major, minor, nlink;
if (pending_hardlinks) { /* Deal with any pending hardlinks */
hardlinks_t *tmp, *oldtmp;
tmp = saved_hardlinks;
oldtmp = NULL;
file_header->link_target = file_header->name;
file_header->size = 0;
while (tmp) {
if (tmp->inode != inode) {
tmp = tmp->next;
continue;
}
file_header->name = tmp->name;
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_data(archive_handle);
archive_handle->action_header(archive_handle->file_header);
}
pending_hardlinks--;
oldtmp = tmp;
tmp = tmp->next;
free(oldtmp->name);
free(oldtmp);
if (oldtmp == saved_hardlinks)
saved_hardlinks = tmp;
}
file_header->name = file_header->link_target;
if (pending_hardlinks > 1) {
bb_error_msg("error resolving hardlink: archive made by GNU cpio 2.0-2.2?");
}
/* No more pending hardlinks, read next file entry */
pending_hardlinks = 0;
}
/* There can be padding before archive header */
data_align(archive_handle, 4);
if (archive_xread_all_eof(archive_handle, (unsigned char*)cpio_header, 110) == 0) {
goto create_hardlinks;
return EXIT_FAILURE;
}
archive_handle->offset += 110;
@@ -43,19 +81,17 @@ char get_header_cpio(archive_handle_t *archive_handle)
bb_error_msg_and_die("unsupported cpio format, use newc or crc");
}
sscanf(cpio_header + 6,
"%8x" "%8x" "%8x" "%8x"
"%8x" "%8x" "%8x" /*maj,min:*/ "%16c"
/*rmaj,rmin:*/"%8x" "%8x" "%8x" /*chksum:*/ "%8c",
&inode, &mode, &uid, &gid,
&nlink, &mtime, &size, dummy,
&major, &minor, &namesize, dummy);
file_header->mode = mode;
file_header->uid = uid;
file_header->gid = gid;
file_header->mtime = mtime;
file_header->size = size;
{
unsigned long tmpsize;
sscanf(cpio_header, "%6c%8x%8x%8x%8x%8x%8lx%8lx%16c%8x%8x%8x%8c",
dummy, &inode, (unsigned int*)&file_header->mode,
(unsigned int*)&file_header->uid, (unsigned int*)&file_header->gid,
&nlink, &file_header->mtime, &tmpsize,
dummy, &major, &minor, &namesize, dummy);
file_header->size = tmpsize;
}
free(file_header->name);
file_header->name = xzalloc(namesize + 1);
/* Read in filename */
xread(archive_handle->src_fd, file_header->name, namesize);
@@ -65,9 +101,25 @@ char get_header_cpio(archive_handle_t *archive_handle)
data_align(archive_handle, 4);
if (strcmp(file_header->name, "TRAILER!!!") == 0) {
/* Always round up. ">> 9" divides by 512 */
printf("%"OFF_FMT"u blocks\n", (archive_handle->offset + 511) >> 9);
goto create_hardlinks;
/* Always round up */
printf("%d blocks\n", (int) (archive_handle->offset % 512 ?
archive_handle->offset / 512 + 1 :
archive_handle->offset / 512
));
if (saved_hardlinks) { /* Bummer - we still have unresolved hardlinks */
hardlinks_t *tmp = saved_hardlinks;
hardlinks_t *oldtmp = NULL;
while (tmp) {
bb_error_msg("%s not created: cannot resolve hardlink", tmp->name);
oldtmp = tmp;
tmp = tmp->next;
free(oldtmp->name);
free(oldtmp);
}
saved_hardlinks = NULL;
pending_hardlinks = 0;
}
return EXIT_FAILURE;
}
if (S_ISLNK(file_header->mode)) {
@@ -78,33 +130,25 @@ char get_header_cpio(archive_handle_t *archive_handle)
} else {
file_header->link_target = NULL;
}
// TODO: data_extract_all can't deal with hardlinks to non-files...
// (should be !S_ISDIR instead of S_ISREG here)
if (nlink > 1 && S_ISREG(file_header->mode)) {
hardlinks_t *new = xmalloc(sizeof(*new) + namesize);
new->inode = inode;
new->mode = mode ;
new->mtime = mtime;
new->uid = uid ;
new->gid = gid ;
strcpy(new->name, file_header->name);
/* Put file on a linked list for later */
if (size == 0) {
if (nlink > 1 && !S_ISDIR(file_header->mode)) {
if (file_header->size == 0) { /* Put file on a linked list for later */
hardlinks_t *new = xmalloc(sizeof(hardlinks_t));
new->next = saved_hardlinks;
new->inode = inode;
/* name current allocated, freed later */
new->name = file_header->name;
file_header->name = NULL;
saved_hardlinks = new;
return EXIT_SUCCESS; /* Skip this one */
/* TODO: this breaks cpio -t (it does not show hardlinks) */
}
new->next = saved_hardlinks_created;
saved_hardlinks_created = new;
/* Found the file with data in */
pending_hardlinks = nlink;
}
file_header->device = makedev(major, minor);
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS) {
archive_handle->action_data(archive_handle);
archive_handle->action_header(file_header);
archive_handle->action_header(archive_handle->file_header);
} else {
data_skip(archive_handle);
}
@@ -112,58 +156,6 @@ char get_header_cpio(archive_handle_t *archive_handle)
archive_handle->offset += file_header->size;
free(file_header->link_target);
free(file_header->name);
file_header->link_target = NULL;
file_header->name = NULL;
return EXIT_SUCCESS;
create_hardlinks:
free(file_header->link_target);
free(file_header->name);
while (saved_hardlinks) {
hardlinks_t *cur;
hardlinks_t *make_me = saved_hardlinks;
saved_hardlinks = make_me->next;
memset(file_header, 0, sizeof(*file_header));
file_header->name = make_me->name;
file_header->mode = make_me->mode;
/*file_header->size = 0;*/
/* Try to find a file we are hardlinked to */
cur = saved_hardlinks_created;
while (cur) {
/* TODO: must match maj/min too! */
if (cur->inode == make_me->inode) {
file_header->link_target = cur->name;
/* link_target != NULL, size = 0: "I am a hardlink" */
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS)
archive_handle->action_data(archive_handle);
free(make_me);
goto next_link;
}
cur = cur->next;
}
/* Oops... no file with such inode was created... do it now
* (happens when hardlinked files are empty (zero length)) */
file_header->mtime = make_me->mtime;
file_header->uid = make_me->uid ;
file_header->gid = make_me->gid ;
if (archive_handle->filter(archive_handle) == EXIT_SUCCESS)
archive_handle->action_data(archive_handle);
/* Move to the list of created hardlinked files */
make_me->next = saved_hardlinks_created;
saved_hardlinks_created = make_me;
next_link: ;
}
while (saved_hardlinks_created) {
hardlinks_t *p = saved_hardlinks_created;
saved_hardlinks_created = p->next;
free(p);
}
return EXIT_FAILURE; /* "No more files to process" */
}
+15 -76
View File
@@ -46,9 +46,6 @@ void BUG_tar_header_size(void);
char get_header_tar(archive_handle_t *archive_handle)
{
static smallint end;
#if ENABLE_FEATURE_TAR_AUTODETECT
static smallint not_first;
#endif
file_header_t *file_header = archive_handle->file_header;
struct {
@@ -93,32 +90,17 @@ char get_header_tar(archive_handle_t *archive_handle)
again_after_align:
#if ENABLE_DESKTOP
i = full_read(archive_handle->src_fd, &tar, 512);
/* if GNU tar sees EOF in above read, it says:
* "tar: A lone zero block at N", where N = kilobyte
* where EOF was met (not EOF block, actual EOF!),
* and tar will exit with error code 0.
* We will mimic exit(EXIT_SUCCESS), although we will not mimic
* the message and we don't check whether we indeed
* saw zero block directly before this. */
if (i == 0)
xfunc_error_retval = 0;
if (i != 512)
bb_error_msg_and_die("short read");
#else
xread(archive_handle->src_fd, &tar, 512);
#endif
archive_handle->offset += 512;
/* If there is no filename its an empty header */
if (tar.name[0] == 0 && tar.prefix[0] == 0) {
if (tar.name[0] == 0) {
if (end) {
/* This is the second consecutive empty header! End of archive!
* Read until the end to empty the pipe from gz or bz2
*/
while (full_read(archive_handle->src_fd, &tar, 512) == 512)
continue;
/* repeat */;
return EXIT_FAILURE;
}
end = 1;
@@ -126,49 +108,16 @@ char get_header_tar(archive_handle_t *archive_handle)
}
end = 0;
/* Check header has valid magic, "ustar" is for the proper tar,
* five NULs are for the old tar format */
if (strncmp(tar.magic, "ustar", 5) != 0
&& (!ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
|| memcmp(tar.magic, "\0\0\0\0", 5) != 0)
) {
#if ENABLE_FEATURE_TAR_AUTODETECT
char (*get_header_ptr)(archive_handle_t *);
/* tar gz/bz autodetect: check for gz/bz2 magic.
* If it is the very first block, and we see the magic,
* we can switch to get_header_tar_gz/bz2/lzma().
* Needs seekable fd. I wish recv(MSG_PEEK) works
* on any fd... */
if (not_first)
goto err;
#if ENABLE_FEATURE_TAR_GZIP
if (tar.name[0] == 0x1f && tar.name[1] == (char)0x8b) { /* gzip */
get_header_ptr = get_header_tar_gz;
} else
/* Check header has valid magic, "ustar" is for the proper tar
* 0's are for the old tar format
*/
if (strncmp(tar.magic, "ustar", 5) != 0) {
#if ENABLE_FEATURE_TAR_OLDGNU_COMPATIBILITY
if (memcmp(tar.magic, "\0\0\0\0", 5) != 0)
#endif
#if ENABLE_FEATURE_TAR_BZIP2
if (tar.name[0] == 'B' && tar.name[1] == 'Z'
&& tar.name[2] == 'h' && isdigit(tar.name[3])
) { /* bzip2 */
get_header_ptr = get_header_tar_bz2;
} else
#endif
goto err;
if (lseek(archive_handle->src_fd, -512, SEEK_CUR) != 0)
goto err;
while (get_header_ptr(archive_handle) == EXIT_SUCCESS)
continue;
return EXIT_FAILURE;
err:
#endif /* FEATURE_TAR_AUTODETECT */
bb_error_msg_and_die("invalid tar magic");
bb_error_msg_and_die("invalid tar magic");
}
#if ENABLE_FEATURE_TAR_AUTODETECT
not_first = 1;
#endif
/* Do checksum on headers.
* POSIX says that checksum is done on unsigned bytes, but
* Sun and HP-UX gets it wrong... more details in
@@ -211,23 +160,18 @@ char get_header_tar(archive_handle_t *archive_handle)
/* getOctal trashes subsequent field, therefore we call it
* on fields in reverse order */
if (tar.devmajor[0]) {
char t = tar.prefix[0];
/* we trash prefix[0] here, but we DO need it later! */
unsigned minor = GET_OCTAL(tar.devminor);
unsigned major = GET_OCTAL(tar.devmajor);
file_header->device = makedev(major, minor);
tar.prefix[0] = t;
}
file_header->link_target = NULL;
if (!linkname && parse_names && tar.linkname[0]) {
file_header->link_target = xstrndup(tar.linkname, sizeof(tar.linkname));
/* we trash magic[0] here, it's ok */
tar.linkname[sizeof(tar.linkname)] = '\0';
file_header->link_target = xstrdup(tar.linkname);
/* FIXME: what if we have non-link object with link_target? */
/* Will link_target be free()ed? */
}
#if ENABLE_FEATURE_TAR_UNAME_GNAME
file_header->uname = tar.uname[0] ? xstrndup(tar.uname, sizeof(tar.uname)) : NULL;
file_header->gname = tar.gname[0] ? xstrndup(tar.gname, sizeof(tar.gname)) : NULL;
#endif
file_header->mtime = GET_OCTAL(tar.mtime);
file_header->size = GET_OCTAL(tar.size);
file_header->gid = GET_OCTAL(tar.gid);
@@ -238,12 +182,10 @@ char get_header_tar(archive_handle_t *archive_handle)
file_header->name = NULL;
if (!longname && parse_names) {
/* we trash mode[0] here, it's ok */
//tar.name[sizeof(tar.name)] = '\0'; - gcc 4.3.0 would complain
tar.mode[0] = '\0';
tar.name[sizeof(tar.name)] = '\0';
if (tar.prefix[0]) {
/* and padding[0] */
//tar.prefix[sizeof(tar.prefix)] = '\0'; - gcc 4.3.0 would complain
tar.padding[0] = '\0';
tar.prefix[sizeof(tar.prefix)] = '\0';
file_header->name = concat_path_file(tar.prefix, tar.name);
} else
file_header->name = xstrdup(tar.name);
@@ -360,9 +302,6 @@ char get_header_tar(archive_handle_t *archive_handle)
free(file_header->link_target);
/* Do not free(file_header->name)! */
#if ENABLE_FEATURE_TAR_UNAME_GNAME
free(file_header->uname);
free(file_header->gname);
#endif
return EXIT_SUCCESS;
}
@@ -10,33 +10,6 @@ void header_verbose_list(const file_header_t *file_header)
{
struct tm *mtime = localtime(&(file_header->mtime));
#if ENABLE_FEATURE_TAR_UNAME_GNAME
char uid[8];
char gid[8];
char *user = file_header->uname;
char *group = file_header->gname;
if (user == NULL) {
snprintf(uid, sizeof(uid), "%u", (unsigned)file_header->uid);
user = uid;
}
if (group == NULL) {
snprintf(gid, sizeof(gid), "%u", (unsigned)file_header->gid);
group = gid;
}
printf("%s %s/%s %9u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
user,
group,
(unsigned int) file_header->size,
1900 + mtime->tm_year,
1 + mtime->tm_mon,
mtime->tm_mday,
mtime->tm_hour,
mtime->tm_min,
mtime->tm_sec,
file_header->name);
#else /* !FEATURE_TAR_UNAME_GNAME */
printf("%s %d/%d %9"OFF_FMT"u %4u-%02u-%02u %02u:%02u:%02u %s",
bb_mode_string(file_header->mode),
file_header->uid,
@@ -49,7 +22,6 @@ void header_verbose_list(const file_header_t *file_header)
mtime->tm_min,
mtime->tm_sec,
file_header->name);
#endif /* FEATURE_TAR_UNAME_GNAME */
if (file_header->link_target) {
printf(" -> %s", file_header->link_target);
+12 -14
View File
@@ -15,50 +15,48 @@ int open_transformer(int src_fd,
USE_DESKTOP(long long) int (*transformer)(int src_fd, int dst_fd),
const char *transform_prog)
{
struct fd_pair fd_pipe;
int fd_pipe[2];
int pid;
xpiped_pair(fd_pipe);
xpipe(fd_pipe);
#if BB_MMU
pid = fork();
if (pid == -1)
bb_perror_msg_and_die("can't fork");
#else
pid = vfork();
if (pid == -1)
bb_perror_msg_and_die("can't vfork");
#endif
if (pid == -1)
bb_perror_msg_and_die("fork failed");
if (pid == 0) {
/* child process */
close(fd_pipe.rd); /* We don't want to read from the parent */
close(fd_pipe[0]); /* We don't wan't to read from the parent */
// FIXME: error check?
#if BB_MMU
transformer(src_fd, fd_pipe.wr);
transformer(src_fd, fd_pipe[1]);
if (ENABLE_FEATURE_CLEAN_UP) {
close(fd_pipe.wr); /* Send EOF */
close(fd_pipe[1]); /* Send EOF */
close(src_fd);
}
exit(EXIT_SUCCESS);
exit(0);
#else
{
char *argv[4];
xmove_fd(src_fd, 0);
xmove_fd(fd_pipe.wr, 1);
xmove_fd(fd_pipe[1], 1);
argv[0] = (char*)transform_prog;
argv[1] = (char*)"-cf";
argv[2] = (char*)"-";
argv[3] = NULL;
BB_EXECVP(transform_prog, argv);
bb_perror_msg_and_die("can't exec %s", transform_prog);
bb_perror_msg_and_die("exec failed");
}
#endif
/* notreached */
}
/* parent process */
close(fd_pipe.wr); /* Don't want to write to the child */
close(fd_pipe[1]); /* Don't want to write to the child */
return fd_pipe.rd;
return fd_pipe[0];
}
+5 -3
View File
@@ -6,12 +6,14 @@
#include "libbb.h"
#include "unarchive.h"
void seek_by_jump(const archive_handle_t *archive_handle, unsigned amount)
void seek_by_jump(const archive_handle_t *archive_handle, const unsigned int amount)
{
if (lseek(archive_handle->src_fd, (off_t) amount, SEEK_CUR) == (off_t) -1) {
if (errno == ESPIPE)
#if ENABLE_FEATURE_UNARCHIVE_TAPE
if (errno == ESPIPE) {
seek_by_read(archive_handle, amount);
else
} else
#endif
bb_perror_msg_and_die("seek failure");
}
}
+2 -2
View File
@@ -6,10 +6,10 @@
#include "libbb.h"
#include "unarchive.h"
/* If we are reading through a pipe, or from stdin then we can't lseek,
/* If we are reading through a pipe(), or from stdin then we can't lseek,
* we must read and discard the data to skip over it.
*/
void seek_by_read(const archive_handle_t *archive_handle, unsigned jump_size)
void seek_by_read(const archive_handle_t *archive_handle, const unsigned int jump_size)
{
if (jump_size)
bb_copyfd_exact_size(archive_handle->src_fd, -1, jump_size);
+8 -8
View File
@@ -13,14 +13,14 @@
#define RPM_HEADER_MAGIC "\216\255\350"
struct rpm_lead {
unsigned char magic[4];
uint8_t major, minor;
uint16_t type;
uint16_t archnum;
char name[66];
uint16_t osnum;
uint16_t signature_type;
char reserved[16];
unsigned char magic[4];
uint8_t major, minor;
uint16_t type;
uint16_t archnum;
char name[66];
uint16_t osnum;
uint16_t signature_type;
char reserved[16];
};
struct rpm_header {
+115 -138
View File
@@ -24,25 +24,12 @@
*/
#include <fnmatch.h>
#include <getopt.h>
#include "libbb.h"
#include "unarchive.h"
/* FIXME: Stop using this non-standard feature */
#ifndef FNM_LEADING_DIR
#define FNM_LEADING_DIR 0
#endif
#define block_buf bb_common_bufsiz1
#if !ENABLE_FEATURE_TAR_GZIP && !ENABLE_FEATURE_TAR_BZIP2
/* Do not pass gzip flag to writeTarFile() */
#define writeTarFile(tar_fd, verboseFlag, dereferenceFlag, include, exclude, gzip) \
writeTarFile(tar_fd, verboseFlag, dereferenceFlag, include, exclude)
#endif
#if ENABLE_FEATURE_TAR_CREATE
/* Tar file constants */
@@ -84,26 +71,26 @@ struct TarHeader { /* byte offset */
*/
typedef struct HardLinkInfo HardLinkInfo;
struct HardLinkInfo {
HardLinkInfo *next; /* Next entry in list */
dev_t dev; /* Device number */
ino_t ino; /* Inode number */
short linkCount; /* (Hard) Link Count */
char name[1]; /* Start of filename (must be last) */
HardLinkInfo *next; /* Next entry in list */
dev_t dev; /* Device number */
ino_t ino; /* Inode number */
short linkCount; /* (Hard) Link Count */
char name[1]; /* Start of filename (must be last) */
};
/* Some info to be carried along when creating a new tarball */
typedef struct TarBallInfo TarBallInfo;
struct TarBallInfo {
int tarFd; /* Open-for-write file descriptor
* for the tarball */
struct stat statBuf; /* Stat info for the tarball, letting
* us know the inode and device that the
* tarball lives, so we can avoid trying
* to include the tarball into itself */
int verboseFlag; /* Whether to print extra stuff or not */
const llist_t *excludeList; /* List of files to not include */
HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
int tarFd; /* Open-for-write file descriptor
for the tarball */
struct stat statBuf; /* Stat info for the tarball, letting
us know the inode and device that the
tarball lives, so we can avoid trying
to include the tarball into itself */
int verboseFlag; /* Whether to print extra stuff or not */
const llist_t *excludeList; /* List of files to not include */
HardLinkInfo *hlInfoHead; /* Hard Link Tracking Information */
HardLinkInfo *hlInfo; /* Hard Link Info for the current file */
};
/* A nice enum with all the possible tar file content types */
@@ -503,90 +490,11 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
return TRUE;
}
#if ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2
#if !(ENABLE_FEATURE_TAR_GZIP && ENABLE_FEATURE_TAR_BZIP2)
#define vfork_compressor(tar_fd, gzip) vfork_compressor(tar_fd)
#endif
/* Don't inline: vfork scares gcc and pessimizes code */
static void NOINLINE vfork_compressor(int tar_fd, int gzip)
{
pid_t gzipPid;
#if ENABLE_FEATURE_TAR_GZIP && ENABLE_FEATURE_TAR_BZIP2
const char *zip_exec = (gzip == 1) ? "gzip" : "bzip2";
#elif ENABLE_FEATURE_TAR_GZIP
const char *zip_exec = "gzip";
#else /* only ENABLE_FEATURE_TAR_BZIP2 */
const char *zip_exec = "bzip2";
#endif
// 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 gzipDataPipe;
#if WAIT_FOR_CHILD
struct fd_pair gzipStatusPipe;
xpiped_pair(gzipStatusPipe);
#endif
xpiped_pair(gzipDataPipe);
signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
#if defined(__GNUC__) && __GNUC__
/* Avoid vfork clobbering */
(void) &zip_exec;
#endif
gzipPid = vfork();
if (gzipPid < 0)
bb_perror_msg_and_die("can't vfork");
if (gzipPid == 0) {
/* child */
/* NB: close _first_, then move fds! */
close(gzipDataPipe.wr);
#if WAIT_FOR_CHILD
close(gzipStatusPipe.rd);
/* gzipStatusPipe.wr will close only on exec -
* parent waits for this close to happen */
fcntl(gzipStatusPipe.wr, F_SETFD, FD_CLOEXEC);
#endif
xmove_fd(gzipDataPipe.rd, 0);
xmove_fd(tar_fd, 1);
/* exec gzip/bzip2 program/applet */
BB_EXECLP(zip_exec, zip_exec, "-f", NULL);
vfork_exec_errno = errno;
_exit(EXIT_FAILURE);
}
/* parent */
xmove_fd(gzipDataPipe.wr, tar_fd);
close(gzipDataPipe.rd);
#if WAIT_FOR_CHILD
close(gzipStatusPipe.wr);
while (1) {
char buf;
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(gzipStatusPipe.rd);
#endif
if (vfork_exec_errno) {
errno = vfork_exec_errno;
bb_perror_msg_and_die("cannot exec %s", zip_exec);
}
}
#endif /* ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2 */
/* gcc 4.2.1 inlines it, making code bigger */
static NOINLINE int writeTarFile(int tar_fd, int verboseFlag,
int dereferenceFlag, const llist_t *include,
const llist_t *exclude, int gzip)
static int writeTarFile(const int tar_fd, const int verboseFlag,
const unsigned long dereferenceFlag, const llist_t *include,
const llist_t *exclude, const int gzip)
{
pid_t gzipPid = 0;
int errorFlag = FALSE;
struct TarBallInfo tbInfo;
@@ -601,10 +509,73 @@ static NOINLINE int writeTarFile(int tar_fd, int verboseFlag,
if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
bb_perror_msg_and_die("cannot stat tar file");
#if ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2
if (gzip)
vfork_compressor(tbInfo.tarFd, gzip);
if ((ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2) && gzip) {
// 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;
#if WAIT_FOR_CHILD
struct { int rd; int wr; } gzipStatusPipe;
#endif
struct { int rd; int wr; } gzipDataPipe;
const char *zip_exec = (gzip == 1) ? "gzip" : "bzip2";
xpipe(&gzipDataPipe.rd);
#if WAIT_FOR_CHILD
xpipe(&gzipStatusPipe.rd);
#endif
signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
#if defined(__GNUC__) && __GNUC__
/* Avoid vfork clobbering */
(void) &include;
(void) &errorFlag;
(void) &zip_exec;
#endif
gzipPid = vfork();
if (gzipPid < 0)
bb_perror_msg_and_die("vfork gzip");
if (gzipPid == 0) {
/* child */
xmove_fd(tbInfo.tarFd, 1);
xmove_fd(gzipDataPipe.rd, 0);
close(gzipDataPipe.wr);
#if WAIT_FOR_CHILD
close(gzipStatusPipe.rd);
fcntl(gzipStatusPipe.wr, F_SETFD, FD_CLOEXEC);
#endif
/* exec gzip/bzip2 program/applet */
BB_EXECLP(zip_exec, zip_exec, "-f", NULL);
vfork_exec_errno = errno;
_exit(1);
}
/* parent */
xmove_fd(gzipDataPipe.wr, tbInfo.tarFd);
close(gzipDataPipe.rd);
#if WAIT_FOR_CHILD
close(gzipStatusPipe.wr);
while (1) {
char buf;
int n;
/* Wait until child execs (or fails to) */
n = full_read(gzipStatusPipe.rd, &buf, 1);
if ((n < 0) && (/*errno == EAGAIN ||*/ errno == EINTR))
continue; /* try it again */
}
close(gzipStatusPipe.rd);
#endif
if (vfork_exec_errno) {
errno = vfork_exec_errno;
bb_perror_msg_and_die("cannot exec %s", zip_exec);
}
}
tbInfo.excludeList = exclude;
@@ -637,34 +608,37 @@ static NOINLINE int writeTarFile(int tar_fd, int verboseFlag,
if (errorFlag)
bb_error_msg("error exit delayed from previous errors");
#if ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2
if (gzip) {
if (gzipPid) {
int status;
if (safe_waitpid(-1, &status, 0) == -1)
if (waitpid(gzipPid, &status, 0) == -1)
bb_perror_msg("waitpid");
else if (!WIFEXITED(status) || WEXITSTATUS(status))
/* gzip was killed or has exited with nonzero! */
errorFlag = TRUE;
}
#endif
return errorFlag;
}
#else
int writeTarFile(int tar_fd, int verboseFlag,
int dereferenceFlag, const llist_t *include,
const llist_t *exclude, int gzip);
int writeTarFile(const int tar_fd, const int verboseFlag,
const unsigned long dereferenceFlag, const llist_t *include,
const llist_t *exclude, const int gzip);
#endif /* FEATURE_TAR_CREATE */
#if ENABLE_FEATURE_TAR_FROM
static llist_t *append_file_list_to_list(llist_t *list)
{
FILE *src_stream;
llist_t *cur = list;
llist_t *tmp;
char *line;
llist_t *newlist = NULL;
while (list) {
src_stream = xfopen(llist_pop(&list), "r");
while ((line = xmalloc_fgetline(src_stream)) != NULL) {
while (cur) {
src_stream = xfopen(cur->data, "r");
tmp = cur;
cur = cur->link;
free(tmp);
while ((line = xmalloc_getline(src_stream)) != NULL) {
/* kill trailing '/' unless the string is just "/" */
char *cp = last_char_is(line, '/');
if (cp > line)
@@ -714,7 +688,7 @@ static void handle_SIGCHLD(int status)
/* Actually, 'status' is a signo. We reuse it for other needs */
/* Wait for any child without blocking */
if (wait_any_nohang(&status) < 0)
if (waitpid(-1, &status, WNOHANG) < 0)
/* wait failed?! I'm confused... */
return;
@@ -800,7 +774,7 @@ static const char tar_longopts[] ALIGN1 =
#endif
int tar_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int tar_main(int argc ATTRIBUTE_UNUSED, char **argv)
int tar_main(int argc, char **argv)
{
char (*get_header_ptr)(archive_handle_t *) = get_header_tar;
archive_handle_t *tar_handle;
@@ -850,7 +824,6 @@ int tar_main(int argc ATTRIBUTE_UNUSED, char **argv)
, &verboseFlag // combined count for -t and -v
, &verboseFlag // combined count for -t and -v
);
argv += optind;
if (verboseFlag) tar_handle->action_header = header_verbose_list;
if (verboseFlag == 1) tar_handle->action_header = header_list;
@@ -896,15 +869,21 @@ int tar_main(int argc ATTRIBUTE_UNUSED, char **argv)
tar_handle->accept = append_file_list_to_list(tar_handle->accept);
#endif
/* Check if we are reading from stdin */
if (argv[optind] && *argv[optind] == '-') {
/* Default is to read from stdin, so just skip to next arg */
optind++;
}
/* Setup an array of filenames to work with */
/* TODO: This is the same as in ar, separate function ? */
while (*argv) {
while (optind < argc) {
/* kill trailing '/' unless the string is just "/" */
char *cp = last_char_is(*argv, '/');
if (cp > *argv)
char *cp = last_char_is(argv[optind], '/');
if (cp > argv[optind])
*cp = '\0';
llist_add_to_end(&tar_handle->accept, *argv);
argv++;
llist_add_to_end(&tar_handle->accept, argv[optind]);
optind++;
}
if (tar_handle->accept || tar_handle->reject)
@@ -947,13 +926,11 @@ int tar_main(int argc ATTRIBUTE_UNUSED, char **argv)
/* create an archive */
if (opt & OPT_CREATE) {
#if ENABLE_FEATURE_TAR_GZIP || ENABLE_FEATURE_TAR_BZIP2
int zipMode = 0;
if (ENABLE_FEATURE_TAR_GZIP && (opt & OPT_GZIP))
if (ENABLE_FEATURE_TAR_GZIP && get_header_ptr == get_header_tar_gz)
zipMode = 1;
if (ENABLE_FEATURE_TAR_BZIP2 && (opt & OPT_BZIP2))
if (ENABLE_FEATURE_TAR_BZIP2 && get_header_ptr == get_header_tar_bz2)
zipMode = 2;
#endif
/* NB: writeTarFile() closes tar_handle->src_fd */
return writeTarFile(tar_handle->src_fd, verboseFlag, opt & OPT_DEREFERENCE,
tar_handle->accept,
@@ -961,7 +938,7 @@ int tar_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
while (get_header_ptr(tar_handle) == EXIT_SUCCESS)
continue;
/* nothing */;
/* Check that every file that should have been extracted was */
while (tar_handle->accept) {
+1 -1
View File
@@ -72,7 +72,7 @@ config RESIZE
terminal.
config FEATURE_RESIZE_PRINT
bool "Print environment variables"
bool "print environment variables"
default n
depends on RESIZE
help
+10 -2
View File
@@ -9,17 +9,25 @@
#include "libbb.h"
/* From <linux/vt.h> */
enum {
VT_ACTIVATE = 0x5606, /* make vt active */
VT_WAITACTIVE = 0x5607 /* wait for vt active */
};
int chvt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int chvt_main(int argc, char **argv)
{
int num;
int fd, num;
if (argc != 2) {
bb_show_usage();
}
fd = get_console_fd();
num = xatou_range(argv[1], 1, 63);
/* double cast suppresses "cast to ptr from int of different size" */
console_make_active(get_console_fd(), num);
xioctl(fd, VT_ACTIVATE, (void *)(ptrdiff_t)num);
xioctl(fd, VT_WAITACTIVE, (void *)(ptrdiff_t)num);
return EXIT_SUCCESS;
}
+1 -1
View File
@@ -13,7 +13,7 @@
#include "libbb.h"
int clear_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int clear_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
int clear_main(int argc, char **argv)
{
return printf("\033[H\033[J") != 6;
}
+8 -4
View File
@@ -16,15 +16,19 @@
enum { VT_DISALLOCATE = 0x5608 }; /* free memory associated to vt */
int deallocvt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int deallocvt_main(int argc ATTRIBUTE_UNUSED, char **argv)
int deallocvt_main(int argc, char **argv)
{
/* num = 0 deallocate all unused consoles */
int num = 0;
if (argv[1]) {
if (argv[2])
bb_show_usage();
switch (argc) {
case 2:
num = xatou_range(argv[1], 1, 63);
/* Fallthrough */
case 1:
break;
default:
bb_show_usage();
}
/* double cast suppresses "cast to ptr from int of different size" */
+8 -11
View File
@@ -7,7 +7,6 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*
*/
/* no options, no getopt */
#include "libbb.h"
@@ -24,17 +23,18 @@ struct kbentry {
#define MAX_NR_KEYMAPS 256
int dumpkmap_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int dumpkmap_main(int ATTRIBUTE_UNUSED argc, char ATTRIBUTE_UNUSED **argv)
int dumpkmap_main(int argc, char **argv)
{
struct kbentry ke;
int i, j, fd;
RESERVE_CONFIG_BUFFER(flags,MAX_NR_KEYMAPS);
char flags[MAX_NR_KEYMAPS];
/* bb_warn_ignoring_args(argc>=2);*/
if (argc >= 2 && argv[1][0] == '-')
bb_show_usage();
fd = xopen(CURRENT_VC, O_RDWR);
write(STDOUT_FILENO, "bkeymap", 7);
write(1, "bkeymap", 7);
/* Here we want to set everything to 0 except for indexes:
* [0-2] [4-6] [8-10] [12] */
@@ -43,7 +43,7 @@ int dumpkmap_main(int ATTRIBUTE_UNUSED argc, char ATTRIBUTE_UNUSED **argv)
flags[3] = flags[7] = flags[11] = 0;
/* dump flags */
write(STDOUT_FILENO, flags, MAX_NR_KEYMAPS);
write(1, flags, MAX_NR_KEYMAPS);
for (i = 0; i < MAX_NR_KEYMAPS; i++) {
if (flags[i] == 1) {
@@ -56,14 +56,11 @@ int dumpkmap_main(int ATTRIBUTE_UNUSED argc, char ATTRIBUTE_UNUSED **argv)
(char *)&ke.kb_table,
&ke.kb_value)
) {
write(STDOUT_FILENO, (void*)&ke.kb_value, 2);
write(1, (void*)&ke.kb_value, 2);
}
}
}
}
if (ENABLE_FEATURE_CLEAN_UP) {
close(fd);
RELEASE_CONFIG_BUFFER(flags);
}
close(fd);
return EXIT_SUCCESS;
}
+49 -34
View File
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
* Mini kbd_mode implementation for busybox
* Mini loadkmap implementation for busybox
*
* Copyright (C) 2007 Loic Grenie <loic.grenie@gmail.com>
* Copyright (C) 2007 Loïc Grenié <loic.grenie@gmail.com>
* written using Andries Brouwer <aeb@cwi.nl>'s kbd_mode from
* console-utils v0.2.3, licensed under GNU GPLv2
*
@@ -10,44 +10,59 @@
*
*/
#include <getopt.h>
#include "libbb.h"
#include <linux/kd.h>
int kbd_mode_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int kbd_mode_main(int ATTRIBUTE_UNUSED argc, char **argv)
int kbd_mode_main(int argc, char **argv)
{
int fd;
unsigned opt;
enum {
SCANCODE = (1<<0),
ASCII = (1<<1),
MEDIUMRAW= (1<<2),
UNICODE = (1<<3)
};
static const char KD_xxx[] ALIGN1 = "saku";
opt = getopt32(argv, KD_xxx);
fd = get_console_fd();
/* if (fd < 0)
return EXIT_FAILURE;
*/
if (!opt) { /* print current setting */
const char *mode = "unknown";
int m;
static const char opts[] = "saku";
ioctl(fd, KDGKBMODE, &m);
if (m == K_RAW)
mode = "raw (scancode)";
else if (m == K_XLATE)
mode = "default (ASCII)";
else if (m == K_MEDIUMRAW)
mode = "mediumraw (keycode)";
else if (m == K_UNICODE)
mode = "Unicode (UTF-8)";
printf("The keyboard is in %s mode\n", mode);
} else {
opt = opt & UNICODE ? 3 : opt >> 1;
/* double cast prevents warnings about widening conversion */
xioctl(fd, KDSKBMODE, (void*)(ptrdiff_t)opt);
const char *opt = argv[1];
const char *p;
int fd;
fd = get_console_fd();
if (fd < 0) /* get_console_fd() already complained */
return EXIT_FAILURE;
if (opt == NULL) {
/* No arg */
const char *msg = "unknown";
int mode;
ioctl(fd, KDGKBMODE, &mode);
switch(mode) {
case K_RAW:
msg = "raw (scancode)";
break;
case K_XLATE:
msg = "default (ASCII)";
break;
case K_MEDIUMRAW:
msg = "mediumraw (keycode)";
break;
case K_UNICODE:
msg = "Unicode (UTF-8)";
break;
}
printf("The keyboard is in %s mode\n", msg);
}
else if (argc > 2 /* more than 1 arg */
|| *opt != '-' /* not an option */
|| (p = strchr(opts, opt[1])) == NULL /* not an option we expect */
|| opt[2] != '\0' /* more than one option char */
) {
bb_show_usage();
/* return EXIT_FAILURE; - not reached */
}
else {
#if K_RAW != 0 || K_XLATE != 1 || K_MEDIUMRAW != 2 || K_UNICODE != 3
#error kbd_mode must be changed
#endif
/* The options are in the order of the various K_xxx */
ioctl(fd, KDSKBMODE, p - opts);
}
if (ENABLE_FEATURE_CLEAN_UP)
+1 -1
View File
@@ -167,7 +167,7 @@ static void loadnewfont(int fd)
}
int loadfont_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int loadfont_main(int argc, char **argv ATTRIBUTE_UNUSED)
int loadfont_main(int argc, char **argv)
{
int fd;
+12 -13
View File
@@ -26,26 +26,28 @@ struct kbentry {
#define MAX_NR_KEYMAPS 256
int loadkmap_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int loadkmap_main(int ATTRIBUTE_UNUSED argc, char **argv ATTRIBUTE_UNUSED)
int loadkmap_main(int argc, char **argv)
{
struct kbentry ke;
int i, j, fd;
uint16_t ibuff[NR_KEYS];
RESERVE_CONFIG_BUFFER(flags,MAX_NR_KEYMAPS);
char flags[MAX_NR_KEYMAPS];
char buff[7];
/* bb_warn_ignoring_args(argc>=2);*/
if (argc != 1)
bb_show_usage();
fd = xopen(CURRENT_VC, O_RDWR);
xread(STDIN_FILENO, flags, 7);
if (strncmp(flags, BINARY_KEYMAP_MAGIC, 7))
bb_error_msg_and_die("not a valid binary keymap");
xread(0, buff, 7);
if (strncmp(buff, BINARY_KEYMAP_MAGIC, 7))
bb_error_msg_and_die("this is not a valid binary keymap");
xread(STDIN_FILENO, flags, MAX_NR_KEYMAPS);
xread(0, flags, MAX_NR_KEYMAPS);
for (i = 0; i < MAX_NR_KEYMAPS; i++) {
if (flags[i] == 1) {
xread(STDIN_FILENO, ibuff, NR_KEYS * sizeof(uint16_t));
xread(0, ibuff, NR_KEYS * sizeof(uint16_t));
for (j = 0; j < NR_KEYS; j++) {
ke.kb_index = j;
ke.kb_table = i;
@@ -55,9 +57,6 @@ int loadkmap_main(int ATTRIBUTE_UNUSED argc, char **argv ATTRIBUTE_UNUSED)
}
}
if (ENABLE_FEATURE_CLEAN_UP) {
close(fd);
RELEASE_CONFIG_BUFFER(flags);
}
return EXIT_SUCCESS;
if (ENABLE_FEATURE_CLEAN_UP) close(fd);
return 0;
}
+15 -161
View File
@@ -8,174 +8,28 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <linux/vt.h>
/* getopt not needed */
#include "libbb.h"
/* "Standard" openvt's man page (we do not support all of this):
openvt [-c NUM] [-fsulv] [--] [command [args]]
Find the first available VT, and run command on it. Stdio is directed
to that VT. If no command is specified then $SHELL is used.
-c NUM
Use the given VT number, not the first free one.
-f
Force opening a VT: don't try to check if VT is already in use.
-s
Switch to the new VT when starting the command.
The VT of the new command will be made the new current VT.
-u
Figure out the owner of the current VT, and run login as that user.
Suitable to be called by init. Shouldn't be used with -c or -l.
-l
Make the command a login shell: a "-" is prepended to the argv[0]
when command is executed.
-v
Verbose.
-w
Wait for command to complete. If -w and -s are used together,
switch back to the controlling terminal when the command completes.
bbox:
-u: not implemented
-f: always in effect
-l: not implemented, ignored
-v: ignored
-ws: does NOT switch back
*/
/* Helper: does this fd understand VT_xxx? */
static int not_vt_fd(int fd)
{
struct vt_stat vtstat;
return ioctl(fd, VT_GETSTATE, &vtstat); /* !0: error, it's not VT fd */
}
/* Helper: get a fd suitable for VT_xxx */
static int get_vt_fd(void)
{
int fd;
/* Do we, by chance, already have it? */
for (fd = 0; fd < 3; fd++)
if (!not_vt_fd(fd))
return fd;
/* _only_ O_NONBLOCK: ask for neither read nor write perms */
/*FIXME: use? device_open(DEV_CONSOLE,0); */
fd = open(DEV_CONSOLE, O_NONBLOCK);
if (fd >= 0 && !not_vt_fd(fd))
return fd;
bb_error_msg_and_die("can't find open VT");
}
static int find_free_vtno(void)
{
int vtno;
int fd = get_vt_fd();
errno = 0;
/*xfunc_error_retval = 3; - do we need compat? */
if (ioctl(fd, VT_OPENQRY, &vtno) != 0 || vtno <= 0)
bb_perror_msg_and_die("can't find open VT");
// Not really needed, grep for DAEMON_ONLY_SANITIZE
// if (fd > 2)
// close(fd);
return vtno;
}
/* vfork scares gcc, it generates bigger code.
* Keep it away from main program.
* TODO: move to libbb; or adapt existing libbb's spawn().
*/
static NOINLINE void vfork_child(char **argv)
{
if (vfork() == 0) {
/* CHILD */
/* Try to make this VT our controlling tty */
setsid(); /* lose old ctty */
ioctl(STDIN_FILENO, TIOCSCTTY, 0 /* 0: don't forcibly steal */);
//bb_error_msg("our sid %d", getsid(0));
//bb_error_msg("our pgrp %d", getpgrp());
//bb_error_msg("VT's sid %d", tcgetsid(0));
//bb_error_msg("VT's pgrp %d", tcgetpgrp(0));
BB_EXECVP(argv[0], argv);
bb_perror_msg_and_die("exec %s", argv[0]);
}
}
int openvt_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int openvt_main(int argc ATTRIBUTE_UNUSED, char **argv)
int openvt_main(int argc, char **argv)
{
char vtname[sizeof(VC_FORMAT) + sizeof(int)*3];
struct vt_stat vtstat;
char *str_c;
int vtno;
int flags;
enum {
OPT_c = (1 << 0),
OPT_w = (1 << 1),
OPT_s = (1 << 2),
OPT_l = (1 << 3),
OPT_f = (1 << 4),
OPT_v = (1 << 5),
};
char vtname[sizeof(VC_FORMAT) + 2];
/* "+" - stop on first non-option */
flags = getopt32(argv, "+c:wslfv", &str_c);
argv += optind;
if (argc < 3)
bb_show_usage();
if (flags & OPT_c) {
/* Check for illegal vt number: < 1 or > 63 */
vtno = xatou_range(str_c, 1, 63);
} else {
vtno = find_free_vtno();
}
/* check for illegal vt number: < 1 or > 63 */
sprintf(vtname, VC_FORMAT, (int)xatou_range(argv[1], 1, 63));
/* Grab new VT */
sprintf(vtname, VC_FORMAT, vtno);
/* (Try to) clean up stray open fds above fd 2 */
bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS | DAEMON_ONLY_SANITIZE, NULL);
close(STDIN_FILENO);
/*setsid(); - BAD IDEA: after we exit, child is SIGHUPed... */
bb_daemonize_or_rexec(DAEMON_CLOSE_EXTRA_FDS, argv);
/* grab new one */
close(0);
xopen(vtname, O_RDWR);
xioctl(STDIN_FILENO, VT_GETSTATE, &vtstat);
dup2(0, STDOUT_FILENO);
dup2(0, STDERR_FILENO);
if (flags & OPT_s) {
console_make_active(STDIN_FILENO, vtno);
}
if (!argv[0]) {
argv--;
argv[0] = getenv("SHELL");
if (!argv[0])
argv[0] = (char *) DEFAULT_SHELL;
/*argv[1] = NULL; - already is */
}
xdup2(STDIN_FILENO, STDOUT_FILENO);
xdup2(STDIN_FILENO, STDERR_FILENO);
#ifdef BLOAT
{
/* Handle -l (login shell) option */
const char *prog = argv[0];
if (flags & OPT_l)
argv[0] = xasprintf("-%s", argv[0]);
}
#endif
vfork_child(argv);
if (flags & OPT_w) {
/* We have only one child, wait for it */
safe_waitpid(-1, NULL, 0); /* loops on EINTR */
if (flags & OPT_s) {
console_make_active(STDIN_FILENO, vtstat.v_active);
// Compat: even with -c N (try to) disallocate:
// # /usr/app/kbd-1.12/bin/openvt -f -c 9 -ws sleep 5
// openvt: could not deallocate console 9
xioctl(STDIN_FILENO, VT_DISALLOCATE, (void*)(ptrdiff_t)vtno);
}
}
return EXIT_SUCCESS;
BB_EXECVP(argv[2], &argv[2]);
_exit(1);
}
+5 -22
View File
@@ -8,25 +8,14 @@
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
/* no options, no getopt */
#include "libbb.h"
/* BTW, which "standard" package has this utility? It doesn't seem
* to be ncurses, coreutils, console-tools... then what? */
#if ENABLE_STTY
int stty_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
#endif
int reset_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int reset_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
int reset_main(int argc, char **argv)
{
static const char *const args[] = {
"stty", "sane", NULL
};
/* no options, no getopt */
if (isatty(STDIN_FILENO) && isatty(STDOUT_FILENO)) {
if (isatty(1)) {
/* See 'man 4 console_codes' for details:
* "ESC c" -- Reset
* "ESC ( K" -- Select user mapping
@@ -35,13 +24,7 @@ int reset_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
* "ESC [ ? 25 h" -- Make cursor visible.
*/
printf("\033c\033(K\033[J\033[0m\033[?25h");
/* http://bugs.busybox.net/view.php?id=1414:
* people want it to reset echo etc: */
#if ENABLE_STTY
return stty_main(2, (char**)args);
#else
execvp("stty", (char**)args);
#endif
}
return EXIT_SUCCESS;
}
+7 -9
View File
@@ -17,14 +17,14 @@ static void
onintr(int sig ATTRIBUTE_UNUSED)
{
tcsetattr(STDERR_FILENO, TCSANOW, &old_termios);
exit(EXIT_FAILURE);
exit(1);
}
int resize_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int resize_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
int resize_main(int argc, char **argv)
{
struct termios new;
struct winsize w = { 0, 0, 0, 0 };
struct winsize w = { 0,0,0,0 };
int ret;
/* We use _stderr_ in order to make resize usable
@@ -37,12 +37,10 @@ int resize_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
new = old_termios;
new.c_cflag |= (CLOCAL | CREAD);
new.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
bb_signals(0
+ (1 << SIGINT)
+ (1 << SIGQUIT)
+ (1 << SIGTERM)
+ (1 << SIGALRM)
, onintr);
signal(SIGINT, onintr);
signal(SIGQUIT, onintr);
signal(SIGTERM, onintr);
signal(SIGALRM, onintr);
tcsetattr(STDERR_FILENO, TCSANOW, &new);
/* save_cursor_pos 7
+20 -13
View File
@@ -3,34 +3,41 @@
* setconsole.c - redirect system console output
*
* Copyright (C) 2004,2005 Enrik Berkhan <Enrik.Berkhan@inka.de>
* Copyright (C) 2008 Bernhard Fischer
*
* Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
*/
#include <getopt.h>
#include "libbb.h"
#if ENABLE_FEATURE_SETCONSOLE_LONG_OPTIONS
static const char setconsole_longopts[] ALIGN1 =
"reset\0" No_argument "r"
;
#endif
#define OPT_SETCONS_RESET 1
int setconsole_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int setconsole_main(int ATTRIBUTE_UNUSED argc, char **argv)
int setconsole_main(int argc, char **argv)
{
unsigned long flags;
const char *device = CURRENT_TTY;
bool reset;
#if ENABLE_FEATURE_SETCONSOLE_LONG_OPTIONS
static const char setconsole_longopts[] ALIGN1 =
"reset\0" No_argument "r"
;
applet_long_options = setconsole_longopts;
#endif
/* at most one non-option argument */
opt_complementary = "?1";
reset = getopt32(argv, "r");
flags = getopt32(argv, "r");
argv += 1 + reset;
if (*argv) {
device = *argv;
if (argc - optind > 1)
bb_show_usage();
if (argc - optind == 1) {
if (flags & OPT_SETCONS_RESET)
bb_show_usage();
device = argv[optind];
} else {
if (reset)
if (flags & OPT_SETCONS_RESET)
device = DEV_CONSOLE;
}
+2 -2
View File
@@ -14,7 +14,7 @@
/* From <linux/kd.h> */
struct kbkeycode {
unsigned scancode, keycode;
unsigned int scancode, keycode;
};
enum {
KDSETKEYCODE = 0x4B4D /* write kernel keycode table entry */
@@ -33,7 +33,7 @@ int setkeycodes_main(int argc, char **argv)
fd = get_console_fd();
while (argc > 2) {
a.keycode = xatou_range(argv[2], 0, 127);
a.keycode = xatoul_range(argv[2], 0, 127);
a.scancode = sc = xstrtoul_range(argv[1], 16, 0, 255);
if (a.scancode > 127) {
a.scancode -= 0xe000;
+8 -7
View File
@@ -12,19 +12,20 @@
#include "libbb.h"
int setlogcons_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int setlogcons_main(int argc ATTRIBUTE_UNUSED, char **argv)
int setlogcons_main(int argc, char **argv)
{
struct {
char fn;
char subarg;
} arg = { 11, /* redirect kernel messages */
0 /* to specified console (current as default) */
};
} arg;
if (argv[1])
arg.subarg = xatou_range(argv[1], 0, 63);
arg.fn = 11; /* redirect kernel messages */
arg.subarg = 0; /* to specified console (current as default) */
if (argc == 2)
arg.subarg = xatoul_range(argv[1], 0, 63);
xioctl(xopen(VC_1, O_RDONLY), TIOCLINUX, &arg);
return EXIT_SUCCESS;
return 0;
}
+3 -17
View File
@@ -488,14 +488,6 @@ config RMDIR
help
rmdir is used to remove empty directories.
config FEATURE_RMDIR_LONG_OPTIONS
bool "Enable long options"
default n
depends on RMDIR && GETOPT_LONG
help
Support long options for the rmdir applet, including
--ignore-fail-on-non-empty for compatibility with GNU rmdir.
config SEQ
bool "seq"
default n
@@ -528,7 +520,7 @@ config SORT
sort is used to sort lines of text in specified files.
config FEATURE_SORT_BIG
bool "Full SuSv3 compliant sort (support -ktcsbdfiozgM)"
bool "full SuSv3 compliant sort (Support -ktcsbdfiozgM)"
default y
depends on SORT
help
@@ -546,7 +538,7 @@ config SPLIT
split a file into pieces.
config FEATURE_SPLIT_FANCY
bool "Fancy extensions"
bool "fancy extensions"
default n
depends on SPLIT
help
@@ -587,12 +579,6 @@ config SYNC
help
sync is used to flush filesystem buffers.
config TAC
bool "tac"
default n
help
tac is used to concatenate and print files in reverse.
config TAIL
bool "tail"
default n
@@ -616,7 +602,7 @@ config TEE
to standard output and files.
config FEATURE_TEE_USE_BLOCK_IO
bool "Enable block I/O (larger/faster) instead of byte I/O"
bool "Enable block i/o (larger/faster) instead of byte i/o."
default n
depends on TEE
help
+2 -8
View File
@@ -12,7 +12,6 @@ lib-$(CONFIG_CAL) += cal.o
lib-$(CONFIG_CAT) += cat.o
lib-$(CONFIG_MORE) += cat.o # more uses it if stdout isn't a tty
lib-$(CONFIG_LESS) += cat.o # less too
lib-$(CONFIG_CRONTAB) += cat.o # crontab -l
lib-$(CONFIG_CATV) += catv.o
lib-$(CONFIG_CHGRP) += chgrp.o chown.o
lib-$(CONFIG_CHMOD) += chmod.o
@@ -30,7 +29,6 @@ lib-$(CONFIG_DOS2UNIX) += dos2unix.o
lib-$(CONFIG_DU) += du.o
lib-$(CONFIG_ECHO) += echo.o
lib-$(CONFIG_ASH) += echo.o # used by ash
lib-$(CONFIG_HUSH) += echo.o # used by hush
lib-$(CONFIG_ENV) += env.o
lib-$(CONFIG_EXPR) += expr.o
lib-$(CONFIG_EXPAND) += expand.o
@@ -54,7 +52,6 @@ lib-$(CONFIG_NOHUP) += nohup.o
lib-$(CONFIG_OD) += od.o
lib-$(CONFIG_PRINTENV) += printenv.o
lib-$(CONFIG_PRINTF) += printf.o
lib-$(CONFIG_ASH_BUILTIN_PRINTF) += printf.o
lib-$(CONFIG_PWD) += pwd.o
lib-$(CONFIG_READLINK) += readlink.o
lib-$(CONFIG_REALPATH) += realpath.o
@@ -69,13 +66,10 @@ lib-$(CONFIG_STAT) += stat.o
lib-$(CONFIG_STTY) += stty.o
lib-$(CONFIG_SUM) += sum.o
lib-$(CONFIG_SYNC) += sync.o
lib-$(CONFIG_TAC) += tac.o
lib-$(CONFIG_TAIL) += tail.o
lib-$(CONFIG_TEE) += tee.o
lib-$(CONFIG_TEST) += test.o test_ptr_hack.o
lib-$(CONFIG_ASH) += test.o test_ptr_hack.o # used by ash
lib-$(CONFIG_HUSH) += test.o test_ptr_hack.o # used by hush
lib-$(CONFIG_MSH) += test.o test_ptr_hack.o # used by msh
lib-$(CONFIG_TEST) += test.o
lib-$(CONFIG_ASH) += test.o # used by ash
lib-$(CONFIG_TOUCH) += touch.o
lib-$(CONFIG_TR) += tr.o
lib-$(CONFIG_TRUE) += true.o
+5 -6
View File
@@ -37,16 +37,15 @@ int basename_main(int argc, char **argv)
/* It should strip slash: /abc/def/ -> def */
s = bb_get_last_path_component_strip(*++argv);
m = strlen(s);
if (*++argv) {
n = strlen(*argv);
m = strlen(s);
if ((m > n) && ((strcmp)(s+m-n, *argv) == 0)) {
m -= n;
/*s[m] = '\0'; - redundant */
s[m-n] = '\0';
}
}
/* puts(s) will do, but we can do without stdio this way: */
s[m++] = '\n';
return full_write(STDOUT_FILENO, s, m) != (ssize_t)m;
puts(s);
return fflush(stdout);
}
+1 -1
View File
@@ -179,7 +179,7 @@ int cal_main(int argc, char **argv)
}
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit(0);
}
/*
+8 -4
View File
@@ -17,16 +17,20 @@
int bb_cat(char **argv)
{
static const char *const argv_dash[] = { "-", NULL };
int fd;
int retval = EXIT_SUCCESS;
if (!*argv)
argv = (char**) &bb_argv_dash;
argv = (char**) &argv_dash;
do {
fd = open_or_warn_stdin(*argv);
fd = STDIN_FILENO;
if (!LONE_DASH(*argv))
fd = open_or_warn(*argv, O_RDONLY);
if (fd >= 0) {
/* This is not a xfunc - never exits */
/* This is not an xfunc - never exits */
off_t r = bb_copyfd_eof(fd, STDOUT_FILENO);
if (fd != STDIN_FILENO)
close(fd);
@@ -40,7 +44,7 @@ int bb_cat(char **argv)
}
int cat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cat_main(int argc ATTRIBUTE_UNUSED, char **argv)
int cat_main(int argc, char **argv)
{
getopt32(argv, "u");
argv += optind;
+8 -4
View File
@@ -13,7 +13,7 @@
#include "libbb.h"
int catv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int catv_main(int argc ATTRIBUTE_UNUSED, char **argv)
int catv_main(int argc, char **argv)
{
int retval = EXIT_SUCCESS;
int fd;
@@ -27,14 +27,18 @@ int catv_main(int argc ATTRIBUTE_UNUSED, char **argv)
argv += optind;
/* Read from stdin if there's nothing else to do. */
if (!argv[0])
*--argv = (char*)"-";
fd = 0;
if (!argv[0]) {
argv--;
goto jump_in;
}
do {
fd = open_or_warn_stdin(*argv);
fd = open_or_warn(*argv, O_RDONLY);
if (fd < 0) {
retval = EXIT_FAILURE;
continue;
}
jump_in:
for (;;) {
int i, res;
+1 -1
View File
@@ -68,7 +68,7 @@ static int fileAction(const char *fileName, struct stat *statbuf, void* param, i
}
int chmod_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int chmod_main(int argc ATTRIBUTE_UNUSED, char **argv)
int chmod_main(int argc, char **argv)
{
int retval = EXIT_SUCCESS;
char *arg, **argp;
+3 -2
View File
@@ -42,7 +42,7 @@ typedef int (*chown_fptr)(const char *, uid_t, gid_t);
static struct bb_uidgid_t ugid = { -1, -1 };
static int fileAction(const char *fileName, struct stat *statbuf,
void *cf, int depth ATTRIBUTE_UNUSED)
void *cf, int depth)
{
uid_t u = (ugid.uid == (uid_t)-1) ? statbuf->st_uid : ugid.uid;
gid_t g = (ugid.gid == (gid_t)-1) ? statbuf->st_gid : ugid.gid;
@@ -61,7 +61,8 @@ static int fileAction(const char *fileName, struct stat *statbuf,
return FALSE;
}
int chown_main(int argc ATTRIBUTE_UNUSED, char **argv)
int chown_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int chown_main(int argc, char **argv)
{
int retval = EXIT_SUCCESS;
int flags;
+3 -1
View File
@@ -19,7 +19,9 @@ int chroot_main(int argc, char **argv)
}
++argv;
xchroot(*argv);
if (chroot(*argv)) {
bb_perror_msg_and_die("cannot change root directory to %s", *argv);
}
xchdir("/");
++argv;
+19 -21
View File
@@ -9,48 +9,46 @@
#include "libbb.h"
int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cksum_main(int argc ATTRIBUTE_UNUSED, char **argv)
int cksum_main(int argc, char **argv)
{
uint32_t *crc32_table = crc32_filltable(NULL, 1);
FILE *fp;
uint32_t crc;
long length, filesize;
int bytes_read;
uint8_t *cp;
char *cp;
#if ENABLE_DESKTOP
getopt32(argv, ""); /* coreutils 6.9 compat */
argv += optind;
#else
argv++;
#endif
int inp_stdin = (argc == optind) ? 1 : 0;
do {
int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
fp = fopen_or_warn_stdin((inp_stdin) ? bb_msg_standard_input : *++argv);
if (fd < 0)
continue;
crc = 0;
length = 0;
#define read_buf bb_common_bufsiz1
while ((bytes_read = safe_read(fd, read_buf, sizeof(read_buf))) > 0) {
cp = (uint8_t *) read_buf;
while ((bytes_read = fread(read_buf, 1, BUFSIZ, fp)) > 0) {
cp = read_buf;
length += bytes_read;
do {
crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *cp++];
} while (--bytes_read);
while (bytes_read--)
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ (*cp++)) & 0xffL];
}
close(fd);
filesize = length;
for (; length; length >>= 8)
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ length) & 0xff];
crc = (crc << 8) ^ crc32_table[((crc >> 24) ^ length) & 0xffL];
crc ^= 0xffffffffL;
printf((*argv ? "%" PRIu32 " %li %s\n" : "%" PRIu32 " %li\n"),
crc, filesize, *argv);
} while (*argv && *++argv);
if (inp_stdin) {
printf("%" PRIu32 " %li\n", crc, filesize);
break;
}
printf("%" PRIu32 " %li %s\n", crc, filesize, *argv);
fclose(fp);
} while (*(argv + 1));
fflush_stdout_and_exit(EXIT_SUCCESS);
}
+1 -1
View File
@@ -36,7 +36,7 @@ static void writeline(char *line, int class, int flags)
}
int comm_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int comm_main(int argc ATTRIBUTE_UNUSED, char **argv)
int comm_main(int argc, char **argv)
{
#define LINE_LEN 100
#define BB_EOF_0 0x1
+11 -13
View File
@@ -37,27 +37,25 @@ int cp_main(int argc, char **argv)
OPT_r = 1 << (sizeof(FILEUTILS_CP_OPTSTR)),
OPT_P = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+1),
OPT_H = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+2),
OPT_L = 1 << (sizeof(FILEUTILS_CP_OPTSTR)+3),
};
// Need at least two arguments
// Soft- and hardlinking doesn't mix
// Soft- and hardlinking don'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)
// -R (and therefore -r) switches on -d (coreutils does this)
// -a = -pdR
opt_complementary = "-2:l--s:s--l:Pd:rRd:Rd:apdR:HL";
flags = getopt32(argv, FILEUTILS_CP_OPTSTR "arPH");
opt_complementary = "-2:l--s:s--l:Pd:rRd:Rd:apdR";
flags = getopt32(argv, FILEUTILS_CP_OPTSTR "arPHL");
argc -= optind;
argv += optind;
flags ^= FILEUTILS_DEREFERENCE; /* the sense of this flag was reversed */
/* coreutils 6.9 compat:
* by default, "cp" derefs symlinks (creates regular dest files),
* but "cp -R" does not. We switch off deref if -r or -R (see above).
* However, "cp -RL" must still deref symlinks: */
if (flags & FILEUTILS_DEREF_SOFTLINK) /* -L */
flags |= FILEUTILS_DEREFERENCE;
/* The behavior of -H is *almost* like -L, but not quite, so let's
* just ignore it too for fun. TODO.
flags ^= FILEUTILS_DEREFERENCE; /* The sense of this flag was reversed. */
/* Default behavior of cp is to dereference, so we don't have to do
* anything special when we are given -L.
* The behavior of -H is *almost* like -L, but not quite, so let's
* just ignore it too for fun.
if (flags & OPT_L) ...
if (flags & OPT_H) ... // deref command-line params only
*/
+18 -11
View File
@@ -51,7 +51,7 @@ static void cut_file(FILE *file, char delim)
unsigned int linenum = 0; /* keep these zero-based to be consistent */
/* go through every line in the file */
while ((line = xmalloc_fgetline(file)) != NULL) {
while ((line = xmalloc_getline(file)) != NULL) {
/* set up a list so we can keep track of what's been printed */
char * printed = xzalloc(strlen(line) * sizeof(char));
@@ -64,7 +64,7 @@ static void cut_file(FILE *file, char delim)
/* print the chars specified in each cut list */
for (; cl_pos < nlists; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
while (spos < (int)strlen(line)) {
while (spos < strlen(line)) {
if (!printed[spos]) {
printed[spos] = 'X';
putchar(line[spos]);
@@ -80,12 +80,12 @@ static void cut_file(FILE *file, char delim)
/* get out if we have no more lists to process or if the lines
* are lower than what we're interested in */
if (((int)linenum < spos) || (cl_pos >= nlists))
if (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 < (int)linenum) {
while (spos < linenum) {
spos++;
/* go to the next list if we're at the end of this one */
if (spos > cut_lists[cl_pos].endpos
@@ -97,7 +97,7 @@ static void cut_file(FILE *file, char delim)
spos = cut_lists[cl_pos].startpos;
/* get out if the current line is lower than the one
* we just became interested in */
if ((int)linenum < spos)
if (linenum < spos)
goto next_line;
}
}
@@ -162,7 +162,7 @@ static void cut_file(FILE *file, char delim)
}
int cut_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cut_main(int argc ATTRIBUTE_UNUSED, char **argv)
int cut_main(int argc, char **argv)
{
char delim = '\t'; /* delimiter, default is tab */
char *sopt, *ltok;
@@ -205,7 +205,7 @@ int cut_main(int argc ATTRIBUTE_UNUSED, char **argv)
char *ntok;
int s = 0, e = 0;
/* take apart the lists, one by one (they are separated with commas) */
/* take apart the lists, one by one (they are separated with commas */
while ((ltok = strsep(&sopt, ",")) != NULL) {
/* it's actually legal to pass an empty list */
@@ -258,18 +258,25 @@ int cut_main(int argc ATTRIBUTE_UNUSED, char **argv)
{
int retval = EXIT_SUCCESS;
FILE *file = stdin;
if (!*argv)
*--argv = (char *)"-";
if (!*argv) {
argv--;
goto jump_in;
}
do {
FILE *file = fopen_or_warn_stdin(*argv);
file = stdin;
if (NOT_LONE_DASH(*argv))
file = fopen_or_warn(*argv, "r");
if (!file) {
retval = EXIT_FAILURE;
continue;
}
jump_in:
cut_file(file, delim);
fclose_if_not_stdin(file);
if (NOT_LONE_DASH(*argv))
fclose(file);
} while (*++argv);
if (ENABLE_FEATURE_CLEAN_UP)
+109 -111
View File
@@ -39,135 +39,131 @@ static void maybe_set_utc(int opt)
}
int date_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int date_main(int argc ATTRIBUTE_UNUSED, char **argv)
int date_main(int argc, char **argv)
{
struct tm tm_time;
time_t tm;
struct tm tm_time;
unsigned opt;
int ifmt = -1;
char *date_str;
char *fmt_dt2str;
char *fmt_str2dt;
char *filename;
char *isofmt_arg = NULL;
char *date_str = NULL;
char *date_fmt = NULL;
char *filename = NULL;
char *isofmt_arg;
char *hintfmt_arg;
opt_complementary = "d--s:s--d"
USE_FEATURE_DATE_ISOFMT(":R--I:I--R");
opt = getopt32(argv, "Rs:ud:r:"
USE_FEATURE_DATE_ISOFMT("I::D:"),
&date_str, &date_str, &filename
USE_FEATURE_DATE_ISOFMT(, &isofmt_arg, &fmt_str2dt));
argv += optind;
USE_FEATURE_DATE_ISOFMT(, &isofmt_arg, &hintfmt_arg));
maybe_set_utc(opt);
if (ENABLE_FEATURE_DATE_ISOFMT && (opt & DATE_OPT_TIMESPEC)) {
ifmt = 0; /* default is date */
if (isofmt_arg) {
static const char isoformats[] ALIGN1 =
"date\0""hours\0""minutes\0""seconds\0";
ifmt = index_in_strings(isoformats, isofmt_arg);
if (ifmt < 0)
bb_show_usage();
if (!isofmt_arg) {
ifmt = 0; /* default is date */
} else {
static const char *const isoformats[] = {
"date", "hours", "minutes", "seconds"
};
for (ifmt = 0; ifmt < 4; ifmt++)
if (!strcmp(isofmt_arg, isoformats[ifmt]))
goto found;
/* parse error */
bb_show_usage();
found: ;
}
}
fmt_dt2str = NULL;
if (argv[0] && argv[0][0] == '+') {
fmt_dt2str = &argv[0][1]; /* Skip over the '+' */
argv++;
}
if (!(opt & (DATE_OPT_SET | DATE_OPT_DATE))) {
/* XXX, date_fmt == NULL from this always */
if ((date_fmt == NULL) && (optind < argc) && (argv[optind][0] == '+')) {
date_fmt = &argv[optind][1]; /* Skip over the '+' */
} else if (date_str == NULL) {
opt |= DATE_OPT_SET;
date_str = argv[0]; /* can be NULL */
if (date_str)
argv++;
date_str = argv[optind];
}
if (*argv)
bb_show_usage();
/* Now we have parsed all the information except the date format
which depends on whether the clock is being set or read */
if (opt & DATE_OPT_REFERENCE) {
if (filename) {
struct stat statbuf;
xstat(filename, &statbuf);
tm = statbuf.st_mtime;
} else
time(&tm);
memcpy(&tm_time, localtime(&tm), sizeof(tm_time));
/* If date string is given, update tm_time, and maybe set date */
/* Zero out fields - take her back to midnight! */
if (date_str != NULL) {
/* 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 & DATE_OPT_HINT)) {
if (strptime(date_str, fmt_str2dt, &tm_time) == NULL)
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
} else {
char end = '\0';
const char *last_colon = strrchr(date_str, ':');
strptime(date_str, hintfmt_arg, &tm_time);
} else if (strchr(date_str, ':') != NULL) {
/* Parse input and assign appropriately to tm_time */
if (last_colon != NULL) {
/* Parse input and assign appropriately to tm_time */
if (sscanf(date_str, "%u:%u%c",
&tm_time.tm_hour,
&tm_time.tm_min,
&end) >= 2) {
/* no adjustments needed */
} else if (sscanf(date_str, "%u.%u-%u:%u%c",
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min,
&end) >= 4) {
/* Adjust dates from 1-12 to 0-11 */
tm_time.tm_mon -= 1;
} else if (sscanf(date_str, "%u.%u.%u-%u:%u%c", &tm_time.tm_year,
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min,
&end) >= 5) {
tm_time.tm_year -= 1900; /* Adjust years */
tm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else if (sscanf(date_str, "%u-%u-%u %u:%u%c", &tm_time.tm_year,
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min,
&end) >= 5) {
tm_time.tm_year -= 1900; /* Adjust years */
tm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
//TODO: coreutils 6.9 also accepts "YYYY-MM-DD HH" (no minutes)
} else {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
if (end == ':') {
if (sscanf(last_colon + 1, "%u%c", &tm_time.tm_sec, &end) == 1)
end = '\0';
/* else end != NUL and we error out */
}
} else {
if (sscanf(date_str, "%2u%2u%2u%2u%u%c", &tm_time.tm_mon,
&tm_time.tm_mday, &tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_year, &end) < 4)
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
/* correct for century - minor Y2K problem here? */
if (tm_time.tm_year >= 1900) {
tm_time.tm_year -= 1900;
}
/* adjust date */
if (sscanf(date_str, "%d:%d:%d", &tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_sec) == 3) {
/* no adjustments needed */
} else if (sscanf(date_str, "%d:%d", &tm_time.tm_hour,
&tm_time.tm_min) == 2) {
/* no adjustments needed */
} else if (sscanf(date_str, "%d.%d-%d:%d:%d", &tm_time.tm_mon,
&tm_time.tm_mday, &tm_time.tm_hour,
&tm_time.tm_min, &tm_time.tm_sec) == 5) {
/* Adjust dates from 1-12 to 0-11 */
tm_time.tm_mon -= 1;
if (end == '.') {
if (sscanf(strchr(date_str, '.') + 1, "%u%c",
&tm_time.tm_sec, &end) == 1)
end = '\0';
/* else end != NUL and we error out */
}
}
if (end != '\0') {
} else if (sscanf(date_str, "%d.%d-%d:%d", &tm_time.tm_mon,
&tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min) == 4) {
/* Adjust dates from 1-12 to 0-11 */
tm_time.tm_mon -= 1;
} else if (sscanf(date_str, "%d.%d.%d-%d:%d:%d", &tm_time.tm_year,
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_sec) == 6) {
tm_time.tm_year -= 1900; /* Adjust years */
tm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else if (sscanf(date_str, "%d.%d.%d-%d:%d", &tm_time.tm_year,
&tm_time.tm_mon, &tm_time.tm_mday,
&tm_time.tm_hour, &tm_time.tm_min) == 5) {
tm_time.tm_year -= 1900; /* Adjust years */
tm_time.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
} else {
int nr;
char *cp;
nr = sscanf(date_str, "%2d%2d%2d%2d%d", &tm_time.tm_mon,
&tm_time.tm_mday, &tm_time.tm_hour, &tm_time.tm_min,
&tm_time.tm_year);
if (nr < 4 || nr > 5) {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
cp = strchr(date_str, '.');
if (cp) {
nr = sscanf(cp + 1, "%2d", &tm_time.tm_sec);
if (nr != 1) {
bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
}
/* correct for century - minor Y2K problem here? */
if (tm_time.tm_year >= 1900) {
tm_time.tm_year -= 1900;
}
/* adjust date */
tm_time.tm_mon -= 1;
}
/* Correct any day of week and day of year etc. fields */
tm_time.tm_isdst = -1; /* Be sure to recheck dst. */
tm = mktime(&tm_time);
@@ -185,53 +181,55 @@ int date_main(int argc ATTRIBUTE_UNUSED, char **argv)
/* Display output */
/* Deal with format string */
if (fmt_dt2str == NULL) {
if (date_fmt == NULL) {
int i;
fmt_dt2str = xzalloc(32);
date_fmt = xzalloc(32);
if (ENABLE_FEATURE_DATE_ISOFMT && ifmt >= 0) {
strcpy(fmt_dt2str, "%Y-%m-%d");
strcpy(date_fmt, "%Y-%m-%d");
if (ifmt > 0) {
i = 8;
fmt_dt2str[i++] = 'T';
fmt_dt2str[i++] = '%';
fmt_dt2str[i++] = 'H';
date_fmt[i++] = 'T';
date_fmt[i++] = '%';
date_fmt[i++] = 'H';
if (ifmt > 1) {
fmt_dt2str[i++] = ':';
fmt_dt2str[i++] = '%';
fmt_dt2str[i++] = 'M';
if (ifmt > 2) {
fmt_dt2str[i++] = ':';
fmt_dt2str[i++] = '%';
fmt_dt2str[i++] = 'S';
}
date_fmt[i++] = ':';
date_fmt[i++] = '%';
date_fmt[i++] = 'M';
}
if (ifmt > 2) {
date_fmt[i++] = ':';
date_fmt[i++] = '%';
date_fmt[i++] = 'S';
}
format_utc:
fmt_dt2str[i++] = '%';
fmt_dt2str[i] = (opt & DATE_OPT_UTC) ? 'Z' : 'z';
date_fmt[i++] = '%';
date_fmt[i] = (opt & DATE_OPT_UTC) ? 'Z' : 'z';
}
} else if (opt & DATE_OPT_RFC2822) {
/* Undo busybox.c for date -R */
if (ENABLE_LOCALE_SUPPORT)
setlocale(LC_TIME, "C");
strcpy(fmt_dt2str, "%a, %d %b %Y %H:%M:%S ");
strcpy(date_fmt, "%a, %d %b %Y %H:%M:%S ");
i = 22;
goto format_utc;
} else /* default case */
fmt_dt2str = (char*)"%a %b %e %H:%M:%S %Z %Y";
date_fmt = (char*)"%a %b %e %H:%M:%S %Z %Y";
}
#define date_buf bb_common_bufsiz1
if (*fmt_dt2str == '\0') {
if (*date_fmt == '\0') {
/* With no format string, just print a blank line */
date_buf[0] = '\0';
} else {
/* Handle special conversions */
if (strncmp(fmt_dt2str, "%f", 2) == 0) {
fmt_dt2str = (char*)"%Y.%m.%d-%H:%M:%S";
if (strncmp(date_fmt, "%f", 2) == 0) {
date_fmt = (char*)"%Y.%m.%d-%H:%M:%S";
}
/* Generate output string */
strftime(date_buf, sizeof(date_buf), fmt_dt2str, &tm_time);
strftime(date_buf, sizeof(date_buf), date_fmt, &tm_time);
}
puts(date_buf);
+82 -101
View File
@@ -65,7 +65,7 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
ssize_t n = full_write_or_warn(buf, len, filename);
if (n < 0)
return 1;
if ((size_t)n == obs)
if (n == obs)
G.out_full++;
else if (n) /* > 0 */
G.out_part++;
@@ -79,31 +79,23 @@ static bool write_and_stats(const void *buf, size_t len, size_t obs,
#endif
int dd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int dd_main(int argc ATTRIBUTE_UNUSED, char **argv)
int dd_main(int argc, char **argv)
{
enum {
/* Must be in the same order as OP_conv_XXX! */
/* (see "flags |= (1 << what)" below) */
FLAG_NOTRUNC = 1 << 0,
FLAG_SYNC = 1 << 1,
FLAG_NOERROR = 1 << 2,
FLAG_FSYNC = 1 << 3,
/* end of conv flags */
FLAG_TWOBUFS = 1 << 4,
FLAG_COUNT = 1 << 5,
FLAG_SYNC = 1 << 0,
FLAG_NOERROR = 1 << 1,
FLAG_NOTRUNC = 1 << 2,
FLAG_TWOBUFS = 1 << 3,
FLAG_COUNT = 1 << 4,
};
static const char keywords[] ALIGN1 =
"bs\0""count\0""seek\0""skip\0""if\0""of\0"
"bs=\0""count=\0""seek=\0""skip=\0""if=\0""of=\0"
#if ENABLE_FEATURE_DD_IBS_OBS
"ibs\0""obs\0""conv\0"
"ibs=\0""obs=\0""conv=\0""notrunc\0""sync\0""noerror\0"
#endif
;
#if ENABLE_FEATURE_DD_IBS_OBS
static const char conv_words[] ALIGN1 =
"notrunc\0""sync\0""noerror\0""fsync\0";
#endif
enum {
OP_bs = 0,
OP_bs = 1,
OP_count,
OP_seek,
OP_skip,
@@ -113,23 +105,9 @@ int dd_main(int argc ATTRIBUTE_UNUSED, char **argv)
OP_ibs,
OP_obs,
OP_conv,
/* Must be in the same order as FLAG_XXX! */
OP_conv_notrunc = 0,
OP_conv_notrunc,
OP_conv_sync,
OP_conv_noerror,
OP_conv_fsync,
/* Unimplemented conv=XXX: */
//nocreat do not create the output file
//excl fail if the output file already exists
//fdatasync physically write output file data before finishing
//swab swap every pair of input bytes
//lcase change upper case to lower case
//ucase change lower case to upper case
//block pad newline-terminated records with spaces to cbs-size
//unblock replace trailing spaces in cbs-size records with newline
//ascii from EBCDIC to ASCII
//ebcdic from ASCII to EBCDIC
//ibm from ASCII to alternate EBCDIC
#endif
};
int exitcode = EXIT_FAILURE;
@@ -143,6 +121,9 @@ int dd_main(int argc ATTRIBUTE_UNUSED, char **argv)
off_t count;
off_t seek, skip;
const char *infile, *outfile;
#if ENABLE_FEATURE_DD_SIGNAL_HANDLING
struct sigaction sigact;
#endif
} Z;
#define flags (Z.flags )
#define oc (Z.oc )
@@ -151,94 +132,98 @@ int dd_main(int argc ATTRIBUTE_UNUSED, char **argv)
#define skip (Z.skip )
#define infile (Z.infile )
#define outfile (Z.outfile)
#define sigact (Z.sigact )
memset(&Z, 0, sizeof(Z));
INIT_G();
//fflush(NULL); - is this needed because of NOEXEC?
#if ENABLE_FEATURE_DD_SIGNAL_HANDLING
signal_SA_RESTART_empty_mask(SIGUSR1, dd_output_status);
sigact.sa_handler = dd_output_status;
sigact.sa_flags = SA_RESTART;
sigemptyset(&sigact.sa_mask);
sigaction(SIGUSR1, &sigact, NULL);
#endif
for (n = 1; argv[n]; n++) {
int what;
char *val;
for (n = 1; n < argc; n++) {
smalluint key_len;
smalluint what;
char *key;
char *arg = argv[n];
#if ENABLE_DESKTOP
/* "dd --". NB: coreutils 6.9 will complain if they see
* more than one of them. We wouldn't. */
if (arg[0] == '-' && arg[1] == '-' && arg[2] == '\0')
continue;
#endif
val = strchr(arg, '=');
if (val == NULL)
//XXX:FIXME: we reject plain "dd --" This would cost ~20 bytes, so..
//if (*arg == '-' && *++arg == '-' && !*++arg) continue;
key = strstr(arg, "=");
if (key == NULL)
bb_show_usage();
*val = '\0';
what = index_in_strings(keywords, arg);
if (what < 0)
key_len = key - arg + 1;
key = xstrndup(arg, key_len);
what = index_in_strings(keywords, key) + 1;
if (ENABLE_FEATURE_CLEAN_UP)
free(key);
if (what == 0)
bb_show_usage();
/* *val = '='; - to preserve ps listing? */
val++;
arg += key_len;
/* Must fit into positive ssize_t */
#if ENABLE_FEATURE_DD_IBS_OBS
if (what == OP_ibs) {
/* Must fit into positive ssize_t */
ibs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
/*continue;*/
}
if (what == OP_obs) {
obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
/*continue;*/
}
if (what == OP_conv) {
while (1) {
/* find ',', replace them with NUL so we can use val for
* index_in_strings() without copying.
* We rely on val being non-null, else strchr would fault.
*/
arg = strchr(val, ',');
if (arg)
*arg = '\0';
what = index_in_strings(conv_words, val);
if (what < 0)
bb_error_msg_and_die(bb_msg_invalid_arg, val, "conv");
flags |= (1 << what);
if (!arg) /* no ',' left, so this was the last specifier */
break;
/* *arg = ','; - to preserve ps listing? */
val = arg + 1; /* skip this keyword and ',' */
if (what == OP_ibs) {
ibs = xatoul_range_sfx(arg, 1, ((size_t)-1L)/2, dd_suffixes);
continue;
}
if (what == OP_obs) {
obs = xatoul_range_sfx(arg, 1, ((size_t)-1L)/2, dd_suffixes);
continue;
}
if (what == OP_conv) {
while (1) {
/* find ',', replace them with nil so we can use arg for
* index_in_strings() without copying.
* We rely on arg being non-null, else strchr would fault.
*/
key = strchr(arg, ',');
if (key)
*key = '\0';
what = index_in_strings(keywords, arg) + 1;
if (what < OP_conv_notrunc)
bb_error_msg_and_die(bb_msg_invalid_arg, arg, "conv");
if (what == OP_conv_notrunc)
flags |= FLAG_NOTRUNC;
if (what == OP_conv_sync)
flags |= FLAG_SYNC;
if (what == OP_conv_noerror)
flags |= FLAG_NOERROR;
if (!key) /* no ',' left, so this was the last specifier */
break;
arg = key + 1; /* skip this keyword and ',' */
}
continue;
}
continue; /* we trashed 'what', can't fall through */
}
#endif
if (what == OP_bs) {
ibs = obs = xatoul_range_sfx(val, 1, ((size_t)-1L)/2, dd_suffixes);
/*continue;*/
ibs = obs = xatoul_range_sfx(arg, 1, ((size_t)-1L)/2, dd_suffixes);
continue;
}
/* These can be large: */
if (what == OP_count) {
flags |= FLAG_COUNT;
count = XATOU_SFX(val, dd_suffixes);
/*continue;*/
count = XATOU_SFX(arg, dd_suffixes);
continue;
}
if (what == OP_seek) {
seek = XATOU_SFX(val, dd_suffixes);
/*continue;*/
seek = XATOU_SFX(arg, dd_suffixes);
continue;
}
if (what == OP_skip) {
skip = XATOU_SFX(val, dd_suffixes);
/*continue;*/
skip = XATOU_SFX(arg, dd_suffixes);
continue;
}
if (what == OP_if) {
infile = val;
/*continue;*/
infile = arg;
continue;
}
if (what == OP_of) {
outfile = val;
/*continue;*/
}
} /* end of "for (argv[n])" */
if (what == OP_of)
outfile = arg;
}
//XXX:FIXME for huge ibs or obs, malloc'ing them isn't the brightest idea ever
ibuf = obuf = xmalloc(ibs);
if (ibs != obs) {
@@ -312,7 +297,7 @@ int dd_main(int argc ATTRIBUTE_UNUSED, char **argv)
while (n) {
size_t d = obs - oc;
if (d > (size_t)n)
if (d > n)
d = n;
memcpy(obuf + oc, tmp, d);
n -= d;
@@ -326,17 +311,13 @@ int dd_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
} else if (write_and_stats(ibuf, n, obs, outfile))
goto out_status;
if (flags & FLAG_FSYNC) {
if (fsync(ofd) < 0)
goto die_outfile;
}
}
if (ENABLE_FEATURE_DD_IBS_OBS && oc) {
w = full_write_or_warn(obuf, oc, outfile);
if (w < 0) goto out_status;
if (w > 0) G.out_part++;
if (w > 0)
G.out_part++;
}
if (close(ifd) < 0) {
die_infile:
+41 -28
View File
@@ -20,52 +20,62 @@ enum {
};
/* if fn is NULL then input is stdin and output is stdout */
static void convert(char *fn, int conv_type)
static int convert(char *fn, int conv_type)
{
FILE *in, *out;
int i;
char *temp_fn = temp_fn; /* for compiler */
char *resolved_fn = resolved_fn;
#define name_buf bb_common_bufsiz1
in = stdin;
out = stdout;
if (fn != NULL) {
struct stat st;
resolved_fn = xmalloc_follow_symlinks(fn);
if (resolved_fn == NULL)
bb_simple_perror_msg_and_die(fn);
in = xfopen(resolved_fn, "r");
fstat(fileno(in), &st);
temp_fn = xasprintf("%sXXXXXX", resolved_fn);
i = mkstemp(temp_fn);
if (i == -1
|| fchmod(i, st.st_mode) == -1
|| !(out = fdopen(i, "w+"))
) {
bb_simple_perror_msg_and_die(temp_fn);
in = xfopen(fn, "rw");
/*
The file is then created with mode read/write and
permissions 0666 for glibc 2.0.6 and earlier or
0600 for glibc 2.0.7 and later.
*/
snprintf(name_buf, sizeof(name_buf), "%sXXXXXX", fn);
i = mkstemp(&name_buf[0]);
if (i == -1 || chmod(name_buf, 0600) == -1) {
bb_perror_nomsg_and_die();
}
out = fdopen(i, "w+");
if (!out) {
close(i);
remove(name_buf);
return -2;
}
}
while ((i = fgetc(in)) != EOF) {
if (i == '\r')
continue;
if (i == '\n')
if (i == '\n') {
if (conv_type == CT_UNIX2DOS)
fputc('\r', out);
fputc('\n', out);
continue;
}
fputc(i, out);
}
if (fn != NULL) {
if (fclose(in) < 0 || fclose(out) < 0) {
unlink(temp_fn);
bb_perror_nomsg_and_die();
bb_perror_nomsg();
remove(name_buf);
return -2;
}
/* Assume they are both on the same filesystem (which
* should be true since we put them into the same directory
* so we _should_ be ok, but you never know... */
if (rename(name_buf, fn) < 0) {
bb_perror_msg("cannot rename '%s' as '%s'", name_buf, fn);
return -1;
}
xrename(temp_fn, resolved_fn);
free(temp_fn);
free(resolved_fn);
}
return 0;
}
int dos2unix_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
@@ -74,9 +84,10 @@ int dos2unix_main(int argc, char **argv)
int o, conv_type;
/* See if we are supposed to be doing dos2unix or unix2dos */
conv_type = CT_UNIX2DOS;
if (applet_name[0] == 'd') {
conv_type = CT_DOS2UNIX;
conv_type = CT_DOS2UNIX; /* 2 */
} else {
conv_type = CT_UNIX2DOS; /* 1 */
}
/* -u convert to unix, -d convert to dos */
@@ -90,9 +101,11 @@ int dos2unix_main(int argc, char **argv)
do {
/* might be convert(NULL) if there is no filename given */
convert(argv[optind], conv_type);
o = convert(argv[optind], conv_type);
if (o < 0)
break;
optind++;
} while (optind < argc);
return 0;
return o;
}
+10 -5
View File
@@ -141,11 +141,12 @@ static unsigned long du(const char *filename)
}
int du_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int du_main(int argc ATTRIBUTE_UNUSED, char **argv)
int du_main(int argc, char **argv)
{
unsigned long total;
int slink_depth_save;
bool print_final_total;
char *smax_print_depth;
unsigned opt;
#if ENABLE_FEATURE_HUMAN_READABLE
@@ -167,8 +168,8 @@ int du_main(int argc ATTRIBUTE_UNUSED, char **argv)
* ignore -a. This is consistent with -s being equivalent to -d 0.
*/
#if ENABLE_FEATURE_HUMAN_READABLE
opt_complementary = "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s:d+";
opt = getopt32(argv, "aHkLsx" "d:" "lc" "hm", &G.max_print_depth);
opt_complementary = "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s";
opt = getopt32(argv, "aHkLsx" "d:" "lc" "hm", &smax_print_depth);
argv += optind;
if (opt & (1 << 9)) {
/* -h opt */
@@ -183,8 +184,8 @@ int du_main(int argc ATTRIBUTE_UNUSED, char **argv)
G.disp_hr = 1024;
}
#else
opt_complementary = "H-L:L-H:s-d:d-s:d+";
opt = getopt32(argv, "aHkLsx" "d:" "lc", &G.max_print_depth);
opt_complementary = "H-L:L-H:s-d:d-s";
opt = getopt32(argv, "aHkLsx" "d:" "lc", &smax_print_depth);
argv += optind;
#if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
if (opt & (1 << 2)) {
@@ -210,6 +211,10 @@ int du_main(int argc ATTRIBUTE_UNUSED, char **argv)
G.max_print_depth = 0;
}
G.one_file_system = opt & (1 << 5); /* -x opt */
if (opt & (1 << 6)) {
/* -d opt */
G.max_print_depth = xatoi_u(smax_print_depth);
}
if (opt & (1 << 7)) {
/* -l opt */
G.count_hardlinks = MAXINT(nlink_t);
+8 -10
View File
@@ -27,9 +27,11 @@
/* This is a NOFORK applet. Be very careful! */
/* NB: can be used by shell even if not enabled as applet */
/* argc is unused, but removing it precludes compiler from
* using call -> jump optimization */
int echo_main(int argc ATTRIBUTE_UNUSED, char **argv)
int echo_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int echo_main(int argc, char **argv)
{
const char *arg;
#if !ENABLE_FEATURE_FANCY_ECHO
@@ -108,19 +110,15 @@ int echo_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
#if !ENABLE_FEATURE_FANCY_ECHO
/* SUSv3 specifies that octal escapes must begin with '0'. */
if ( ((int)(unsigned char)(*arg) - '0') >= 8) /* '8' or bigger */
if ( (((unsigned char)*arg) - '1') >= 7)
#endif
{
/* Since SUSv3 mandates a first digit of 0, 4-digit octals
* of the form \0### are accepted. */
if (*arg == '0') {
/* NB: don't turn "...\0" into "...\" */
if (arg[1] && ((unsigned char)(arg[1]) - '0') < 8) {
arg++;
}
if (*arg == '0' && ((unsigned char)(arg[1]) - '0') < 8) {
arg++;
}
/* bb_process_escape_sequence handles NUL correctly
* ("...\" case). */
/* bb_process_escape_sequence can handle nul correctly */
c = bb_process_escape_sequence(&arg);
}
}
+7 -3
View File
@@ -29,6 +29,9 @@
* - use xfunc_error_retval
*/
#include <getopt.h> /* struct option */
extern char **environ;
#include "libbb.h"
#if ENABLE_FEATURE_ENV_LONG_OPTIONS
@@ -39,7 +42,7 @@ static const char env_longopts[] ALIGN1 =
#endif
int env_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int env_main(int argc ATTRIBUTE_UNUSED, char **argv)
int env_main(int argc, char **argv)
{
/* cleanenv was static - why? */
char *cleanenv[1];
@@ -62,7 +65,8 @@ int env_main(int argc ATTRIBUTE_UNUSED, char **argv)
environ = cleanenv;
} else {
while (unset_env) {
unsetenv(llist_pop(&unset_env));
unsetenv(unset_env->data);
unset_env = unset_env->link;
}
}
@@ -84,7 +88,7 @@ int env_main(int argc ATTRIBUTE_UNUSED, char **argv)
puts(*ep);
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit(0);
}
/*
+19 -10
View File
@@ -41,7 +41,7 @@ static void expand(FILE *file, unsigned tab_size, unsigned opt)
char *line;
char *ptr;
int convert;
unsigned pos;
int pos;
/* Increment tab_size by 1 locally.*/
tab_size++;
@@ -80,7 +80,7 @@ static void unexpand(FILE *file, unsigned int tab_size, unsigned opt)
int convert;
int pos;
int i = 0;
unsigned column = 0;
int column = 0;
while ((line = xmalloc_fgets(file)) != NULL) {
convert = 1;
@@ -126,7 +126,7 @@ static void unexpand(FILE *file, unsigned int tab_size, unsigned opt)
#endif
int expand_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int expand_main(int argc ATTRIBUTE_UNUSED, char **argv)
int expand_main(int argc, char **argv)
{
/* Default 8 spaces for 1 tab */
const char *opt_t = "8";
@@ -154,7 +154,7 @@ int expand_main(int argc ATTRIBUTE_UNUSED, char **argv)
if (ENABLE_EXPAND && (!ENABLE_UNEXPAND || applet_name[0] == 'e')) {
USE_FEATURE_EXPAND_LONG_OPTIONS(applet_long_options = expand_longopts);
opt = getopt32(argv, "it:", &opt_t);
} else {
} else if (ENABLE_UNEXPAND) {
USE_FEATURE_UNEXPAND_LONG_OPTIONS(applet_long_options = unexpand_longopts);
/* -t NUM sets also -a */
opt_complementary = "ta";
@@ -166,23 +166,32 @@ int expand_main(int argc ATTRIBUTE_UNUSED, char **argv)
argv += optind;
/* If no args are given, read from stdin */
if (!*argv) {
*--argv = (char*)bb_msg_standard_input;
goto use_stdin;
}
do {
file = fopen_or_warn_stdin(*argv);
if (!file) {
exit_status = EXIT_FAILURE;
continue;
if (NOT_LONE_CHAR(*argv, '-')) {
file = fopen_or_warn(*argv, "r");
if (!file) {
exit_status = EXIT_FAILURE;
continue;
}
} else {
use_stdin:
file = stdin;
}
if (ENABLE_EXPAND && (!ENABLE_UNEXPAND || applet_name[0] == 'e'))
USE_EXPAND(expand(file, tab_size, opt));
else
else if (ENABLE_UNEXPAND)
USE_UNEXPAND(unexpand(file, tab_size, opt));
/* Check and close the file */
if (fclose_if_not_stdin(file)) {
/* We do want all of them to execute, thus | instead of || */
if (ferror(file) | fclose_if_not_stdin(file)) {
bb_simple_perror_msg(*argv);
exit_status = EXIT_FAILURE;
}
+87 -84
View File
@@ -28,6 +28,13 @@
#include "libbb.h"
#include "xregex.h"
/* The kinds of value we can have. */
enum valtype {
integer,
string
};
typedef enum valtype TYPE;
#if ENABLE_EXPR_MATH_SUPPORT_64
typedef int64_t arith_t;
@@ -44,16 +51,10 @@ typedef long arith_t;
/* TODO: use bb_strtol[l]? It's easier to check for errors... */
/* The kinds of value we can have. */
enum {
INTEGER,
STRING
};
/* A value is.... */
struct valinfo {
smallint type; /* Which kind. */
union { /* The value itself. */
TYPE type; /* Which kind. */
union { /* The value itself. */
arith_t i;
char *s;
} u;
@@ -76,9 +77,8 @@ static VALUE *int_value(arith_t i)
{
VALUE *v;
v = xzalloc(sizeof(VALUE));
if (INTEGER) /* otherwise xzaaloc did it already */
v->type = INTEGER;
v = xmalloc(sizeof(VALUE));
v->type = integer;
v->u.i = i;
return v;
}
@@ -89,47 +89,46 @@ static VALUE *str_value(const char *s)
{
VALUE *v;
v = xzalloc(sizeof(VALUE));
if (STRING) /* otherwise xzaaloc did it already */
v->type = STRING;
v = xmalloc(sizeof(VALUE));
v->type = string;
v->u.s = xstrdup(s);
return v;
}
/* Free VALUE V, including structure components. */
static void freev(VALUE *v)
static void freev(VALUE * v)
{
if (v->type == STRING)
if (v->type == string)
free(v->u.s);
free(v);
}
/* Return nonzero if V is a null-string or zero-number. */
static int null(VALUE *v)
static int null(VALUE * v)
{
if (v->type == INTEGER)
if (v->type == integer)
return v->u.i == 0;
/* STRING: */
/* string: */
return v->u.s[0] == '\0' || LONE_CHAR(v->u.s, '0');
}
/* Coerce V to a STRING value (can't fail). */
/* Coerce V to a string value (can't fail). */
static void tostring(VALUE *v)
static void tostring(VALUE * v)
{
if (v->type == INTEGER) {
if (v->type == integer) {
v->u.s = xasprintf("%" PF_REZ "d", PF_REZ_TYPE v->u.i);
v->type = STRING;
v->type = string;
}
}
/* Coerce V to an INTEGER value. Return 1 on success, 0 on failure. */
/* Coerce V to an integer value. Return 1 on success, 0 on failure. */
static bool toarith(VALUE *v)
static bool toarith(VALUE * v)
{
if (v->type == STRING) {
if (v->type == string) {
arith_t i;
char *e;
@@ -140,54 +139,50 @@ static bool toarith(VALUE *v)
return 0;
free(v->u.s);
v->u.i = i;
v->type = INTEGER;
v->type = integer;
}
return 1;
}
/* Return str[0]+str[1] if the next token matches STR exactly.
/* Return nonzero if the next token matches STR exactly.
STR must not be NULL. */
static int nextarg(const char *str)
static bool nextarg(const char *str)
{
if (*G.args == NULL || strcmp(*G.args, str) != 0)
if (*G.args == NULL)
return 0;
return (unsigned char)str[0] + (unsigned char)str[1];
return strcmp(*G.args, str) == 0;
}
/* The comparison operator handling functions. */
static int cmp_common(VALUE *l, VALUE *r, int op)
static int cmp_common(VALUE * l, VALUE * r, int op)
{
arith_t ll, rr;
int cmpval;
ll = l->u.i;
rr = r->u.i;
if (l->type == STRING || r->type == STRING) {
if (l->type == string || r->type == string) {
tostring(l);
tostring(r);
ll = strcmp(l->u.s, r->u.s);
rr = 0;
}
/* calculating ll - rr and checking the result is prone to overflows.
* We'll do it differently: */
cmpval = strcmp(l->u.s, r->u.s);
} else
cmpval = l->u.i - r->u.i;
if (op == '<')
return ll < rr;
if (op == ('<' + '='))
return ll <= rr;
if (op == '=' || (op == '=' + '='))
return ll == rr;
if (op == '!' + '=')
return ll != rr;
return cmpval < 0;
if (op == ('L' + 'E'))
return cmpval <= 0;
if (op == '=')
return cmpval == 0;
if (op == '!')
return cmpval != 0;
if (op == '>')
return ll > rr;
return cmpval > 0;
/* >= */
return ll >= rr;
return cmpval >= 0;
}
/* The arithmetic operator handling functions. */
static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
static arith_t arithmetic_common(VALUE * l, VALUE * r, int op)
{
arith_t li, ri;
@@ -195,24 +190,25 @@ static arith_t arithmetic_common(VALUE *l, VALUE *r, int op)
bb_error_msg_and_die("non-numeric argument");
li = l->u.i;
ri = r->u.i;
if ((op == '/' || op == '%') && ri == 0)
bb_error_msg_and_die("division by zero");
if (op == '+')
return li + ri;
if (op == '-')
else if (op == '-')
return li - ri;
if (op == '*')
else if (op == '*')
return li * ri;
if (ri == 0)
bb_error_msg_and_die("division by zero");
if (op == '/')
else if (op == '/')
return li / ri;
return li % ri;
else
return li % ri;
}
/* Do the : operator.
SV is the VALUE for the lhs (the string),
PV is the VALUE for the rhs (the pattern). */
static VALUE *docolon(VALUE *sv, VALUE *pv)
static VALUE *docolon(VALUE * sv, VALUE * pv)
{
VALUE *v;
regex_t re_buffer;
@@ -234,16 +230,14 @@ of a basic regular expression is not portable; it is being ignored", pv->u.s);
/* expr uses an anchored pattern match, so check that there was a
* match and that the match starts at offset 0. */
if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH
&& re_regs[0].rm_so == 0
) {
if (regexec(&re_buffer, sv->u.s, NMATCH, re_regs, 0) != REG_NOMATCH &&
re_regs[0].rm_so == 0) {
/* Were \(...\) used? */
if (re_buffer.re_nsub > 0) {
sv->u.s[re_regs[1].rm_eo] = '\0';
v = str_value(sv->u.s + re_regs[1].rm_so);
} else {
} else
v = int_value(re_regs[0].rm_eo);
}
} else {
/* Match failed -- return the right kind of null. */
if (re_buffer.re_nsub > 0)
@@ -333,7 +327,7 @@ static VALUE *eval6(void)
v = str_value("");
else {
v = xmalloc(sizeof(VALUE));
v->type = STRING;
v->type = string;
v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
}
freev(l);
@@ -373,11 +367,14 @@ static VALUE *eval4(void)
l = eval5();
while (1) {
op = nextarg("*");
if (!op) { op = nextarg("/");
if (!op) { op = nextarg("%");
if (!op) return l;
}}
if (nextarg("*"))
op = '*';
else if (nextarg("/"))
op = '/';
else if (nextarg("%"))
op = '%';
else
return l;
G.args++;
r = eval5();
val = arithmetic_common(l, r, op);
@@ -397,11 +394,12 @@ static VALUE *eval3(void)
l = eval4();
while (1) {
op = nextarg("+");
if (!op) {
op = nextarg("-");
if (!op) return l;
}
if (nextarg("+"))
op = '+';
else if (nextarg("-"))
op = '-';
else
return l;
G.args++;
r = eval4();
val = arithmetic_common(l, r, op);
@@ -421,15 +419,20 @@ static VALUE *eval2(void)
l = eval3();
while (1) {
op = nextarg("<");
if (!op) { op = nextarg("<=");
if (!op) { op = nextarg("=");
if (!op) { op = nextarg("==");
if (!op) { op = nextarg("!=");
if (!op) { op = nextarg(">=");
if (!op) { op = nextarg(">");
if (!op) return l;
}}}}}}
if (nextarg("<"))
op = '<';
else if (nextarg("<="))
op = 'L' + 'E';
else if (nextarg("=") || nextarg("=="))
op = '=';
else if (nextarg("!="))
op = '!';
else if (nextarg(">="))
op = 'G' + 'E';
else if (nextarg(">"))
op = '>';
else
return l;
G.args++;
r = eval3();
toarith(l);
@@ -495,7 +498,7 @@ int expr_main(int argc, char **argv)
if (*G.args)
bb_error_msg_and_die("syntax error");
if (v->type == INTEGER)
if (v->type == integer)
printf("%" PF_REZ "d\n", PF_REZ_TYPE v->u.i);
else
puts(v->u.s);
+1 -1
View File
@@ -8,7 +8,7 @@
*/
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/000095399/utilities/false.html */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/false.html */
#include "libbb.h"
+16 -13
View File
@@ -12,17 +12,18 @@
#include "libbb.h"
/* Must match getopt32 call */
#define FLAG_COUNT_BYTES 1
#define FLAG_BREAK_SPACES 2
#define FLAG_WIDTH 4
static unsigned long flags;
#define FLAG_COUNT_BYTES 1
#define FLAG_BREAK_SPACES 2
#define FLAG_WIDTH 4
/* Assuming the current column is COLUMN, return the column that
printing C will move the cursor to.
The first column is 0. */
static int adjust_column(int column, char c)
{
if (!(option_mask32 & FLAG_COUNT_BYTES)) {
if (!(flags & FLAG_COUNT_BYTES)) {
if (c == '\b') {
if (column > 0)
column--;
@@ -53,27 +54,29 @@ int fold_main(int argc, char **argv)
char const *a = argv[i];
if (*a++ == '-') {
if (*a == '-' && !a[1]) /* "--" */
if (*a == '-' && !a[1])
break;
if (isdigit(*a))
if (isdigit(*a)) {
argv[i] = xasprintf("-w%s", a);
}
}
}
}
getopt32(argv, "bsw:", &w_opt);
if (option_mask32 & FLAG_WIDTH)
flags = getopt32(argv, "bsw:", &w_opt);
if (flags & FLAG_WIDTH)
width = xatoul_range(w_opt, 1, 10000);
argv += optind;
if (!*argv)
if (!*argv) {
*--argv = (char*)"-";
}
do {
FILE *istream = fopen_or_warn_stdin(*argv);
int c;
int column = 0; /* Screen column where next char will go. */
int offset_out = 0; /* Index in 'line_out' for next char. */
int offset_out = 0; /* Index in `line_out' for next char. */
if (istream == NULL) {
errs |= EXIT_FAILURE;
@@ -99,7 +102,7 @@ int fold_main(int argc, char **argv)
/* This character would make the line too long.
Print the line plus a newline, and make this character
start the next line. */
if (option_mask32 & FLAG_BREAK_SPACES) {
if (flags & FLAG_BREAK_SPACES) {
/* Look for the last blank. */
int logical_end;
@@ -141,7 +144,7 @@ int fold_main(int argc, char **argv)
fwrite(line_out, sizeof(char), (size_t) offset_out, stdout);
}
if (fclose_if_not_stdin(istream)) {
if (ferror(istream) || fclose_if_not_stdin(istream)) {
bb_simple_perror_msg(*argv); /* Avoid multibyte problems. */
errs |= EXIT_FAILURE;
}
+5 -5
View File
@@ -91,19 +91,19 @@ int head_main(int argc, char **argv)
}
}
argc -= optind;
argv += optind;
if (!*argv)
if (!*argv) {
*--argv = (char*)"-";
}
fmt = header_fmt_str + 1;
#if ENABLE_FEATURE_FANCY_HEAD
if (argc <= header_threshhold) {
if (argc - optind <= header_threshhold) {
header_threshhold = 0;
}
#else
if (argc <= 1) {
fmt += 11; /* "" */
if (argc <= optind + 1) {
fmt += 11;
}
/* Now define some things here to avoid #ifdefs in the code below.
* These should optimize out of the if conditions below. */
+1 -1
View File
@@ -37,7 +37,7 @@ static int printf_full(unsigned int id, const char *arg, const char prefix)
}
int id_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int id_main(int argc ATTRIBUTE_UNUSED, char **argv)
int id_main(int argc, char **argv)
{
struct passwd *p;
uid_t uid;
+3
View File
@@ -9,6 +9,9 @@
* owner/group, will probably modify bb_make_directory(...)
*/
#include <libgen.h>
#include <getopt.h> /* struct option */
#include "libbb.h"
#include "libcoreutils/coreutils.h"
+1 -9
View File
@@ -6,19 +6,11 @@
#ifndef COREUTILS_H
#define COREUTILS_H 1
#if __GNUC_PREREQ(4,1)
# pragma GCC visibility push(hidden)
#endif
typedef int (*stat_func)(const char *fn, struct stat *ps);
int cp_mv_stat2(const char *fn, struct stat *fn_stat, stat_func sf);
int cp_mv_stat(const char *fn, struct stat *fn_stat);
mode_t getopt_mk_fifo_nod(char **argv);
#if __GNUC_PREREQ(4,1)
# pragma GCC visibility pop
#endif
mode_t getopt_mk_fifo_nod(int argc, char **argv);
#endif
-6
View File
@@ -27,12 +27,6 @@ int cp_mv_stat2(const char *fn, struct stat *fn_stat, stat_func sf)
{
if (sf(fn, fn_stat) < 0) {
if (errno != ENOENT) {
#if ENABLE_FEATURE_VERBOSE_CP_MESSAGE
if (errno == ENOTDIR) {
bb_error_msg("cannot stat '%s': Path has non-directory component", fn);
return -1;
}
#endif
bb_perror_msg("cannot stat '%s'", fn);
return -1;
}
+1 -1
View File
@@ -23,7 +23,7 @@
#include "libbb.h"
#include "coreutils.h"
mode_t getopt_mk_fifo_nod(char **argv)
mode_t getopt_mk_fifo_nod(int argc, char **argv)
{
mode_t mode = 0666;
char *smode = NULL;
+70 -89
View File
@@ -29,12 +29,9 @@
* 1. requires lstat (BSD) - how do you do it without?
*/
#include <getopt.h>
#include "libbb.h"
#if ENABLE_FEATURE_ASSUME_UNICODE
#include <wchar.h>
#endif
/* This is a NOEXEC applet. Be very careful! */
@@ -118,6 +115,18 @@ SPLIT_SUBDIR = 2,
#define ATTR(mode) ("\00\00\01\00\01\00\01\00"\
"\00\00\01\00\01\00\00\01" [TYPEINDEX(mode)])
/* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
#if ENABLE_FEATURE_LS_COLOR
static smallint show_color;
/* long option entry used only for --color, which has no short option
* equivalent */
static const char ls_color_opt[] ALIGN1 =
"color\0" Optional_argument "\xff" /* no short equivalent */
;
#else
enum { show_color = 0 };
#endif
/*
* a directory entry and its stat info are stored here
*/
@@ -129,68 +138,25 @@ struct dnode { /* the basic node */
USE_SELINUX(security_context_t sid;)
struct dnode *next; /* point at the next node */
};
typedef struct dnode dnode_t;
static struct dnode **list_dir(const char *);
static struct dnode **dnalloc(int);
static int list_single(const struct dnode *);
static int list_single(struct dnode *);
static unsigned all_fmt;
struct globals {
#if ENABLE_FEATURE_LS_COLOR
smallint show_color;
#endif
smallint exit_code;
unsigned all_fmt;
#if ENABLE_FEATURE_AUTOWIDTH
unsigned tabstops; // = COLUMN_GAP;
unsigned terminal_width; // = TERMINAL_WIDTH;
#endif
#if ENABLE_FEATURE_LS_TIMESTAMPS
/* Do time() just once. Saves one syscall per file for "ls -l" */
time_t current_time_t;
#endif
};
#define G (*(struct globals*)&bb_common_bufsiz1)
#if ENABLE_FEATURE_LS_COLOR
#define show_color (G.show_color )
#else
enum { show_color = 0 };
#endif
#define exit_code (G.exit_code )
#define all_fmt (G.all_fmt )
#if ENABLE_FEATURE_AUTOWIDTH
#define tabstops (G.tabstops )
#define terminal_width (G.terminal_width)
static unsigned tabstops = COLUMN_GAP;
static unsigned terminal_width = TERMINAL_WIDTH;
#else
enum {
tabstops = COLUMN_GAP,
terminal_width = TERMINAL_WIDTH,
};
#endif
#define current_time_t (G.current_time_t)
/* memset: we have to zero it out because of NOEXEC */
#define INIT_G() do { \
memset(&G, 0, sizeof(G)); \
USE_FEATURE_AUTOWIDTH(tabstops = COLUMN_GAP;) \
USE_FEATURE_AUTOWIDTH(terminal_width = TERMINAL_WIDTH;) \
USE_FEATURE_LS_TIMESTAMPS(time(&current_time_t);) \
} while (0)
#if ENABLE_FEATURE_ASSUME_UNICODE
/* libbb candidate */
static size_t mbstrlen(const char *string)
{
size_t width = mbsrtowcs(NULL /*dest*/, &string,
MAXINT(size_t) /*len*/, NULL /*state*/);
if (width == (size_t)-1)
return strlen(string);
return width;
}
#else
#define mbstrlen(string) strlen(string)
#endif
static int status = EXIT_SUCCESS;
static struct dnode *my_stat(const char *fullname, const char *name, int force_follow)
{
@@ -206,7 +172,7 @@ static struct dnode *my_stat(const char *fullname, const char *name, int force_f
#endif
if (stat(fullname, &dstat)) {
bb_simple_perror_msg(fullname);
exit_code = EXIT_FAILURE;
status = EXIT_FAILURE;
return 0;
}
} else {
@@ -217,7 +183,7 @@ static struct dnode *my_stat(const char *fullname, const char *name, int force_f
#endif
if (lstat(fullname, &dstat)) {
bb_simple_perror_msg(fullname);
exit_code = EXIT_FAILURE;
status = EXIT_FAILURE;
return 0;
}
}
@@ -430,7 +396,7 @@ static void showfiles(struct dnode **dn, int nfiles)
} else {
/* find the longest file name, use that as the column width */
for (i = 0; i < nfiles; i++) {
int len = mbstrlen(dn[i]->name);
int len = strlen(dn[i]->name);
if (column_width < len)
column_width = len;
}
@@ -529,7 +495,7 @@ static struct dnode **list_dir(const char *path)
nfiles = 0;
dir = warn_opendir(path);
if (dir == NULL) {
exit_code = EXIT_FAILURE;
status = EXIT_FAILURE;
return NULL; /* could not open the dir */
}
while ((entry = readdir(dir)) != NULL) {
@@ -573,7 +539,13 @@ static struct dnode **list_dir(const char *path)
}
static int list_single(const struct dnode *dn)
#if ENABLE_FEATURE_LS_TIMESTAMPS
/* Do time() just once. Saves one syscall per file for "ls -l" */
/* Initialized in main() */
static time_t current_time_t;
#endif
static int list_single(struct dnode *dn)
{
int i, column = 0;
@@ -687,12 +659,7 @@ static int list_single(const struct dnode *dn)
fgcolor(info.st_mode));
}
#endif
#if ENABLE_FEATURE_ASSUME_UNICODE
printf("%s", dn->name);
column += mbstrlen(dn->name);
#else
column += printf("%s", dn->name);
#endif
if (show_color) {
printf("\033[0m");
}
@@ -735,7 +702,6 @@ static int list_single(const struct dnode *dn)
return column;
}
/* "[-]Cadil1", POSIX mandated options, busybox always supports */
/* "[-]gnsx", POSIX non-mandated options, busybox always supports */
/* "[-]Ak" GNU options, busybox always supports */
@@ -814,18 +780,11 @@ static const unsigned opt_flags[] = {
};
/* colored LS support by JaWi, janwillem.janssen@lxtreme.nl */
#if ENABLE_FEATURE_LS_COLOR
/* long option entry used only for --color, which has no short option
* equivalent */
static const char ls_color_opt[] ALIGN1 =
"color\0" Optional_argument "\xff" /* no short equivalent */
;
#endif
/* THIS IS A "SAFE" APPLET, main() MAY BE CALLED INTERNALLY FROM SHELL */
/* BE CAREFUL! */
int ls_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int ls_main(int argc ATTRIBUTE_UNUSED, char **argv)
int ls_main(int argc, char **argv)
{
struct dnode **dnd;
struct dnode **dnf;
@@ -833,13 +792,20 @@ int ls_main(int argc ATTRIBUTE_UNUSED, char **argv)
struct dnode *dn;
struct dnode *cur;
unsigned opt;
int nfiles;
int nfiles = 0;
int dnfiles;
int dndirs;
int oi;
int ac;
int i;
char **av;
USE_FEATURE_AUTOWIDTH(char *tabstops_str = NULL;)
USE_FEATURE_AUTOWIDTH(char *terminal_width_str = NULL;)
USE_FEATURE_LS_COLOR(char *color_opt;)
INIT_G();
#if ENABLE_FEATURE_LS_TIMESTAMPS
time(&current_time_t);
#endif
all_fmt = LIST_SHORT |
(ENABLE_FEATURE_LS_SORTFILES * (SORT_NAME | SORT_FORWARD));
@@ -854,9 +820,12 @@ int ls_main(int argc ATTRIBUTE_UNUSED, char **argv)
/* process options */
USE_FEATURE_LS_COLOR(applet_long_options = ls_color_opt;)
#if ENABLE_FEATURE_AUTOWIDTH
opt_complementary = "T+:w+"; /* -T N, -w N */
opt = getopt32(argv, ls_options, &tabstops, &terminal_width
opt = getopt32(argv, ls_options, &tabstops_str, &terminal_width_str
USE_FEATURE_LS_COLOR(, &color_opt));
if (tabstops_str)
tabstops = xatou(tabstops_str);
if (terminal_width_str)
terminal_width = xatou(terminal_width_str);
#else
opt = getopt32(argv, ls_options USE_FEATURE_LS_COLOR(, &color_opt));
#endif
@@ -920,27 +889,39 @@ int ls_main(int argc ATTRIBUTE_UNUSED, char **argv)
if (!(all_fmt & STYLE_MASK))
all_fmt |= (isatty(STDOUT_FILENO) ? STYLE_COLUMNS : STYLE_SINGLE);
argv += optind;
if (!argv[0])
*--argv = (char*)".";
/*
* when there are no cmd line args we have to supply a default "." arg.
* we will create a second argv array, "av" that will hold either
* our created "." arg, or the real cmd line args. The av array
* just holds the pointers- we don't move the date the pointers
* point to.
*/
ac = argc - optind; /* how many cmd line args are left */
if (ac < 1) {
static const char *const dotdir[] = { "." };
if (argv[1])
all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
av = (char **) dotdir;
ac = 1;
} else {
av = argv + optind;
}
/* now, everything is in the av array */
if (ac > 1)
all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
/* stuff the command line file names into a dnode array */
dn = NULL;
nfiles = 0;
do {
for (oi = 0; oi < ac; oi++) {
/* ls w/o -l follows links on command line */
cur = my_stat(*argv, *argv, !(all_fmt & STYLE_LONG));
argv++;
cur = my_stat(av[oi], av[oi], !(all_fmt & STYLE_LONG));
if (!cur)
continue;
cur->allocated = 0;
cur->next = dn;
dn = cur;
nfiles++;
} while (*argv);
}
/* now that we know how many files there are
* allocate memory for an array to hold dnode pointers
@@ -975,5 +956,5 @@ int ls_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
if (ENABLE_FEATURE_CLEAN_UP)
dfree(dnp, nfiles);
return exit_code;
return status;
}
+25 -16
View File
@@ -21,7 +21,7 @@ static unsigned char *hash_bin_to_hex(unsigned char *hash_value,
/* xzalloc zero-terminates */
char *hex_value = xzalloc((hash_length * 2) + 1);
bin2hex(hex_value, (char*)hash_value, hash_length);
return (unsigned char *)hex_value;
return hex_value;
}
static uint8_t *hash_file(const char *filename, hash_algo_t hash_algo)
@@ -36,9 +36,12 @@ static uint8_t *hash_file(const char *filename, hash_algo_t hash_algo)
void (*update)(const void*, size_t, void*);
void (*final)(void*, void*);
src_fd = open_or_warn_stdin(filename);
if (src_fd < 0) {
return NULL;
src_fd = STDIN_FILENO;
if (NOT_LONE_DASH(filename)) {
src_fd = open_or_warn(filename, O_RDONLY);
if (src_fd < 0) {
return NULL;
}
}
/* figure specific hash algorithims */
@@ -75,7 +78,7 @@ static uint8_t *hash_file(const char *filename, hash_algo_t hash_algo)
}
int md5_sha1_sum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int md5_sha1_sum_main(int argc ATTRIBUTE_UNUSED, char **argv)
int md5_sha1_sum_main(int argc, char **argv)
{
int return_value = EXIT_SUCCESS;
uint8_t *hash_value;
@@ -87,10 +90,6 @@ int md5_sha1_sum_main(int argc ATTRIBUTE_UNUSED, char **argv)
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK)
flags = getopt32(argv, "scw");
else optind = 1;
argv += optind;
//argc -= optind;
if (!*argv)
*--argv = (char*)"-";
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK && !(flags & FLAG_CHECK)) {
if (flags & FLAG_SILENT) {
@@ -102,20 +101,28 @@ int md5_sha1_sum_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
}
if (argc == optind) {
argv[argc++] = (char*)"-";
}
if (ENABLE_FEATURE_MD5_SHA1_SUM_CHECK && (flags & FLAG_CHECK)) {
FILE *pre_computed_stream;
int count_total = 0;
int count_failed = 0;
char *file_ptr = argv[optind];
char *line;
if (argv[1]) {
if (optind + 1 != argc) {
bb_error_msg_and_die
("only one argument may be specified when using -c");
}
pre_computed_stream = xfopen_stdin(argv[0]);
pre_computed_stream = stdin;
if (NOT_LONE_DASH(file_ptr)) {
pre_computed_stream = xfopen(file_ptr, "r");
}
while ((line = xmalloc_fgetline(pre_computed_stream)) != NULL) {
while ((line = xmalloc_getline(pre_computed_stream)) != NULL) {
char *filename_ptr;
count_total++;
@@ -161,15 +168,17 @@ int md5_sha1_sum_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
*/
} else {
do {
hash_value = hash_file(*argv, hash_algo);
while (optind < argc) {
char *file_ptr = argv[optind++];
hash_value = hash_file(file_ptr, hash_algo);
if (hash_value == NULL) {
return_value = EXIT_FAILURE;
} else {
printf("%s %s\n", hash_value, *argv);
printf("%s %s\n", hash_value, file_ptr);
free(hash_value);
}
} while (*++argv);
}
}
return return_value;
}
+1
View File
@@ -19,6 +19,7 @@
/* Nov 28, 2006 Yoshinori Sato <ysato@users.sourceforge.jp>: Add SELinux Support.
*/
#include <getopt.h> /* struct option */
#include "libbb.h"
/* This is a NOFORK applet. Be very careful! */
+2 -2
View File
@@ -14,12 +14,12 @@
#include "libcoreutils/coreutils.h"
int mkfifo_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int mkfifo_main(int argc ATTRIBUTE_UNUSED, char **argv)
int mkfifo_main(int argc, char **argv)
{
mode_t mode;
int retval = EXIT_SUCCESS;
mode = getopt_mk_fifo_nod(argv);
mode = getopt_mk_fifo_nod(argc, argv);
argv += optind;
if (!*argv) {
+1 -1
View File
@@ -24,7 +24,7 @@ int mknod_main(int argc, char **argv)
dev_t dev;
const char *name;
mode = getopt_mk_fifo_nod(argv);
mode = getopt_mk_fifo_nod(argc, argv);
argv += optind;
argc -= optind;
+5 -5
View File
@@ -13,6 +13,10 @@
* Size reduction and improved error checking.
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <getopt.h> /* struct option */
#include "libbb.h"
#include "libcoreutils/coreutils.h"
@@ -71,8 +75,7 @@ int mv_main(int argc, char **argv)
}
DO_MOVE:
if (dest_exists
&& !(flags & OPT_FILEUTILS_FORCE)
if (dest_exists && !(flags & OPT_FILEUTILS_FORCE)
&& ((access(dest, W_OK) < 0 && isatty(0))
|| (flags & OPT_FILEUTILS_INTERACTIVE))
) {
@@ -109,9 +112,6 @@ int mv_main(int argc, char **argv)
goto RET_1;
}
}
/* FILEUTILS_RECUR also prevents nasties like
* "read from device and write contents to dst"
* instead of "create same device node" */
copy_flag = FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS;
#if ENABLE_SELINUX
copy_flag |= FILEUTILS_PRESERVE_SECURITY_CONTEXT;
+15 -33
View File
@@ -12,41 +12,21 @@
#include "libbb.h"
/* Compat info: nohup (GNU coreutils 6.8) does this:
# nohup true
nohup: ignoring input and appending output to `nohup.out'
# nohup true 1>/dev/null
nohup: ignoring input and redirecting stderr to stdout
# nohup true 2>zz
# cat zz
nohup: ignoring input and appending output to `nohup.out'
# nohup true 2>zz 1>/dev/null
# cat zz
nohup: ignoring input
# nohup true </dev/null 1>/dev/null
nohup: redirecting stderr to stdout
# nohup true </dev/null 2>zz 1>/dev/null
# cat zz
(nothing)
#
*/
int nohup_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int nohup_main(int argc, char **argv)
{
int nullfd;
const char *nohupout;
char *home;
char *home = NULL;
xfunc_error_retval = 127;
if (argc < 2) bb_show_usage();
nullfd = xopen(bb_dev_null, O_WRONLY|O_APPEND);
/* If stdin is a tty, detach from it. */
if (isatty(STDIN_FILENO)) {
/* bb_error_msg("ignoring input"); */
close(STDIN_FILENO);
xopen(bb_dev_null, O_RDONLY); /* will be fd 0 (STDIN_FILENO) */
}
if (isatty(STDIN_FILENO))
dup2(nullfd, STDIN_FILENO);
nohupout = "nohup.out";
/* Redirect stdout to nohup.out, either in "." or in "$HOME". */
@@ -57,22 +37,24 @@ int nohup_main(int argc, char **argv)
if (home) {
nohupout = concat_path_file(home, nohupout);
xopen3(nohupout, O_CREAT|O_WRONLY|O_APPEND, S_IRUSR|S_IWUSR);
} else {
xopen(bb_dev_null, O_RDONLY); /* will be fd 1 */
}
}
bb_error_msg("appending output to %s", nohupout);
}
} else dup2(nullfd, STDOUT_FILENO);
/* If we have a tty on stderr, redirect to stdout. */
/* If we have a tty on stderr, announce filename and redirect to stdout.
* Else redirect to /dev/null.
*/
if (isatty(STDERR_FILENO)) {
/* if (stdout_wasnt_a_tty)
bb_error_msg("redirecting stderr to stdout"); */
bb_error_msg("appending to %s", nohupout);
dup2(STDOUT_FILENO, STDERR_FILENO);
}
} else dup2(nullfd, STDERR_FILENO);
if (nullfd > 2)
close(nullfd);
signal(SIGHUP, SIG_IGN);
BB_EXECVP(argv[1], argv+1);
if (ENABLE_FEATURE_CLEAN_UP && home)
free((char*)nohupout);
bb_simple_perror_msg_and_die(argv[1]);
}
+1
View File
@@ -17,6 +17,7 @@
/* This one provides -t (busybox's own build script needs it) */
#include "od_bloaty.c"
#else
#include <getopt.h>
#include "dump.h"
+39 -26
View File
@@ -17,7 +17,7 @@
/* Written by Jim Meyering. */
/* Busyboxed by Denys Vlasenko
/* Busyboxed by Denis Vlasenko
Based on od.c from coreutils-5.2.1
Top bloat sources:
@@ -50,6 +50,7 @@ diff -u -a std bbox >bbox.diff || { echo Different!; sleep 1; }
*/
#include "libbb.h"
#include <getopt.h>
#define assert(a) ((void)0)
@@ -187,7 +188,7 @@ static off_t pseudo_offset;
a multiple of the least common multiple of the sizes associated with
the specified output types. It should be as large as possible, but
no larger than 16 -- unless specified with the -w option. */
static unsigned bytes_per_block = 32; /* have to use unsigned, not size_t */
static size_t bytes_per_block;
/* A NULL-terminated list of the file-arguments from the command line. */
static const char *const *file_list;
@@ -359,7 +360,7 @@ print_long_double(size_t n_bytes, const char *block, const char *fmt_string)
}
/* print_[named]_ascii are optimized for speed.
* Remember, someday you may want to pump gigabytes through this thing.
* Remember, someday you may want to pump gigabytes thru this thing.
* Saving a dozen of .text bytes here is counter-productive */
static void
@@ -508,10 +509,10 @@ check_and_close(void)
}
/* If S points to a single valid modern od format string, put
a description of that format in *TSPEC, return pointer to
character following the just-decoded format.
For example, if S were "d4afL", we will return a rtp to "afL"
and *TSPEC would be
a description of that format in *TSPEC, make *NEXT point at the
character following the just-decoded format (if *NEXT is non-NULL),
and return zero. For example, if S were "d4afL"
*NEXT would be set to "afL" and *TSPEC would be
{
fmt = SIGNED_DECIMAL;
size = INT or LONG; (whichever integral_type_size[4] resolves to)
@@ -521,8 +522,9 @@ check_and_close(void)
S_ORIG is solely for reporting errors. It should be the full format
string argument. */
static const char *
decode_one_format(const char *s_orig, const char *s, struct tspec *tspec)
static void
decode_one_format(const char *s_orig, const char *s, const char **next,
struct tspec *tspec)
{
enum size_spec size_spec;
unsigned size;
@@ -535,6 +537,7 @@ decode_one_format(const char *s_orig, const char *s, struct tspec *tspec)
unsigned field_width = 0;
int pos;
assert(tspec != NULL);
switch (*s) {
case 'd':
@@ -560,14 +563,13 @@ decode_one_format(const char *s_orig, const char *s, struct tspec *tspec)
s = end;
}
} else {
static const uint8_t CSIL_sizeof[4] = {
static const uint8_t CSIL_sizeof[] = {
sizeof(char),
sizeof(short),
sizeof(int),
sizeof(long),
};
size = CSIL_sizeof[p - CSIL];
s++; /* skip C/S/I/L */
}
#define ISPEC_TO_FORMAT(Spec, Min_format, Long_format, Max_format) \
@@ -715,12 +717,13 @@ decode_one_format(const char *s_orig, const char *s, struct tspec *tspec)
if (tspec->hexl_mode_trailer)
s++;
return s;
if (next != NULL)
*next = s;
}
/* Decode the modern od format string S. Append the decoded
representation to the global array SPEC, reallocating SPEC if
necessary. */
necessary. Return zero if S is valid, nonzero otherwise. */
static void
decode_format_string(const char *s)
@@ -731,7 +734,7 @@ decode_format_string(const char *s)
struct tspec tspec;
const char *next;
next = decode_one_format(s_orig, s, &tspec);
decode_one_format(s_orig, s, &next, &tspec);
assert(s != next);
s = next;
@@ -773,18 +776,18 @@ skip(off_t n_skip)
as large as the size of the current file, we can
decrement n_skip and go on to the next file. */
if (fstat(fileno(in_stream), &file_stats) == 0
&& S_ISREG(file_stats.st_mode) && file_stats.st_size > 0
&& S_ISREG(file_stats.st_mode) && file_stats.st_size >= 0
) {
if (file_stats.st_size < n_skip) {
n_skip -= file_stats.st_size;
/* take "check & close / open_next" route */
/* take check&close / open_next route */
} else {
if (fseeko(in_stream, n_skip, SEEK_CUR) != 0)
ioerror = 1;
return;
}
} else {
/* If it's not a regular file with positive size,
/* If it's not a regular file with nonnegative size,
position the file pointer by reading. */
char buf[1024];
size_t n_bytes_to_read = 1024;
@@ -997,7 +1000,9 @@ parse_old_offset(const char *s, off_t *offset)
spec, extend the input block with zero bytes until its length is a
multiple of all format spec sizes. Write the final block. Finally,
write on a line by itself the offset of the byte after the last byte
read. */
read. Accumulate return values from calls to read_block and
check_and_close, and if any was nonzero, return nonzero.
Otherwise, return zero. */
static void
dump(off_t current_offset, off_t end_offset)
@@ -1073,7 +1078,8 @@ dump(off_t current_offset, off_t end_offset)
and INPUT_FILENAME so they correspond to the next file in the list.
Then try to read a byte from the newly opened file. Repeat if
necessary until EOF is reached for the last file in FILE_LIST, then
set *C to EOF and return. Subsequent calls do likewise. */
set *C to EOF and return. Subsequent calls do likewise. The return
value is nonzero if any errors occured, zero otherwise. */
static void
read_char(int *c)
@@ -1106,7 +1112,8 @@ read_char(int *c)
A string constant is a run of at least 'string_min' ASCII
graphic (or formatting) characters terminated by a null.
Based on a function written by Richard Stallman for a
traditional version of od. */
traditional version of od. Return nonzero if an error
occurs. Otherwise, return zero. */
static void
dump_strings(off_t address, off_t end_offset)
@@ -1174,6 +1181,7 @@ dump_strings(off_t address, off_t end_offset)
int od_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int od_main(int argc, char **argv)
{
static char const *const default_file_list[] = { "-", NULL };
static const struct suffix_mult bkm[] = {
{ "b", 512 },
{ "k", 1024 },
@@ -1214,6 +1222,7 @@ int od_main(int argc, char **argv)
;
#endif
char *str_A, *str_N, *str_j, *str_S;
char *str_w = NULL;
llist_t *lst_t = NULL;
unsigned opt;
int l_c_m;
@@ -1234,7 +1243,7 @@ int od_main(int argc, char **argv)
/* flag_dump_strings = 0; - already is */
/* Parse command line */
opt_complementary = "w+:t::"; /* -w N, -t is a list */
opt_complementary = "t::"; // list
#if ENABLE_GETOPT_LONG
applet_long_options = od_longopts;
#endif
@@ -1243,7 +1252,7 @@ int od_main(int argc, char **argv)
// -S was -s and also had optional parameter
// but in coreutils 6.3 it was renamed and now has
// _mandatory_ parameter
&str_A, &str_N, &str_j, &lst_t, &str_S, &bytes_per_block);
&str_A, &str_N, &str_j, &lst_t, &str_S, &str_w);
argc -= optind;
argv += optind;
if (opt & OPT_A) {
@@ -1281,7 +1290,8 @@ int od_main(int argc, char **argv)
if (opt & OPT_o) decode_format_string("o2");
//if (opt & OPT_t)...
while (lst_t) {
decode_format_string(llist_pop(&lst_t));
decode_format_string(lst_t->data);
lst_t = lst_t->link;
}
if (opt & OPT_v) verbose = 1;
if (opt & OPT_x) decode_format_string("x2");
@@ -1378,7 +1388,7 @@ int od_main(int argc, char **argv)
/* If no files were listed on the command line,
set the global pointer FILE_LIST so that it
references the null-terminated list of one name: "-". */
file_list = bb_argv_dash;
file_list = default_file_list;
if (argc > 0) {
/* Set the global pointer FILE_LIST so that it
references the first file-argument on the command-line. */
@@ -1398,9 +1408,12 @@ int od_main(int argc, char **argv)
l_c_m = get_lcm();
if (opt & OPT_w) { /* -w: width */
bytes_per_block = 32;
if (str_w)
bytes_per_block = xatou(str_w);
if (!bytes_per_block || bytes_per_block % l_c_m != 0) {
bb_error_msg("warning: invalid width %u; using %d instead",
(unsigned)bytes_per_block, l_c_m);
bb_error_msg("warning: invalid width %zu; using %d instead",
bytes_per_block, l_c_m);
bytes_per_block = l_c_m;
}
} else {
+4 -3
View File
@@ -9,12 +9,13 @@
*/
#include "libbb.h"
extern char **environ;
int printenv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int printenv_main(int argc ATTRIBUTE_UNUSED, char **argv)
int printenv_main(int argc, char **argv)
{
/* no variables specified, show whole env */
if (!argv[1]) {
if (argc == 1) {
int e = 0;
while (environ[e])
puts(environ[e++]);
@@ -29,5 +30,5 @@ int printenv_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
}
fflush_stdout_and_exit(EXIT_SUCCESS);
fflush_stdout_and_exit(0);
}
+57 -64
View File
@@ -107,28 +107,28 @@ static void print_esc_string(char *str)
}
}
static void print_direc(char *format, unsigned fmt_length,
int field_width, int precision,
static void print_direc(char *start, size_t length, int field_width, int precision,
const char *argument)
{
char saved;
char *p; /* Null-terminated copy of % directive. */
saved = format[fmt_length];
format[fmt_length] = '\0';
p = xmalloc((unsigned) (length + 1));
strncpy(p, start, length);
p[length] = 0;
switch (format[fmt_length - 1]) {
switch (p[length - 1]) {
case 'd':
case 'i':
if (field_width < 0) {
if (precision < 0)
printf(format, my_xstrtol(argument));
printf(p, my_xstrtol(argument));
else
printf(format, precision, my_xstrtol(argument));
printf(p, precision, my_xstrtol(argument));
} else {
if (precision < 0)
printf(format, field_width, my_xstrtol(argument));
printf(p, field_width, my_xstrtol(argument));
else
printf(format, field_width, precision, my_xstrtol(argument));
printf(p, field_width, precision, my_xstrtol(argument));
}
break;
case 'o':
@@ -137,14 +137,14 @@ static void print_direc(char *format, unsigned fmt_length,
case 'X':
if (field_width < 0) {
if (precision < 0)
printf(format, my_xstrtoul(argument));
printf(p, my_xstrtoul(argument));
else
printf(format, precision, my_xstrtoul(argument));
printf(p, precision, my_xstrtoul(argument));
} else {
if (precision < 0)
printf(format, field_width, my_xstrtoul(argument));
printf(p, field_width, my_xstrtoul(argument));
else
printf(format, field_width, precision, my_xstrtoul(argument));
printf(p, field_width, precision, my_xstrtoul(argument));
}
break;
case 'f':
@@ -154,48 +154,51 @@ static void print_direc(char *format, unsigned fmt_length,
case 'G':
if (field_width < 0) {
if (precision < 0)
printf(format, my_xstrtod(argument));
printf(p, my_xstrtod(argument));
else
printf(format, precision, my_xstrtod(argument));
printf(p, precision, my_xstrtod(argument));
} else {
if (precision < 0)
printf(format, field_width, my_xstrtod(argument));
printf(p, field_width, my_xstrtod(argument));
else
printf(format, field_width, precision, my_xstrtod(argument));
printf(p, field_width, precision, my_xstrtod(argument));
}
break;
case 'c':
printf(format, *argument);
printf(p, *argument);
break;
case 's':
if (field_width < 0) {
if (precision < 0)
printf(format, argument);
printf(p, argument);
else
printf(format, precision, argument);
printf(p, precision, argument);
} else {
if (precision < 0)
printf(format, field_width, argument);
printf(p, field_width, argument);
else
printf(format, field_width, precision, argument);
printf(p, field_width, precision, argument);
}
break;
}
format[fmt_length] = saved;
free(p);
}
/* Print the text in FORMAT, using ARGV for arguments to any '%' directives.
Return advanced ARGV. */
static char **print_formatted(char *f, char **argv)
/* Print the text in FORMAT, using ARGV (with ARGC elements) for
arguments to any '%' directives.
Return the number of elements of ARGV used. */
static int print_formatted(char *format, int argc, char **argv)
{
int save_argc = argc; /* Preserve original value. */
char *f; /* Pointer into 'format'. */
char *direc_start; /* Start of % directive. */
unsigned direc_length; /* Length of % directive. */
size_t direc_length; /* Length of % directive. */
int field_width; /* Arg to first '*', or -1 if none. */
int precision; /* Arg to second '*', or -1 if none. */
char **saved_argv = argv;
for (; *f; ++f) {
for (f = format; *f; ++f) {
switch (*f) {
case '%':
direc_start = f++;
@@ -206,9 +209,10 @@ static char **print_formatted(char *f, char **argv)
break;
}
if (*f == 'b') {
if (*argv) {
if (argc > 0) {
print_esc_string(*argv);
++argv;
--argc;
}
break;
}
@@ -219,9 +223,10 @@ static char **print_formatted(char *f, char **argv)
if (*f == '*') {
++f;
++direc_length;
if (*argv) {
if (argc > 0) {
field_width = my_xstrtoul(*argv);
++argv;
--argc;
} else
field_width = 0;
} else {
@@ -236,9 +241,10 @@ static char **print_formatted(char *f, char **argv)
if (*f == '*') {
++f;
++direc_length;
if (*argv) {
if (argc > 0) {
precision = my_xstrtoul(*argv);
++argv;
--argc;
} else
precision = 0;
} else
@@ -256,18 +262,18 @@ static char **print_formatted(char *f, char **argv)
fprintf(stderr, "%%%c: invalid directive", *f);
*/
++direc_length;
if (*argv) {
if (argc > 0) {
print_direc(direc_start, direc_length, field_width,
precision, *argv);
++argv;
--argc;
} else
print_direc(direc_start, direc_length, field_width,
precision, "");
break;
case '\\':
if (*++f == 'c') {
return saved_argv; /* causes main() to exit */
}
if (*++f == 'c')
exit(0);
bb_putchar(bb_process_escape_sequence((const char **)&f));
f--;
break;
@@ -276,45 +282,32 @@ static char **print_formatted(char *f, char **argv)
}
}
return argv;
return save_argc - argc;
}
int printf_main(int argc ATTRIBUTE_UNUSED, char **argv)
int printf_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int printf_main(int argc, char **argv)
{
char *format;
char **argv2;
int args_used;
/* We must check that stdout is not closed.
* The reason for this is highly non-obvious. printf_main is used from shell.
* Shell must correctly handle 'printf "%s" foo'
* if stdout is closed. With stdio, output gets shoveled into
* stdout buffer, and even fflush cannot clear it out. It seems that
* even if libc receives EBADF on write attempts, it feels determined
* to output data no matter what. So it will try later,
* and possibly will clobber future output. Not good. */
if (dup2(1, 1) != 1)
return -1;
/* bash builtin errors out on "printf '-%s-\n' foo",
* coreutils-6.9 works. Both work with "printf -- '-%s-\n' foo".
* We will mimic coreutils. */
if (argv[1] && argv[1][0] == '-' && argv[1][1] == '-' && argv[1][2] == '\0')
argv++;
if (!argv[1])
if (argc <= 1 || argv[1][0] == '-') {
bb_show_usage();
}
format = argv[1];
argv2 = argv + 2;
argc -= 2;
argv += 2;
do {
argv = argv2;
argv2 = print_formatted(format, argv);
} while (argv2 != argv && *argv2);
args_used = print_formatted(format, argc, argv);
argc -= args_used;
argv += args_used;
} while (args_used > 0 && argc > 0);
/* coreutils compat (bash doesn't do this):
if (*argv)
/* if (argc > 0)
fprintf(stderr, "excess args ignored");
*/
*/
return EXIT_SUCCESS;
}
+1 -1
View File
@@ -12,7 +12,7 @@
/* This is a NOFORK applet. Be very careful! */
int pwd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int pwd_main(int argc ATTRIBUTE_UNUSED, char **argv ATTRIBUTE_UNUSED)
int pwd_main(int argc, char **argv)
{
char *buf;
+2 -1
View File
@@ -7,10 +7,11 @@
* Licensed under GPL v2 or later, see file LICENSE in this tarball for details.
*/
#include <getopt.h>
#include "libbb.h"
int readlink_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int readlink_main(int argc ATTRIBUTE_UNUSED, char **argv)
int readlink_main(int argc, char **argv)
{
char *buf;
char *fname;
+4 -3
View File
@@ -13,7 +13,7 @@
#include "libbb.h"
int realpath_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int realpath_main(int argc ATTRIBUTE_UNUSED, char **argv)
int realpath_main(int argc, char **argv)
{
int retval = EXIT_SUCCESS;
@@ -25,18 +25,19 @@ int realpath_main(int argc ATTRIBUTE_UNUSED, char **argv)
# define resolved_path_MUST_FREE 0
#endif
if (!*++argv) {
if (--argc == 0) {
bb_show_usage();
}
do {
argv++;
if (realpath(*argv, resolved_path) != NULL) {
puts(resolved_path);
} else {
retval = EXIT_FAILURE;
bb_simple_perror_msg(*argv);
}
} while (*++argv);
} while (--argc);
#if ENABLE_FEATURE_CLEAN_UP && resolved_path_MUST_FREE
RELEASE_CONFIG_BUFFER(resolved_path);
+1 -1
View File
@@ -20,7 +20,7 @@
/* This is a NOFORK applet. Be very careful! */
int rm_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int rm_main(int argc ATTRIBUTE_UNUSED, char **argv)
int rm_main(int argc, char **argv)
{
int status = 0;
int flags = 0;
+13 -22
View File
@@ -10,30 +10,20 @@
/* BB_AUDIT SUSv3 compliant */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/rmdir.html */
#include <libgen.h>
#include "libbb.h"
/* This is a NOFORK applet. Be very careful! */
#define PARENTS 0x01
#define IGNORE_NON_EMPTY 0x02
int rmdir_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int rmdir_main(int argc ATTRIBUTE_UNUSED, char **argv)
int rmdir_main(int argc, char **argv)
{
int status = EXIT_SUCCESS;
int flags;
int do_dot;
char *path;
#if ENABLE_FEATURE_RMDIR_LONG_OPTIONS
static const char rmdir_longopts[] ALIGN1 =
"parents\0" No_argument "p"
/* Debian etch: many packages fail to be purged or installed
* because they desperately want this option: */
"ignore-fail-on-non-empty\0" No_argument "\xff"
;
applet_long_options = rmdir_longopts;
#endif
flags = getopt32(argv, "p");
argv += optind;
@@ -44,26 +34,27 @@ int rmdir_main(int argc ATTRIBUTE_UNUSED, char **argv)
do {
path = *argv;
/* Record if the first char was a '.' so we can use dirname later. */
do_dot = (*path == '.');
while (1) {
if (rmdir(path) < 0) {
#if ENABLE_FEATURE_RMDIR_LONG_OPTIONS
if ((flags & IGNORE_NON_EMPTY) && errno == ENOTEMPTY)
break;
#endif
bb_perror_msg("'%s'", path); /* Match gnu rmdir msg. */
status = EXIT_FAILURE;
} else if (flags & PARENTS) {
/* Note: path was not "" since rmdir succeeded. */
} else if (flags) {
/* Note: path was not empty or null since rmdir succeeded. */
path = dirname(path);
/* Path is now just the parent component. Dirname
* returns "." if there are no parents.
/* Path is now just the parent component. Note that dirname
* returns "." if there are no parents. We must distinguish
* this from the case of the original path starting with '.'.
*/
if (NOT_LONE_CHAR(path, '.')) {
if (do_dot || (*path != '.') || path[1]) {
continue;
}
}
break;
}
} while (*++argv);
return status;
+11 -6
View File
@@ -34,16 +34,17 @@ static const struct suffix_mult sfx[] = {
#endif
int sleep_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sleep_main(int argc ATTRIBUTE_UNUSED, char **argv)
int sleep_main(int argc, char **argv)
{
unsigned duration;
++argv;
if (!*argv)
bb_show_usage();
#if ENABLE_FEATURE_FANCY_SLEEP
if (argc < 2) {
bb_show_usage();
}
++argv;
duration = 0;
do {
duration += xatoul_range_sfx(*argv, 0, UINT_MAX-duration, sfx);
@@ -51,7 +52,11 @@ int sleep_main(int argc ATTRIBUTE_UNUSED, char **argv)
#else /* FEATURE_FANCY_SLEEP */
duration = xatou(*argv);
if (argc != 2) {
bb_show_usage();
}
duration = xatou(argv[1]);
#endif /* FEATURE_FANCY_SLEEP */
+15 -19
View File
@@ -32,7 +32,7 @@ enum {
FLAG_u = 8, /* Unique */
FLAG_c = 0x10, /* Check: no output, exit(!ordered) */
FLAG_s = 0x20, /* Stable sort, no ascii fallback at end */
FLAG_z = 0x40, /* Input and output is NUL terminated, not \n */
FLAG_z = 0x40, /* Input is null terminated, not \n */
/* These can be applied to search keys, the previous four can't */
FLAG_b = 0x80, /* Ignore leading blanks */
FLAG_r = 0x100, /* Reverse */
@@ -59,8 +59,7 @@ static struct sort_key {
static char *get_key(char *str, struct sort_key *key, int flags)
{
int start = 0, end = 0, len, j;
unsigned i;
int start = 0, end = 0, len, i, j;
/* Special case whole string, so we don't have to make a copy */
if (key->range[0] == 1 && !key->range[1] && !key->range[2] && !key->range[3]
@@ -151,9 +150,9 @@ static struct sort_key *add_key(void)
#define GET_LINE(fp) \
((option_mask32 & FLAG_z) \
? bb_get_chunk_from_file(fp, NULL) \
: xmalloc_fgetline(fp))
: xmalloc_getline(fp))
#else
#define GET_LINE(fp) xmalloc_fgetline(fp)
#define GET_LINE(fp) xmalloc_getline(fp)
#endif
/* Iterate through keys list and perform comparisons */
@@ -276,7 +275,7 @@ static unsigned str2u(char **str)
#endif
int sort_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sort_main(int argc ATTRIBUTE_UNUSED, char **argv)
int sort_main(int argc, char **argv)
{
FILE *fp, *outfile = stdout;
char *line, **lines = NULL;
@@ -314,7 +313,7 @@ int sort_main(int argc ATTRIBUTE_UNUSED, char **argv)
0
};
struct sort_key *key = add_key();
char *str_k = llist_pop(&lst_k);
char *str_k = lst_k->data;
const char *temp2;
i = 0; /* i==0 before comma, 1 after (-k3,6) */
@@ -344,19 +343,18 @@ int sort_main(int argc ATTRIBUTE_UNUSED, char **argv)
str_k++;
}
}
/* leaking lst_k... */
lst_k = lst_k->link;
}
#endif
/* global b strips leading and trailing spaces */
if (option_mask32 & FLAG_b) option_mask32 |= FLAG_bb;
/* Open input files and read data */
argv += optind;
if (!*argv)
*--argv = (char*)"-";
do {
/* coreutils 6.9 compat: abort on first open error,
* do not continue to next file: */
fp = xfopen_stdin(*argv);
for (i = argv[optind] ? optind : optind-1; argv[i]; i++) {
fp = stdin;
if (i >= optind && NOT_LONE_DASH(argv[i]))
fp = xfopen(argv[i], "r");
for (;;) {
line = GET_LINE(fp);
if (!line) break;
@@ -364,9 +362,8 @@ int sort_main(int argc ATTRIBUTE_UNUSED, char **argv)
lines = xrealloc(lines, sizeof(char *) * (linecount + 64));
lines[linecount++] = line;
}
fclose_if_not_stdin(fp);
} while (*++argv);
fclose(fp);
}
#if ENABLE_FEATURE_SORT_BIG
/* if no key, perform alphabetic sort */
if (!key_list)
@@ -399,9 +396,8 @@ int sort_main(int argc ATTRIBUTE_UNUSED, char **argv)
if (linecount) linecount = flag+1;
}
/* Print it */
flag = (option_mask32 & FLAG_z) ? '\0' : '\n';
for (i = 0; i < linecount; i++)
fprintf(outfile, "%s%c", lines[i], flag);
fprintf(outfile, "%s\n", lines[i]);
fflush_stdout_and_exit(EXIT_SUCCESS);
}
+10 -8
View File
@@ -56,7 +56,7 @@ enum { READ_BUFFER_SIZE = COMMON_BUFSIZE - 1 };
#define SPLIT_OPT_a (1<<2)
int split_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int split_main(int argc ATTRIBUTE_UNUSED, char **argv)
int split_main(int argc, char **argv)
{
unsigned suffix_len = 2;
char *pfx;
@@ -68,13 +68,15 @@ int split_main(int argc ATTRIBUTE_UNUSED, char **argv)
ssize_t bytes_read, to_write;
char *src;
opt_complementary = "?2:a+"; /* max 2 args; -a N */
opt = getopt32(argv, "l:b:a:", &count_p, &count_p, &suffix_len);
opt_complementary = "?2";
opt = getopt32(argv, "l:b:a:", &count_p, &count_p, &sfx);
if (opt & SPLIT_OPT_l)
cnt = XATOOFF(count_p);
if (opt & SPLIT_OPT_b) // FIXME: also needs XATOOFF
cnt = xatoull_sfx(count_p, split_suffices);
cnt = xatoul(count_p);
if (opt & SPLIT_OPT_b)
cnt = xatoul_sfx(count_p, split_suffices);
if (opt & SPLIT_OPT_a)
suffix_len = xatou(sfx);
sfx = "x";
argv += optind;
@@ -98,7 +100,7 @@ int split_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
while (1) {
bytes_read = safe_read(STDIN_FILENO, read_buffer, READ_BUFFER_SIZE);
bytes_read = safe_read(0, read_buffer, READ_BUFFER_SIZE);
if (!bytes_read)
break;
if (bytes_read < 0)
@@ -130,7 +132,7 @@ int split_main(int argc ATTRIBUTE_UNUSED, char **argv)
}
}
xwrite(STDOUT_FILENO, src, to_write);
xwrite(1, src, to_write);
bytes_read -= to_write;
src += to_write;
} while (bytes_read);
+3 -18
View File
@@ -21,12 +21,6 @@
#define OPT_DEREFERENCE (1 << 2)
#define OPT_SELINUX (1 << 3)
#if ENABLE_FEATURE_STAT_FORMAT
typedef bool (*statfunc_ptr)(const char *, const char *);
#else
typedef bool (*statfunc_ptr)(const char *);
#endif
static const char *file_type(const struct stat *st)
{
/* See POSIX 1003.1-2001 XCU Table 4-8 lines 17093-17107
@@ -344,14 +338,8 @@ static void print_it(const char *masterformat, const char *filename,
#endif
/* Stat the file system and print what we find. */
#if !ENABLE_FEATURE_STAT_FORMAT
#define do_statfs(filename, format) do_statfs(filename)
#endif
static bool do_statfs(const char *filename, const char *format)
{
#if !ENABLE_FEATURE_STAT_FORMAT
const char *format;
#endif
struct statfs statfsbuf;
#if ENABLE_SELINUX
security_context_t scontext = NULL;
@@ -459,9 +447,6 @@ static bool do_statfs(const char *filename, const char *format)
}
/* stat the file and print what we find */
#if !ENABLE_FEATURE_STAT_FORMAT
#define do_stat(filename, format) do_stat(filename)
#endif
static bool do_stat(const char *filename, const char *format)
{
struct stat statbuf;
@@ -627,10 +612,10 @@ static bool do_stat(const char *filename, const char *format)
int stat_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int stat_main(int argc, char **argv)
{
USE_FEATURE_STAT_FORMAT(char *format = NULL;)
char *format = NULL;
int i;
int ok = 1;
statfunc_ptr statfunc = do_stat;
bool (*statfunc)(const char *, const char *) = do_stat;
getopt32(argv, "ftL"
USE_SELINUX("Z")
@@ -648,7 +633,7 @@ int stat_main(int argc, char **argv)
}
#endif /* ENABLE_SELINUX */
for (i = optind; i < argc; ++i)
ok &= statfunc(argv[i] USE_FEATURE_STAT_FORMAT(, format));
ok &= statfunc(argv[i], format);
return (ok ? EXIT_SUCCESS : EXIT_FAILURE);
}
+6 -5
View File
@@ -627,10 +627,11 @@ struct globals {
char buf[10];
};
#define G (*(struct globals*)&bb_common_bufsiz1)
#define INIT_G() do { \
G.device_name = bb_msg_standard_input; \
G.max_col = 80; \
} while (0)
#define INIT_G() \
do { \
G.device_name = bb_msg_standard_input; \
G.max_col = 80; \
} while (0)
/* Return a string that is the printable representation of character CH */
@@ -709,7 +710,7 @@ static void wrapf(const char *message, ...)
{
char buf[128];
va_list args;
unsigned buflen;
int buflen;
va_start(args, message);
buflen = vsnprintf(buf, sizeof(buf), message, args);
+14 -13
View File
@@ -21,17 +21,20 @@ enum { SUM_BSD, PRINT_NAME, SUM_SYSV };
The checksum varies depending on sizeof (int). */
/* SYSV: calculate and print the checksum and the size in 512-byte blocks */
/* Return 1 if successful. */
static unsigned sum_file(const char *file, unsigned type)
static unsigned sum_file(const char *file, const unsigned type)
{
#define buf bb_common_bufsiz1
unsigned long long total_bytes = 0;
int fd, r;
int fd = 0, r;
/* The sum of all the input bytes, modulo (UINT_MAX + 1). */
unsigned s = 0;
fd = open_or_warn_stdin(file);
if (fd == -1)
return 0;
if (NOT_LONE_DASH(file)) {
fd = open(file, O_RDONLY);
if (fd == -1)
goto ret_bad;
}
while (1) {
size_t bytes_read = safe_read(fd, buf, BUFSIZ);
@@ -41,6 +44,7 @@ static unsigned sum_file(const char *file, unsigned type)
if (!bytes_read && !r)
/* no error */
break;
ret_bad:
bb_perror_msg(file);
return 0;
}
@@ -71,29 +75,26 @@ static unsigned sum_file(const char *file, unsigned type)
}
int sum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int sum_main(int argc ATTRIBUTE_UNUSED, char **argv)
int sum_main(int argc, char **argv)
{
unsigned n;
unsigned type = SUM_BSD;
n = getopt32(argv, "sr");
argv += optind;
if (n & 1) type = SUM_SYSV;
/* give the bsd priority over sysv func */
if (n & 2) type = SUM_BSD;
if (!argv[0]) {
if (argc == optind) {
/* Do not print the name */
n = sum_file("-", type);
} else {
/* Need to print the name if either
- more than one file given
- doing sysv */
type += (argv[1] || type == SUM_SYSV);
n = 1;
do {
n &= sum_file(*argv, type);
} while (*++argv);
type += argc - 1 > optind || type == SUM_SYSV;
for (n = 1; optind < argc; optind++)
n &= sum_file(argv[optind], type);
}
return !n;
}
Loaded 100 of 661 files, more files were not shown because too many files have changed in this diff. Show more