Compare commits

..
12 Commits
Author SHA1 Message Date
Denys Vlasenko db726ae0c6 Bump version to 1.33.2
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-11-24 14:27:03 +01:00
Denys Vlasenko bb61205290 hush: fix handling of "cmd && &"
function                                             old     new   delta
done_pipe                                            213     231     +18

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 83a4967e50)
2021-11-23 05:31:30 +01:00
Denys Vlasenko 56a335378a hush: fix handling of \^C and "^C"
function                                             old     new   delta
parse_stream                                        2238    2252     +14
encode_string                                        243     256     +13
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 2/0 up/down: 27/0)               Total: 27 bytes

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 1b7a9b68d0)
2021-11-23 05:31:30 +01:00
Denys Vlasenko 5b939a6d29 ash: parser: Fix VSLENGTH parsing with trailing garbage
Let's adopt Herbert Xu's patch, not waiting for it to reach dash git:
hush already has a similar fix.

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 53a7a9cd8c)
2021-11-23 05:31:30 +01:00
Denys Vlasenko d326be2850 unlzma: fix a case where we could read before beginning of buffer
Testcase:

  21 01 01 00 00 00 00 00 e7 01 01 01 ef 00 df b6
  00 17 02 10 11 0f ff 00 16 00 00

Unfortunately, the bug is not reliably causing a segfault,
the behavior depends on what's in memory before the buffer.

function                                             old     new   delta
unpack_lzma_stream                                  2762    2768      +6

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
(cherry picked from commit 04f052c56d)
2021-11-23 05:31:30 +01:00
Denys Vlasenko bcc5b0e6ca Bump version to 1.33.1
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-05-03 20:07:13 +02:00
Denys Vlasenko 611bbfc148 ash: fix ${unset_var/pattern/repl}
function                                             old     new   delta
subevalvar                                          1349    1353      +4

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-05-03 20:06:49 +02:00
Samuel Sapalski 23dd1c75b7 decompress_gunzip: Fix DoS if gzip is corrupt
On certain corrupt gzip files, huft_build will set the error bit on
the result pointer. If afterwards abort_unzip is called huft_free
might run into a segmentation fault or an invalid pointer to
free(p).

In order to mitigate this, we check in huft_free if the error bit
is set and clear it before the linked list is freed.

Signed-off-by: Samuel Sapalski <samuel.sapalski@nokia.com>
Signed-off-by: Peter Kaestle <peter.kaestle@nokia.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-05-03 14:50:09 +02:00
Denys Vlasenko 89358a7131 traceroute: fix option parsing
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
Bernd Kuhls 39b71881b8 update_passwd: fix context variable
Commit
https://git.busybox.net/busybox/commit/libbb/update_passwd.c?id=2496616b0a8d1c80cd1416b73a4847b59b9f969a

changed the variable used from context to seuser but forgot this
change resulting in build errors detected by buildroot autobuilders:

http://autobuild.buildroot.net/results/b89/b89b7d0f0601bb706e76cea31cf4e43326e5540c//build-end.log

libbb/update_passwd.c:51:11: error: 'context' undeclared (first use in
 this function); did you mean 'ucontext'?
   freecon(context);

Signed-off-by: Bernd Kuhls <bernd.kuhls@t-online.de>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
Denys Vlasenko 67cc582d42 ash: make a strdup copy of $HISTFILE for line editing
Otherwise if $HISTFILE is unset or reassigned, bad things can happen.

function                                             old     new   delta
ash_main                                            1210    1218      +8

Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
Maxim Storchak ee1e0987e4 httpd: fix offset for sendfile
If the Range: header is not present it the request,
the offset passed to sendfile is wrong,
and httpd falls back to the read-write loop.

function                                             old     new   delta
send_file_and_exit                                   857     865      +8
handle_incoming_and_exit                            2239    2230      -9
------------------------------------------------------------------------------
(add/remove: 0/0 grow/shrink: 1/1 up/down: 8/-9)               Total: -1 bytes

Signed-off-by: Maxim Storchak <m.storchak@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
2021-03-09 00:28:26 +01:00
261 changed files with 4294 additions and 7611 deletions

No files matched your search

+2 -3
View File
@@ -1,6 +1,6 @@
VERSION = 1
PATCHLEVEL = 34
SUBLEVEL = 1
PATCHLEVEL = 33
SUBLEVEL = 2
EXTRAVERSION =
NAME = Unnamed
@@ -612,7 +612,6 @@ quiet_cmd_busybox__ ?= LINK $@
"$(core-y)" \
"$(libs-y)" \
"$(LDLIBS)" \
"$(CONFIG_EXTRA_LDLIBS)" \
&& $(srctree)/scripts/generate_BUFSIZ.sh --post include/common_bufsiz.h
# Generate System.map
+10 -10
View File
@@ -145,21 +145,18 @@ CFLAGS += --sysroot=$(CONFIG_SYSROOT)
export SYSROOT=$(CONFIG_SYSROOT)
endif
# libm may be needed for dc, awk, ntpd
LDLIBS += m
# Android has no separate crypt library
# gcc-4.2.1 fails if we try to feed C source on stdin:
# echo 'int main(void){return 0;}' | $(CC) $(CFLAGS) -lcrypt -o /dev/null -xc -
# fall back to using a temp file:
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) -lcrypt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
RT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >bb_libtest.c; $(CC) $(CFLAGS) -lrt -o /dev/null bb_libtest.c >/dev/null 2>&1 && echo "y"; rm bb_libtest.c)
CRYPT_AVAILABLE := $(shell echo 'int main(void){return 0;}' >crypttest.c; $(CC) $(CFLAGS) -lcrypt -o /dev/null crypttest.c >/dev/null 2>&1 && echo "y"; rm crypttest.c)
ifeq ($(CRYPT_AVAILABLE),y)
LDLIBS += crypt
LDLIBS += m rt crypt
else
LDLIBS += m rt
endif
# libm may be needed for dc, awk, ntpd
# librt may be needed for clock_gettime()
ifeq ($(RT_AVAILABLE),y)
LDLIBS += rt
endif
# libpam may use libpthread, libdl and/or libaudit.
# On some platforms that requires an explicit -lpthread, -ldl, -laudit.
@@ -184,10 +181,8 @@ LDLIBS += $(if $(SELINUX_LIBS),$(SELINUX_LIBS:-l%=%),$(SELINUX_PC_MODULES:lib%=%
endif
ifeq ($(CONFIG_FEATURE_NSLOOKUP_BIG),y)
ifneq (,$(findstring linux,$(shell $(CC) $(CFLAGS) -dumpmachine)))
LDLIBS += resolv
endif
endif
ifeq ($(CONFIG_EFENCE),y)
LDLIBS += efence
@@ -212,6 +207,11 @@ LDFLAGS += $(strip $(subst ",,$(CONFIG_EXTRA_LDFLAGS)))
#"))
endif
ifneq ($(CONFIG_EXTRA_LDLIBS),)
LDLIBS += $(strip $(subst ",,$(CONFIG_EXTRA_LDLIBS)))
#"))
endif
# Busybox is a stack-fatty so make sure we increase default size
# TODO: use "make stksizes" to find & fix big stack users
# (we stole scripts/checkstack.pl from the kernel... thanks guys!)
+1 -1
View File
@@ -56,7 +56,7 @@ static int cmp_name(const void *a, const void *b)
static int str_isalnum_(const char *s)
{
while (*s) {
if (!isalnum((unsigned char)*s) && *s != '_')
if (!isalnum(*s) && *s != '_')
return 0;
s++;
}
+1 -1
View File
@@ -19,6 +19,6 @@ int main(int argc, char **argv)
void bb_show_usage(void)
{
fputs_stdout(APPLET_full_usage "\n");
fputs(APPLET_full_usage "\n", stdout);
exit(EXIT_FAILURE);
}
+1 -1
View File
@@ -71,7 +71,7 @@ int main(void)
} else {
printf(", ");
}
printf("%s", usage_array[i].aname);
printf(usage_array[i].aname);
col += len2;
}
printf("\n\n");
+3 -7
View File
@@ -284,7 +284,7 @@ int uncompress_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define gunzip_example_usage
//usage: "$ ls -la /tmp/BusyBox*\n"
@@ -407,8 +407,6 @@ int gunzip_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define bzcat_trivial_usage
//usage: "[FILE]..."
//usage:#define bzcat_full_usage "\n\n"
@@ -467,7 +465,6 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define lzma_trivial_usage
//usage: "-d [-cfk] [FILE]..."
@@ -477,7 +474,6 @@ int bunzip2_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage:
//usage:#define lzcat_trivial_usage
//usage: "[FILE]..."
@@ -540,7 +536,7 @@ int unlzma_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define xz_trivial_usage
//usage: "-d [-cfk] [FILE]..."
@@ -550,7 +546,7 @@ int unlzma_main(int argc UNUSED_PARAM, char **argv)
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: "\n -t Test integrity"
//usage: "\n -t Test file integrity"
//usage:
//usage:#define xzcat_trivial_usage
//usage: "[FILE]..."
+1 -3
View File
@@ -56,13 +56,11 @@
//usage: "\n -1..9 Compression level"
//usage: IF_FEATURE_BZIP2_DECOMPRESS(
//usage: "\n -d Decompress"
//usage: "\n -t Test file integrity"
//usage: )
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: IF_FEATURE_BZIP2_DECOMPRESS(
//usage: "\n -t Test integrity"
//usage: )
#include "libbb.h"
#include "bb_archive.h"
+1 -7
View File
@@ -418,8 +418,7 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
if (argv[0] == NULL)
bb_show_usage();
if (opt & OPT_CREATE_LEADING_DIR)
/* GNU cpio 2.13: "cpio -d -p a/b/c" works */
bb_make_directory(argv[0], -1, FILEUTILS_RECUR);
mkdir(argv[0], 0777);
/* Crude existence check:
* close(xopen(argv[0], O_RDONLY | O_DIRECTORY));
* We can also xopen, fstat, IS_DIR, later fchdir.
@@ -429,11 +428,6 @@ int cpio_main(int argc UNUSED_PARAM, char **argv)
* a diffrerent problem earlier.
* This is good enough for now.
*/
//FIXME: GNU cpio -d -p DIR does not immediately create DIR -
//it just prepends "DIR/" to the names of files to be created.
//The first file (fails to) be copied, and then the -d logic
//triggers and creates all necessary directories.
//IOW: bare "cpio -d -p DIR" + ^C shouldn't create anything.
#if !BB_MMU
pp.rd = 3;
pp.wr = 4;
+1 -3
View File
@@ -77,13 +77,11 @@ aa: 85.1% -- replaced with aa.gz
//usage: )
//usage: IF_FEATURE_GZIP_DECOMPRESS(
//usage: "\n -d Decompress"
//usage: "\n -t Test file integrity"
//usage: )
//usage: "\n -c Write to stdout"
//usage: "\n -f Force"
//usage: "\n -k Keep input files"
//usage: IF_FEATURE_GZIP_DECOMPRESS(
//usage: "\n -t Test integrity"
//usage: )
//usage:
//usage:#define gzip_example_usage
//usage: "$ ls -la /tmp/busybox*\n"
-4
View File
@@ -159,10 +159,6 @@ void FAST_FUNC data_extract_all(archive_handle_t *archive_handle)
break;
}
case S_IFDIR:
//TODO: this causes problems if tarball contains a r-xr-xr-x directory:
// we create this directory, and then fail to create files inside it
// (if tar xf isn't run as root).
// GNU tar works around this by chmod-ing directories *after* all files are extracted.
res = mkdir(dst_name, file_header->mode);
if ((res != 0)
&& (errno != EISDIR) /* btw, Linux doesn't return this */
+3 -2
View File
@@ -230,8 +230,9 @@ static void huft_free(huft_t *p)
* If 'p' has the error bit set we have to clear it, otherwise we might run
* into a segmentation fault or an invalid pointer to free(p)
*/
//if (BAD_HUFT(p)) // commented out, since bit clearing has effect only if condition is true
p = (huft_t*)((uintptr_t)p & ~(uintptr_t)ERR_RET);
if (BAD_HUFT(p)) {
p = (huft_t*)((uintptr_t)(p) ^ (uintptr_t)(ERR_RET));
}
/* Go through linked list, freeing from the malloced (t[-1]) address. */
while (p) {
+1 -2
View File
@@ -20,7 +20,7 @@ typedef struct hardlinks_t {
char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
{
file_header_t *file_header = archive_handle->file_header;
char cpio_header[111];
char cpio_header[110];
int namesize;
int major, minor, nlink, mode, inode;
unsigned size, uid, gid, mtime;
@@ -43,7 +43,6 @@ char FAST_FUNC get_header_cpio(archive_handle_t *archive_handle)
bb_simple_error_msg_and_die("unsupported cpio format, use newc or crc");
}
cpio_header[110] = '\0'; /* sscanf may call strlen which may break without this */
if (sscanf(cpio_header + 6,
"%8x" "%8x" "%8x" "%8x"
"%8x" "%8x" "%8x" /*maj,min:*/ "%*16c"
-1
View File
@@ -86,7 +86,6 @@
//usage: "\n -f Force"
//usage: "\n -U Delete input files"
///////: "\n -k Keep input files" (default, so why bother documenting?)
//usage: "\n -t Test integrity"
//usage: "\n -v Verbose"
//usage: "\n -F Don't verify checksum"
+12 -13
View File
@@ -507,9 +507,6 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
if (header_name[0] == '\0')
return TRUE;
if (exclude_file(tbInfo->excludeList, header_name))
return SKIP; /* "do not recurse on this directory", no error message printed */
/* It is against the rules to archive a socket */
if (S_ISSOCK(statbuf->st_mode)) {
bb_error_msg("%s: socket ignored", fileName);
@@ -543,6 +540,9 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
return TRUE;
}
if (exclude_file(tbInfo->excludeList, header_name))
return SKIP;
# if !ENABLE_FEATURE_TAR_GNU_EXTENSIONS
if (strlen(header_name) >= NAME_SIZE) {
bb_simple_error_msg("names longer than "NAME_SIZE_STR" chars not supported");
@@ -555,13 +555,13 @@ static int FAST_FUNC writeFileToTarball(struct recursive_state *state,
/* open the file we want to archive, and make sure all is well */
inputFileFd = open_or_warn(fileName, O_RDONLY);
if (inputFileFd < 0) {
return FALSE; /* make recursive_action() return FALSE */
return FALSE;
}
}
/* Add an entry to the tarball */
if (writeTarHeader(tbInfo, header_name, fileName, statbuf) == FALSE) {
return FALSE; /* make recursive_action() return FALSE */
return FALSE;
}
/* If it was a regular file, write out the body */
@@ -775,7 +775,7 @@ static llist_t *append_file_list_to_list(llist_t *list)
//usage: IF_FEATURE_TAR_NOPRESERVE_TIME("m")
//usage: "vokO] "
//usage: "[-f TARFILE] [-C DIR] "
//usage: IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[LONGOPT]... "))
//usage: IF_FEATURE_TAR_FROM("[-T FILE] [-X FILE] "IF_FEATURE_TAR_LONG_OPTIONS("[OPTION]... "))
//usage: "[FILE]..."
//usage:#define tar_full_usage "\n\n"
//usage: IF_FEATURE_TAR_CREATE("Create, extract, ")
@@ -1132,15 +1132,14 @@ int tar_main(int argc UNUSED_PARAM, char **argv)
tar_handle->ah_flags &= ~ARCHIVE_RESTORE_DATE;
#if ENABLE_FEATURE_TAR_FROM
/* Convert each -X EXCLFILE to list of to-be-rejected glob patterns */
tar_handle->reject = append_file_list_to_list(tar_handle->reject);
# if ENABLE_FEATURE_TAR_LONG_OPTIONS
/* Append --exclude=GLOBPATTERNs to reject */
if (excludes) {
llist_t **p2next = &tar_handle->reject;
while (*p2next)
p2next = &((*p2next)->link);
*p2next = excludes;
/* Append excludes to reject */
while (excludes) {
llist_t *next = excludes->link;
excludes->link = tar_handle->reject;
tar_handle->reject = excludes;
excludes = next;
}
# endif
tar_handle->accept = append_file_list_to_list(tar_handle->accept);
+7 -31
View File
@@ -56,15 +56,14 @@
//kbuild:lib-$(CONFIG_UNZIP) += unzip.o
//usage:#define unzip_trivial_usage
//usage: "[-lnojpq] FILE[.zip] [FILE]... [-x FILE]... [-d DIR]"
//usage: "[-lnojpq] FILE[.zip] [FILE]... [-x FILE...] [-d DIR]"
//usage:#define unzip_full_usage "\n\n"
//usage: "Extract FILEs from ZIP archive\n"
//usage: "\n -l List contents (with -q for short form)"
//usage: "\n -n Never overwrite files (default: ask)"
//usage: "\n -o Overwrite"
//usage: "\n -j Do not restore paths"
//usage: "\n -p Write to stdout"
//usage: "\n -t Test"
//usage: "\n -p Print to stdout"
//usage: "\n -q Quiet"
//usage: "\n -x FILE Exclude FILEs"
//usage: "\n -d DIR Extract into DIR"
@@ -83,13 +82,11 @@ enum {
ZIP_FILEHEADER_MAGIC = 0x504b0304,
ZIP_CDF_MAGIC = 0x504b0102, /* CDF item */
ZIP_CDE_MAGIC = 0x504b0506, /* End of CDF */
ZIP64_CDE_MAGIC = 0x504b0606, /* End of Zip64 CDF */
ZIP_DD_MAGIC = 0x504b0708,
#else
ZIP_FILEHEADER_MAGIC = 0x04034b50,
ZIP_CDF_MAGIC = 0x02014b50,
ZIP_CDE_MAGIC = 0x06054b50,
ZIP64_CDE_MAGIC = 0x06064b50,
ZIP_DD_MAGIC = 0x08074b50,
#endif
};
@@ -263,12 +260,6 @@ static uint32_t find_cdf_offset(void)
continue;
/* we found CDE! */
memcpy(cde.raw, p + 1, CDE_LEN);
dbg("cde.this_disk_no:%d", cde.fmt.this_disk_no );
dbg("cde.disk_with_cdf_no:%d", cde.fmt.disk_with_cdf_no );
dbg("cde.cdf_entries_on_this_disk:%d", cde.fmt.cdf_entries_on_this_disk);
dbg("cde.cdf_entries_total:%d", cde.fmt.cdf_entries_total );
dbg("cde.cdf_size:%d", cde.fmt.cdf_size );
dbg("cde.cdf_offset:%x", cde.fmt.cdf_offset );
FIX_ENDIANNESS_CDE(cde);
/*
* I've seen .ZIP files with seemingly valid CDEs
@@ -311,27 +302,19 @@ static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf)
dbg("got ZIP_CDE_MAGIC");
return 0; /* EOF */
}
if (magic == ZIP64_CDE_MAGIC) { /* seen in .zip with >4GB files */
dbg("got ZIP64_CDE_MAGIC");
return 0; /* EOF */
}
xread(zip_fd, cdf->raw, CDF_HEADER_LEN);
FIX_ENDIANNESS_CDF(*cdf);
dbg(" magic:%08x filename_len:%u extra_len:%u file_comment_length:%u",
magic,
dbg(" filename_len:%u extra_len:%u file_comment_length:%u",
(unsigned)cdf->fmt.filename_len,
(unsigned)cdf->fmt.extra_len,
(unsigned)cdf->fmt.file_comment_length
);
//TODO: require that magic == ZIP_CDF_MAGIC?
cdf_offset += 4 + CDF_HEADER_LEN
+ cdf->fmt.filename_len
+ cdf->fmt.extra_len
+ cdf->fmt.file_comment_length;
dbg("Next cdf_offset 0x%x", cdf_offset);
return cdf_offset;
};
#endif
@@ -453,9 +436,7 @@ static void unzip_extract(zip_header_t *zip, int dst_fd)
}
/* Validate decompression - size */
if (zip->fmt.ucmpsize != 0xffffffff /* seen on files with >4GB uncompressed data */
&& zip->fmt.ucmpsize != xstate.bytes_out
) {
if (zip->fmt.ucmpsize != xstate.bytes_out) {
/* Don't die. Who knows, maybe len calculation
* was botched somewhere. After all, crc matched! */
bb_simple_error_msg("bad length");
@@ -557,7 +538,7 @@ int unzip_main(int argc, char **argv)
opts = 0;
/* '-' makes getopt return 1 for non-options */
while ((i = getopt(argc, argv, "-d:lnotpqxjv")) != -1) {
while ((i = getopt(argc, argv, "-d:lnopqxjv")) != -1) {
switch (i) {
case 'd': /* Extract to base directory */
base_dir = optarg;
@@ -575,13 +556,8 @@ int unzip_main(int argc, char **argv)
overwrite = O_ALWAYS;
break;
case 't': /* Extract files to /dev/null */
xmove_fd(xopen("/dev/null", O_WRONLY), STDOUT_FILENO);
/*fallthrough*/
case 'p': /* Extract files to stdout */
case 'p': /* Extract files to stdout and fall through to set verbosity */
dst_fd = STDOUT_FILENO;
/*fallthrough*/
case 'q': /* Be quiet */
quiet++;
@@ -990,6 +966,7 @@ int unzip_main(int argc, char **argv)
/* O_NOFOLLOW defends against symlink attacks */
dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
#endif
do_extract:
if (!quiet) {
printf(/* zip.fmt.method == 0
? " extracting: %s\n"
@@ -997,7 +974,6 @@ int unzip_main(int argc, char **argv)
printable_string(dst_fn)
);
}
do_extract:
#if ENABLE_FEATURE_UNZIP_CDF
if (S_ISLNK(file_mode)) {
if (dst_fd != STDOUT_FILENO) /* not -p? */
+2
View File
@@ -33,6 +33,7 @@
## Assorted header problems:
## # CONFIG_HOSTID is not set
## # CONFIG_FEATURE_SYNC_FANCY is not set - syncfs()
## # CONFIG_FEATURE_TOUCH_NODEREF is not set - lutimes()
## # CONFIG_LOGNAME is not set - getlogin_r()
## # CONFIG_LOADFONT is not set
## # CONFIG_SETFONT is not set
@@ -268,6 +269,7 @@ CONFIG_SYNC=y
CONFIG_TEST=y
CONFIG_FEATURE_TEST_64=y
CONFIG_TOUCH=y
# CONFIG_FEATURE_TOUCH_NODEREF is not set
CONFIG_FEATURE_TOUCH_SUSV3=y
CONFIG_TR=y
CONFIG_FEATURE_TR_CLASSES=y
+1
View File
@@ -193,6 +193,7 @@ CONFIG_SYNC=y
CONFIG_TEST=y
CONFIG_FEATURE_TEST_64=y
CONFIG_TOUCH=y
# CONFIG_FEATURE_TOUCH_NODEREF is not set
CONFIG_FEATURE_TOUCH_SUSV3=y
CONFIG_TR=y
CONFIG_FEATURE_TR_CLASSES=y
+1 -1
View File
@@ -399,7 +399,7 @@ setfont [-O font+umap.orig] [-o font.orig] [-om cmap.orig]
-V Version
*/
//usage:#define setfont_trivial_usage
//usage: "[-m MAPFILE] [-C TTY] FILE"
//usage: "FONT [-m MAPFILE] [-C TTY]"
//usage:#define setfont_full_usage "\n\n"
//usage: "Load a console font\n"
//usage: "\n -m MAPFILE Load console screen map"
+1 -1
View File
@@ -106,7 +106,7 @@ int showkey_main(int argc UNUSED_PARAM, char **argv)
xioctl(STDIN_FILENO, KDSKBMODE, (void *)(ptrdiff_t)((option_mask32 & OPT_k) ? K_MEDIUMRAW : K_RAW));
// we should exit on any signal; signals should interrupt read
bb_signals_norestart(BB_FATAL_SIGS, record_signo);
bb_signals_recursive_norestart(BB_FATAL_SIGS, record_signo);
// inform user that program ends after time of inactivity
printf(press_keys, "10s after last keypress");
+2 -2
View File
@@ -152,7 +152,7 @@ static int catv(unsigned opts, char **argv)
eol_seen = (c == eol_char);
#endif
visible(c, buf, opts);
fputs_stdout(buf);
fputs(buf, stdout);
}
}
if (ENABLE_FEATURE_CLEAN_UP && fd)
@@ -201,7 +201,7 @@ int cat_main(int argc UNUSED_PARAM, char **argv)
ns.start = 1;
ns.inc = 1;
ns.sep = "\t";
ns.empty_str = NULL;
ns.empty_str = "\n";
ns.all = !(opts & CAT_OPT_b); /* -n without -b */
ns.nonempty = (opts & CAT_OPT_b); /* -b (with or without -n) */
exitcode = EXIT_SUCCESS;
+2 -6
View File
@@ -23,17 +23,13 @@
//usage:#define chgrp_trivial_usage
//usage: "[-Rh"IF_DESKTOP("LHPcvf")"]... GROUP FILE..."
//usage:#define chgrp_full_usage "\n\n"
//usage: "Change the group membership of FILEs to GROUP"
//usage: "\n"
//usage: "Change the group membership of each FILE to GROUP\n"
//usage: "\n -R Recurse"
//usage: "\n -h Affect symlinks instead of symlink targets"
//usage: IF_DESKTOP(
//usage: "\n -L Traverse all symlinks to directories"
//usage: "\n -H Traverse symlinks on command line only"
//usage: "\n -P Don't traverse symlinks (default)"
//usage: )
//next 4 options are the same for chmod/chown/chgrp:
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -f Hide errors"
+3 -4
View File
@@ -26,13 +26,12 @@
//usage:#define chmod_trivial_usage
//usage: "[-R"IF_DESKTOP("cvf")"] MODE[,MODE]... FILE..."
//usage:#define chmod_full_usage "\n\n"
//usage: "MODE is octal number (bit pattern sstrwxrwxrwx) or [ugoa]{+|-|=}[rwxXst]"
//usage: "\n"
//next 4 options are the same for chmod/chown/chgrp:
//usage: "Each MODE is one or more of the letters ugoa, one of the\n"
//usage: "symbols +-= and one or more of the letters rwxst\n"
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -v List all files"
//usage: "\n -f Hide errors"
//usage: )
//usage:
+3 -7
View File
@@ -28,19 +28,15 @@
//usage:#define chown_trivial_usage
//usage: "[-Rh"IF_DESKTOP("LHPcvf")"]... USER[:[GRP]] FILE..."
//usage:#define chown_full_usage "\n\n"
//usage: "Change the owner and/or group of FILEs to USER and/or GRP"
//usage: "\n"
//usage: "Change the owner and/or group of each FILE to USER and/or GRP\n"
//usage: "\n -R Recurse"
//usage: "\n -h Affect symlinks instead of symlink targets"
//usage: IF_DESKTOP(
//usage: "\n -L Traverse all symlinks to directories"
//usage: "\n -H Traverse symlinks on command line only"
//usage: "\n -P Don't traverse symlinks (default)"
//usage: )
//next 4 options are the same for chmod/chown/chgrp:
//usage: "\n -R Recurse"
//usage: IF_DESKTOP(
//usage: "\n -c List changed files"
//usage: "\n -v Verbose"
//usage: "\n -v List all files"
//usage: "\n -f Hide errors"
//usage: )
//usage:
+16 -38
View File
@@ -9,40 +9,32 @@
//config:config CKSUM
//config: bool "cksum (4.1 kb)"
//config: default y
//config:
//config:config CRC32
//config: bool "crc32 (4.1 kb)"
//config: default y
//config: help
//config: cksum is used to calculate the CRC32 checksum of a file.
// APPLET_NOEXEC:name main location suid_type help
//applet:IF_CKSUM(APPLET_NOEXEC(cksum, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
//applet:IF_CRC32(APPLET_NOEXEC(crc32, cksum, BB_DIR_USR_BIN, BB_SUID_DROP, cksum))
/* bb_common_bufsiz1 usage here is safe wrt NOEXEC: not expecting it to be zeroed. */
//kbuild:lib-$(CONFIG_CKSUM) += cksum.o
//kbuild:lib-$(CONFIG_CRC32) += cksum.o
//usage:#define cksum_trivial_usage
//usage: "FILE..."
//usage:#define cksum_full_usage "\n\n"
//usage: "Calculate CRC32 checksum of FILEs"
//usage: "Calculate the CRC32 checksums of FILEs"
#include "libbb.h"
#include "common_bufsiz.h"
/* This is a NOEXEC applet. Be very careful! */
#define IS_CKSUM (ENABLE_CKSUM && (!ENABLE_CRC32 || applet_name[1] == 'k'))
#define IS_CRC32 (ENABLE_CRC32 && (!ENABLE_CKSUM || applet_name[1] == 'r'))
int cksum_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int cksum_main(int argc UNUSED_PARAM, char **argv)
{
uint32_t *crc32_table = crc32_filltable(NULL, IS_CKSUM);
uint32_t *crc32_table = crc32_filltable(NULL, 1);
int exit_code = EXIT_SUCCESS;
#if ENABLE_DESKTOP
getopt32(argv, ""); /* cksum coreutils 6.9 compat */
getopt32(argv, ""); /* coreutils 6.9 compat */
argv += optind;
#else
argv++;
@@ -51,55 +43,41 @@ int cksum_main(int argc UNUSED_PARAM, char **argv)
setup_common_bufsiz();
do {
uint32_t crc;
IF_CKSUM(off_t filesize;)
const char *fname = *argv ? *argv : bb_msg_standard_input;
int fd = open_or_warn_stdin(fname);
off_t filesize;
int fd = open_or_warn_stdin(*argv ? *argv : bb_msg_standard_input);
if (fd < 0) {
exit_code = EXIT_FAILURE;
continue;
}
crc = IS_CKSUM ? 0 : 0xffffffff;
IF_CKSUM(filesize = 0;)
crc = 0;
filesize = 0;
#define read_buf bb_common_bufsiz1
for (;;) {
uoff_t t;
int bytes_read = safe_read(fd, read_buf, COMMON_BUFSIZE);
if (bytes_read < 0)
bb_simple_perror_msg_and_die(fname);
if (bytes_read > 0) {
IF_CKSUM(filesize += bytes_read;)
filesize += bytes_read;
} else {
IF_CKSUM(uoff_t t;)
/* Checksum filesize bytes, LSB first, and exit */
close(fd);
if (IS_CRC32)
break;
#if ENABLE_CKSUM
fd = -1; /* break flag */
/* Checksum filesize bytes, LSB first */
t = filesize;
/*bytes_read = 0; - already is */
bytes_read = 0;
while (t != 0) {
read_buf[bytes_read++] = (uint8_t)t;
t >>= 8;
}
#endif
}
crc = (IS_CKSUM ? crc32_block_endian1 : crc32_block_endian0)(crc, read_buf, bytes_read, crc32_table);
if (ENABLE_CKSUM && fd < 0)
crc = crc32_block_endian1(crc, read_buf, bytes_read, crc32_table);
if (fd < 0)
break;
}
crc = ~crc;
#if ENABLE_CKSUM
if (IS_CKSUM)
printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
printf((*argv ? "%u %"OFF_FMT"u %s\n" : "%u %"OFF_FMT"u\n"),
(unsigned)crc, filesize, *argv);
else
#endif
printf((*argv ? "%08x %s\n" : "%08x\n"),
(unsigned)crc, *argv);
} while (*argv && *++argv);
fflush_stdout_and_exit(exit_code);
+98 -111
View File
@@ -37,57 +37,10 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/cp.html */
// Options of cp from GNU coreutils 6.10:
// -a, --archive
// -f, --force
// -i, --interactive
// -l, --link
// -L, --dereference
// -P, --no-dereference
// -R, -r, --recursive
// -s, --symbolic-link
// -v, --verbose
// -H follow command-line symbolic links in SOURCE
// -d same as --no-dereference --preserve=links
// -p same as --preserve=mode,ownership,timestamps
// -c same as --preserve=context
// -u, --update
// copy only when the SOURCE file is newer than the destination
// file or when the destination file is missing
// --remove-destination
// remove each existing destination file before attempting to open
// --parents
// use full source file name under DIRECTORY
// -T, --no-target-directory
// treat DEST as a normal file
// NOT SUPPORTED IN BBOX:
// --backup[=CONTROL]
// make a backup of each existing destination file
// -b like --backup but does not accept an argument
// --copy-contents
// copy contents of special files when recursive
// --preserve[=ATTR_LIST]
// preserve attributes (default: mode,ownership,timestamps),
// if possible additional attributes: security context,links,all
// --no-preserve=ATTR_LIST
// --sparse=WHEN
// control creation of sparse files
// --strip-trailing-slashes
// remove any trailing slashes from each SOURCE argument
// -S, --suffix=SUFFIX
// override the usual backup suffix
// -t, --target-directory=DIRECTORY
// copy all SOURCE arguments into DIRECTORY
// -x, --one-file-system
// stay on this file system
// -Z, --context=CONTEXT
// (SELinux) set SELinux security context of copy to CONTEXT
//usage:#define cp_trivial_usage
//usage: "[-arPLHpfinlsTu] SOURCE DEST\n"
//usage: "or: cp [-arPLHpfinlsu] SOURCE... { -t DIRECTORY | DIRECTORY }"
//usage: "[-arPLHpfilsTu] SOURCE... DEST"
//usage:#define cp_full_usage "\n\n"
//usage: "Copy SOURCEs to DEST\n"
//usage: "Copy SOURCE(s) to DEST\n"
//usage: "\n -a Same as -dpR"
//usage: IF_SELINUX(
//usage: "\n -c Preserve security context"
@@ -99,10 +52,8 @@
//usage: "\n -p Preserve file attributes if possible"
//usage: "\n -f Overwrite"
//usage: "\n -i Prompt before overwrite"
//usage: "\n -n Don't overwrite"
//usage: "\n -l,-s Create (sym)links"
//usage: "\n -T Refuse to copy if DEST is a directory"
//usage: "\n -t DIR Copy all SOURCEs into DIR"
//usage: "\n -T Treat DEST as a normal file"
//usage: "\n -u Copy only newer files"
#include "libbb.h"
@@ -121,46 +72,44 @@ int cp_main(int argc, char **argv)
int d_flags;
int flags;
int status;
#if ENABLE_FEATURE_CP_LONG_OPTIONS
enum {
/*OPT_rmdest = FILEUTILS_RMDEST = 1 << FILEUTILS_CP_OPTBITS */
OPT_parents = 1 << (FILEUTILS_CP_OPTBITS+1),
OPT_reflink = 1 << (FILEUTILS_CP_OPTBITS+2),
FILEUTILS_CP_OPTNUM = sizeof(FILEUTILS_CP_OPTSTR)-1,
#if ENABLE_FEATURE_CP_LONG_OPTIONS
/*OPT_rmdest = FILEUTILS_RMDEST = 1 << FILEUTILS_CP_OPTNUM */
OPT_parents = 1 << (FILEUTILS_CP_OPTNUM+1),
OPT_reflink = 1 << (FILEUTILS_CP_OPTNUM+2),
#endif
};
#if ENABLE_FEATURE_CP_LONG_OPTIONS
# if ENABLE_FEATURE_CP_REFLINK
char *reflink = NULL;
# endif
flags = getopt32long(argv, "^"
FILEUTILS_CP_OPTSTR
"\0"
// Need at least one argument. (Usually two+, but -t DIR can have only one)
// Need at least two arguments
// Soft- and hardlinking doesn't mix
// -P and -d are the same (-P is POSIX, -d is GNU)
// -r and -R are the same
// -R (and therefore -r) turns on -d (coreutils does this)
// -a = -pdR
// -i overrides -n and vice versa (last wins)
"-1:l--s:s--l:Pd:rRd:Rd:apdR:i-n:n-i",
"-2:l--s:s--l:Pd:rRd:Rd:apdR",
"archive\0" No_argument "a"
"force\0" No_argument "f"
"interactive\0" No_argument "i"
"no-clobber\0" No_argument "n"
"link\0" No_argument "l"
"dereference\0" No_argument "L"
"no-dereference\0" No_argument "P"
"recursive\0" No_argument "R"
"symbolic-link\0" No_argument "s"
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
"verbose\0" No_argument "v"
"update\0" No_argument "u"
"remove-destination\0" No_argument "\xff"
"parents\0" No_argument "\xfe"
# if ENABLE_FEATURE_CP_REFLINK
"reflink\0" Optional_argument "\xfd"
# endif
, &last
# if ENABLE_FEATURE_CP_REFLINK
, &reflink
# endif
);
@@ -179,10 +128,55 @@ int cp_main(int argc, char **argv)
flags = getopt32(argv, "^"
FILEUTILS_CP_OPTSTR
"\0"
"-1:l--s:s--l:Pd:rRd:Rd:apdR"
, &last
"-2:l--s:s--l:Pd:rRd:Rd:apdR"
);
#endif
/* Options of cp from GNU coreutils 6.10:
* -a, --archive
* -f, --force
* -i, --interactive
* -l, --link
* -L, --dereference
* -P, --no-dereference
* -R, -r, --recursive
* -s, --symbolic-link
* -v, --verbose
* -H follow command-line symbolic links in SOURCE
* -d same as --no-dereference --preserve=links
* -p same as --preserve=mode,ownership,timestamps
* -c same as --preserve=context
* -u, --update
* copy only when the SOURCE file is newer than the destination
* file or when the destination file is missing
* --remove-destination
* remove each existing destination file before attempting to open
* --parents
* use full source file name under DIRECTORY
* -T, --no-target-directory
* treat DEST as a normal file
* NOT SUPPORTED IN BBOX:
* --backup[=CONTROL]
* make a backup of each existing destination file
* -b like --backup but does not accept an argument
* --copy-contents
* copy contents of special files when recursive
* --preserve[=ATTR_LIST]
* preserve attributes (default: mode,ownership,timestamps),
* if possible additional attributes: security context,links,all
* --no-preserve=ATTR_LIST
* --sparse=WHEN
* control creation of sparse files
* --strip-trailing-slashes
* remove any trailing slashes from each SOURCE argument
* -S, --suffix=SUFFIX
* override the usual backup suffix
* -t, --target-directory=DIRECTORY
* copy all SOURCE arguments into DIRECTORY
* -x, --one-file-system
* stay on this file system
* -Z, --context=CONTEXT
* (SELinux) set SELinux security context of copy to CONTEXT
*/
argc -= optind;
argv += optind;
/* Reverse this bit. If there is -d, bit is not set: */
@@ -201,56 +195,49 @@ int cp_main(int argc, char **argv)
#endif
status = EXIT_SUCCESS;
if (!(flags & FILEUTILS_TARGET_DIR)) {
last = argv[argc - 1];
if (argc < 2)
bb_show_usage();
if (argc != 2) {
if (flags & FILEUTILS_NO_TARGET_DIR)
bb_show_usage();
/* "cp A B C... DIR" - target must be dir */
} else /* argc == 2 */ {
/* "cp A B" - only case where target can be not a dir */
s_flags = cp_mv_stat2(*argv, &source_stat,
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0) /* error other than ENOENT */
return EXIT_FAILURE;
last = argv[argc - 1];
/* If there are only two arguments and... */
if (argc == 2) {
s_flags = cp_mv_stat2(*argv, &source_stat,
(flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
if (s_flags < 0)
return EXIT_FAILURE;
d_flags = cp_mv_stat(last, &dest_stat);
if (d_flags < 0)
return EXIT_FAILURE;
if (flags & FILEUTILS_NO_TARGET_DIR) { /* -T */
if (!(s_flags & 2) && (d_flags & 2))
/* cp -T NOTDIR DIR */
bb_error_msg_and_die("'%s' is a directory", last);
}
if (flags & FILEUTILS_NO_TARGET_DIR) { /* -T */
if (!(s_flags & 2) && (d_flags & 2))
/* cp -T NOTDIR DIR */
bb_error_msg_and_die("'%s' is a directory", last);
}
#if ENABLE_FEATURE_CP_LONG_OPTIONS
//bb_error_msg("flags:%x FILEUTILS_RMDEST:%x OPT_parents:%x",
// flags, FILEUTILS_RMDEST, OPT_parents);
if (flags & OPT_parents) {
if (!(d_flags & 2)) {
bb_simple_error_msg_and_die("with --parents, the destination must be a directory");
}
}
if (flags & FILEUTILS_RMDEST) {
flags |= FILEUTILS_FORCE;
}
#endif
/* ...if neither is a directory... */
if (!((s_flags | d_flags) & 2)
/* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */
|| ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
|| (flags & FILEUTILS_NO_TARGET_DIR)
) {
/* Do a simple copy */
dest = last;
goto DO_COPY; /* NB: argc==2 -> *++argv==last */
//bb_error_msg("flags:%x FILEUTILS_RMDEST:%x OPT_parents:%x",
// flags, FILEUTILS_RMDEST, OPT_parents);
if (flags & OPT_parents) {
if (!(d_flags & 2)) {
bb_simple_error_msg_and_die("with --parents, the destination must be a directory");
}
}
if (flags & FILEUTILS_RMDEST) {
flags |= FILEUTILS_FORCE;
}
#endif
/* ...if neither is a directory... */
if (!((s_flags | d_flags) & 2)
/* ...or: recursing, the 1st is a directory, and the 2nd doesn't exist... */
|| ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags)
|| (flags & FILEUTILS_NO_TARGET_DIR)
) {
/* Do a simple copy */
dest = last;
goto DO_COPY; /* NB: argc==2 -> *++argv==last */
}
} else if (flags & FILEUTILS_NO_TARGET_DIR) {
bb_simple_error_msg_and_die("too many arguments");
}
/* else: last is DIR from "-t DIR" */
while (1) {
#if ENABLE_FEATURE_CP_LONG_OPTIONS
@@ -272,7 +259,7 @@ int cp_main(int argc, char **argv)
if (copy_file(*argv, dest, flags) < 0) {
status = EXIT_FAILURE;
}
if (!*++argv || *argv == last) {
if (*++argv == last) {
/* possibly leaking dest... */
break;
}
+96 -110
View File
@@ -14,13 +14,6 @@
//config: help
//config: cut is used to print selected parts of lines from
//config: each file to stdout.
//config:
//config:config FEATURE_CUT_REGEX
//config: bool "cut -F"
//config: default y
//config: depends on CUT
//config: help
//config: Allow regex based delimiters.
//applet:IF_CUT(APPLET_NOEXEC(cut, cut, BB_DIR_USR_BIN, BB_SUID_DROP, cut))
@@ -29,19 +22,13 @@
//usage:#define cut_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage:#define cut_full_usage "\n\n"
//usage: "Print selected fields from FILEs to stdout\n"
//usage: "Print selected fields from each input FILE to stdout\n"
//usage: "\n -b LIST Output only bytes from LIST"
//usage: "\n -c LIST Output only characters from LIST"
//usage: "\n -d SEP Field delimiter for input (default -f TAB, -F run of whitespace)"
//usage: "\n -O SEP Field delimeter for output (default = -d for -f, one space for -F)"
//usage: "\n -D Don't sort/collate sections or match -fF lines without delimeter"
//usage: "\n -f LIST Print only these fields (-d is single char)"
//usage: IF_FEATURE_CUT_REGEX(
//usage: "\n -F LIST Print only these fields (-d is regex)"
//usage: )
//usage: "\n -s Output only lines containing delimiter"
//usage: "\n -d CHAR Use CHAR instead of tab as the field delimiter"
//usage: "\n -s Output only the lines containing delimiter"
//usage: "\n -f N Print only these fields"
//usage: "\n -n Ignored"
//(manpage:-n with -b: don't split multibyte characters)
//usage:
//usage:#define cut_example_usage
//usage: "$ echo \"Hello world\" | cut -f 1 -d ' '\n"
@@ -51,49 +38,38 @@
#include "libbb.h"
#if ENABLE_FEATURE_CUT_REGEX
#include "xregex.h"
#else
#define regex_t int
typedef struct { int rm_eo, rm_so; } regmatch_t;
#define xregcomp(x, ...) *(x) = 0
#define regexec(...) 0
#endif
/* This is a NOEXEC applet. Be very careful! */
/* option vars */
#define OPT_STR "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
#define OPT_STR "b:c:f:d:sn"
#define CUT_OPT_BYTE_FLGS (1 << 0)
#define CUT_OPT_CHAR_FLGS (1 << 1)
#define CUT_OPT_FIELDS_FLGS (1 << 2)
#define CUT_OPT_DELIM_FLGS (1 << 3)
#define CUT_OPT_ODELIM_FLGS (1 << 4)
#define CUT_OPT_SUPPRESS_FLGS (1 << 5)
#define CUT_OPT_NOSORT_FLGS (1 << 6)
#define CUT_OPT_REGEX_FLGS ((1 << 7) * ENABLE_FEATURE_CUT_REGEX)
#define CUT_OPT_SUPPRESS_FLGS (1 << 4)
struct cut_list {
int startpos;
int endpos;
};
enum {
BOL = 0,
EOL = INT_MAX,
NON_RANGE = -1
};
static int cmpfunc(const void *a, const void *b)
{
return (((struct cut_list *) a)->startpos -
((struct cut_list *) b)->startpos);
}
static void cut_file(FILE *file, const char *delim, const char *odelim,
const struct cut_list *cut_lists, unsigned nlists)
static void cut_file(FILE *file, char delim, const struct cut_list *cut_lists, unsigned nlists)
{
char *line;
unsigned linenum = 0; /* keep these zero-based to be consistent */
regex_t reg;
int spos, shoe = option_mask32 & CUT_OPT_REGEX_FLGS;
if (shoe) xregcomp(&reg, delim, REG_EXTENDED);
/* go through every line in the file */
while ((line = xmalloc_fgetline(file)) != NULL) {
@@ -103,22 +79,29 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
char *printed = xzalloc(linelen + 1);
char *orig_line = line;
unsigned cl_pos = 0;
int spos;
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (option_mask32 & (CUT_OPT_CHAR_FLGS | CUT_OPT_BYTE_FLGS)) {
/* print the chars specified in each cut list */
for (; cl_pos < nlists; cl_pos++) {
for (spos = cut_lists[cl_pos].startpos; spos < linelen;) {
spos = cut_lists[cl_pos].startpos;
while (spos < linelen) {
if (!printed[spos]) {
printed[spos] = 'X';
putchar(line[spos]);
}
if (++spos > cut_lists[cl_pos].endpos) {
spos++;
if (spos > cut_lists[cl_pos].endpos
/* NON_RANGE is -1, so if below is true,
* the above was true too (spos is >= 0) */
/* || cut_lists[cl_pos].endpos == NON_RANGE */
) {
break;
}
}
}
} else if (*delim == '\n') { /* cut by lines */
} else if (delim == '\n') { /* cut by lines */
spos = cut_lists[cl_pos].startpos;
/* get out if we have no more lists to process or if the lines
@@ -131,7 +114,9 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
while (spos < (int)linenum) {
spos++;
/* go to the next list if we're at the end of this one */
if (spos > cut_lists[cl_pos].endpos) {
if (spos > cut_lists[cl_pos].endpos
|| cut_lists[cl_pos].endpos == NON_RANGE
) {
cl_pos++;
/* get out if there's no more lists to process */
if (cl_pos >= nlists)
@@ -149,56 +134,55 @@ static void cut_file(FILE *file, const char *delim, const char *odelim,
puts(line);
goto next_line;
} else { /* cut by fields */
unsigned uu = 0, start = 0, end = 0, out = 0;
int dcount = 0;
int ndelim = -1; /* zero-based / one-based problem */
int nfields_printed = 0;
char *field = NULL;
char delimiter[2];
/* Loop through bytes, finding next delimiter */
for (;;) {
/* End of current range? */
if (end == linelen || dcount > cut_lists[cl_pos].endpos) {
if (++cl_pos >= nlists) break;
if (option_mask32 & CUT_OPT_NOSORT_FLGS)
start = dcount = uu = 0;
end = 0;
}
/* End of current line? */
if (uu == linelen) {
/* If we've seen no delimiters, check -s */
if (!cl_pos && !dcount && !shoe) {
if (option_mask32 & CUT_OPT_SUPPRESS_FLGS)
goto next_line;
} else if (dcount<cut_lists[cl_pos].startpos)
start = linelen;
end = linelen;
} else {
/* Find next delimiter */
if (shoe) {
regmatch_t rr = {-1, -1};
delimiter[0] = delim;
delimiter[1] = 0;
if (!regexec(&reg, line+uu, 1, &rr, REG_NOTBOL|REG_NOTEOL)) {
end = uu + rr.rm_so;
uu += rr.rm_eo;
} else {
uu = linelen;
continue;
}
} else if (line[end = uu++] != *delim)
continue;
/* does this line contain any delimiters? */
if (strchr(line, delim) == NULL) {
if (!(option_mask32 & CUT_OPT_SUPPRESS_FLGS))
puts(line);
goto next_line;
}
/* Got delimiter. Loop if not yet within range. */
if (dcount++ < cut_lists[cl_pos].startpos) {
start = uu;
continue;
/* process each list on this line, for as long as we've got
* a line to process */
for (; cl_pos < nlists && line; cl_pos++) {
spos = cut_lists[cl_pos].startpos;
do {
/* find the field we're looking for */
while (line && ndelim < spos) {
field = strsep(&line, delimiter);
ndelim++;
}
}
if (end != start || !shoe)
printf("%s%.*s", out++ ? odelim : "", end-start, line + start);
start = uu;
if (!dcount)
break;
/* we found it, and it hasn't been printed yet */
if (field && ndelim == spos && !printed[ndelim]) {
/* if this isn't our first time through, we need to
* print the delimiter after the last field that was
* printed */
if (nfields_printed > 0)
putchar(delim);
fputs(field, stdout);
printed[ndelim] = 'X';
nfields_printed++; /* shouldn't overflow.. */
}
spos++;
/* keep going as long as we have a line to work with,
* this is a list, and we're not at the end of that
* list */
} while (spos <= cut_lists[cl_pos].endpos && line
&& cut_lists[cl_pos].endpos != NON_RANGE);
}
}
/* if we printed anything, finish with newline */
/* if we printed anything at all, we need to finish it with a
* newline cuz we were handed a chomped line */
putchar('\n');
next_line:
linenum++;
@@ -213,35 +197,37 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* growable array holding a series of lists */
struct cut_list *cut_lists = NULL;
unsigned nlists = 0; /* number of elements in above list */
char delim = '\t'; /* delimiter, default is tab */
char *sopt, *ltok;
const char *delim = NULL;
const char *odelim = NULL;
unsigned opt;
#define ARG "bcf"IF_FEATURE_CUT_REGEX("F")
opt = getopt32(argv, "^"
OPT_STR // = "b:c:f:d:O:sD"IF_FEATURE_CUT_REGEX("F:")"n"
"\0" "b--"ARG":c--"ARG":f--"ARG IF_FEATURE_CUT_REGEX("F--"ARG),
&sopt, &sopt, &sopt, &delim, &odelim IF_FEATURE_CUT_REGEX(, &sopt)
OPT_STR
"\0" "b--bcf:c--bcf:f--bcf",
&sopt, &sopt, &sopt, &ltok
);
if (!delim || !*delim)
delim = (opt & CUT_OPT_REGEX_FLGS) ? "[[:space:]]+" : "\t";
if (!odelim) odelim = (opt & CUT_OPT_REGEX_FLGS) ? " " : delim;
// argc -= optind;
argv += optind;
if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS | CUT_OPT_REGEX_FLGS)))
if (!(opt & (CUT_OPT_BYTE_FLGS | CUT_OPT_CHAR_FLGS | CUT_OPT_FIELDS_FLGS)))
bb_simple_error_msg_and_die("expected a list of bytes, characters, or fields");
if (opt & CUT_OPT_DELIM_FLGS) {
if (ltok[0] && ltok[1]) { /* more than 1 char? */
bb_simple_error_msg_and_die("the delimiter must be a single character");
}
delim = ltok[0];
}
/* non-field (char or byte) cutting has some special handling */
if (!(opt & (CUT_OPT_FIELDS_FLGS|CUT_OPT_REGEX_FLGS))) {
if (!(opt & CUT_OPT_FIELDS_FLGS)) {
static const char _op_on_field[] ALIGN1 = " only when operating on fields";
if (opt & CUT_OPT_SUPPRESS_FLGS) {
bb_error_msg_and_die
("suppressing non-delimited lines makes sense%s", _op_on_field);
("suppressing non-delimited lines makes sense%s",
_op_on_field);
}
if (opt & CUT_OPT_DELIM_FLGS) {
if (delim != '\t') {
bb_error_msg_and_die
("a delimiter may be specified%s", _op_on_field);
}
@@ -266,7 +252,7 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* get the start pos */
ntok = strsep(&ltok, "-");
if (!ntok[0]) {
s = 0;
s = BOL;
} else {
s = xatoi_positive(ntok);
/* account for the fact that arrays are zero based, while
@@ -277,23 +263,24 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* get the end pos */
if (ltok == NULL) {
e = s;
e = NON_RANGE;
} else if (!ltok[0]) {
e = INT_MAX;
e = EOL;
} else {
e = xatoi_positive(ltok);
/* if the user specified and end position of 0,
* that means "til the end of the line" */
if (!*ltok)
e = INT_MAX;
else if (e < s)
bb_error_msg_and_die("%d<%d", e, s);
if (e == 0)
e = EOL;
e--; /* again, arrays are zero based, lines are 1 based */
if (e == s)
e = NON_RANGE;
}
/* add the new list */
cut_lists = xrealloc_vector(cut_lists, 4, nlists);
/* NB: startpos is always >= 0 */
/* NB: startpos is always >= 0,
* while endpos may be = NON_RANGE (-1) */
cut_lists[nlists].startpos = s;
cut_lists[nlists].endpos = e;
nlists++;
@@ -306,8 +293,7 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
/* now that the lists are parsed, we need to sort them to make life
* easier on us when it comes time to print the chars / fields / lines
*/
if (!(opt & CUT_OPT_NOSORT_FLGS))
qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
qsort(cut_lists, nlists, sizeof(cut_lists[0]), cmpfunc);
}
{
@@ -322,7 +308,7 @@ int cut_main(int argc UNUSED_PARAM, char **argv)
retval = EXIT_FAILURE;
continue;
}
cut_file(file, delim, odelim, cut_lists, nlists);
cut_file(file, delim, cut_lists, nlists);
fclose_if_not_stdin(file);
} while (*++argv);
+20 -34
View File
@@ -56,10 +56,10 @@
//kbuild:lib-$(CONFIG_DD) += dd.o
//usage:#define dd_trivial_usage
//usage: "[if=FILE] [of=FILE] [" IF_FEATURE_DD_IBS_OBS("ibs=N obs=N/") "bs=N] [count=N] [skip=N] [seek=N]"
//usage: IF_FEATURE_DD_IBS_OBS("\n"
//usage: "[if=FILE] [of=FILE] [" IF_FEATURE_DD_IBS_OBS("ibs=N obs=N/") "bs=N] [count=N] [skip=N] [seek=N]\n"
//usage: IF_FEATURE_DD_IBS_OBS(
//usage: " [conv=notrunc|noerror|sync|fsync]\n"
//usage: " [iflag=skip_bytes|count_bytes|fullblock|direct] [oflag=seek_bytes|append|direct]"
//usage: " [iflag=skip_bytes|fullblock|direct] [oflag=seek_bytes|append|direct]"
//usage: )
//usage:#define dd_full_usage "\n\n"
//usage: "Copy a file with converting and formatting\n"
@@ -82,7 +82,6 @@
//usage: "\n conv=fsync Physically write data out before finishing"
//usage: "\n conv=swab Swap every pair of bytes"
//usage: "\n iflag=skip_bytes skip=N is in bytes"
//usage: "\n iflag=count_bytes count=N is in bytes"
//usage: "\n oflag=seek_bytes seek=N is in bytes"
//usage: "\n iflag=direct O_DIRECT input"
//usage: "\n oflag=direct O_DIRECT output"
@@ -137,22 +136,21 @@ enum {
FLAG_SWAB = (1 << 4) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of conv flags */
/* start of input flags */
FLAG_IFLAG_SHIFT = 5,
FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT_BYTES = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_FULLBLOCK = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IDIRECT = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IFLAG_SHIFT = 5,
FLAG_SKIP_BYTES = (1 << 5) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_FULLBLOCK = (1 << 6) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_IDIRECT = (1 << 7) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of input flags */
/* start of output flags */
FLAG_OFLAG_SHIFT = 9,
FLAG_SEEK_BYTES = (1 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_APPEND = (1 << 10) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_ODIRECT = (1 << 11) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_OFLAG_SHIFT = 8,
FLAG_SEEK_BYTES = (1 << 8) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_APPEND = (1 << 9) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_ODIRECT = (1 << 10) * ENABLE_FEATURE_DD_IBS_OBS,
/* end of output flags */
FLAG_TWOBUFS = (1 << 12) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 13,
FLAG_STATUS_NONE = 1 << 14,
FLAG_STATUS_NOXFER = 1 << 15,
FLAG_TWOBUFS = (1 << 11) * ENABLE_FEATURE_DD_IBS_OBS,
FLAG_COUNT = 1 << 12,
FLAG_STATUS_NONE = 1 << 13,
FLAG_STATUS_NOXFER = 1 << 14,
};
static void dd_output_status(int UNUSED_PARAM cur_signal)
@@ -177,9 +175,8 @@ static void dd_output_status(int UNUSED_PARAM cur_signal)
//So far we react to it (we print the stats),
//status=none only suppresses final, non-USR1 generated status message.
# endif
fprintf(stderr, /*G.total_bytes < 1024
? "%llu bytes copied, " : */ "%llu bytes (%sB) copied, "
, G.total_bytes,
fprintf(stderr, "%llu bytes (%sB) copied, ",
G.total_bytes,
/* show fractional digit, use suffixes */
make_human_readable_str(G.total_bytes, 1, 0)
);
@@ -320,7 +317,7 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
static const char conv_words[] ALIGN1 =
"notrunc\0""sync\0""noerror\0""fsync\0""swab\0";
static const char iflag_words[] ALIGN1 =
"skip_bytes\0""count_bytes\0""fullblock\0""direct\0";
"skip_bytes\0""fullblock\0""direct\0";
static const char oflag_words[] ALIGN1 =
"seek_bytes\0append\0""direct\0";
#endif
@@ -362,7 +359,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
/* Partially implemented: */
//swab swap every pair of input bytes: will abort on non-even reads
OP_iflag_skip_bytes,
OP_iflag_count_bytes,
OP_iflag_fullblock,
OP_iflag_direct,
OP_oflag_seek_bytes,
@@ -555,17 +551,8 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
goto die_outfile;
}
while (1) {
ssize_t n = ibs;
if (G.flags & FLAG_COUNT) {
if (count == 0)
break;
if ((G.flags & FLAG_COUNT_BYTES) && count < ibs)
n = count;
}
n = dd_read(ibuf, n);
while (!(G.flags & FLAG_COUNT) || (G.in_full + G.in_part != count)) {
ssize_t n = dd_read(ibuf, ibs);
if (n == 0)
break;
if (n < 0) {
@@ -600,7 +587,6 @@ int dd_main(int argc UNUSED_PARAM, char **argv)
p16++;
}
}
count -= (G.flags & FLAG_COUNT_BYTES) ? n : 1;
if ((size_t)n == ibs)
G.in_full++;
else {
+19 -26
View File
@@ -45,7 +45,7 @@
//usage: IF_FEATURE_HUMAN_READABLE("mh")
//usage: "T"
//usage: IF_FEATURE_DF_FANCY("ai] [-B SIZE")
//usage: "] [-t TYPE] [FILESYSTEM]..."
//usage: "] [FILESYSTEM]..."
//usage:#define df_full_usage "\n\n"
//usage: "Print filesystem usage statistics\n"
//usage: "\n -P POSIX output format"
@@ -55,7 +55,6 @@
//usage: "\n -h Human readable (e.g. 1K 243M 2G)"
//usage: )
//usage: "\n -T Print filesystem type"
//usage: "\n -t TYPE Print only mounts of this type"
//usage: IF_FEATURE_DF_FANCY(
//usage: "\n -a Show all filesystems"
//usage: "\n -i Inodes"
@@ -98,31 +97,24 @@ int df_main(int argc UNUSED_PARAM, char **argv)
FILE *mount_table;
struct mntent *mount_entry;
struct statvfs s;
enum {
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_t = (1 << 3),
OPT_ALL = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 6) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (5 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_KILO = (1 << 0),
OPT_POSIX = (1 << 1),
OPT_FSTYPE = (1 << 2),
OPT_ALL = (1 << 3) * ENABLE_FEATURE_DF_FANCY,
OPT_INODE = (1 << 4) * ENABLE_FEATURE_DF_FANCY,
OPT_BSIZE = (1 << 5) * ENABLE_FEATURE_DF_FANCY,
OPT_HUMAN = (1 << (3 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
OPT_MEGA = (1 << (4 + 3*ENABLE_FEATURE_DF_FANCY)) * ENABLE_FEATURE_HUMAN_READABLE,
};
const char *disp_units_hdr = NULL;
char *chp, *opt_t;
char *chp;
init_unicode();
/* From the manpage of df from coreutils-6.10:
* Disk space is shown in 1K blocks by default, unless the environment
* variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
*/
if (getenv("POSIXLY_CORRECT")) /* TODO - a new libbb function? */
df_disp_hr = 512;
opt = getopt32(argv, "^"
"kPTt:"
"kPT"
IF_FEATURE_DF_FANCY("aiB:")
IF_FEATURE_HUMAN_READABLE("hm")
"\0"
@@ -131,7 +123,6 @@ int df_main(int argc UNUSED_PARAM, char **argv)
#elif ENABLE_FEATURE_HUMAN_READABLE
"k-m:m-k"
#endif
, &opt_t
IF_FEATURE_DF_FANCY(, &chp)
);
if (opt & OPT_MEGA)
@@ -151,6 +142,13 @@ int df_main(int argc UNUSED_PARAM, char **argv)
got_it: ;
}
/* From the manpage of df from coreutils-6.10:
* Disk space is shown in 1K blocks by default, unless the environment
* variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
*/
if (getenv("POSIXLY_CORRECT")) /* TODO - a new libbb function? */
df_disp_hr = 512;
if (opt & OPT_HUMAN) {
df_disp_hr = 0;
disp_units_hdr = " Size";
@@ -216,11 +214,6 @@ int df_main(int argc UNUSED_PARAM, char **argv)
mount_point = mount_entry->mnt_dir;
fs_type = mount_entry->mnt_type;
if (opt & OPT_t) {
if (strcmp(fs_type, opt_t) != 0)
continue;
}
if (statvfs(mount_point, &s) != 0) {
bb_simple_perror_msg(mount_point);
goto set_error;
+13 -22
View File
@@ -40,9 +40,8 @@
//usage:#define du_trivial_usage
//usage: "[-aHLdclsx" IF_FEATURE_HUMAN_READABLE("hm") "k] [FILE]..."
//usage:#define du_full_usage "\n\n"
//usage: "Summarize disk space used for FILEs (or directories)\n"
//usage: "Summarize disk space used for each FILE and/or directory\n"
//usage: "\n -a Show file sizes too"
//usage: "\n -b Apparent size (including holes)"
//usage: "\n -L Follow all symlinks"
//usage: "\n -H Follow symlinks on command line"
//usage: "\n -d N Limit output to directories (and files with -a) of depth < N"
@@ -85,9 +84,8 @@ enum {
OPT_d_maxdepth = (1 << 6),
OPT_l_hardlinks = (1 << 7),
OPT_c_total = (1 << 8),
OPT_b = (1 << 9),
OPT_h_for_humans = (1 << 10),
OPT_m_mbytes = (1 << 11),
OPT_h_for_humans = (1 << 9),
OPT_m_mbytes = (1 << 10),
};
struct globals {
@@ -111,7 +109,7 @@ static void print(unsigned long long size, const char *filename)
/* TODO - May not want to defer error checking here. */
#if ENABLE_FEATURE_HUMAN_READABLE
# if ENABLE_DESKTOP
/* ~30 bytes of code for extra compat:
/* ~30 bytes of code for extra comtat:
* coreutils' du rounds sizes up:
* for example, 1025k file is shown as "2" by du -m.
* We round to nearest if human-readable [too hard to fix],
@@ -126,16 +124,12 @@ static void print(unsigned long long size, const char *filename)
* If G.disp_unit == 0, show one fractional
* and use suffixes
*/
make_human_readable_str(size, (option_mask32 & OPT_b) ? 1 : 512, G.disp_unit),
make_human_readable_str(size, 512, G.disp_unit),
filename);
#else
if (G.disp_k) {
if (!(option_mask32 & OPT_b)) {
size++;
size >>= 1;
} else {
size >>= 10;
}
size++;
size >>= 1;
}
printf("%llu\t%s\n", size, filename);
#endif
@@ -161,7 +155,7 @@ static unsigned long long du(const char *filename)
}
}
sum = ((option_mask32 & OPT_b) ? statbuf.st_size : statbuf.st_blocks);
sum = statbuf.st_blocks;
if (S_ISLNK(statbuf.st_mode)) {
if (G.slink_depth > G.du_depth) { /* -H or -L */
@@ -170,7 +164,7 @@ static unsigned long long du(const char *filename)
G.status = EXIT_FAILURE;
return 0;
}
sum = ((option_mask32 & OPT_b) ? statbuf.st_size : statbuf.st_blocks);
sum = statbuf.st_blocks;
if (G.slink_depth == 1) {
/* Convert -H to -L */
G.slink_depth = INT_MAX;
@@ -247,14 +241,11 @@ int du_main(int argc UNUSED_PARAM, char **argv)
*/
#if ENABLE_FEATURE_HUMAN_READABLE
opt = getopt32(argv, "^"
"aHkLsxd:+lcbhm"
"aHkLsxd:+lchm"
"\0" "h-km:k-hm:m-hk:H-L:L-H:s-d:d-s",
&G.max_print_depth
);
argv += optind;
if (opt & OPT_b) {
G.disp_unit = 1;
}
if (opt & OPT_h_for_humans) {
G.disp_unit = 0;
}
@@ -266,16 +257,16 @@ int du_main(int argc UNUSED_PARAM, char **argv)
}
#else
opt = getopt32(argv, "^"
"aHkLsxd:+lcb"
"aHkLsxd:+lc"
"\0" "H-L:L-H:s-d:d-s",
&G.max_print_depth
);
argv += optind;
# if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
#if !ENABLE_FEATURE_DU_DEFAULT_BLOCKSIZE_1K
if (opt & OPT_k_kbytes) {
G.disp_k = 1;
}
# endif
#endif
#endif
if (opt & OPT_H_follow_links) {
G.slink_depth = 1;
+9 -9
View File
@@ -43,10 +43,10 @@
//usage:#define echo_trivial_usage
//usage: IF_FEATURE_FANCY_ECHO("[-neE] ") "[ARG]..."
//usage:#define echo_full_usage "\n\n"
//usage: "Print ARGs to stdout"
//usage: "Print the specified ARGs to stdout"
//usage: IF_FEATURE_FANCY_ECHO( "\n"
//usage: "\n -n No trailing newline"
//usage: "\n -e Interpret backslash escapes (\\t=tab etc)"
//usage: "\n -n Suppress trailing newline"
//usage: "\n -e Interpret backslash escapes (i.e., \\t=tab)"
//usage: "\n -E Don't interpret backslash escapes (default)"
//usage: )
//usage:
@@ -87,7 +87,6 @@ int echo_main(int argc UNUSED_PARAM, char **argv)
char *out;
char *buffer;
unsigned buflen;
int err;
#if !ENABLE_FEATURE_FANCY_ECHO
enum {
eflag = 0, /* 0 -- disable escape sequences */
@@ -186,12 +185,13 @@ int echo_main(int argc UNUSED_PARAM, char **argv)
do_write:
/* Careful to error out on partial writes too (think ENOSPC!) */
errno = 0;
err = full_write(STDOUT_FILENO, buffer, out - buffer) != out - buffer;
if (err) {
bb_simple_perror_msg(bb_msg_write_error);
}
/*r =*/ full_write(STDOUT_FILENO, buffer, out - buffer);
free(buffer);
return err;
if (/*WRONG:r < 0*/ errno) {
bb_simple_perror_msg(bb_msg_write_error);
return 1;
}
return 0;
}
/*
+7 -12
View File
@@ -39,15 +39,12 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/env.html */
//usage:#define env_trivial_usage
//usage: "[-i0] [-u NAME]... [-] [NAME=VALUE]... [PROG ARGS]"
// The "-" can occur only once (unlike, say, -i): it terminates option processing,
// so if it is followed by another "-" arg (or any option-looking arg),
// that arg will be taken as PROG (or even as NAME=VALUE, example: "-z=QWE").
//usage: "[-iu] [-] [name=value]... [PROG ARGS]"
//usage:#define env_full_usage "\n\n"
//usage: "Print current environment or run PROG after setting up environment\n"
//usage: "\n -, -i Start with empty environment"
//usage: "\n -0 NUL terminated output"
//usage: "\n -u NAME Remove variable from environment"
//usage: "Print the current environment or run PROG after setting up\n"
//usage: "the specified environment\n"
//usage: "\n -, -i Start with an empty environment"
//usage: "\n -u Remove variable from the environment"
#include "libbb.h"
@@ -57,9 +54,8 @@ int env_main(int argc UNUSED_PARAM, char **argv)
unsigned opts;
llist_t *unset_env = NULL;
opts = getopt32long(argv, "+i0u:*",
opts = getopt32long(argv, "+iu:*",
"ignore-environment\0" No_argument "i"
"null\0" No_argument "0"
"unset\0" Required_argument "u"
, &unset_env
);
@@ -94,9 +90,8 @@ int env_main(int argc UNUSED_PARAM, char **argv)
if (environ) { /* clearenv() may set environ == NULL! */
char **ep;
opts = (opts & 2) ? 0 : '\n';
for (ep = environ; *ep; ep++) {
printf("%s%c", *ep, opts);
puts(*ep);
}
}
+1 -1
View File
@@ -123,7 +123,7 @@ static void expand(FILE *file, unsigned tab_size, unsigned opt)
}
ptr++;
}
fputs_stdout(ptr_strbeg);
fputs(ptr_strbeg, stdout);
free(line);
}
}
+2 -2
View File
@@ -45,7 +45,7 @@
//usage:#define expr_trivial_usage
//usage: "EXPRESSION"
//usage:#define expr_full_usage "\n\n"
//usage: "Print the value of EXPRESSION\n"
//usage: "Print the value of EXPRESSION to stdout\n"
//usage: "\n"
//usage: "EXPRESSION may be:\n"
//usage: " ARG1 | ARG2 ARG1 if it is neither null nor 0, otherwise ARG2\n"
@@ -63,7 +63,7 @@
//usage: " ARG1 % ARG2\n"
//usage: " STRING : REGEXP Anchored pattern match of REGEXP in STRING\n"
//usage: " match STRING REGEXP Same as STRING : REGEXP\n"
//usage: " substr STRING POS LEN Substring of STRING, POS counts from 1\n"
//usage: " substr STRING POS LENGTH Substring of STRING, POS counted from 1\n"
//usage: " index STRING CHARS Index in STRING where any CHARS is found, or 0\n"
//usage: " length STRING Length of STRING\n"
//usage: " quote TOKEN Interpret TOKEN as a string, even if\n"
+1 -1
View File
@@ -23,7 +23,7 @@
//usage:#define fold_trivial_usage
//usage: "[-bs] [-w WIDTH] [FILE]..."
//usage:#define fold_full_usage "\n\n"
//usage: "Wrap input lines in FILEs (or stdin), writing to stdout\n"
//usage: "Wrap input lines in each FILE (or stdin), writing to stdout\n"
//usage: "\n -b Count bytes rather than columns"
//usage: "\n -s Break at spaces"
//usage: "\n -w Use WIDTH columns instead of 80"
+7 -8
View File
@@ -29,18 +29,17 @@
//usage:#define head_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage:#define head_full_usage "\n\n"
//usage: "Print first 10 lines of FILEs (or stdin).\n"
//usage: "Print first 10 lines of each FILE (or stdin) to stdout.\n"
//usage: "With more than one FILE, precede each with a filename header.\n"
//usage: "\n -n N[bkm] Print first N lines"
//usage: IF_FEATURE_FANCY_HEAD(
//usage: "\n -n -N[bkm] Print all except N last lines"
//usage: "\n -c [-]N[bkm] Print first N bytes"
//usage: )
//usage: "\n (b:*512 k:*1024 m:*1024^2)"
//usage: "\n -n N[kbm] Print first N lines"
//usage: IF_FEATURE_FANCY_HEAD(
//usage: "\n -n -N[kbm] Print all except N last lines"
//usage: "\n -c [-]N[kbm] Print first N bytes"
//usage: "\n -q Never print headers"
//usage: "\n -v Always print headers"
//usage: )
//usage: "\n"
//usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
//usage:
//usage:#define head_example_usage
//usage: "$ head -n 2 /etc/passwd\n"
@@ -118,7 +117,7 @@ print_except_N_last_lines(FILE *fp, unsigned count)
char *c;
if (head == count)
head = 0;
fputs_stdout(circle[head]);
fputs(circle[head], stdout);
c = xmalloc_fgets(fp);
if (!c)
goto ret;
+2 -2
View File
@@ -52,7 +52,7 @@
//usage:#define groups_trivial_usage
//usage: "[USER]"
//usage:#define groups_full_usage "\n\n"
//usage: "Print the groups USER is in"
//usage: "Print the group memberships of USER or for the current process"
//usage:
//usage:#define groups_example_usage
//usage: "$ groups\n"
@@ -258,7 +258,7 @@ int id_main(int argc UNUSED_PARAM, char **argv)
bb_error_msg_and_die("can't get process context%s",
username ? " for a different user" : "");
}
fputs_stdout(scontext);
fputs(scontext, stdout);
}
/* freecon(NULL) seems to be harmless */
if (ENABLE_FEATURE_CLEAN_UP)
+14 -18
View File
@@ -109,11 +109,11 @@
//usage:#define ls_full_usage "\n\n"
//usage: "List directory contents\n"
//usage: "\n -1 One column output"
//usage: "\n -a Include names starting with ."
//usage: "\n -a Include entries which start with ."
//usage: "\n -A Like -a, but exclude . and .."
////usage: "\n -C List by columns" - don't show, this is a default anyway
//usage: "\n -x List by lines"
//usage: "\n -d List directory names, not contents"
//usage: "\n -d List directory entries instead of contents"
//usage: IF_FEATURE_LS_FOLLOWLINKS(
//usage: "\n -L Follow symlinks"
//usage: "\n -H Follow symlinks on command line"
@@ -122,10 +122,10 @@
//usage: "\n -R Recurse"
//usage: )
//usage: IF_FEATURE_LS_FILETYPES(
//usage: "\n -p Append / to directory names"
//usage: "\n -F Append indicator (one of */=@|) to names"
//usage: "\n -p Append / to dir entries"
//usage: "\n -F Append indicator (one of */=@|) to entries"
//usage: )
//usage: "\n -l Long format"
//usage: "\n -l Long listing format"
//usage: "\n -i List inode numbers"
//usage: "\n -n List numeric UIDs and GIDs instead of names"
//usage: "\n -s List allocated blocks"
@@ -134,7 +134,7 @@
//usage: "\n -lu List atime"
//usage: )
//usage: IF_FEATURE_LS_TIMESTAMPS(IF_LONG_OPTS(
//usage: "\n --full-time List full date/time"
//usage: "\n --full-time List full date and time"
//usage: ))
//usage: IF_FEATURE_HUMAN_READABLE(
//usage: "\n -h Human readable sizes (1K 243M 2G)"
@@ -160,7 +160,7 @@
//usage: "\n -w N Format N columns wide"
//usage: )
//usage: IF_FEATURE_LS_COLOR(
//usage: "\n --color[={always,never,auto}]"
//usage: "\n --color[={always,never,auto}] Control coloring"
//usage: )
#include "libbb.h"
@@ -187,7 +187,7 @@
enum {
TERMINAL_WIDTH = 80, /* use 79 if terminal has linefold bug */
TERMINAL_WIDTH = 80, /* use 79 if terminal has linefold bug */
SPLIT_FILE = 0,
SPLIT_DIR = 1,
@@ -298,7 +298,7 @@ struct dnode {
// but there are invisible fields as well
// (such as nanosecond-resolution timespamps)
// and padding, which we also don't want to store.
// We also pre-parse dev_t dn_rdev (in glibc, it's huge).
// We also can pre-parse dev_t dn_rdev (in glibc, it's huge).
// On 32-bit uclibc: dnode size went from 112 to 84 bytes.
//
/* Same names as in struct stat, but with dn_ instead of st_ pfx: */
@@ -453,7 +453,7 @@ static unsigned print_name(const char *name)
name = printable_string2(&uni_stat, name);
if (!(option_mask32 & OPT_Q)) {
fputs_stdout(name);
fputs(name, stdout);
return uni_stat.unicode_width;
}
@@ -1145,15 +1145,11 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
#if ENABLE_FEATURE_LS_COLOR
/* set G_show_color = 1/0 */
if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && !is_TERM_dumb()) {
if (ENABLE_FEATURE_LS_COLOR_IS_DEFAULT && isatty(STDOUT_FILENO)) {
char *p = getenv("LS_COLORS");
/* LS_COLORS is unset, or (not empty && not "none") ? */
if (!p || (p[0] && strcmp(p, "none") != 0)) {
if (isatty(STDOUT_FILENO)) {
/* check isatty() last because it's expensive (syscall) */
G_show_color = 1;
}
}
if (!p || (p[0] && strcmp(p, "none") != 0))
G_show_color = 1;
}
if (opt & OPT_color) {
if (color_opt[0] == 'n')
@@ -1162,7 +1158,7 @@ int ls_main(int argc UNUSED_PARAM, char **argv)
case 3:
case 4:
case 5:
if (!is_TERM_dumb() && isatty(STDOUT_FILENO)) {
if (isatty(STDOUT_FILENO)) {
case 0:
case 1:
case 2:
+1 -3
View File
@@ -36,9 +36,7 @@
//usage: "$ mknod /dev/fd0 b 2 0\n"
//usage: "$ mknod -m 644 /tmp/pipe p\n"
#ifdef __linux__
# include <sys/sysmacros.h> // For makedev
#endif
#include <sys/sysmacros.h> // For makedev
#include "libbb.h"
#include "libcoreutils/coreutils.h"
+26 -52
View File
@@ -23,15 +23,13 @@
//kbuild:lib-$(CONFIG_MV) += mv.o
//usage:#define mv_trivial_usage
//usage: "[-finT] SOURCE DEST\n"
//usage: "or: mv [-fin] SOURCE... { -t DIRECTORY | DIRECTORY }"
//usage: "[-fin] SOURCE DEST\n"
//usage: "or: mv [-fin] SOURCE... DIRECTORY"
//usage:#define mv_full_usage "\n\n"
//usage: "Rename SOURCE to DEST, or move SOURCEs to DIRECTORY\n"
//usage: "Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY\n"
//usage: "\n -f Don't prompt before overwriting"
//usage: "\n -i Interactive, prompt before overwrite"
//usage: "\n -n Don't overwrite an existing file"
//usage: "\n -T Refuse to move if DEST is a directory"
//usage: "\n -t DIR Move all SOURCEs into DIR"
//usage:
//usage:#define mv_example_usage
//usage: "$ mv /tmp/foo /bin/bar\n"
@@ -42,7 +40,7 @@
int mv_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int mv_main(int argc, char **argv)
{
struct stat statbuf;
struct stat dest_stat;
const char *last;
const char *dest;
unsigned flags;
@@ -53,66 +51,41 @@ int mv_main(int argc, char **argv)
#define OPT_FORCE (1 << 0)
#define OPT_INTERACTIVE (1 << 1)
#define OPT_NOCLOBBER (1 << 2)
#define OPT_DESTNOTDIR (1 << 3)
#define OPT_DESTDIR (1 << 4)
#define OPT_VERBOSE ((1 << 5) * ENABLE_FEATURE_VERBOSE)
#define OPT_VERBOSE ((1 << 3) * ENABLE_FEATURE_VERBOSE)
/* Need at least two arguments.
* If more than one of -f, -i, -n is specified , only the final one
* takes effect (it unsets previous options).
*/
flags = getopt32long(argv, "^"
"finTt:v"
"finv"
"\0"
/* At least one argument. (Usually two+, but -t DIR can have only one) */
"-1"
/* only the final one of -f, -i, -n takes effect */
":f-in:i-fn:n-fi"
/* -t and -T don't mix */
":t--T:T--t",
"-2:f-in:i-fn:n-fi",
"interactive\0" No_argument "i"
"force\0" No_argument "f"
"no-clobber\0" No_argument "n"
"no-target-directory\0" No_argument "T"
"target-directory\0" Required_argument "t"
IF_FEATURE_VERBOSE(
"verbose\0" No_argument "v",
&last
"verbose\0" No_argument "v"
)
);
argc -= optind;
argv += optind;
last = argv[argc - 1];
if (!(flags & OPT_DESTDIR)) {
last = argv[argc - 1];
if (argc < 2)
bb_show_usage();
if (argc != 2) {
if (flags & OPT_DESTNOTDIR)
bb_show_usage();
/* "mv A B C... DIR" - target must be dir */
} else /* argc == 2 */ {
/* "mv A B" - only case where target can be not a dir */
dest_exists = cp_mv_stat(last, &statbuf);
if (dest_exists < 0) { /* error other than ENOENT */
return EXIT_FAILURE;
}
if (!(dest_exists & 2)) {
/* last is not a directory */
dest = last;
goto DO_MOVE;
}
/* last is a directory */
if (flags & OPT_DESTNOTDIR) {
if (stat(argv[0], &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
bb_error_msg_and_die("'%s' is a directory", last);
/* "mv -T DIR1 DIR2" is allowed (renames a dir) */
dest = last;
goto DO_MOVE;
}
/* else: fall through into "do { move SRC to DIR/SRC } while" loop */
if (argc == 2) {
dest_exists = cp_mv_stat(last, &dest_stat);
if (dest_exists < 0) {
return EXIT_FAILURE;
}
if (!(dest_exists & 2)) { /* last is not a directory */
dest = last;
goto DO_MOVE;
}
}
/* else: last is DIR from "-t DIR" */
do {
dest = concat_path_file(last, bb_get_last_path_component_strip(*argv));
dest_exists = cp_mv_stat(dest, &statbuf);
dest_exists = cp_mv_stat(dest, &dest_stat);
if (dest_exists < 0) {
goto RET_1;
}
@@ -135,10 +108,11 @@ int mv_main(int argc, char **argv)
}
if (rename(*argv, dest) < 0) {
struct stat source_stat;
int source_exists;
if (errno != EXDEV
|| (source_exists = cp_mv_stat2(*argv, &statbuf, lstat)) < 1
|| (source_exists = cp_mv_stat2(*argv, &source_stat, lstat)) < 1
) {
bb_perror_msg("can't rename '%s'", *argv);
} else {
@@ -185,7 +159,7 @@ int mv_main(int argc, char **argv)
if (dest != last) {
free((void *) dest);
}
} while (*++argv && *argv != last);
} while (*++argv != last);
return status;
}
+1 -1
View File
@@ -68,7 +68,7 @@ int nl_main(int argc UNUSED_PARAM, char **argv)
&ns.width, &ns.sep, &ns.start, &ns.inc, &opt_b);
ns.all = (opt_b[0] == 'a');
ns.nonempty = (opt_b[0] == 't');
ns.empty_str = xasprintf("%*s", ns.width + (int)strlen(ns.sep), "");
ns.empty_str = xasprintf("%*s\n", ns.width + (int)strlen(ns.sep), "");
argv += optind;
if (!*argv)
+2 -2
View File
@@ -14,7 +14,7 @@
//kbuild:lib-$(CONFIG_NPROC) += nproc.o
//usage:#define nproc_trivial_usage
//usage: ""IF_LONG_OPTS("[--all] [--ignore=N]")
//usage: ""IF_LONG_OPTS("--all --ignore=N")
//usage:#define nproc_full_usage "\n\n"
//usage: "Print number of available CPUs"
//usage: IF_LONG_OPTS(
@@ -48,7 +48,7 @@ int nproc_main(int argc UNUSED_PARAM, char **argv UNUSED_PARAM)
if (cpuid && isdigit(cpuid[strlen(cpuid) - 1]))
count++;
}
IF_FEATURE_CLEAN_UP(closedir(cpusd);)
closedir(cpusd);
}
} else
#endif
+13 -13
View File
@@ -422,19 +422,19 @@ print_named_ascii(size_t n_bytes, const char *block,
masked_c &= 0x7f;
if (masked_c == 0x7f) {
fputs_stdout(" del");
fputs(" del", stdout);
continue;
}
if (masked_c > ' ') {
buf[3] = masked_c;
fputs_stdout(buf);
fputs(buf, stdout);
continue;
}
/* Why? Because printf(" %3.3s") is much slower... */
buf[6] = charname[masked_c][0];
buf[7] = charname[masked_c][1];
buf[8] = charname[masked_c][2];
fputs_stdout(buf+5);
fputs(buf+5, stdout);
}
}
@@ -451,7 +451,7 @@ print_ascii(size_t n_bytes, const char *block,
if (ISPRINT(c)) {
buf[3] = c;
fputs_stdout(buf);
fputs(buf, stdout);
continue;
}
switch (c) {
@@ -485,7 +485,7 @@ print_ascii(size_t n_bytes, const char *block,
buf[8] = (c & 7) + '0';
s = buf + 5;
}
fputs_stdout(s);
fputs(s, stdout);
}
}
@@ -881,7 +881,7 @@ format_address_label(off_t address, char c)
static void
dump_hexl_mode_trailer(size_t n_bytes, const char *block)
{
fputs_stdout(" >");
fputs(" >", stdout);
while (n_bytes--) {
unsigned c = *(unsigned char *) block++;
c = (ISPRINT(c) ? c : '.');
@@ -1121,13 +1121,13 @@ dump_strings(off_t address, off_t end_offset)
for (i = 0; (c = buf[i]); i++) {
switch (c) {
case '\007': fputs_stdout("\\a"); break;
case '\b': fputs_stdout("\\b"); break;
case '\f': fputs_stdout("\\f"); break;
case '\n': fputs_stdout("\\n"); break;
case '\r': fputs_stdout("\\r"); break;
case '\t': fputs_stdout("\\t"); break;
case '\v': fputs_stdout("\\v"); break;
case '\007': fputs("\\a", stdout); break;
case '\b': fputs("\\b", stdout); break;
case '\f': fputs("\\f", stdout); break;
case '\n': fputs("\\n", stdout); break;
case '\r': fputs("\\r", stdout); break;
case '\t': fputs("\\t", stdout); break;
case '\v': fputs("\\v", stdout); break;
default: putchar(c);
}
}
+2 -2
View File
@@ -53,7 +53,7 @@ static void paste_files(FILE** files, int file_cnt, char* delims, int del_cnt)
--active_files;
continue;
}
fputs_stdout(line);
fputs(line, stdout);
free(line);
delim = '\n';
if (i != file_cnt - 1) {
@@ -79,7 +79,7 @@ static void paste_files_separate(FILE** files, char* delims, int del_cnt)
line = NULL;
while ((next_line = xmalloc_fgetline(files[i])) != NULL) {
if (line) {
fputs_stdout(line);
fputs(line, stdout);
free(line);
delim = delims[del_idx++];
if (del_idx == del_cnt)
-1
View File
@@ -122,7 +122,6 @@ static void FAST_FUNC conv_strtod(const char *arg, void *result)
char *end;
/* Well, this one allows leading whitespace... so what? */
/* What I like much less is that "-" accepted too! :( */
//TODO: needs setlocale(LC_NUMERIC, "C")?
*(double*)result = strtod(arg, &end);
if (end[0]) {
errno = ERANGE;
+1 -1
View File
@@ -23,7 +23,7 @@
//usage:#define realpath_trivial_usage
//usage: "FILE..."
//usage:#define realpath_full_usage "\n\n"
//usage: "Print absolute pathnames of FILEs"
//usage: "Return the absolute pathnames of given FILE"
#include "libbb.h"
+11 -16
View File
@@ -15,15 +15,14 @@
//kbuild:lib-$(CONFIG_SHRED) += shred.o
//usage:#define shred_trivial_usage
//usage: "[-fuz] [-n N] [-s SIZE] FILE..."
//usage: "FILE..."
//usage:#define shred_full_usage "\n\n"
//usage: "Overwrite/delete FILEs\n"
//usage: "\n -f Chmod to ensure writability"
//usage: "\n -s SIZE Size to write"
//usage: "\n -n N Overwrite N times (default 3)"
//usage: "\n -z Final overwrite with zeros"
//usage: "\n -u Remove file"
//-x (exact: don't round up to 4k) and -v (verbose) are accepted but have no effect
//-x and -v are accepted but have no effect
/* shred (GNU coreutils) 8.25:
-f, --force change permissions to allow writing if necessary
@@ -42,7 +41,6 @@
int shred_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int shred_main(int argc UNUSED_PARAM, char **argv)
{
char *opt_s;
int rand_fd = rand_fd; /* for compiler */
int zero_fd;
unsigned num_iter = 3;
@@ -54,16 +52,18 @@ int shred_main(int argc UNUSED_PARAM, char **argv)
OPT_n = (1 << 3),
OPT_v = (1 << 4),
OPT_x = (1 << 5),
OPT_s = (1 << 6),
};
opt = getopt32(argv, "^" "fuzn:+vxs:" "\0" "-1"/*min 1 arg*/, &num_iter, &opt_s);
opt = getopt32(argv, "fuzn:+vx", &num_iter);
argv += optind;
zero_fd = xopen("/dev/zero", O_RDONLY);
if (num_iter != 0)
rand_fd = xopen("/dev/urandom", O_RDONLY);
if (!*argv)
bb_show_usage();
for (;;) {
struct stat sb;
const char *fname;
@@ -85,11 +85,6 @@ int shred_main(int argc UNUSED_PARAM, char **argv)
if (fstat(fd, &sb) == 0 && sb.st_size > 0) {
off_t size = sb.st_size;
if (opt & OPT_s) {
size = BB_STRTOOFF(opt_s, NULL, 0); /* accepts oct/hex */
if (errno || size < 0) bb_show_usage();
}
for (i = 0; i < num_iter; i++) {
bb_copyfd_size(rand_fd, fd, size);
fdatasync(fd);
@@ -99,12 +94,12 @@ int shred_main(int argc UNUSED_PARAM, char **argv)
bb_copyfd_size(zero_fd, fd, size);
fdatasync(fd);
}
if (opt & OPT_u) {
ftruncate(fd, 0);
xunlink(fname);
}
xclose(fd);
}
if (opt & OPT_u) {
ftruncate(fd, 0);
xunlink(fname);
}
xclose(fd);
}
return EXIT_SUCCESS;
+4
View File
@@ -74,6 +74,10 @@ int sleep_main(int argc UNUSED_PARAM, char **argv)
sleep(INT_MAX);
#if ENABLE_FEATURE_FANCY_SLEEP
# if ENABLE_FLOAT_DURATION
/* undo busybox.c setlocale */
setlocale(LC_NUMERIC, "C");
# endif
duration = 0;
do {
duration += parse_duration_str(*argv);
+1 -2
View File
@@ -67,7 +67,7 @@
//usage: "\n -r Reverse sort order"
//usage: "\n -s Stable (don't sort ties alphabetically)"
//usage: "\n -u Suppress duplicate lines"
//usage: "\n -z NUL terminated input and output"
//usage: "\n -z Lines are terminated by NUL, not newline"
///////: "\n -m Ignored for GNU compatibility"
///////: "\n -S BUFSZ Ignored for GNU compatibility"
///////: "\n -T TMPDIR Ignored for GNU compatibility"
@@ -295,7 +295,6 @@ static int compare_keys(const void *xarg, const void *yarg)
#if ENABLE_FEATURE_SORT_BIG
case FLAG_g: {
char *xx, *yy;
//TODO: needs setlocale(LC_NUMERIC, "C")?
double dx = strtod(x, &xx);
double dy = strtod(y, &yy);
/* not numbers < NaN < -infinity < numbers < +infinity) */
+1 -1
View File
@@ -439,7 +439,7 @@ static void print_it(const char *masterformat,
/* print preceding string */
*p = '\0';
fputs_stdout(b);
fputs(b, stdout);
p += len;
b = p + 1;
+1 -1
View File
@@ -855,7 +855,7 @@ static void wrapf(const char *message, ...)
}
}
}
fputs_stdout(buf);
fputs(buf, stdout);
G.current_col += buflen;
if (buf[buflen-1] == '\n')
G.current_col = 0;
+27 -42
View File
@@ -48,20 +48,19 @@
//usage:#define tail_trivial_usage
//usage: "[OPTIONS] [FILE]..."
//usage:#define tail_full_usage "\n\n"
//usage: "Print last 10 lines of FILEs (or stdin) to.\n"
//usage: "Print last 10 lines of each FILE (or stdin) to stdout.\n"
//usage: "With more than one FILE, precede each with a filename header.\n"
//usage: "\n -c [+]N[bkm] Print last N bytes"
//usage: "\n -n N[bkm] Print last N lines"
//usage: "\n -n +N[bkm] Start on Nth line and print the rest"
//usage: "\n (b:*512 k:*1024 m:*1024^2)"
//usage: "\n -f Print data as file grows"
//usage: "\n -c [+]N[kbm] Print last N bytes"
//usage: "\n -n N[kbm] Print last N lines"
//usage: "\n -n +N[kbm] Start on Nth line and print the rest"
//usage: IF_FEATURE_FANCY_TAIL(
//usage: "\n -q Never print headers"
//usage: "\n -v Always print headers"
//usage: )
//usage: "\n -f Print data as file grows"
//usage: IF_FEATURE_FANCY_TAIL(
//usage: "\n -F Same as -f, but keep retrying"
//usage: "\n -s SECONDS Wait SECONDS between reads with -f"
//usage: "\n -v Always print headers"
//usage: "\n -F Same as -f, but keep retrying"
//usage: "\n"
//usage: "\nN may be suffixed by k (x1024), b (x512), or m (x1024^2)."
//usage: )
//usage:
//usage:#define tail_example_usage
@@ -119,7 +118,7 @@ int tail_main(int argc, char **argv)
char *tailbuf;
size_t tailbufsize;
unsigned header_threshold = 1;
unsigned header_threshhold = 1;
unsigned nfiles;
int i, opt;
@@ -152,10 +151,10 @@ int tail_main(int argc, char **argv)
if (opt & 0x2) count = eat_num(str_c); // -c
if (opt & 0x4) count = eat_num(str_n); // -n
#if ENABLE_FEATURE_FANCY_TAIL
/* q: make it impossible for nfiles to be > header_threshold */
if (opt & 0x8) header_threshold = UINT_MAX; // -q
/* q: make it impossible for nfiles to be > header_threshhold */
if (opt & 0x8) header_threshhold = UINT_MAX; // -q
//if (opt & 0x10) // -s
if (opt & 0x20) header_threshold = 0; // -v
if (opt & 0x20) header_threshhold = 0; // -v
# define FOLLOW_RETRY (opt & 0x40)
#else
# define FOLLOW_RETRY 0
@@ -216,7 +215,7 @@ int tail_main(int argc, char **argv)
if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
continue; /* may happen with -F */
if (nfiles > header_threshold) {
if (nfiles > header_threshhold) {
tail_xprint_header(fmt, argv[i]);
fmt = header_fmt_str;
}
@@ -346,11 +345,9 @@ int tail_main(int argc, char **argv)
int nread;
const char *filename = argv[i];
int fd = fds[i];
int new_fd = -1;
struct stat sbuf;
if (FOLLOW_RETRY) {
struct stat fsbuf;
struct stat sbuf, fsbuf;
if (fd < 0
|| fstat(fd, &fsbuf) < 0
@@ -358,51 +355,39 @@ int tail_main(int argc, char **argv)
|| fsbuf.st_dev != sbuf.st_dev
|| fsbuf.st_ino != sbuf.st_ino
) {
/* Looks like file has been created/renamed/deleted */
int new_fd;
if (fd >= 0)
close(fd);
new_fd = open(filename, O_RDONLY);
if (new_fd >= 0) {
bb_error_msg("%s has %s; following end of new file",
filename, (fd < 0) ? "appeared" : "been replaced"
);
if (fd < 0) {
/* No previously open fd for this file,
* start using new_fd immediately. */
fds[i] = fd = new_fd;
new_fd = -1;
}
} else if (fd >= 0) {
bb_perror_msg("%s has been renamed or deleted", filename);
bb_perror_msg("%s has become inaccessible", filename);
}
fds[i] = fd = new_fd;
}
}
if (ENABLE_FEATURE_FANCY_TAIL && fd < 0)
continue;
if (nfiles > header_threshold) {
if (nfiles > header_threshhold) {
fmt = header_fmt_str;
}
for (;;) {
/* tail -f keeps following files even if they are truncated */
struct stat sbuf;
/* /proc files report zero st_size, don't lseek them */
if (fstat(fd, &sbuf) == 0
/* && S_ISREG(sbuf.st_mode) TODO? */
&& sbuf.st_size > 0
) {
if (fstat(fd, &sbuf) == 0 && sbuf.st_size > 0) {
off_t current = lseek(fd, 0, SEEK_CUR);
if (sbuf.st_size < current) {
//bb_perror_msg("%s: file truncated", filename); - says coreutils 8.32
if (sbuf.st_size < current)
xlseek(fd, 0, SEEK_SET);
}
}
nread = tail_read(fd, tailbuf, BUFSIZ);
if (nread <= 0) {
if (new_fd < 0)
break;
/* Switch to "tail -F"ing the new file */
xmove_fd(new_fd, fd);
new_fd = -1;
continue;
}
if (nread <= 0)
break;
if (fmt && (fd != prev_fd)) {
tail_xprint_header(fmt, filename);
fmt = NULL;
+74 -69
View File
@@ -19,8 +19,16 @@
//config: touch is used to create or change the access and/or
//config: modification timestamp of specified files.
//config:
//config:config FEATURE_TOUCH_NODEREF
//config: bool "Add support for -h"
//config: default y
//config: depends on TOUCH
//config: help
//config: Enable touch to have the -h option.
//config: This requires libc support for lutimes() function.
//config:
//config:config FEATURE_TOUCH_SUSV3
//config: bool "Add support for SUSV3 features (-a -d -m -t -r)"
//config: bool "Add support for SUSV3 features (-d -t -r)"
//config: default y
//config: depends on TOUCH
//config: help
@@ -30,17 +38,18 @@
//kbuild:lib-$(CONFIG_TOUCH) += touch.o
/* BB_AUDIT SUSv3 _NOT_ compliant -- options -a, -m not supported. */
/* http://www.opengroup.org/onlinepubs/007904975/utilities/touch.html */
//usage:#define touch_trivial_usage
//usage: "[-ch" IF_FEATURE_TOUCH_SUSV3("am") "]"
//usage: IF_FEATURE_TOUCH_SUSV3(" [-d DATE] [-t DATE] [-r FILE]")
//usage: " FILE..."
//usage: "[-c]" IF_FEATURE_TOUCH_SUSV3(" [-d DATE] [-t DATE] [-r FILE]") " FILE..."
//usage:#define touch_full_usage "\n\n"
//usage: "Update mtime of FILEs\n"
//usage: "Update the last-modified date on the given FILE[s]\n"
//usage: "\n -c Don't create files"
//usage: IF_FEATURE_TOUCH_NODEREF(
//usage: "\n -h Don't follow links"
//usage: )
//usage: IF_FEATURE_TOUCH_SUSV3(
//usage: "\n -a Change only atime"
//usage: "\n -m Change only mtime"
//usage: "\n -d DT Date/time to use"
//usage: "\n -t DT Date/time to use"
//usage: "\n -r FILE Use FILE's date/time"
@@ -76,68 +85,70 @@ int touch_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int touch_main(int argc UNUSED_PARAM, char **argv)
{
int fd;
int status = EXIT_SUCCESS;
int opts;
smalluint status = EXIT_SUCCESS;
enum {
OPT_c = (1 << 0),
OPT_r = (1 << 1) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_d = (1 << 2) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_t = (1 << 3) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_h = (1 << 4) * ENABLE_FEATURE_TOUCH_NODEREF,
};
#if ENABLE_FEATURE_TOUCH_SUSV3
char *reference_file;
char *date_str;
/* timebuf[0] is atime, timebuf[1] is mtime */
struct timespec timebuf[2];
# if ENABLE_LONG_OPTS
static const char touch_longopts[] ALIGN1 =
/* name, has_arg, val */
"no-create\0" No_argument "c"
"reference\0" Required_argument "r"
"date\0" Required_argument "d"
IF_FEATURE_TOUCH_NODEREF("no-dereference\0" No_argument "h")
;
# define GETOPT32 getopt32long
# define LONGOPTS ,touch_longopts
# else
# define GETOPT32 getopt32
# define LONGOPTS
# endif
char *reference_file = NULL;
char *date_str = NULL;
struct timeval timebuf[2];
timebuf[1].tv_usec = timebuf[0].tv_usec = 0;
#else
# define reference_file NULL
# define date_str NULL
# define timebuf ((struct timespec*)NULL)
# define timebuf ((struct timeval*)NULL)
# define GETOPT32 getopt32
# define LONGOPTS
#endif
enum {
OPT_c = (1 << 0),
OPT_h = (1 << 1),
OPT_r = (1 << 2) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_d = (1 << 3) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_t = (1 << 4) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_a = (1 << 5) * ENABLE_FEATURE_TOUCH_SUSV3,
OPT_m = (1 << 6) * ENABLE_FEATURE_TOUCH_SUSV3,
};
#if ENABLE_LONG_OPTS
static const char touch_longopts[] ALIGN1 =
/* name, has_arg, val */
"no-create\0" No_argument "c"
"no-dereference\0" No_argument "h"
IF_FEATURE_TOUCH_SUSV3("reference\0" Required_argument "r")
IF_FEATURE_TOUCH_SUSV3("date\0" Required_argument "d")
;
#endif
/* -d and -t both set time. In coreutils,
* accepted data format differs a bit between -d and -t.
* We accept the same formats for both
*/
opts = getopt32long(argv, "^"
"ch"
IF_FEATURE_TOUCH_SUSV3("r:d:t:am")
/*ignored:*/ "f" IF_NOT_FEATURE_TOUCH_SUSV3("am")
"\0" /* opt_complementary: */
/* at least one arg: */ "-1"
/* coreutils forbids -r and -t at once: */ IF_FEATURE_TOUCH_SUSV3(":r--t:t--r")
/* but allows these combinations: "r--d:d--r:t--d:d--t" */
, touch_longopts
#if ENABLE_FEATURE_TOUCH_SUSV3
, &reference_file
, &date_str
, &date_str
#endif
* We accept the same formats for both */
opts = GETOPT32(argv, "c" IF_FEATURE_TOUCH_SUSV3("r:d:t:")
IF_FEATURE_TOUCH_NODEREF("h")
/*ignored:*/ "fma"
LONGOPTS
IF_FEATURE_TOUCH_SUSV3(, &reference_file)
IF_FEATURE_TOUCH_SUSV3(, &date_str)
IF_FEATURE_TOUCH_SUSV3(, &date_str)
);
#if ENABLE_FEATURE_TOUCH_SUSV3
timebuf[0].tv_nsec = timebuf[1].tv_nsec = UTIME_NOW;
if (opts & OPT_r) {
argv += optind;
if (!*argv) {
bb_show_usage();
}
if (reference_file) {
struct stat stbuf;
xstat(reference_file, &stbuf);
timebuf[0].tv_sec = stbuf.st_atime;
timebuf[1].tv_sec = stbuf.st_mtime;
timebuf[0].tv_nsec = stbuf.st_atim.tv_nsec;
timebuf[1].tv_nsec = stbuf.st_mtim.tv_nsec;
timebuf[1].tv_sec = timebuf[0].tv_sec = stbuf.st_mtime;
/* Can use .st_mtim.tv_nsec
* (or is it .st_mtimensec?? see date.c)
* to set microseconds too.
*/
}
if (opts & (OPT_d|OPT_t)) {
if (date_str) {
struct tm tm_time;
time_t t;
@@ -152,21 +163,15 @@ int touch_main(int argc UNUSED_PARAM, char **argv)
t = validate_tm_time(date_str, &tm_time);
timebuf[1].tv_sec = timebuf[0].tv_sec = t;
timebuf[1].tv_nsec = timebuf[0].tv_nsec = 0;
}
/* If both -a and -m specified, both times should be set.
* IOW: set OMIT only if one, not both, of them is given!
*/
if ((opts & (OPT_a|OPT_m)) == OPT_a)
timebuf[1].tv_nsec = UTIME_OMIT;
if ((opts & (OPT_a|OPT_m)) == OPT_m)
timebuf[0].tv_nsec = UTIME_OMIT;
#endif
argv += optind;
do {
int result = utimensat(AT_FDCWD, *argv, timebuf,
(opts & OPT_h) ? AT_SYMLINK_NOFOLLOW : 0);
int result;
result = (
#if ENABLE_FEATURE_TOUCH_NODEREF
(opts & OPT_h) ? lutimes :
#endif
utimes)(*argv, (reference_file || date_str) ? timebuf : NULL);
if (result != 0) {
if (errno == ENOENT) { /* no such file? */
if (opts & OPT_c) {
@@ -176,9 +181,9 @@ int touch_main(int argc UNUSED_PARAM, char **argv)
/* Try to create the file */
fd = open(*argv, O_RDWR | O_CREAT, 0666);
if (fd >= 0) {
if (opts & (OPT_r|OPT_d|OPT_t))
futimens(fd, timebuf);
xclose(fd);
if (reference_file || date_str)
utimes(*argv, timebuf);
continue;
}
}
+2 -2
View File
@@ -19,9 +19,9 @@
//usage:#define truncate_trivial_usage
//usage: "[-c] -s SIZE FILE..."
//usage:#define truncate_full_usage "\n\n"
//usage: "Truncate FILEs to SIZE\n"
//usage: "Truncate FILEs to the given size\n"
//usage: "\n -c Do not create files"
//usage: "\n -s SIZE"
//usage: "\n -s SIZE Truncate to SIZE"
//usage:
//usage:#define truncate_example_usage
//usage: "$ truncate -s 1G foo"
+1 -1
View File
@@ -21,7 +21,7 @@
/* http://www.opengroup.org/onlinepubs/9699919799/utilities/tty.html */
//usage:#define tty_trivial_usage
//usage: "" IF_INCLUDE_SUSv2("[-s]")
//usage: ""
//usage:#define tty_full_usage "\n\n"
//usage: "Print file name of stdin's terminal"
//usage: IF_INCLUDE_SUSv2( "\n"
+2 -2
View File
@@ -79,13 +79,13 @@
//usage:#define uname_full_usage "\n\n"
//usage: "Print system information\n"
//usage: "\n -a Print all"
//usage: "\n -m Machine (hardware) type"
//usage: "\n -m The machine (hardware) type"
//usage: "\n -n Hostname"
//usage: "\n -r Kernel release"
//usage: "\n -s Kernel name (default)"
//usage: "\n -p Processor type"
//usage: "\n -v Kernel version"
//usage: "\n -i Hardware platform"
//usage: "\n -i The hardware platform"
//usage: "\n -o OS name"
//usage:
//usage:#define uname_example_usage
+10 -14
View File
@@ -20,14 +20,13 @@
/* http://www.opengroup.org/onlinepubs/007904975/utilities/uniq.html */
//usage:#define uniq_trivial_usage
//usage: "[-cduiz] [-f,s,w N] [FILE [OUTFILE]]"
//usage: "[-cdui] [-f,s,w N] [INPUT [OUTPUT]]"
//usage:#define uniq_full_usage "\n\n"
//usage: "Discard duplicate lines\n"
//usage: "\n -c Prefix lines by the number of occurrences"
//usage: "\n -d Only print duplicate lines"
//usage: "\n -u Only print unique lines"
//usage: "\n -i Ignore case"
//usage: "\n -z NUL terminated output"
//usage: "\n -f N Skip first N fields"
//usage: "\n -s N Skip first N chars (after any skipped fields)"
//usage: "\n -w N Compare N characters in line"
@@ -46,25 +45,23 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
const char *input_filename;
unsigned skip_fields, skip_chars, max_chars;
unsigned opt;
char eol;
char *cur_line;
const char *cur_compare;
enum {
OPT_c = 1 << 0,
OPT_d = 1 << 1, /* print only dups */
OPT_u = 1 << 2, /* print only uniq */
OPT_f = 1 << 3,
OPT_s = 1 << 4,
OPT_w = 1 << 5,
OPT_i = 1 << 6,
OPT_z = 1 << 7,
OPT_c = 0x1,
OPT_d = 0x2, /* print only dups */
OPT_u = 0x4, /* print only uniq */
OPT_f = 0x8,
OPT_s = 0x10,
OPT_w = 0x20,
OPT_i = 0x40,
};
skip_fields = skip_chars = 0;
max_chars = INT_MAX;
opt = getopt32(argv, "cduf:+s:+w:+iz", &skip_fields, &skip_chars, &max_chars);
opt = getopt32(argv, "cduf:+s:+w:+i", &skip_fields, &skip_chars, &max_chars);
argv += optind;
input_filename = argv[0];
@@ -89,7 +86,6 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
}
cur_compare = cur_line = NULL; /* prime the pump */
eol = (opt & OPT_z) ? 0 : '\n';
do {
unsigned i;
@@ -131,7 +127,7 @@ int uniq_main(int argc UNUSED_PARAM, char **argv)
/* %7lu matches GNU coreutils 6.9 */
printf("%7lu ", dups + 1);
}
printf("%s%c", old_line, eol);
puts(old_line);
}
free(old_line);
}
+5 -7
View File
@@ -183,7 +183,7 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
//usage:#define base32_trivial_usage
//usage: "[-d] [-w COL] [FILE]"
//usage:#define base32_full_usage "\n\n"
//usage: "Base32 encode or decode FILE to standard output\n"
//usage: "Base32 encode or decode FILE to standard output"
//usage: "\n -d Decode data"
//usage: "\n -w COL Wrap lines at COL (default 76, 0 disables)"
////usage: "\n -i When decoding, ignore non-alphabet characters"
@@ -191,12 +191,10 @@ int uudecode_main(int argc UNUSED_PARAM, char **argv)
//usage:#define base64_trivial_usage
//usage: "[-d] [-w COL] [FILE]"
//usage:#define base64_full_usage "\n\n"
//usage: "Base64 encode or decode FILE to standard output\n"
//usage: "Base64 encode or decode FILE to standard output"
//usage: "\n -d Decode data"
//usage: "\n -w COL Wrap lines at COL (default 76, 0 disables)"
///////: "\n -i When decoding, ignore non-alphabet characters"
// -i is accepted but has no effect: currently, decode_base32/64() functions
// (called via read_base64()) skip invalid chars unconditionally.
////usage: "\n -i When decoding, ignore non-alphabet characters"
// APPLET_ODDNAME:name main location suid_type help
//applet:IF_BASE32(APPLET_ODDNAME(base32, baseNUM, BB_DIR_BIN, BB_SUID_DROP, base32))
@@ -274,7 +272,7 @@ int baseNUM_main(int argc UNUSED_PARAM, char **argv)
unsigned opts;
unsigned col = 76;
opts = getopt32(argv, "^" "diw:+" "\0" "?1"/* 1 arg max*/, &col);
opts = getopt32(argv, "^" "dw:+" "\0" "?1"/* 1 arg max*/, &col);
argv += optind;
if (!argv[0])
@@ -321,7 +319,7 @@ int baseNUM_main(int argc UNUSED_PARAM, char **argv)
}
if (col == 0) {
fputs_stdout(dst_buf);
fputs(dst_buf, stdout);
} else {
char *result = dst_buf;
if (rem == 0)
+1 -1
View File
@@ -80,7 +80,7 @@
//usage: "[-c"IF_UNICODE_SUPPORT("m")"lwL] [FILE]..."
//usage:
//usage:#define wc_full_usage "\n\n"
//usage: "Count lines, words, and bytes for FILEs (or stdin)\n"
//usage: "Count lines, words, and bytes for each FILE (or stdin)\n"
//usage: "\n -c Count bytes"
//usage: IF_UNICODE_SUPPORT(
//usage: "\n -m Count characters"
+1 -1
View File
@@ -78,7 +78,7 @@
// root pts/1 Mon13 3:24m 1:01 0.01s w
//usage:#define who_trivial_usage
//usage: "[-aH]"
//usage: "[-a]"
//usage:#define who_full_usage "\n\n"
//usage: "Show who is logged on\n"
//usage: "\n -a Show all"
+2 -2
View File
@@ -27,7 +27,7 @@
//usage:#define yes_trivial_usage
//usage: "[STRING]"
//usage:#define yes_full_usage "\n\n"
//usage: "Repeatedly print a line with STRING, or 'y'"
//usage: "Repeatedly output a line with STRING, or 'y'"
#include "libbb.h"
@@ -43,7 +43,7 @@ int yes_main(int argc UNUSED_PARAM, char **argv)
do {
pp = argv;
while (1) {
fputs_stdout(*pp);
fputs(*pp, stdout);
if (!*++pp)
break;
putchar(' ');
+2 -13
View File
@@ -113,24 +113,13 @@ enum {
};
/* Is this a valid filename (upper/lower alpha, digits,
* underscores, hyphens, and non-leading dots only?)
* underscores, and hyphens only?)
*/
static bool invalid_name(const char *c)
{
c = bb_basename(c);
if (*c == '.')
return *c;
/* Debian run-parts 4.8.3, manpage:
* "...the names must consist entirely of ASCII letters,
* ASCII digits, ASCII underscores, and ASCII minus-hyphens.
* However, the name must not begin with a period."
* The last sentence is a giveaway that something is fishy
* (why mention leading dot if dots are not allowed anyway?).
* Yes, you guessed it right: in fact non-leading dots ARE allowed.
*/
while (isalnum(*c) || *c == '_' || *c == '-' || *c == '.')
while (*c && (isalnum(*c) || *c == '_' || *c == '-'))
c++;
return *c; /* TRUE (!0) if terminating NUL is not reached */
-1
View File
@@ -37,7 +37,6 @@ incorrect, please send in an update.
=for html <br>
Emanuele Aina <emanuele.aina@tiscali.it>
run-parts
=for html <br>
+47 -98
View File
@@ -20,52 +20,40 @@
//kbuild:lib-$(CONFIG_CHATTR) += chattr.o e2fs_lib.o
//usage:#define chattr_trivial_usage
//usage: "[-R] [-v VERSION] [-p PROJID] [-+=AacDdijsStTu] FILE..."
//usage: "[-R] [-v VERSION] [-+=AacDdijsStTu] FILE..."
//usage:#define chattr_full_usage "\n\n"
//usage: "Change ext2 file attributes\n"
//usage: "\n -R Recurse"
//usage: "\n -v NUM Set version/generation number"
//usage: "\n -p NUM Set project number"
//usage: "\n -v VER Set version/generation number"
//-V, -f accepted but ignored
//usage: "\nModifiers:"
//usage: "\n -,+,= Remove/add/set attributes"
//usage: "\nAttributes:"
//usage: "\n A No atime"
//usage: "\n a Append only"
//usage: "\n C No copy-on-write"
//usage: "\n c Compressed"
//usage: "\n D Synchronous dir updates"
//usage: "\n A Don't track atime"
//usage: "\n a Append mode only"
//usage: "\n c Enable compress"
//usage: "\n D Write dir contents synchronously"
//usage: "\n d Don't backup with dump"
//usage: "\n E Encrypted"
//usage: "\n e File uses extents"
//usage: "\n F Case-insensitive dir"
//usage: "\n I Indexed dir"
//usage: "\n i Immutable"
//usage: "\n j Write data to journal first"
//usage: "\n N File is stored in inode"
//usage: "\n P Hierarchical project ID dir"
//usage: "\n S Synchronous file updates"
//usage: "\n s Zero storage when deleted"
//usage: "\n T Top of dir hierarchy"
//usage: "\n t Don't tail-merge with other files"
//usage: "\n u Allow undelete"
//usage: "\n V Verity"
//usage: "\n i Cannot be modified (immutable)"
//usage: "\n j Write all data to journal first"
//usage: "\n s Zero disk storage when deleted"
//usage: "\n S Write synchronously"
//usage: "\n t Disable tail-merging of partial blocks with other files"
//usage: "\n u Allow file to be undeleted"
#include "libbb.h"
#include "e2fs_lib.h"
#define OPT_ADD (1 << 0)
#define OPT_REM (1 << 1)
#define OPT_SET (1 << 2)
#define OPT_SET_VER (1 << 3)
#define OPT_SET_PROJ (1 << 4)
#define OPT_ADD 1
#define OPT_REM 2
#define OPT_SET 4
#define OPT_SET_VER 8
struct globals {
unsigned version;
unsigned af;
unsigned rf;
unsigned long version;
unsigned long af;
unsigned long rf;
int flags;
uint32_t projid;
smallint recursive;
};
@@ -79,15 +67,13 @@ static unsigned long get_flag(char c)
static char** decode_arg(char **argv, struct globals *gp)
{
unsigned *fl;
unsigned long *fl;
const char *arg = *argv;
char opt = *arg;
fl = &gp->af;
if (opt == '-') {
/* gp->flags |= OPT_REM; - WRONG, it can be an option */
/* testcase: chattr =ae -R FILE should not complain "= is incompatible with - and +" */
/* (and should not read flags, with =FLAGS they can be just set directly) */
gp->flags |= OPT_REM;
fl = &gp->rf;
} else if (opt == '+') {
gp->flags |= OPT_ADD;
@@ -117,21 +103,14 @@ static char** decode_arg(char **argv, struct globals *gp)
if (*arg == 'v') {
if (!*++argv)
bb_show_usage();
gp->version = xatou(*argv);
gp->version = xatoul(*argv);
gp->flags |= OPT_SET_VER;
continue;
}
if (*arg == 'p') {
if (!*++argv)
bb_show_usage();
gp->projid = xatou32(*argv);
gp->flags |= OPT_SET_PROJ;
continue;
}
//TODO: "-p PROJECT_NUM" ?
/* not a known option, try as an attribute */
gp->flags |= OPT_REM;
}
*fl |= get_flag(*arg); /* aborts on bad flag letter */
*fl |= get_flag(*arg);
}
return argv;
@@ -141,8 +120,6 @@ static void change_attributes(const char *name, struct globals *gp);
static int FAST_FUNC chattr_dir_proc(const char *dir_name, struct dirent *de, void *gp)
{
//TODO: use de->d_type (if it's not DT_UNKNOWN) to skip !(REG || DIR || LNK) entries without lstat?
char *path = concat_subpath_file(dir_name, de->d_name);
/* path is NULL if de->d_name is "." or "..", else... */
if (path) {
@@ -154,14 +131,15 @@ static int FAST_FUNC chattr_dir_proc(const char *dir_name, struct dirent *de, vo
static void change_attributes(const char *name, struct globals *gp)
{
unsigned fsflags;
int fd;
unsigned long fsflags;
struct stat st;
if (lstat(name, &st) != 0) {
bb_perror_msg("can't stat '%s'", name);
bb_perror_msg("stat %s", name);
return;
}
if (S_ISLNK(st.st_mode) && gp->recursive)
return;
/* Don't try to open device files, fifos etc. We probably
* ought to display an error if the file was explicitly given
@@ -170,58 +148,29 @@ static void change_attributes(const char *name, struct globals *gp)
if (!S_ISREG(st.st_mode) && !S_ISLNK(st.st_mode) && !S_ISDIR(st.st_mode))
return;
/* There is no way to run needed ioctls on a symlink.
* open(O_PATH | O_NOFOLLOW) _can_ be used to get a fd referring to the symlink,
* but ioctls fail on such a fd (tried on 4.12.0 kernel).
* e2fsprogs-1.46.2 uses open(O_NOFOLLOW), it fails on symlinks.
*/
fd = open_or_warn(name, O_RDONLY | O_NONBLOCK | O_NOCTTY | O_NOFOLLOW);
if (fd >= 0) {
int r;
if (gp->flags & OPT_SET_VER)
if (fsetversion(name, gp->version) != 0)
bb_perror_msg("setting version on %s", name);
if (gp->flags & OPT_SET_VER) {
r = ioctl(fd, EXT2_IOC_SETVERSION, &gp->version);
if (r != 0)
bb_perror_msg("setting %s on %s", "version", name);
if (gp->flags & OPT_SET) {
fsflags = gp->af;
} else {
if (fgetflags(name, &fsflags) != 0) {
bb_perror_msg("reading flags on %s", name);
goto skip_setflags;
}
if (gp->flags & OPT_SET_PROJ) {
struct ext2_fsxattr fsxattr;
r = ioctl(fd, EXT2_IOC_FSGETXATTR, &fsxattr);
/* note: ^^^ may fail in 32-bit userspace on 64-bit kernel (seen on 4.12.0) */
if (r != 0) {
bb_perror_msg("getting %s on %s", "project ID", name);
} else {
fsxattr.fsx_projid = gp->projid;
r = ioctl(fd, EXT2_IOC_FSSETXATTR, &fsxattr);
if (r != 0)
bb_perror_msg("setting %s on %s", "project ID", name);
}
}
if (gp->flags & OPT_SET) {
fsflags = gp->af;
} else {
r = ioctl(fd, EXT2_IOC_GETFLAGS, &fsflags);
if (r != 0) {
bb_perror_msg("getting %s on %s", "flags", name);
goto skip_setflags;
}
/*if (gp->flags & OPT_REM) - not needed, rf is zero otherwise */
fsflags &= ~gp->rf;
/*if (gp->flags & OPT_ADD) - not needed, af is zero otherwise */
fsflags |= gp->af;
/*if (gp->flags & OPT_REM) - not needed, rf is zero otherwise */
fsflags &= ~gp->rf;
/*if (gp->flags & OPT_ADD) - not needed, af is zero otherwise */
fsflags |= gp->af;
// What is this? And why it's not done for SET case?
if (!S_ISDIR(st.st_mode))
fsflags &= ~EXT2_DIRSYNC_FL;
}
r = ioctl(fd, EXT2_IOC_SETFLAGS, &fsflags);
if (r != 0)
bb_perror_msg("setting %s on %s", "flags", name);
skip_setflags:
close(fd);
if (!S_ISDIR(st.st_mode))
fsflags &= ~EXT2_DIRSYNC_FL;
}
if (fsetflags(name, fsflags) != 0)
bb_perror_msg("setting flags on %s", name);
skip_setflags:
if (gp->recursive && S_ISDIR(st.st_mode))
iterate_on_dir(name, chattr_dir_proc, gp);
}
@@ -251,7 +200,7 @@ int chattr_main(int argc UNUSED_PARAM, char **argv)
if (g.rf & g.af)
bb_simple_error_msg_and_die("can't set and unset a flag");
if (!g.flags)
bb_simple_error_msg_and_die("must use -v, -p, =, - or +");
bb_simple_error_msg_and_die("must use '-v', =, - or +");
/* now run chattr on all the files passed to us */
do change_attributes(*argv, &g); while (*++argv);
+153 -51
View File
@@ -8,13 +8,133 @@
#include "libbb.h"
#include "e2fs_lib.h"
#define HAVE_EXT2_IOCTLS 1
#if INT_MAX == LONG_MAX
#define IF_LONG_IS_SAME(...) __VA_ARGS__
#define IF_LONG_IS_WIDER(...)
#else
#define IF_LONG_IS_SAME(...)
#define IF_LONG_IS_WIDER(...) __VA_ARGS__
#endif
static void close_silently(int fd)
{
int e = errno;
close(fd);
errno = e;
}
/* Iterate a function on each entry of a directory */
int iterate_on_dir(const char *dir_name,
int FAST_FUNC (*func)(const char *, struct dirent *, void *),
void *private)
{
DIR *dir;
struct dirent *de;
dir = opendir(dir_name);
if (dir == NULL) {
return -1;
}
while ((de = readdir(dir)) != NULL) {
func(dir_name, de, private);
}
closedir(dir);
return 0;
}
/* Get/set a file version on an ext2 file system */
int fgetsetversion(const char *name, unsigned long *get_version, unsigned long set_version)
{
#if HAVE_EXT2_IOCTLS
int fd, r;
IF_LONG_IS_WIDER(int ver;)
fd = open(name, O_RDONLY | O_NONBLOCK);
if (fd == -1)
return -1;
if (!get_version) {
IF_LONG_IS_WIDER(
ver = (int) set_version;
r = ioctl(fd, EXT2_IOC_SETVERSION, &ver);
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_SETVERSION, (void*)&set_version);
)
} else {
IF_LONG_IS_WIDER(
r = ioctl(fd, EXT2_IOC_GETVERSION, &ver);
*get_version = ver;
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_GETVERSION, (void*)get_version);
)
}
close_silently(fd);
return r;
#else /* ! HAVE_EXT2_IOCTLS */
errno = EOPNOTSUPP;
return -1;
#endif /* ! HAVE_EXT2_IOCTLS */
}
/* Get/set a file flags on an ext2 file system */
int fgetsetflags(const char *name, unsigned long *get_flags, unsigned long set_flags)
{
#if HAVE_EXT2_IOCTLS
struct stat buf;
int fd, r;
IF_LONG_IS_WIDER(int f;)
if (stat(name, &buf) == 0 /* stat is ok */
&& !S_ISREG(buf.st_mode) && !S_ISDIR(buf.st_mode)
) {
goto notsupp;
}
fd = open(name, O_RDONLY | O_NONBLOCK); /* neither read nor write asked for */
if (fd == -1)
return -1;
if (!get_flags) {
IF_LONG_IS_WIDER(
f = (int) set_flags;
r = ioctl(fd, EXT2_IOC_SETFLAGS, &f);
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_SETFLAGS, (void*)&set_flags);
)
} else {
IF_LONG_IS_WIDER(
r = ioctl(fd, EXT2_IOC_GETFLAGS, &f);
*get_flags = f;
)
IF_LONG_IS_SAME(
r = ioctl(fd, EXT2_IOC_GETFLAGS, (void*)get_flags);
)
}
close_silently(fd);
return r;
notsupp:
#endif /* HAVE_EXT2_IOCTLS */
errno = EOPNOTSUPP;
return -1;
}
/* Print file attributes on an ext2 file system */
const uint32_t e2attr_flags_value[] ALIGN4 = {
#ifdef ENABLE_COMPRESSION
EXT2_COMPRBLK_FL,
EXT2_DIRTY_FL,
EXT2_NOCOMPR_FL,
EXT2_ECOMPR_FL,
#endif
EXT2_INDEX_FL,
EXT2_SECRM_FL,
EXT2_UNRM_FL,
EXT2_SYNC_FL,
@@ -24,31 +144,26 @@ const uint32_t e2attr_flags_value[] ALIGN4 = {
EXT2_NODUMP_FL,
EXT2_NOATIME_FL,
EXT2_COMPR_FL,
EXT2_ECOMPR_FL,
EXT3_JOURNAL_DATA_FL,
EXT2_INDEX_FL,
EXT2_NOTAIL_FL,
EXT2_TOPDIR_FL,
EXT2_EXTENT_FL,
EXT2_NOCOW_FL,
EXT2_CASEFOLD_FL,
EXT2_INLINE_DATA_FL,
EXT2_PROJINHERIT_FL,
EXT2_VERITY_FL,
EXT2_TOPDIR_FL
};
const char e2attr_flags_sname[] ALIGN1 =
#ifdef ENABLE_COMPRESSION
"BZX"
"BZXE"
#endif
"suSDiadAcEjItTeCFNPV";
"I"
"suSDiadAcjtT";
static const char e2attr_flags_lname[] ALIGN1 =
#ifdef ENABLE_COMPRESSION
"Compressed_File" "\0"
"Compressed_Dirty_File" "\0"
"Compression_Raw_Access" "\0"
"Compression_Error" "\0"
#endif
"Indexed_directory" "\0"
"Secure_Deletion" "\0"
"Undelete" "\0"
"Synchronous_Updates" "\0"
@@ -58,54 +173,41 @@ static const char e2attr_flags_lname[] ALIGN1 =
"No_Dump" "\0"
"No_Atime" "\0"
"Compression_Requested" "\0"
"Encrypted" "\0"
"Journaled_Data" "\0"
"Indexed_directory" "\0"
"No_Tailmerging" "\0"
"Top_of_Directory_Hierarchies" "\0"
"Extents" "\0"
"No_COW" "\0"
"Casefold" "\0"
"Inline_Data" "\0"
"Project_Hierarchy" "\0"
"Verity" "\0"
/* Another trailing NUL is added by compiler */;
void print_e2flags_long(unsigned flags)
{
const uint32_t *fv;
const char *fn;
int first = 1;
fv = e2attr_flags_value;
fn = e2attr_flags_lname;
do {
if (flags & *fv) {
if (!first)
fputs(", ", stdout);
fputs(fn, stdout);
first = 0;
}
fv++;
fn += strlen(fn) + 1;
} while (*fn);
if (first)
fputs("---", stdout);
}
void print_e2flags(unsigned flags)
void print_e2flags(FILE *f, unsigned long flags, unsigned options)
{
const uint32_t *fv;
const char *fn;
fv = e2attr_flags_value;
fn = e2attr_flags_sname;
do {
char c = '-';
if (flags & *fv)
c = *fn;
putchar(c);
fv++;
fn++;
} while (*fn);
if (options & PFOPT_LONG) {
int first = 1;
fn = e2attr_flags_lname;
do {
if (flags & *fv) {
if (!first)
fputs(", ", f);
fputs(fn, f);
first = 0;
}
fv++;
fn += strlen(fn) + 1;
} while (*fn);
if (first)
fputs("---", f);
} else {
fn = e2attr_flags_sname;
do {
char c = '-';
if (flags & *fv)
c = *fn;
fputc(c, f);
fv++;
fn++;
} while (*fn);
}
}
+18 -2
View File
@@ -11,9 +11,25 @@
PUSH_AND_SET_FUNCTION_VISIBILITY_TO_HIDDEN
/* Iterate a function on each entry of a directory */
int iterate_on_dir(const char *dir_name,
int FAST_FUNC (*func)(const char *, struct dirent *, void *),
void *private);
/* Get/set a file version on an ext2 file system */
int fgetsetversion(const char *name, unsigned long *get_version, unsigned long set_version);
#define fgetversion(name, version) fgetsetversion(name, version, 0)
#define fsetversion(name, version) fgetsetversion(name, NULL, version)
/* Get/set a file flags on an ext2 file system */
int fgetsetflags(const char *name, unsigned long *get_flags, unsigned long set_flags);
#define fgetflags(name, flags) fgetsetflags(name, flags, 0)
#define fsetflags(name, flags) fgetsetflags(name, NULL, flags)
/* Must be 1 for compatibility with 'int long_format'. */
#define PFOPT_LONG 1
/* Print file attributes on an ext2 file system */
void print_e2flags_long(unsigned flags);
void print_e2flags(unsigned flags);
void print_e2flags(FILE *f, unsigned long flags, unsigned options);
extern const uint32_t e2attr_flags_value[];
extern const char e2attr_flags_sname[];
+22 -53
View File
@@ -21,79 +21,52 @@
//kbuild:lib-$(CONFIG_LSATTR) += lsattr.o e2fs_lib.o
//usage:#define lsattr_trivial_usage
//usage: "[-Radlpv] [FILE]..."
//usage: "[-Radlv] [FILE]..."
//usage:#define lsattr_full_usage "\n\n"
//usage: "List ext2 file attributes\n"
//usage: "\n -R Recurse"
//usage: "\n -a Include names starting with ."
//usage: "\n -d List directory names, not contents"
// -a,-d text should match ls --help
//usage: "\n -a Don't hide entries starting with ."
//usage: "\n -d List directory entries instead of contents"
//usage: "\n -l List long flag names"
//usage: "\n -p List project ID"
//usage: "\n -v List version/generation number"
#include "libbb.h"
#include "e2fs_lib.h"
enum {
OPT_RECUR = 1 << 0,
OPT_ALL = 1 << 1,
OPT_DIRS_OPT = 1 << 2,
OPT_PF_LONG = 1 << 3,
OPT_GENERATION = 1 << 4,
OPT_PROJID = 1 << 5,
OPT_RECUR = 0x1,
OPT_ALL = 0x2,
OPT_DIRS_OPT = 0x4,
OPT_PF_LONG = 0x8,
OPT_GENERATION = 0x10,
};
static void list_attributes(const char *name)
{
unsigned fsflags;
int fd, r;
unsigned long fsflags;
unsigned long generation;
/* There is no way to run needed ioctls on a symlink.
* open(O_PATH | O_NOFOLLOW) _can_ be used to get a fd referring to the symlink,
* but ioctls fail on such a fd (tried on 4.12.0 kernel).
* e2fsprogs-1.46.2 uses open(O_NOFOLLOW), it fails on symlinks.
*/
fd = open_or_warn(name, O_RDONLY | O_NONBLOCK | O_NOCTTY | O_NOFOLLOW);
if (fd < 0)
return;
if (option_mask32 & OPT_PROJID) {
struct ext2_fsxattr fsxattr;
r = ioctl(fd, EXT2_IOC_FSGETXATTR, &fsxattr);
/* note: ^^^ may fail in 32-bit userspace on 64-bit kernel (seen on 4.12.0) */
if (r != 0)
goto read_err;
printf("%5u ", (unsigned)fsxattr.fsx_projid);
}
if (option_mask32 & OPT_GENERATION) {
unsigned generation;
r = ioctl(fd, EXT2_IOC_GETVERSION, &generation);
if (r != 0)
goto read_err;
printf("%-10u ", generation);
}
r = ioctl(fd, EXT2_IOC_GETFLAGS, &fsflags);
if (r != 0)
if (fgetflags(name, &fsflags) != 0)
goto read_err;
close(fd);
if (option_mask32 & OPT_GENERATION) {
if (fgetversion(name, &generation) != 0)
goto read_err;
printf("%5lu ", generation);
}
if (option_mask32 & OPT_PF_LONG) {
printf("%-28s ", name);
print_e2flags_long(fsflags);
print_e2flags(stdout, fsflags, PFOPT_LONG);
bb_putchar('\n');
} else {
print_e2flags(fsflags);
print_e2flags(stdout, fsflags, 0);
printf(" %s\n", name);
}
return;
read_err:
bb_perror_msg("reading %s", name);
close(fd);
}
static int FAST_FUNC lsattr_dir_proc(const char *dir_name,
@@ -106,13 +79,9 @@ static int FAST_FUNC lsattr_dir_proc(const char *dir_name,
path = concat_path_file(dir_name, de->d_name);
if (lstat(path, &st) != 0)
bb_perror_msg("can't stat '%s'", path);
bb_perror_msg("stat %s", path);
else if (de->d_name[0] != '.' || (option_mask32 & OPT_ALL)) {
/* Don't try to open device files, fifos etc */
if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode) || S_ISDIR(st.st_mode))
list_attributes(path);
list_attributes(path);
if (S_ISDIR(st.st_mode) && (option_mask32 & OPT_RECUR)
&& !DOT_OR_DOTDOT(de->d_name)
) {
@@ -131,7 +100,7 @@ static void lsattr_args(const char *name)
struct stat st;
if (lstat(name, &st) == -1) {
bb_perror_msg("can't stat '%s'", name);
bb_perror_msg("stat %s", name);
} else if (S_ISDIR(st.st_mode) && !(option_mask32 & OPT_DIRS_OPT)) {
iterate_on_dir(name, lsattr_dir_proc, NULL);
} else {
@@ -142,7 +111,7 @@ static void lsattr_args(const char *name)
int lsattr_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int lsattr_main(int argc UNUSED_PARAM, char **argv)
{
getopt32(argv, "Radlvp");
getopt32(argv, "Radlv");
argv += optind;
if (!*argv)
+867 -1215
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -18,7 +18,7 @@
//kbuild:lib-$(CONFIG_CMP) += cmp.o
//usage:#define cmp_trivial_usage
//usage: "[-ls] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage: "[-l] [-s] FILE1 [FILE2" IF_DESKTOP(" [SKIP1 [SKIP2]]") "]"
//usage:#define cmp_full_usage "\n\n"
//usage: "Compare FILE1 with FILE2 (or stdin)\n"
//usage: "\n -l Write the byte numbers (decimal) and values (octal)"
+1 -1
View File
@@ -1050,7 +1050,7 @@ int diff_main(int argc UNUSED_PARAM, char **argv)
/* diffreg can get non-regular files here */
print_status(gotstdin > 1 ? STATUS_SAME : diffreg(file), file);
if (ENABLE_FEATURE_CLEAN_UP && dirfile)
if (dirfile)
free(file[dir]);
}
+1 -1
View File
@@ -553,7 +553,7 @@ static int printLines(int num1, int num2, int expandFlag)
fputc_printable(ch | PRINTABLE_META, stdout);
}
fputs_stdout("$\n");
fputs("$\n", stdout);
setCurNum(num1++);
lp = lp->next;
+1 -1
View File
@@ -70,7 +70,7 @@
//usage:#define sed_full_usage "\n\n"
//usage: " -e CMD Add CMD to sed commands to be executed"
//usage: "\n -f FILE Add FILE contents to sed commands to be executed"
//usage: "\n -i[SFX] Edit files in-place (otherwise write to stdout)"
//usage: "\n -i[SFX] Edit files in-place (otherwise sends to stdout)"
//usage: "\n Optionally back files up, appending SFX"
//usage: "\n -n Suppress automatic printing of pattern space"
//usage: "\n -r,-E Use extended regex syntax"
+643 -1192
View File
File diff suppressed because it is too large. Load diff
+3 -6
View File
@@ -79,7 +79,7 @@ option staticroutes 10.0.0.0/8 10.127.0.1, 10.11.12.0/24 10.11.12.1
option 0x08 01020304 # option 8: "cookie server IP addr: 1.2.3.4"
option 14 "dumpfile"
# Currently supported options [hex option value] (for more info, see common.c):
# Currently supported options [hex option value] (for more info, see options.c):
#opt lease NUM # [0x33]
#opt subnet IP # [0x01]
#opt broadcast IP # [0x1c]
@@ -91,20 +91,17 @@ option 14 "dumpfile"
#opt search STRING_LIST # [0x77] search domains
#opt nisdomain STRING # [0x28]
#opt timezone NUM # [0x02] (localtime - UTC_time) in seconds. signed
#opt tzstr STRING # [0x64] RFC 4833. IEEE 1003.1 TZ string
#opt tzdbstr STRING # [0x65] RFC 4833. Reference to the TZ database string
#opt tftp STRING # [0x42] tftp server name
#opt bootfile STRING # [0x43] tftp file to download (e.g. kernel image)
#opt bootsize NUM # [0x0d] size of that file
#opt rootpath STRING # [0x11] (NFS) path to mount as root fs
#opt wpad STRING # [0xfc] Web Proxy Auto Discovery Protocol
#opt serverid IP # [0x36] default: server's IP
#opt message STRING # [0x38] error message (if set, udhcpd would send it on success too)
#opt message STRING # [0x38] error message (udhcpd sends it on success too)
#opt vlanid NUM # [0x84] 802.1P VLAN ID
#opt vlanpriority NUM # [0x85] 802.1Q VLAN priority
#opt vendor STRING # [0x3c] client's vendor string, not intended to be sent by DHCP servers
# RFC 5071: PXELINUX Options
#opt 0xd0 F100747E # [0xd0] magic needed for other options to be recognized by clients
#opt 0xd0 F100747E # [0xd0] magic
#opt pxeconffile STRING # [0xd1]
#opt pxepathprefix STRING # [0xd2]
#opt reboottime NUM # [0xd3] bootstrap timeout
+4 -2
View File
@@ -57,12 +57,14 @@
#include "common_bufsiz.h"
#include "xregex.h"
/* options */
//usage:#define grep_trivial_usage
//usage: "[-HhnlLoqvsrRiwFE"
//usage: IF_EXTRA_COMPAT("z")
//usage: "] [-m N] "
//usage: IF_FEATURE_GREP_CONTEXT("[-A|B|C N] ")
//usage: "{ PATTERN | -e PATTERN... | -f FILE... } [FILE]..."
//usage: IF_FEATURE_GREP_CONTEXT("[-A/B/C N] ")
//usage: "PATTERN/-e PATTERN.../-f FILE [FILE]..."
//usage:#define grep_full_usage "\n\n"
//usage: "Search for PATTERN in FILEs (or stdin)\n"
//usage: "\n -H Add 'filename:' prefix"
+5 -18
View File
@@ -182,12 +182,11 @@ struct ext2_dx_countlimit {
#define EXT2_NOTAIL_FL 0x00008000 /* file tail should not be merged */
#define EXT2_DIRSYNC_FL 0x00010000 /* Synchronous directory modifications */
#define EXT2_TOPDIR_FL 0x00020000 /* Top of directory hierarchies*/
#define EXT2_EXTENT_FL 0x00080000 /* Extents */
#define EXT2_VERITY_FL 0x00100000
#define EXT2_NOCOW_FL 0x00800000 /* Do not cow file */
#define EXT2_INLINE_DATA_FL 0x10000000
#define EXT2_PROJINHERIT_FL 0x20000000
#define EXT2_CASEFOLD_FL 0x40000000
#define EXT3_EXTENTS_FL 0x00080000 /* Inode uses extents */
#define EXT2_RESERVED_FL 0x80000000 /* reserved for ext2 lib */
#define EXT2_FL_USER_VISIBLE 0x0003DFFF /* User visible flags */
#define EXT2_FL_USER_MODIFIABLE 0x000080FF /* User modifiable flags */
/*
* ioctl commands
@@ -196,18 +195,6 @@ struct ext2_dx_countlimit {
#define EXT2_IOC_SETFLAGS _IOW('f', 2, long)
#define EXT2_IOC_GETVERSION _IOR('v', 1, long)
#define EXT2_IOC_SETVERSION _IOW('v', 2, long)
//NB: despite "long" in defs above, these ioctls use an _int_!
//passing them a pointer to long will read/write only int-sized data!
struct ext2_fsxattr {
uint32_t fsx_xflags; /* xflags field value (get/set) */
uint32_t fsx_extsize; /* extsize field value (get/set)*/
uint32_t fsx_nextents; /* nextents field value (get) */
uint32_t fsx_projid; /* project identifier (get/set) */
uint32_t fsx_cowextsize; /* CoW extsize field value (get/set)*/
unsigned char fsx_pad[8];
};
#define EXT2_IOC_FSGETXATTR _IOR('X', 31, struct ext2_fsxattr)
#define EXT2_IOC_FSSETXATTR _IOW('X', 32, struct ext2_fsxattr)
/*
* Structure of an inode on the disk
+1 -3
View File
@@ -32,10 +32,8 @@ typedef struct dumper_t {
off_t dump_skip; /* bytes to skip */
int dump_length; /* max bytes to read */
smallint dump_vflag; /*enum dump_vflag_t*/
const char *eofstring;
FS *fshead;
const char *xxd_eofstring;
off_t address; /* address/offset in stream */
long long xxd_displayoff;
} dumper_t;
dumper_t* alloc_dumper(void) FAST_FUNC;
+18 -59
View File
@@ -106,11 +106,7 @@
# define updwtmpx updwtmp
# define _PATH_UTMPX _PATH_UTMP
# else
# if !defined(__FreeBSD__)
# include <utmp.h>
# else
# define _PATH_UTMPX "/var/run/utx.active"
# endif
# include <utmp.h>
# include <utmpx.h>
# if defined _PATH_UTMP && !defined _PATH_UTMPX
# define _PATH_UTMPX _PATH_UTMP
@@ -192,28 +188,6 @@ int klogctl(int type, char *b, int len);
# define BUFSIZ 4096
#endif
#if __GNUC_PREREQ(5,0)
/* Since musl is apparently unable to get it right and would use
* a function call to a single-instruction function of "bswap %eax",
* reroute to gcc builtins:
*/
# undef bswap_16
# undef bswap_32
# undef bswap_64
# define bswap_16(x) __builtin_bswap16(x)
# define bswap_32(x) __builtin_bswap32(x)
# define bswap_64(x) __builtin_bswap64(x)
# if BB_LITTLE_ENDIAN
# undef ntohs
# undef htons
# undef ntohl
# undef htonl
# define ntohs(x) __builtin_bswap16(x)
# define htons(x) __builtin_bswap16(x)
# define ntohl(x) __builtin_bswap32(x)
# define htonl(x) __builtin_bswap32(x)
# endif
#endif
/* Busybox does not use threads, we can speed up stdio. */
#ifdef HAVE_UNLOCKED_STDIO
@@ -450,29 +424,23 @@ enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing th
FILEUTILS_RECUR = 1 << 2, /* -R */
FILEUTILS_FORCE = 1 << 3, /* -f */
FILEUTILS_INTERACTIVE = 1 << 4, /* -i */
FILEUTILS_NO_OVERWRITE = 1 << 5, /* -n */
FILEUTILS_MAKE_HARDLINK = 1 << 6, /* -l */
FILEUTILS_MAKE_SOFTLINK = 1 << 7, /* -s */
FILEUTILS_DEREF_SOFTLINK = 1 << 8, /* -L */
FILEUTILS_DEREFERENCE_L0 = 1 << 9, /* -H */
FILEUTILS_MAKE_HARDLINK = 1 << 5, /* -l */
FILEUTILS_MAKE_SOFTLINK = 1 << 6, /* -s */
FILEUTILS_DEREF_SOFTLINK = 1 << 7, /* -L */
FILEUTILS_DEREFERENCE_L0 = 1 << 8, /* -H */
/* -a = -pdR (mapped in cp.c) */
/* -r = -dR (mapped in cp.c) */
/* -P = -d (mapped in cp.c) */
FILEUTILS_VERBOSE = (1 << 13) * ENABLE_FEATURE_VERBOSE, /* -v */
FILEUTILS_UPDATE = 1 << 14, /* -u */
FILEUTILS_NO_TARGET_DIR = 1 << 15, /* -T */
FILEUTILS_TARGET_DIR = 1 << 16, /* -t DIR */
FILEUTILS_VERBOSE = (1 << 12) * ENABLE_FEATURE_VERBOSE, /* -v */
FILEUTILS_UPDATE = 1 << 13, /* -u */
FILEUTILS_NO_TARGET_DIR = 1 << 14, /* -T */
#if ENABLE_SELINUX
FILEUTILS_PRESERVE_SECURITY_CONTEXT = 1 << 17, /* -c */
FILEUTILS_PRESERVE_SECURITY_CONTEXT = 1 << 15, /* -c */
#endif
#define FILEUTILS_CP_OPTSTR "pdRfinlsLHarPvuTt:" IF_SELINUX("c")
/* How many bits in FILEUTILS_CP_OPTSTR? */
FILEUTILS_CP_OPTBITS = 18 - !ENABLE_SELINUX,
FILEUTILS_RMDEST = 1 << (19 - !ENABLE_SELINUX), /* cp --remove-destination */
/* bit 18 skipped for "cp --parents" */
FILEUTILS_REFLINK = 1 << (20 - !ENABLE_SELINUX), /* cp --reflink=auto */
FILEUTILS_REFLINK_ALWAYS = 1 << (21 - !ENABLE_SELINUX), /* cp --reflink[=always] */
FILEUTILS_RMDEST = 1 << (16 - !ENABLE_SELINUX), /* --remove-destination */
/* bit 17 skipped for "cp --parents" */
FILEUTILS_REFLINK = 1 << (18 - !ENABLE_SELINUX), /* cp --reflink=auto */
FILEUTILS_REFLINK_ALWAYS = 1 << (19 - !ENABLE_SELINUX), /* cp --reflink[=always] */
/*
* Hole. cp may have some bits set here,
* they should not affect remove_file()/copy_file()
@@ -482,7 +450,7 @@ enum { /* cp.c, mv.c, install.c depend on these values. CAREFUL when changing th
#endif
FILEUTILS_IGNORE_CHMOD_ERR = 1 << 31,
};
#define FILEUTILS_CP_OPTSTR "pdRfilsLHarPvuT" IF_SELINUX("c")
extern int remove_file(const char *path, int flags) FAST_FUNC;
/* NB: without FILEUTILS_RECUR in flags, it will basically "cat"
* the source, not copy (unless "source" is a directory).
@@ -512,11 +480,6 @@ int recursive_action(const char *fileName, unsigned flags,
void *userData
) FAST_FUNC;
/* Simpler version: call a function on each dirent in a directory */
int iterate_on_dir(const char *dir_name,
int FAST_FUNC (*func)(const char *, struct dirent *, void *),
void *private) FAST_FUNC;
extern int device_open(const char *device, int mode) FAST_FUNC;
enum { GETPTY_BUFSIZE = 16 }; /* more than enough for "/dev/ttyXXX" */
extern int xgetpty(char *line) FAST_FUNC;
@@ -604,7 +567,7 @@ void bb_signals(int sigs, void (*f)(int)) FAST_FUNC;
/* Unlike signal() and bb_signals, sets handler with sigaction()
* and in a way that while signal handler is run, no other signals
* will be blocked; syscalls will not be restarted: */
void bb_signals_norestart(int sigs, void (*f)(int)) FAST_FUNC;
void bb_signals_recursive_norestart(int sigs, void (*f)(int)) FAST_FUNC;
/* syscalls like read() will be interrupted with EINTR: */
void signal_no_SA_RESTART_empty_mask(int sig, void (*handler)(int)) FAST_FUNC;
/* syscalls like read() won't be interrupted (though select/poll will be): */
@@ -656,7 +619,7 @@ uoff_t FAST_FUNC get_volume_size_in_bytes(int fd,
unsigned override_units,
int extend);
void xpipe(int *filedes) FAST_FUNC;
void xpipe(int filedes[2]) FAST_FUNC;
/* In this form code with pipes is much more readable */
struct fd_pair { int rd; int wr; };
#define piped_pair(pair) pipe(&((pair).rd))
@@ -694,7 +657,6 @@ void parse_datestr(const char *date_str, struct tm *ptm) FAST_FUNC;
time_t validate_tm_time(const char *date_str, struct tm *ptm) FAST_FUNC;
char *strftime_HHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
char *strftime_YYYYMMDDHHMMSS(char *buf, unsigned len, time_t *tp) FAST_FUNC;
void xgettimeofday(struct timeval *tv) FAST_FUNC;
void xsettimeofday(const struct timeval *tv) FAST_FUNC;
@@ -907,7 +869,6 @@ char *xmalloc_substitute_string(const char *src, int count, const char *sub, con
int bb_putchar(int ch) FAST_FUNC;
/* Note: does not use stdio, writes to fd 2 directly */
int bb_putchar_stderr(char ch) FAST_FUNC;
int fputs_stdout(const char *s) FAST_FUNC;
char *xasprintf(const char *format, ...) __attribute__ ((format(printf, 1, 2))) FAST_FUNC RETURNS_MALLOC;
char *auto_string(char *str) FAST_FUNC;
// gcc-4.1.1 still isn't good enough at optimizing it
@@ -1076,10 +1037,10 @@ char *smart_ulltoa5(unsigned long long ul, char buf[5], const char *scale) FAST_
/* If block_size == 0, display size without fractional part,
* else display (size * block_size) with one decimal digit.
* If display_unit == 0, show value no bigger than 1024 with suffix (K,M,G...),
* else divide by display_unit and do not use suffix.
* Returns "auto pointer" */
* else divide by display_unit and do not use suffix. */
#define HUMAN_READABLE_MAX_WIDTH 7 /* "1024.0G" */
#define HUMAN_READABLE_MAX_WIDTH_STR "7"
//TODO: provide pointer to buf (avoid statics)?
const char *make_human_readable_str(unsigned long long size,
unsigned long block_size, unsigned long display_unit) FAST_FUNC;
/* Put a string of hex bytes ("1b2e66fe"...), return advanced pointer */
@@ -1252,7 +1213,6 @@ void run_noexec_applet_and_exit(int a, const char *name, char **argv) NORETURN F
int find_applet_by_name(const char *name) FAST_FUNC;
void run_applet_no_and_exit(int a, const char *name, char **argv) NORETURN FAST_FUNC;
#endif
void show_usage_if_dash_dash_help(int applet_no, char **argv) FAST_FUNC;
#if defined(__linux__)
void set_task_comm(const char *comm) FAST_FUNC;
#else
@@ -1784,7 +1744,6 @@ extern void print_login_issue(const char *issue_file, const char *tty) FAST_FUNC
extern void print_login_prompt(void) FAST_FUNC;
char *xmalloc_ttyname(int fd) FAST_FUNC RETURNS_MALLOC;
int is_TERM_dumb(void) FAST_FUNC;
/* NB: typically you want to pass fd 0, not 1. Think 'applet | grep something' */
int get_terminal_width_height(int fd, unsigned *width, unsigned *height) FAST_FUNC;
int get_terminal_width(int fd) FAST_FUNC;
+1 -16
View File
@@ -195,7 +195,6 @@
#endif
#if ULONG_MAX > 0xffffffff
/* inline 64-bit bswap only on 64-bit arches */
# define bb_bswap_64(x) bswap_64(x)
#endif
@@ -320,7 +319,7 @@ typedef unsigned smalluint;
#endif
/* Define bb_setpgrp */
#if (defined(__digital__) && defined(__unix__)) || defined(__FreeBSD__)
#if defined(__digital__) && defined(__unix__)
/* use legacy setpgrp(pid_t, pid_t) for now. move to platform.c */
# define bb_setpgrp() do { pid_t __me = getpid(); setpgrp(__me, __me); } while (0)
#else
@@ -408,7 +407,6 @@ typedef unsigned smalluint;
#define HAVE_SETBIT 1
#define HAVE_SIGHANDLER_T 1
#define HAVE_STPCPY 1
#define HAVE_STPNCPY 1
#define HAVE_MEMPCPY 1
#define HAVE_STRCASESTR 1
#define HAVE_STRCHRNUL 1
@@ -425,9 +423,6 @@ typedef unsigned smalluint;
#define HAVE_NET_ETHERNET_H 1
#define HAVE_SYS_STATFS_H 1
#define HAVE_PRINTF_PERCENTM 1
#define HAVE_WAIT3 1
#define HAVE_DEV_FD 1
#define DEV_FD_PREFIX "/dev/fd/"
#if defined(__UCLIBC__)
# if UCLIBC_VERSION < KERNEL_VERSION(0, 9, 32)
@@ -447,7 +442,6 @@ typedef unsigned smalluint;
# undef HAVE_MKDTEMP
# undef HAVE_SETBIT
# undef HAVE_STPCPY
# undef HAVE_STPNCPY
# undef HAVE_STRCASESTR
# undef HAVE_STRCHRNUL
# undef HAVE_STRSEP
@@ -520,7 +514,6 @@ typedef unsigned smalluint;
#if defined(__digital__) && defined(__unix__)
# undef HAVE_STPCPY
# undef HAVE_STPNCPY
#endif
#if defined(ANDROID) || defined(__ANDROID__)
@@ -537,10 +530,6 @@ typedef unsigned smalluint;
# undef HAVE_TTYNAME_R
# undef HAVE_GETLINE
# undef HAVE_STPCPY
# undef HAVE_STPNCPY
# endif
# if __ANDROID_API__ >= 21
# undef HAVE_WAIT3
# endif
# undef HAVE_MEMPCPY
# undef HAVE_STRCHRNUL
@@ -585,10 +574,6 @@ typedef void (*sighandler_t)(int);
extern char *stpcpy(char *p, const char *to_add) FAST_FUNC;
#endif
#ifndef HAVE_STPNCPY
extern char *stpncpy(char *p, const char *to_add, size_t n) FAST_FUNC;
#endif
#ifndef HAVE_MEMPCPY
#include <string.h>
/* In case we are wrong about !HAVE_MEMPCPY, and toolchain _does_ have
+5 -5
View File
@@ -218,10 +218,10 @@ static char *make_tempdir(void)
static void do_logging(unsigned sample_period_us, int process_accounting)
{
FILE *proc_stat = xfopen_for_write("proc_stat.log");
FILE *proc_diskstats = xfopen_for_write("proc_diskstats.log");
//FILE *proc_netdev = xfopen_for_write("proc_netdev.log");
FILE *proc_ps = xfopen_for_write("proc_ps.log");
FILE *proc_stat = xfopen("proc_stat.log", "w");
FILE *proc_diskstats = xfopen("proc_diskstats.log", "w");
//FILE *proc_netdev = xfopen("proc_netdev.log", "w");
FILE *proc_ps = xfopen("proc_ps.log", "w");
int look_for_login_process = (getppid() == 1);
unsigned count = 60*1000*1000 / sample_period_us; /* ~1 minute */
@@ -268,7 +268,7 @@ static void finalize(char *tempdir, const char *prog, int process_accounting)
//local pacct=
//[ -e kernel_pacct ] && pacct=kernel_pacct
FILE *header_fp = xfopen_for_write("header");
FILE *header_fp = xfopen("header", "w");
if (process_accounting)
acct(NULL);
+1 -1
View File
@@ -5,7 +5,7 @@
*/
//config:config NUKE
//config: bool "nuke (2.9 kb)"
//config: default n # off by default: too "accidentally destructive"
//config: default y
//config: help
//config: Alias to "rm -rf".
+1 -8
View File
@@ -103,17 +103,10 @@ int resume_main(int argc UNUSED_PARAM, char **argv)
if (major(resume_device) == 0) {
bb_error_msg_and_die("invalid resume device: %s", argv[0]);
}
ofs = (argv[1] ? xstrtoull(argv[1], 0) : 0);
/* Old kernels have no /sys/power/resume_offset, set it only if necessary */
if (ofs != 0) {
fd = xopen("/sys/power/resume_offset", O_WRONLY);
s = xasprintf("%llu", ofs);
xwrite_str(fd, s);
}
fd = xopen("/sys/power/resume", O_WRONLY);
s = xasprintf("%u:%u", major(resume_device), minor(resume_device));
s = xasprintf("%u:%u:%llu", major(resume_device), minor(resume_device), ofs);
xwrite_str(fd, s);
/* if write() returns, resume did not succeed */
+101 -66
View File
@@ -176,7 +176,7 @@ void FAST_FUNC bb_show_usage(void)
int FAST_FUNC find_applet_by_name(const char *name)
{
unsigned i;
unsigned i, max;
int j;
const char *p;
@@ -200,43 +200,105 @@ int FAST_FUNC find_applet_by_name(const char *name)
#endif
p = applet_names;
#if KNOWN_APPNAME_OFFSETS <= 0
i = 0;
#if KNOWN_APPNAME_OFFSETS <= 0
max = NUM_APPLETS;
#else
i = NUM_APPLETS * (KNOWN_APPNAME_OFFSETS - 1);
max = NUM_APPLETS * KNOWN_APPNAME_OFFSETS;
for (j = ARRAY_SIZE(applet_nameofs)-1; j >= 0; j--) {
const char *pp = applet_names + applet_nameofs[j];
if (strcmp(name, pp) >= 0) {
//bb_error_msg("name:'%s' >= pp:'%s'", name, pp);
p = pp;
i = max - NUM_APPLETS;
break;
}
i -= NUM_APPLETS;
max -= NUM_APPLETS;
}
max /= (unsigned)KNOWN_APPNAME_OFFSETS;
i /= (unsigned)KNOWN_APPNAME_OFFSETS;
//bb_error_msg("name:'%s' starting from:'%s' i:%u", name, p, i);
//bb_error_msg("name:'%s' starting from:'%s' i:%u max:%u", name, p, i, max);
#endif
/* Open-coded linear search without strcmp/strlen calls for speed */
while (*p) {
/* Do we see "name\0" at current position in applet_names? */
for (j = 0; *p == name[j]; ++j) {
if (*p++ == '\0') {
//bb_error_msg("found:'%s' i:%u", name, i);
return i; /* yes */
}
}
/* No. Have we gone too far, alphabetically? */
if (*p > name[j]) {
//bb_error_msg("break:'%s' i:%u", name, i);
break;
}
/* No. Move to the start of the next applet name. */
while (*p++ != '\0')
#if 0 /*BB_UNALIGNED_MEMACCESS_OK && BB_LITTLE_ENDIAN*/
/* skip "[\0" name, it's surely not it */
if (ENABLE_TEST && LONE_CHAR(p, '['))
i++, p += 2;
/* All remaining applet names in p[] are at least 2 chars long */
/* name[] is also at least 2 chars long */
n32 = (name[0] << 0) | (name[1] << 8) | (name[2] << 16);
while (i < max) {
uint32_t p32;
char ch;
/* Quickly check match of the first 3 bytes */
move_from_unaligned32(p32, p);
p += 3;
if ((p32 & 0x00ffffff) != n32) {
/* Most likely case: 3 first bytes do not match */
i++;
if ((p32 & 0x00ff0000) == '\0')
continue; // p[2] was NUL
p++;
if ((p32 & 0xff000000) == '\0')
continue; // p[3] was NUL
/* p[0..3] aren't matching and none is NUL, check the rest */
while (*p++ != '\0')
continue;
continue;
}
/* Unlikely branch: first 3 bytes ([0..2]) match */
if ((p32 & 0x00ff0000) == '\0') {
/* name is 2-byte long, it is full match */
//bb_error_msg("found:'%s' i:%u", name, i);
return i;
}
/* Check remaining bytes [3..NUL] */
ch = (p32 >> 24);
j = 3;
while (ch == name[j]) {
if (ch == '\0') {
//bb_error_msg("found:'%s' i:%u", name, i);
return i;
}
ch = *++p;
j++;
}
/* Not a match. Skip it, including NUL */
while (ch != '\0')
ch = *++p;
p++;
i++;
}
return -1;
#else
while (i < max) {
char ch;
j = 0;
/* Do we see "name\0" in applet_names[p] position? */
while ((ch = *p) == name[j]) {
if (ch == '\0') {
//bb_error_msg("found:'%s' i:%u", name, i);
return i; /* yes */
}
p++;
j++;
}
/* No.
* p => 1st non-matching char in applet_names[],
* skip to and including NUL.
*/
while (ch != '\0')
ch = *++p;
p++;
i++;
}
return -1;
#endif
}
@@ -263,14 +325,9 @@ void lbb_prepare(const char *applet
&& strcmp(argv[1], "--help") == 0
&& !is_prefixed_with(applet, "busybox")
) {
/* Special cases. POSIX says "test --help"
* should be no different from e.g. "test --foo".
*/
if (!(ENABLE_TEST && strcmp(applet_name, "test") == 0)
&& !(ENABLE_TRUE && strcmp(applet_name, "true") == 0)
&& !(ENABLE_FALSE && strcmp(applet_name, "false") == 0)
&& !(ENABLE_ECHO && strcmp(applet_name, "echo") == 0)
)
/* Special case. POSIX says "test --help"
* should be no different from e.g. "test --foo". */
if (!ENABLE_TEST || strcmp(applet_name, "test") != 0)
bb_show_usage();
}
#endif
@@ -893,39 +950,37 @@ int busybox_main(int argc UNUSED_PARAM, char **argv)
if (strcmp(argv[1], "--help") == 0) {
/* "busybox --help [<applet>]" */
if (!argv[2]
# if ENABLE_FEATURE_SH_STANDALONE && ENABLE_FEATURE_TAB_COMPLETION
|| strcmp(argv[2], "busybox") == 0 /* prevent getting "No help available" */
# endif
)
if (!argv[2])
goto help;
/* convert to "<applet> --help" */
applet_name = argv[0] = argv[2];
argv[0] = argv[2];
argv[2] = NULL;
if (find_applet_by_name(applet_name) >= 0) {
/* Make "--help foo" exit with 0: */
xfunc_error_retval = 0;
bb_show_usage();
} /* else: unknown applet, fall through (causes "applet not found" later) */
} else {
/* "busybox <applet> arg1 arg2 ..." */
argv++;
/* We support "busybox /a/path/to/applet args..." too. Allows for
* "#!/bin/busybox"-style wrappers
*/
applet_name = bb_get_last_path_component_nostrip(argv[0]);
}
/* We support "busybox /a/path/to/applet args..." too. Allows for
* "#!/bin/busybox"-style wrappers */
applet_name = bb_get_last_path_component_nostrip(argv[0]);
run_applet_and_exit(applet_name, argv);
}
# endif
# if NUM_APPLETS > 0
void FAST_FUNC show_usage_if_dash_dash_help(int applet_no, char **argv)
void FAST_FUNC run_applet_no_and_exit(int applet_no, const char *name, char **argv)
{
int argc = string_array_len(argv);
/*
* We do not use argv[0]: do not want to repeat massaging of
* "-/sbin/halt" -> "halt", for example.
*/
applet_name = name;
/* Special case. POSIX says "test --help"
* should be no different from e.g. "test --foo".
* Thus for "test", we skip --help check.
* "true", "false", "echo" are also special.
* "true" and "false" are also special.
*/
if (1
# if defined APPLET_NO_test
@@ -936,37 +991,17 @@ void FAST_FUNC show_usage_if_dash_dash_help(int applet_no, char **argv)
# endif
# if defined APPLET_NO_false
&& applet_no != APPLET_NO_false
# endif
# if defined APPLET_NO_echo
&& applet_no != APPLET_NO_echo
# endif
) {
if (argv[1] && !argv[2] && strcmp(argv[1], "--help") == 0) {
if (argc == 2 && strcmp(argv[1], "--help") == 0) {
/* Make "foo --help" exit with 0: */
xfunc_error_retval = 0;
bb_show_usage();
}
}
}
void FAST_FUNC run_applet_no_and_exit(int applet_no, const char *name, char **argv)
{
int argc;
/*
* We do not use argv[0]: do not want to repeat massaging of
* "-/sbin/halt" -> "halt", for example.
*/
applet_name = name;
show_usage_if_dash_dash_help(applet_no, argv);
if (ENABLE_FEATURE_SUID)
check_suid(applet_no);
argc = string_array_len(argv);
xfunc_error_retval = applet_main[applet_no](argc, argv);
/* Note: applet_main() may also not return (die on a xfunc or such) */
xfunc_die();
}
+1 -1
View File
@@ -25,7 +25,7 @@ char* FAST_FUNC bb_ask_noecho(int fd, int timeout, const char *prompt)
/* Was buggy: was printing prompt *before* flushing input,
* which was upsetting "expect" based scripts of some users.
*/
fputs_stdout(prompt);
fputs(prompt, stdout);
fflush_all();
tcgetattr(fd, &oldtio);
+4 -10
View File
@@ -63,19 +63,13 @@ int FAST_FUNC index_in_str_array(const char *const string_array[], const char *k
int FAST_FUNC index_in_strings(const char *strings, const char *key)
{
int j, idx = 0;
int idx = 0;
while (*strings) {
/* Do we see "key\0" at current position in strings? */
for (j = 0; *strings == key[j]; ++j) {
if (*strings++ == '\0') {
//bb_error_msg("found:'%s' i:%u", key, idx);
return idx; /* yes */
}
if (strcmp(strings, key) == 0) {
return idx;
}
/* No. Move to the start of the next string. */
while (*strings++ != '\0')
continue;
strings += strlen(strings) + 1; /* skip NUL */
idx++;
}
return -1;
-2
View File
@@ -111,8 +111,6 @@ int FAST_FUNC copy_file(const char *source, const char *dest, int flags)
bb_error_msg("'%s' and '%s' are the same file", source, dest);
return -1;
}
if (flags & FILEUTILS_NO_OVERWRITE) /* cp -n */
return 0;
dest_exists = 1;
}
+20 -21
View File
@@ -34,6 +34,7 @@ typedef struct priv_dumper_t {
FU *endfu;
off_t savaddress; /* saved address/offset in stream */
off_t eaddress; /* end address */
off_t address; /* address/offset in stream */
int blocksize;
smallint exitval; /* final exit value */
@@ -210,7 +211,7 @@ static NOINLINE void rewrite(priv_dumper_t *dumper, FS *fs)
pr->bcnt = fu->bcnt;
if (fu->bcnt == 0) {
if (!prec)
bb_simple_error_msg_and_die("%s needs precision or byte count");
bb_simple_error_msg_and_die("%%s needs precision or byte count");
pr->bcnt = atoi(prec);
}
} else
@@ -227,8 +228,7 @@ static NOINLINE void rewrite(priv_dumper_t *dumper, FS *fs)
if ((p1[2] != 'd') && (p1[2] != 'o') && (p1[2] != 'x')) {
goto DO_BAD_CONV_CHAR;
}
*p1++ = 'l';
*p1++ = 'l';
*p1 = p1[2];
break;
case 'c': /* %_c: chars, \ooo, \n \r \t etc */
pr->flags = F_C;
@@ -334,14 +334,14 @@ static void do_skip(priv_dumper_t *dumper, const char *fname)
) {
/* If st_size is valid and pub.dump_skip >= st_size */
dumper->pub.dump_skip -= sbuf.st_size;
dumper->pub.address += sbuf.st_size;
dumper->address += sbuf.st_size;
return;
}
if (fseeko(stdin, dumper->pub.dump_skip, SEEK_SET)) {
bb_simple_perror_msg_and_die(fname);
}
dumper->pub.address += dumper->pub.dump_skip;
dumper->savaddress = dumper->pub.address;
dumper->address += dumper->pub.dump_skip;
dumper->savaddress = dumper->address;
dumper->pub.dump_skip = 0;
}
@@ -356,7 +356,6 @@ static NOINLINE int next(priv_dumper_t *dumper)
if (!freopen(fname, "r", stdin)) {
bb_simple_perror_msg(fname);
dumper->exitval = 1;
dumper->next__done = 1;
continue;
}
}
@@ -380,7 +379,7 @@ static unsigned char *get(priv_dumper_t *dumper)
int blocksize = dumper->blocksize;
if (!dumper->get__curp) {
dumper->pub.address = (off_t)0; /*DBU:[dave@cray.com] initialize,initialize..*/
dumper->address = (off_t)0; /*DBU:[dave@cray.com] initialize,initialize..*/
dumper->get__curp = xmalloc(blocksize);
dumper->get__savp = xzalloc(blocksize); /* need to be initialized */
} else {
@@ -388,7 +387,7 @@ static unsigned char *get(priv_dumper_t *dumper)
dumper->get__curp = dumper->get__savp;
dumper->get__savp = tmp;
dumper->savaddress += blocksize;
dumper->pub.address = dumper->savaddress;
dumper->address = dumper->savaddress;
}
need = blocksize;
nread = 0;
@@ -411,7 +410,7 @@ static unsigned char *get(priv_dumper_t *dumper)
}
}
memset(dumper->get__curp + nread, 0, need);
dumper->eaddress = dumper->pub.address + nread;
dumper->eaddress = dumper->address + nread;
return dumper->get__curp;
}
n = fread(dumper->get__curp + nread, sizeof(unsigned char),
@@ -443,7 +442,7 @@ static unsigned char *get(priv_dumper_t *dumper)
}
dumper->pub.dump_vflag = DUP;
dumper->savaddress += blocksize;
dumper->pub.address = dumper->savaddress;
dumper->address = dumper->savaddress;
need = blocksize;
nread = 0;
} else {
@@ -544,8 +543,8 @@ static void display(priv_dumper_t* dumper)
fs = dumper->pub.fshead;
savebp = bp;
saveaddress = dumper->pub.address;
for (; fs; fs = fs->nextfs, bp = savebp, dumper->pub.address = saveaddress) {
saveaddress = dumper->address;
for (; fs; fs = fs->nextfs, bp = savebp, dumper->address = saveaddress) {
FU *fu;
for (fu = fs->nextfu; fu; fu = fu->nextfu) {
int cnt;
@@ -554,14 +553,14 @@ static void display(priv_dumper_t* dumper)
}
for (cnt = fu->reps; cnt; --cnt) {
PR *pr;
for (pr = fu->nextpr; pr; dumper->pub.address += pr->bcnt,
for (pr = fu->nextpr; pr; dumper->address += pr->bcnt,
bp += pr->bcnt, pr = pr->nextpr) {
if (dumper->eaddress
&& dumper->pub.address >= dumper->eaddress
&& dumper->address >= dumper->eaddress
) {
if (dumper->pub.xxd_eofstring) {
if (dumper->pub.eofstring) {
/* xxd support: requested to not pad incomplete blocks */
fputs_stdout(dumper->pub.xxd_eofstring);
fputs(dumper->pub.eofstring, stdout);
return;
}
if (!(pr->flags & (F_TEXT | F_BPAD)))
@@ -573,7 +572,7 @@ static void display(priv_dumper_t* dumper)
}
switch (pr->flags) {
case F_ADDRESS:
printf(pr->fmt, (unsigned long long) dumper->pub.address + dumper->pub.xxd_displayoff);
printf(pr->fmt, (unsigned) dumper->address);
break;
case F_BPAD:
printf(pr->fmt, "");
@@ -667,15 +666,15 @@ static void display(priv_dumper_t* dumper)
* of blocksize, and no partial block ever found.
*/
if (!dumper->eaddress) {
if (!dumper->pub.address) {
if (!dumper->address) {
return;
}
dumper->eaddress = dumper->pub.address;
dumper->eaddress = dumper->address;
}
for (pr = dumper->endfu->nextpr; pr; pr = pr->nextpr) {
switch (pr->flags) {
case F_ADDRESS:
printf(pr->fmt, (unsigned long long) dumper->eaddress + dumper->pub.xxd_displayoff);
printf(pr->fmt, (unsigned) dumper->eaddress);
break;
case F_TEXT:
printf(pr->fmt);
+2 -12
View File
@@ -37,18 +37,8 @@ duration_t FAST_FUNC parse_duration_str(char *str)
if (strchr(str, '.')) {
double d;
char *pp;
int len;
char sv;
# if ENABLE_LOCALE_SUPPORT
/* Undo busybox.c: on input, we want to use dot
* as fractional separator in strtod(),
* regardless of current locale
*/
setlocale(LC_NUMERIC, "C");
# endif
len = strspn(str, "0123456789.");
sv = str[len];
int len = strspn(str, "0123456789.");
char sv = str[len];
str[len] = '\0';
errno = 0;
d = strtod(str, &pp);
+12 -5
View File
@@ -17,7 +17,7 @@ static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string,
int linebufsz = 0;
int idx = 0;
int ch;
size_t maxsz = maxsz_p ? *maxsz_p : INT_MAX - 4095;
size_t maxsz = *maxsz_p;
while (1) {
ch = fgetc(file);
@@ -53,8 +53,7 @@ static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string,
/* Grow/shrink *first*, then store NUL */
linebuf = xrealloc(linebuf, idx + 1);
linebuf[idx] = '\0';
if (maxsz_p)
*maxsz_p = idx;
*maxsz_p = idx;
return linebuf;
}
@@ -64,15 +63,23 @@ static char *xmalloc_fgets_internal(FILE *file, const char *terminating_string,
* Return NULL if EOF is reached immediately. */
char* FAST_FUNC xmalloc_fgets_str(FILE *file, const char *terminating_string)
{
return xmalloc_fgets_internal(file, terminating_string, 0, NULL);
size_t maxsz = INT_MAX - 4095;
return xmalloc_fgets_internal(file, terminating_string, 0, &maxsz);
}
char* FAST_FUNC xmalloc_fgets_str_len(FILE *file, const char *terminating_string, size_t *maxsz_p)
{
size_t maxsz;
if (!maxsz_p) {
maxsz = INT_MAX - 4095;
maxsz_p = &maxsz;
}
return xmalloc_fgets_internal(file, terminating_string, 0, maxsz_p);
}
char* FAST_FUNC xmalloc_fgetline_str(FILE *file, const char *terminating_string)
{
return xmalloc_fgets_internal(file, terminating_string, 1, NULL);
size_t maxsz = INT_MAX - 4095;
return xmalloc_fgets_internal(file, terminating_string, 1, &maxsz);
}
+4 -7
View File
@@ -89,12 +89,6 @@ getopt32(char **argv, const char *applet_opts, ...)
root:x:0:0:root:/root:/bin/bash
user:x:500:500::/home/user:/bin/bash
"^" options string is "^optchars""\0""opt_complementary".
"!" If the first character in the applet_opts string is a '!',
report bad options, missing required options,
inconsistent options with all-ones return value (instead of abort.
"+" If the first character in the applet_opts string is a plus,
then option processing will stop as soon as a non-option is
encountered in the argv array. Useful for applets like env
@@ -102,7 +96,10 @@ getopt32(char **argv, const char *applet_opts, ...)
env -i ls -d /
Here we want env to process just the '-i', not the '-d'.
(The order of multiple prefixes must be "^!+...")
"!" Report bad options, missing required options,
inconsistent options with all-ones return value (instead of abort).
"^" options string is "^optchars""\0""opt_complementary".
uint32_t
getopt32long(char **argv, const char *applet_opts, const char *logopts...)
-28
View File
@@ -1,28 +0,0 @@
/* vi: set sw=4 ts=4: */
/*
* See README for additional information
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*/
//kbuild:lib-y += iterate_on_dir.o
#include "libbb.h"
/* Iterate a function on each entry of a directory */
int FAST_FUNC iterate_on_dir(const char *dir_name,
int FAST_FUNC (*func)(const char *, struct dirent *, void *),
void *private)
{
DIR *dir;
struct dirent *de;
dir = opendir(dir_name);
if (dir == NULL) {
return -1;
}
while ((de = readdir(dir)) != NULL) {
func(dir_name, de, private);
}
closedir(dir);
return 0;
}
+12 -10
View File
@@ -312,7 +312,7 @@ static void BB_PUTCHAR(wchar_t c)
ssize_t len = wcrtomb(buf, c, &mbst);
if (len > 0) {
buf[len] = '\0';
fputs_stdout(buf);
fputs(buf, stdout);
}
} else {
/* In this case, c is always one byte */
@@ -460,7 +460,7 @@ static void beep(void)
*/
static void put_prompt_custom(bool is_full)
{
fputs_stdout((is_full ? cmdedit_prompt : prompt_last_line));
fputs((is_full ? cmdedit_prompt : prompt_last_line), stdout);
cursor = 0;
cmdedit_y = cmdedit_prmt_len / cmdedit_termw; /* new quasireal y */
cmdedit_x = cmdedit_prmt_len % cmdedit_termw;
@@ -769,6 +769,8 @@ static unsigned path_parse(char ***p)
if (!tmp)
break;
tmp++;
if (*tmp == '\0')
break; /* :<empty> */
npth++;
}
@@ -780,6 +782,8 @@ static unsigned path_parse(char ***p)
if (!tmp)
break;
*tmp++ = '\0'; /* ':' -> '\0' */
if (*tmp == '\0')
break; /* :<empty> */
res[npth++] = tmp;
}
/* special case: "match subdirectories of the current directory" */
@@ -850,7 +854,6 @@ static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
struct dirent *next;
struct stat st;
char *found;
const char *lpath;
if (paths[i] == NULL) { /* path_parse()'s last component? */
/* in PATH completion, current dir's subdir names
@@ -860,8 +863,7 @@ static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
paths[i] = (char *)".";
}
lpath = *paths[i] ? paths[i] : ".";
dir = opendir(lpath);
dir = opendir(paths[i]);
if (!dir)
continue; /* don't print an error */
@@ -876,7 +878,7 @@ static NOINLINE unsigned complete_cmd_dir_file(const char *command, int type)
if (strncmp(basecmd, name_found, baselen) != 0)
continue; /* no */
found = concat_path_file(lpath, name_found);
found = concat_path_file(paths[i], name_found);
/* NB: stat() first so that we see is it a directory;
* but if that fails, use lstat() so that
* we still match dangling links */
@@ -1071,7 +1073,7 @@ static NOINLINE int build_match_prefix(char *match_buf)
continue;
for (--i; i >= 0; i--) {
int cur = int_buf[i];
if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&' || cur == '=') {
if (cur == ' ' || cur == '<' || cur == '>' || cur == '|' || cur == '&') {
remove_chunk(int_buf, 0, i + 1);
break;
}
@@ -1314,7 +1316,7 @@ static NOINLINE void input_tab(smallint *lastWasTab)
strcpy(&command[cursor_mb], chosen_match + match_pfx_len);
len = load_string(command);
/* add match and tail */
stpcpy(stpcpy(&command[cursor_mb], chosen_match + match_pfx_len), match_buf);
sprintf(&command[cursor_mb], "%s%s", chosen_match + match_pfx_len, match_buf);
command_len = load_string(command);
/* write out the matched command */
/* paranoia: load_string can return 0 on conv error,
@@ -1849,7 +1851,7 @@ static void ask_terminal(void)
pfd.events = POLLIN;
if (safe_poll(&pfd, 1, 0) == 0) {
S.sent_ESC_br6n = 1;
fputs_stdout(ESC"[6n");
fputs(ESC"[6n", stdout);
fflush_all(); /* make terminal see it ASAP! */
}
}
@@ -2955,7 +2957,7 @@ int FAST_FUNC read_line_input(line_input_t *st, const char *prompt, char *comman
#undef read_line_input
int FAST_FUNC read_line_input(const char* prompt, char* command, int maxsize)
{
fputs_stdout(prompt);
fputs(prompt, stdout);
fflush_all();
if (!fgets(command, maxsize, stdin))
return -1;
+3 -3
View File
@@ -120,7 +120,7 @@ void FAST_FUNC print_login_issue(const char *issue_file, const char *tty)
buf[0] = c;
}
}
fputs_stdout(outbuf);
fputs(outbuf, stdout);
}
fclose(fp);
fflush_all();
@@ -130,8 +130,8 @@ void FAST_FUNC print_login_prompt(void)
{
char *hostname = safe_gethostname();
fputs_stdout(hostname);
fputs_stdout(LOGIN);
fputs(hostname, stdout);
fputs(LOGIN, stdout);
fflush_all();
free(hostname);
}
-12
View File
@@ -166,18 +166,6 @@ char* FAST_FUNC stpcpy(char *p, const char *to_add)
}
#endif
#ifndef HAVE_STPNCPY
char* FAST_FUNC stpncpy(char *p, const char *to_add, size_t n)
{
while (n != 0 && (*p = *to_add) != '\0') {
p++;
to_add++;
n--;
}
return p;
}
#endif
#ifndef HAVE_GETLINE
ssize_t FAST_FUNC getline(char **lineptr, size_t *n, FILE *stream)
{
+2 -3
View File
@@ -22,11 +22,10 @@ int FAST_FUNC print_numbered_lines(struct number_state *ns, const char *filename
if (ns->all
|| (ns->nonempty && line[0])
) {
printf("%*u%s", ns->width, N, ns->sep);
printf("%*u%s%s\n", ns->width, N, ns->sep, line);
N += ns->inc;
} else if (ns->empty_str)
fputs_stdout(ns->empty_str);
puts(line);
fputs(ns->empty_str, stdout);
free(line);
}
ns->start = N;
+28 -17
View File
@@ -21,29 +21,40 @@ typedef struct cache_t {
int size;
} cache_t;
static cache_t *cache_user_group;
static cache_t username, groupname;
static void clear_cache(cache_t *cp)
{
free(cp->cache);
cp->cache = NULL;
cp->size = 0;
}
void FAST_FUNC clear_username_cache(void)
{
if (cache_user_group) {
free(cache_user_group[0].cache);
free(cache_user_group[1].cache);
free(cache_user_group);
cache_user_group = NULL;
}
clear_cache(&username);
clear_cache(&groupname);
}
static char* get_cached(int user_group, uid_t id,
#if 0 /* more generic, but we don't need that yet */
/* Returns -N-1 if not found. */
/* cp->cache[N] is allocated and must be filled in this case */
static int get_cached(cache_t *cp, uid_t id)
{
int i;
for (i = 0; i < cp->size; i++)
if (cp->cache[i].id == id)
return i;
i = cp->size++;
cp->cache = xrealloc_vector(cp->cache, 2, i);
cp->cache[i++].id = id;
return -i;
}
#endif
static char* get_cached(cache_t *cp, uid_t id,
char* FAST_FUNC x2x_utoa(uid_t id))
{
cache_t *cp;
int i;
if (!cache_user_group)
cache_user_group = xzalloc(sizeof(cache_user_group[0]) * 2);
cp = &cache_user_group[user_group];
for (i = 0; i < cp->size; i++)
if (cp->cache[i].id == id)
return cp->cache[i].name;
@@ -56,11 +67,11 @@ static char* get_cached(int user_group, uid_t id,
}
const char* FAST_FUNC get_cached_username(uid_t uid)
{
return get_cached(0, uid, uid2uname_utoa);
return get_cached(&username, uid, uid2uname_utoa);
}
const char* FAST_FUNC get_cached_groupname(gid_t gid)
{
return get_cached(1, gid, gid2group_utoa);
return get_cached(&groupname, gid, gid2group_utoa);
}
+1 -3
View File
@@ -7,9 +7,7 @@
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*/
#if !ENABLE_USE_BB_CRYPT
# if !defined(__FreeBSD__)
# include <crypt.h>
# endif
#include <crypt.h>
#endif
#include "libbb.h"
+5 -1
View File
@@ -60,7 +60,11 @@ int FAST_FUNC remove_file(const char *path, int flags)
status = -1;
free(new_path);
}
closedir(dp);
if (closedir(dp) < 0) {
bb_perror_msg("can't close '%s'", path);
return -1;
}
if (flags & FILEUTILS_INTERACTIVE) {
fprintf(stderr, "%s: remove directory '%s'? ",
+1 -1
View File
@@ -56,7 +56,7 @@ void FAST_FUNC bb_signals(int sigs, void (*f)(int))
}
}
void FAST_FUNC bb_signals_norestart(int sigs, void (*f)(int))
void FAST_FUNC bb_signals_recursive_norestart(int sigs, void (*f)(int))
{
int sig_no = 0;
int bit = 1;
+3 -3
View File
@@ -291,19 +291,19 @@ unsigned FAST_FUNC monotonic_sec(void)
unsigned long long FAST_FUNC monotonic_ns(void)
{
struct timeval tv;
xgettimeofday(&tv);
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000000ULL + tv.tv_usec * 1000;
}
unsigned long long FAST_FUNC monotonic_us(void)
{
struct timeval tv;
xgettimeofday(&tv);
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000000ULL + tv.tv_usec;
}
unsigned long long FAST_FUNC monotonic_ms(void)
{
struct timeval tv;
xgettimeofday(&tv);
gettimeofday(&tv, NULL);
return tv.tv_sec * 1000ULL + tv.tv_usec / 1000;
}
unsigned FAST_FUNC monotonic_sec(void)
-5
View File
@@ -109,13 +109,8 @@ int FAST_FUNC run_nofork_applet(int applet_no, char **argv)
char *tmp_argv[argc+1];
memcpy(tmp_argv, argv, (argc+1) * sizeof(tmp_argv[0]));
applet_name = tmp_argv[0];
/* longjmp's (instead of returning) if --help is seen */
show_usage_if_dash_dash_help(applet_no, argv);
/* Finally we can call NOFORK applet's main() */
rc = applet_main[applet_no](argc, tmp_argv);
/* Important for shells: `which CMD` was failing */
fflush_all();
} else {
Loaded 100 of 261 files, more files were not shown because too many files have changed in this diff. Show more