aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Makefile2
-rw-r--r--applets/applets.c18
-rw-r--r--applets/busybox.c20
-rw-r--r--archival/ar.c12
-rw-r--r--archival/bunzip2.c16
-rw-r--r--archival/cpio.c4
-rw-r--r--archival/dpkg.c91
-rw-r--r--archival/dpkg_deb.c6
-rw-r--r--archival/gunzip.c30
-rw-r--r--archival/gzip.c32
-rw-r--r--archival/libunarchive/archive_copy_file.c2
-rw-r--r--archival/libunarchive/archive_xread.c2
-rw-r--r--archival/libunarchive/archive_xread_all.c2
-rw-r--r--archival/libunarchive/archive_xread_all_eof.c2
-rw-r--r--archival/libunarchive/check_header_gzip.c16
-rw-r--r--archival/libunarchive/data_extract_all.c16
-rw-r--r--archival/libunarchive/decompress_bunzip2.c8
-rw-r--r--archival/libunarchive/decompress_uncompress.c8
-rw-r--r--archival/libunarchive/decompress_unzip.c32
-rw-r--r--archival/libunarchive/get_header_ar.c16
-rw-r--r--archival/libunarchive/get_header_cpio.c16
-rw-r--r--archival/libunarchive/get_header_tar.c10
-rw-r--r--archival/libunarchive/get_header_tar_gz.c2
-rw-r--r--archival/libunarchive/header_verbose_list.c2
-rw-r--r--archival/libunarchive/seek_by_jump.c2
-rw-r--r--archival/libunarchive/uncompress.c8
-rw-r--r--archival/libunarchive/unpack_ar_archive.c2
-rw-r--r--archival/libunarchive/unzip.c32
-rw-r--r--archival/rpm.c14
-rw-r--r--archival/rpm2cpio.c18
-rw-r--r--archival/tar.c55
-rw-r--r--archival/uncompress.c20
-rw-r--r--archival/unzip.c18
-rw-r--r--console-tools/chvt.c6
-rw-r--r--console-tools/deallocvt.c10
-rw-r--r--console-tools/dumpkmap.c6
-rw-r--r--console-tools/loadacm.c36
-rw-r--r--console-tools/loadfont.c30
-rw-r--r--console-tools/loadkmap.c10
-rw-r--r--console-tools/openvt.c10
-rw-r--r--console-tools/setkeycodes.c8
-rw-r--r--coreutils/Config.in41
-rw-r--r--coreutils/basename.c35
-rw-r--r--coreutils/cal.c484
-rw-r--r--coreutils/cat.c60
-rw-r--r--coreutils/chgrp.c60
-rw-r--r--coreutils/chmod.c85
-rw-r--r--coreutils/chown.c104
-rw-r--r--coreutils/chroot.c50
-rw-r--r--coreutils/cmp.c156
-rw-r--r--coreutils/cp.c130
-rw-r--r--coreutils/cut.c23
-rw-r--r--coreutils/date.c22
-rw-r--r--coreutils/dd.c47
-rw-r--r--coreutils/df.c185
-rw-r--r--coreutils/dirname.c14
-rw-r--r--coreutils/dos2unix.c20
-rw-r--r--coreutils/du.c227
-rw-r--r--coreutils/echo.c133
-rw-r--r--coreutils/env.c52
-rw-r--r--coreutils/expr.c24
-rw-r--r--coreutils/false.c3
-rw-r--r--coreutils/head.c154
-rw-r--r--coreutils/hostid.c12
-rw-r--r--coreutils/id.c76
-rw-r--r--coreutils/length.c14
-rw-r--r--coreutils/libcoreutils/Makefile30
-rw-r--r--coreutils/libcoreutils/Makefile.in32
-rw-r--r--coreutils/libcoreutils/coreutils.h12
-rw-r--r--coreutils/libcoreutils/cp_mv_stat.c45
-rw-r--r--coreutils/libcoreutils/getopt_mk_fifo_nod.c45
-rw-r--r--coreutils/libcoreutils/xgetoptfile_sort_uniq.c38
-rw-r--r--coreutils/ln.c163
-rw-r--r--coreutils/logname.c29
-rw-r--r--coreutils/ls.c557
-rw-r--r--coreutils/md5sum.c38
-rw-r--r--coreutils/mkdir.c58
-rw-r--r--coreutils/mkfifo.c53
-rw-r--r--coreutils/mknod.c94
-rw-r--r--coreutils/mv.c203
-rw-r--r--coreutils/od.c203
-rw-r--r--coreutils/printf.c2
-rw-r--r--coreutils/pwd.c16
-rw-r--r--coreutils/realpath.c20
-rw-r--r--coreutils/rm.c67
-rw-r--r--coreutils/rmdir.c105
-rw-r--r--coreutils/sha1sum.c4
-rw-r--r--coreutils/sleep.c65
-rw-r--r--coreutils/sort.c98
-rw-r--r--coreutils/stty.c493
-rw-r--r--coreutils/sync.c8
-rw-r--r--coreutils/tail.c396
-rw-r--r--coreutils/tee.c115
-rw-r--r--coreutils/test.c12
-rw-r--r--coreutils/touch.c67
-rw-r--r--coreutils/tr.c10
-rw-r--r--coreutils/true.c3
-rw-r--r--coreutils/tty.c44
-rw-r--r--coreutils/uname.c38
-rw-r--r--coreutils/uniq.c126
-rw-r--r--coreutils/usleep.c16
-rw-r--r--coreutils/uudecode.c26
-rw-r--r--coreutils/uuencode.c38
-rw-r--r--coreutils/watch.c91
-rw-r--r--coreutils/wc.c325
-rw-r--r--coreutils/who.c6
-rw-r--r--coreutils/whoami.c11
-rw-r--r--coreutils/yes.c45
-rw-r--r--debianutils/mktemp.c2
-rw-r--r--debianutils/readlink.c2
-rw-r--r--debianutils/run_parts.c6
-rw-r--r--debianutils/start_stop_daemon.c22
-rw-r--r--debianutils/which.c2
-rw-r--r--editors/awk.c66
-rw-r--r--editors/sed.c62
-rw-r--r--editors/vi.c16
-rw-r--r--findutils/find.c28
-rw-r--r--findutils/grep.c24
-rw-r--r--findutils/xargs.c12
-rw-r--r--include/dump.h11
-rw-r--r--include/libbb.h216
-rw-r--r--include/usage.h97
-rw-r--r--init/halt.c2
-rw-r--r--init/init.c26
-rw-r--r--init/mesg.c4
-rw-r--r--init/poweroff.c2
-rw-r--r--init/reboot.c4
-rw-r--r--init/start_stop_daemon.c22
-rw-r--r--libbb/Makefile.in59
-rw-r--r--libbb/ask_confirmation.c50
-rw-r--r--libbb/bb_asprintf.c19
-rw-r--r--libbb/change_identity.c6
-rw-r--r--libbb/compare_string_array.c3
-rw-r--r--libbb/concat_path_file.c2
-rw-r--r--libbb/copy_file.c54
-rw-r--r--libbb/copy_file_chunk.c70
-rw-r--r--libbb/copyfd.c76
-rw-r--r--libbb/correct_password.c4
-rw-r--r--libbb/create_icmp6_socket.c4
-rw-r--r--libbb/create_icmp_socket.c4
-rw-r--r--libbb/default_error_retval.c32
-rw-r--r--libbb/dirname.c60
-rw-r--r--libbb/dump.c517
-rw-r--r--libbb/error_msg.c4
-rw-r--r--libbb/error_msg_and_die.c6
-rw-r--r--libbb/fclose_nonstdin.c37
-rw-r--r--libbb/fflush_stdout_and_exit.c37
-rw-r--r--libbb/find_root_device.c6
-rw-r--r--libbb/full_read.c11
-rw-r--r--libbb/full_write.c10
-rw-r--r--libbb/get_console.c2
-rw-r--r--libbb/get_last_path_component.c6
-rw-r--r--libbb/get_line_from_file.c48
-rw-r--r--libbb/getopt_ulflags.c (renamed from libbb/time_string.c)51
-rw-r--r--libbb/herror_msg.c4
-rw-r--r--libbb/herror_msg_and_die.c6
-rw-r--r--libbb/inet_common.c26
-rw-r--r--libbb/interface.c30
-rw-r--r--libbb/kernel_version.c2
-rw-r--r--libbb/loop.c12
-rw-r--r--libbb/make_directory.c118
-rw-r--r--libbb/messages.c59
-rw-r--r--libbb/mode_string.c150
-rw-r--r--libbb/module_syscalls.c2
-rw-r--r--libbb/mtab.c13
-rw-r--r--libbb/mtab_file.c4
-rw-r--r--libbb/my_getgrnam.c2
-rw-r--r--libbb/my_getpwnam.c2
-rw-r--r--libbb/my_getpwnamegid.c4
-rw-r--r--libbb/obscure.c6
-rw-r--r--libbb/parse_mode.c215
-rw-r--r--libbb/parse_number.c84
-rw-r--r--libbb/perror_msg.c4
-rw-r--r--libbb/perror_msg_and_die.c6
-rw-r--r--libbb/perror_nomsg.c30
-rw-r--r--libbb/perror_nomsg_and_die.c30
-rw-r--r--libbb/print_file.c49
-rw-r--r--libbb/printf.c177
-rw-r--r--libbb/process_escape_sequence.c39
-rw-r--r--libbb/procps.c2
-rw-r--r--libbb/read_package_field.c4
-rw-r--r--libbb/recursive_action.c10
-rw-r--r--libbb/remove_file.c26
-rw-r--r--libbb/run_parts.c14
-rw-r--r--libbb/run_shell.c6
-rw-r--r--libbb/setup_environment.c4
-rw-r--r--libbb/simplify_path.c9
-rw-r--r--libbb/skip_whitespace.c33
-rw-r--r--libbb/speed_table.c130
-rw-r--r--libbb/syscalls.c4
-rw-r--r--libbb/syslog_msg_with_name.c2
-rw-r--r--libbb/verror_msg.c4
-rw-r--r--libbb/vherror_msg.c4
-rw-r--r--libbb/vperror_msg.c4
-rw-r--r--libbb/warn_ignoring_args.c30
-rw-r--r--libbb/wfopen.c4
-rw-r--r--libbb/wfopen_input.c54
-rw-r--r--libbb/xconnect.c6
-rw-r--r--libbb/xfuncs.c89
-rw-r--r--libbb/xgetcwd.c2
-rw-r--r--libbb/xgethostbyname.c2
-rw-r--r--libbb/xgethostbyname2.c2
-rw-r--r--libbb/xgetlarg.c11
-rw-r--r--libbb/xgetularg.c160
-rw-r--r--libbb/xreadlink.c2
-rw-r--r--libbb/xregcomp.c2
-rw-r--r--libpwdgrp/shadow.c2
-rw-r--r--loginutils/addgroup.c23
-rw-r--r--loginutils/adduser.c38
-rw-r--r--loginutils/deluser.c38
-rw-r--r--loginutils/getty.c23
-rw-r--r--loginutils/login.c16
-rw-r--r--loginutils/passwd.c26
-rw-r--r--loginutils/su.c14
-rw-r--r--loginutils/sulogin.c6
-rw-r--r--loginutils/vlock.c15
-rw-r--r--miscutils/adjtimex.c6
-rw-r--r--miscutils/crond.c10
-rw-r--r--miscutils/crontab.c28
-rw-r--r--miscutils/dc.c10
-rw-r--r--miscutils/dutmp.c95
-rw-r--r--miscutils/makedevs.c8
-rw-r--r--miscutils/mt.c12
-rw-r--r--miscutils/strings.c4
-rw-r--r--miscutils/time.c16
-rw-r--r--miscutils/update.c4
-rw-r--r--miscutils/watchdog.c4
-rw-r--r--modutils/insmod.c126
-rw-r--r--modutils/lsmod.c11
-rw-r--r--modutils/modprobe.c36
-rw-r--r--modutils/rmmod.c10
-rw-r--r--networking/arping.c42
-rw-r--r--networking/ftpgetput.c50
-rw-r--r--networking/hostname.c12
-rw-r--r--networking/httpd.c58
-rw-r--r--networking/ifconfig.c16
-rw-r--r--networking/ifupdown.c84
-rw-r--r--networking/inetd.c6
-rw-r--r--networking/ip.c4
-rw-r--r--networking/ipcalc.c12
-rw-r--r--networking/libiproute/ip_parse_common_args.c4
-rw-r--r--networking/libiproute/ipaddress.c24
-rw-r--r--networking/libiproute/iplink.c8
-rw-r--r--networking/libiproute/iproute.c34
-rw-r--r--networking/libiproute/iptunnel.c40
-rw-r--r--networking/libiproute/libnetlink.c70
-rw-r--r--networking/libiproute/ll_addr.c6
-rw-r--r--networking/libiproute/utils.c18
-rw-r--r--networking/nameif.c16
-rw-r--r--networking/nc.c24
-rw-r--r--networking/netstat.c14
-rw-r--r--networking/nslookup.c4
-rw-r--r--networking/ping.c26
-rw-r--r--networking/ping6.c32
-rw-r--r--networking/route.c76
-rw-r--r--networking/telnet.c2
-rw-r--r--networking/telnetd.c14
-rw-r--r--networking/tftp.c42
-rw-r--r--networking/traceroute.c26
-rw-r--r--networking/udhcp/dhcpc.c6
-rw-r--r--networking/vconfig.c62
-rw-r--r--networking/wget.c46
-rw-r--r--procps/free.c2
-rw-r--r--procps/kill.c16
-rw-r--r--procps/pidof.c2
-rw-r--r--procps/renice.c4
-rw-r--r--procps/top.c20
-rw-r--r--shell/ash.c32
-rw-r--r--shell/cmdedit.c25
-rw-r--r--shell/hush.c66
-rw-r--r--shell/lash.c70
-rw-r--r--shell/msh.c6
-rw-r--r--sysklogd/klogd.c10
-rw-r--r--sysklogd/logger.c6
-rw-r--r--sysklogd/logread.c2
-rw-r--r--sysklogd/syslogd.c34
-rw-r--r--util-linux/dmesg.c8
-rw-r--r--util-linux/fbset.c16
-rw-r--r--util-linux/fdflush.c12
-rw-r--r--util-linux/fdisk.c10
-rw-r--r--util-linux/freeramdisk.c6
-rw-r--r--util-linux/fsck_minix.c10
-rw-r--r--util-linux/getopt.c22
-rw-r--r--util-linux/hexdump.c149
-rw-r--r--util-linux/hwclock.c18
-rw-r--r--util-linux/losetup.c6
-rw-r--r--util-linux/mkfs_minix.c62
-rw-r--r--util-linux/mkswap.c46
-rw-r--r--util-linux/more.c4
-rw-r--r--util-linux/mount.c34
-rw-r--r--util-linux/nfsmount.c30
-rw-r--r--util-linux/pivot_root.c4
-rw-r--r--util-linux/rdate.c8
-rw-r--r--util-linux/swaponoff.c14
-rw-r--r--util-linux/umount.c21
295 files changed, 6907 insertions, 5533 deletions
diff --git a/Makefile b/Makefile
index 48911f77e..6be57b554 100644
--- a/Makefile
+++ b/Makefile
@@ -29,7 +29,7 @@ include Rules.mak
DIRS:=applets archival archival/libunarchive coreutils console-tools \
debianutils editors findutils init miscutils modutils networking \
networking/libiproute networking/udhcp procps loginutils shell \
- sysklogd util-linux libbb libpwdgrp
+ sysklogd util-linux libbb libpwdgrp coreutils/libcoreutils
ifeq ($(strip $(HAVE_DOT_CONFIG)),y)
diff --git a/applets/applets.c b/applets/applets.c
index 9f69da185..1b69ade92 100644
--- a/applets/applets.c
+++ b/applets/applets.c
@@ -78,7 +78,7 @@ static struct BB_suid_config *suid_config;
-extern void show_usage(void)
+extern void bb_show_usage(void)
{
const char *format_string;
const char *usage_string = usage_messages;
@@ -93,7 +93,7 @@ extern void show_usage(void)
format_string = "%s\n\nUsage: %s %s\n\n";
if(*usage_string == '\b')
format_string = "%s\n\nNo help available.\n\n";
- fprintf(stderr, format_string, full_version, applet_using->name, usage_string);
+ fprintf(stderr, format_string, bb_msg_full_version, applet_using->name, usage_string);
exit(EXIT_FAILURE);
}
@@ -127,7 +127,7 @@ void run_applet_by_name(const char *name, int argc, char **argv)
recurse_level++;
/* Do a binary search to find the applet entry given the name. */
if ((applet_using = find_applet_by_name(name)) != NULL) {
- applet_name = applet_using->name;
+ bb_applet_name = applet_using->name;
if (argv[1] && strcmp(argv[1], "--help") == 0) {
if (strcmp(applet_using->name, "busybox")==0) {
if(argv[2])
@@ -136,7 +136,7 @@ void run_applet_by_name(const char *name, int argc, char **argv)
applet_using = NULL;
}
if(applet_using)
- show_usage();
+ bb_show_usage();
been_there_done_that=1;
busybox_main(0, NULL);
}
@@ -201,18 +201,18 @@ void check_suid ( struct BB_applet *applet )
m >>= 3;
if (!( m & S_IXOTH )) /* is x bit not set ? */
- error_msg_and_die ( "You have no permission to run this applet!" );
+ bb_error_msg_and_die ( "You have no permission to run this applet!" );
if (( sct-> m_mode & ( S_ISGID | S_IXGRP )) == ( S_ISGID | S_IXGRP )) { /* *both* have to be set for sgid */
if ( setegid ( sct-> m_gid ))
- error_msg_and_die ( "BusyBox binary has insufficient rights to set proper GID for applet!" );
+ bb_error_msg_and_die ( "BusyBox binary has insufficient rights to set proper GID for applet!" );
}
else
setgid ( rgid ); /* no sgid -> drop */
if ( sct-> m_mode & S_ISUID ) {
if ( seteuid ( sct-> m_uid ))
- error_msg_and_die ( "BusyBox binary has insufficient rights to set proper UID for applet!" );
+ bb_error_msg_and_die ( "BusyBox binary has insufficient rights to set proper UID for applet!" );
}
else
setuid ( ruid ); /* no suid -> drop */
@@ -237,7 +237,7 @@ void check_suid ( struct BB_applet *applet )
if ( applet-> need_suid == _BB_SUID_ALWAYS ) {
if ( geteuid ( ) != 0 )
- error_msg_and_die ( "This applet requires root priviledges!" );
+ bb_error_msg_and_die ( "This applet requires root priviledges!" );
}
else if ( applet-> need_suid == _BB_SUID_NEVER ) {
setgid ( rgid ); /* drop all priviledges */
@@ -280,7 +280,7 @@ int parse_config_file ( void )
p = strchr ( buffer, '#' );
if ( p )
*p = 0;
- p = buffer + xstrlen ( buffer );
+ p = buffer + bb_strlen ( buffer );
while (( p > buffer ) && isspace ( *--p ))
*p = 0;
diff --git a/applets/busybox.c b/applets/busybox.c
index 4f1ef2661..457a85a68 100644
--- a/applets/busybox.c
+++ b/applets/busybox.c
@@ -10,7 +10,7 @@
#endif
int been_there_done_that = 0; /* Also used in applets.c */
-const char *applet_name;
+const char *bb_applet_name;
#ifdef CONFIG_FEATURE_INSTALLER
/*
@@ -60,7 +60,7 @@ static void install_links(const char *busybox, int use_symbolic_links)
install_dir[applets[i].location], applets[i].name);
rc = Link(busybox, fpc);
if (rc!=0 && errno!=EEXIST) {
- perror_msg("%s", fpc);
+ bb_perror_msg("%s", fpc);
}
free(fpc);
}
@@ -72,14 +72,14 @@ int main(int argc, char **argv)
{
const char *s;
- applet_name = argv[0];
+ bb_applet_name = argv[0];
- if (applet_name[0] == '-')
- applet_name++;
+ if (bb_applet_name[0] == '-')
+ bb_applet_name++;
- for (s = applet_name; *s != '\0';) {
+ for (s = bb_applet_name; *s != '\0';) {
if (*s++ == '/')
- applet_name = s;
+ bb_applet_name = s;
}
#ifdef CONFIG_LOCALE_SUPPORT
@@ -91,8 +91,8 @@ int main(int argc, char **argv)
}
#endif
- run_applet_by_name(applet_name, argc, argv);
- error_msg_and_die("applet not found");
+ run_applet_by_name(bb_applet_name, argc, argv);
+ bb_error_msg_and_die("applet not found");
}
@@ -143,7 +143,7 @@ int busybox_main(int argc, char **argv)
"\tutilities into a single executable. Most people will create a\n"
"\tlink to busybox for each function they wish to use, and BusyBox\n"
"\twill act like whatever it was invoked as.\n"
- "\nCurrently defined functions:\n", full_version);
+ "\nCurrently defined functions:\n", bb_msg_full_version);
while (a->name != 0) {
col +=
diff --git a/archival/ar.c b/archival/ar.c
index 87968f7be..57ec92719 100644
--- a/archival/ar.c
+++ b/archival/ar.c
@@ -40,7 +40,7 @@
static void header_verbose_list_ar(const file_header_t *file_header)
{
- const char *mode = mode_string(file_header->mode);
+ const char *mode = bb_mode_string(file_header->mode);
char *mtime;
mtime = ctime(&file_header->mtime);
@@ -58,7 +58,7 @@ static void data_extract_regular_file(archive_handle_t *archive_handle)
int dst_fd;
file_header = archive_handle->file_header;
- dst_fd = xopen(file_header->name, O_WRONLY | O_CREAT);
+ dst_fd = bb_xopen(file_header->name, O_WRONLY | O_CREAT);
archive_copy_file(archive_handle, dst_fd);
close(dst_fd);
@@ -110,16 +110,16 @@ extern int ar_main(int argc, char **argv)
archive_handle->action_header = header_verbose_list_ar;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
/* check the src filename was specified */
if (optind == argc) {
- show_usage();
+ bb_show_usage();
}
- archive_handle->src_fd = xopen(argv[optind++], O_RDONLY);
+ archive_handle->src_fd = bb_xopen(argv[optind++], O_RDONLY);
/* TODO: This is the same as in tar, seperate function ? */
while (optind < argc) {
@@ -133,7 +133,7 @@ extern int ar_main(int argc, char **argv)
#else
archive_xread_all(archive_handle, magic, 7);
if (strncmp(magic, "!<arch>", 7) != 0) {
- error_msg_and_die("Invalid ar magic");
+ bb_error_msg_and_die("Invalid ar magic");
}
archive_handle->offset += 7;
diff --git a/archival/bunzip2.c b/archival/bunzip2.c
index d5c06f4fd..eb5238cd4 100644
--- a/archival/bunzip2.c
+++ b/archival/bunzip2.c
@@ -41,7 +41,7 @@ int bunzip2_main(int argc, char **argv)
char *delete_name = NULL;
/* if called as bzcat */
- if (strcmp(applet_name, "bzcat") == 0)
+ if (strcmp(bb_applet_name, "bzcat") == 0)
flags |= bunzip_to_stdout;
while ((opt = getopt(argc, argv, "cfh")) != -1) {
@@ -54,7 +54,7 @@ int bunzip2_main(int argc, char **argv)
break;
case 'h':
default:
- show_usage(); /* exit's inside usage */
+ bb_show_usage(); /* exit's inside usage */
}
}
@@ -64,23 +64,23 @@ int bunzip2_main(int argc, char **argv)
src_fd = fileno(stdin);
} else {
/* Open input file */
- src_fd = xopen(argv[optind], O_RDONLY);
+ src_fd = bb_xopen(argv[optind], O_RDONLY);
- save_name = xstrdup(argv[optind]);
+ save_name = bb_xstrdup(argv[optind]);
if (strcmp(save_name + strlen(save_name) - 4, ".bz2") != 0)
- error_msg_and_die("Invalid extension");
+ bb_error_msg_and_die("Invalid extension");
save_name[strlen(save_name) - 4] = '\0';
}
/* Check that the input is sane. */
if (isatty(src_fd) && (flags & bunzip_force) == 0) {
- error_msg_and_die("compressed data not read from terminal. Use -f to force it.");
+ bb_error_msg_and_die("compressed data not read from terminal. Use -f to force it.");
}
if (flags & bunzip_to_stdout) {
dst_fd = fileno(stdout);
} else {
- dst_fd = xopen(save_name, O_WRONLY | O_CREAT);
+ dst_fd = bb_xopen(save_name, O_WRONLY | O_CREAT);
}
if (uncompressStream(src_fd, dst_fd)) {
@@ -96,7 +96,7 @@ int bunzip2_main(int argc, char **argv)
}
if ((delete_name) && (unlink(delete_name) < 0)) {
- error_msg_and_die("Couldn't remove %s", delete_name);
+ bb_error_msg_and_die("Couldn't remove %s", delete_name);
}
return status;
diff --git a/archival/cpio.c b/archival/cpio.c
index 49f3f88e4..111807c43 100644
--- a/archival/cpio.c
+++ b/archival/cpio.c
@@ -63,11 +63,11 @@ extern int cpio_main(int argc, char **argv)
archive_handle->action_header = header_list;
break;
case 'F':
- archive_handle->src_fd = xopen(optarg, O_RDONLY);
+ archive_handle->src_fd = bb_xopen(optarg, O_RDONLY);
archive_handle->seek = seek_by_jump;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
diff --git a/archival/dpkg.c b/archival/dpkg.c
index 692592268..3288f7e63 100644
--- a/archival/dpkg.c
+++ b/archival/dpkg.c
@@ -177,7 +177,7 @@ int search_name_hashtable(const char *key)
}
}
}
- name_hashtable[probe_address] = xstrdup(key);
+ name_hashtable[probe_address] = bb_xstrdup(key);
return(probe_address);
}
@@ -218,10 +218,10 @@ int version_compare_part(const char *version1, const char *version2)
int ret;
if (version1 == NULL) {
- version1 = xstrdup("");
+ version1 = bb_xstrdup("");
}
if (version2 == NULL) {
- version2 = xstrdup("");
+ version2 = bb_xstrdup("");
}
upstream_len1 = strlen(version1);
upstream_len2 = strlen(version2);
@@ -229,10 +229,10 @@ int version_compare_part(const char *version1, const char *version2)
while ((len1 < upstream_len1) || (len2 < upstream_len2)) {
/* Compare non-digit section */
tmp_int = strcspn(&version1[len1], "0123456789");
- name1_char = xstrndup(&version1[len1], tmp_int);
+ name1_char = bb_xstrndup(&version1[len1], tmp_int);
len1 += tmp_int;
tmp_int = strcspn(&version2[len2], "0123456789");
- name2_char = xstrndup(&version2[len2], tmp_int);
+ name2_char = bb_xstrndup(&version2[len2], tmp_int);
len2 += tmp_int;
tmp_int = strcmp(name1_char, name2_char);
free(name1_char);
@@ -244,10 +244,10 @@ int version_compare_part(const char *version1, const char *version2)
/* Compare digits */
tmp_int = strspn(&version1[len1], "0123456789");
- name1_char = xstrndup(&version1[len1], tmp_int);
+ name1_char = bb_xstrndup(&version1[len1], tmp_int);
len1 += tmp_int;
tmp_int = strspn(&version2[len2], "0123456789");
- name2_char = xstrndup(&version2[len2], tmp_int);
+ name2_char = bb_xstrndup(&version2[len2], tmp_int);
len2 += tmp_int;
ver_num1 = atoi(name1_char);
ver_num2 = atoi(name2_char);
@@ -306,8 +306,8 @@ int version_compare(const unsigned int ver1, const unsigned int ver2)
}
/* Compare upstream version */
- upstream_ver1 = xstrdup(ver1_ptr);
- upstream_ver2 = xstrdup(ver2_ptr);
+ upstream_ver1 = bb_xstrdup(ver1_ptr);
+ upstream_ver2 = bb_xstrdup(ver2_ptr);
/* Chop off debian version, and store for later use */
deb_ver1 = strrchr(upstream_ver1, '-');
@@ -397,7 +397,7 @@ int search_package_hashtable(const unsigned int name, const unsigned int version
*/
void add_split_dependencies(common_node_t *parent_node, const char *whole_line, unsigned int edge_type)
{
- char *line = xstrdup(whole_line);
+ char *line = bb_xstrdup(whole_line);
char *line2;
char *line_ptr1 = NULL;
char *line_ptr2 = NULL;
@@ -410,7 +410,7 @@ void add_split_dependencies(common_node_t *parent_node, const char *whole_line,
field = strtok_r(line, ",", &line_ptr1);
do {
- line2 = xstrdup(field);
+ line2 = bb_xstrdup(field);
field2 = strtok_r(line2, "|", &line_ptr2);
if ((edge_type == EDGE_DEPENDS) && (strcmp(field, field2) != 0)) {
type = EDGE_OR_DEPENDS;
@@ -457,7 +457,7 @@ void add_split_dependencies(common_node_t *parent_node, const char *whole_line,
else if (strncmp(version, ">=", offset_ch) == 0) {
edge->operator = VER_MORE_EQUAL;
} else {
- error_msg_and_die("Illegal operator\n");
+ bb_error_msg_and_die("Illegal operator\n");
}
}
/* skip to start of version numbers */
@@ -588,7 +588,7 @@ unsigned int get_status(const unsigned int status_node, const int num)
status_string += strspn(status_string, " ");
}
len = strcspn(status_string, " \n\0");
- state_sub_string = xstrndup(status_string, len);
+ state_sub_string = bb_xstrndup(status_string, len);
state_sub_num = search_name_hashtable(state_sub_string);
free(state_sub_string);
return(state_sub_num);
@@ -620,7 +620,7 @@ void set_status(const unsigned int status_node_num, const char *new_value, const
status_len = new_value_len;
break;
default:
- error_msg_and_die("DEBUG ONLY: this shouldnt happen");
+ bb_error_msg_and_die("DEBUG ONLY: this shouldnt happen");
}
new_status = (char *) xmalloc(want_len + flag_len + status_len + 3);
@@ -638,7 +638,7 @@ void index_status_file(const char *filename)
status_node_t *status_node = NULL;
unsigned int status_num;
- status_file = xfopen(filename, "r");
+ status_file = bb_xfopen(filename, "r");
while ((control_buffer = fgets_str(status_file, "\n\n")) != NULL) {
const unsigned int package_num = fill_package_struct(control_buffer);
if (package_num != -1) {
@@ -648,7 +648,7 @@ void index_status_file(const char *filename)
if (status_line != NULL) {
status_line += 7;
status_line += strspn(status_line, " \n\t");
- status_line = xstrndup(status_line, strcspn(status_line, "\n\0"));
+ status_line = bb_xstrndup(status_line, strcspn(status_line, "\n\0"));
status_node->status = search_name_hashtable(status_line);
free(status_line);
}
@@ -754,8 +754,8 @@ void write_buffer_no_status(FILE *new_status_file, const char *control_buffer)
/* This could do with a cleanup */
void write_status_file(deb_file_t **deb_file)
{
- FILE *old_status_file = xfopen("/var/lib/dpkg/status", "r");
- FILE *new_status_file = xfopen("/var/lib/dpkg/status.udeb", "w");
+ FILE *old_status_file = bb_xfopen("/var/lib/dpkg/status", "r");
+ FILE *new_status_file = bb_xfopen("/var/lib/dpkg/status.udeb", "w");
char *package_name;
char *status_from_file;
char *control_buffer = NULL;
@@ -773,14 +773,14 @@ void write_status_file(deb_file_t **deb_file)
tmp_string += 8;
tmp_string += strspn(tmp_string, " \n\t");
- package_name = xstrndup(tmp_string, strcspn(tmp_string, "\n\0"));
+ package_name = bb_xstrndup(tmp_string, strcspn(tmp_string, "\n\0"));
write_flag = FALSE;
tmp_string = strstr(control_buffer, "Status:");
if (tmp_string != NULL) {
/* Seperate the status value from the control buffer */
tmp_string += 7;
tmp_string += strspn(tmp_string, " \n\t");
- status_from_file = xstrndup(tmp_string, strcspn(tmp_string, "\n"));
+ status_from_file = bb_xstrndup(tmp_string, strcspn(tmp_string, "\n"));
} else {
status_from_file = NULL;
}
@@ -810,7 +810,7 @@ void write_status_file(deb_file_t **deb_file)
}
/* This is temperary, debugging only */
if (deb_file[i] == NULL) {
- error_msg_and_die("ALERT: Couldnt find a control file, your status file may be broken, status may be incorrect for %s", package_name);
+ bb_error_msg_and_die("ALERT: Couldnt find a control file, your status file may be broken, status may be incorrect for %s", package_name);
}
}
else if (strcmp("not-installed", name_hashtable[state_status]) == 0) {
@@ -881,15 +881,15 @@ void write_status_file(deb_file_t **deb_file)
if (rename("/var/lib/dpkg/status", "/var/lib/dpkg/status.udeb.bak") == -1) {
struct stat stat_buf;
if (stat("/var/lib/dpkg/status", &stat_buf) == 0) {
- error_msg_and_die("Couldnt create backup status file");
+ bb_error_msg_and_die("Couldnt create backup status file");
}
/* Its ok if renaming the status file fails becasue status
* file doesnt exist, maybe we are starting from scratch */
- error_msg("No status file found, creating new one");
+ bb_error_msg("No status file found, creating new one");
}
if (rename("/var/lib/dpkg/status.udeb", "/var/lib/dpkg/status") == -1) {
- error_msg_and_die("DANGER: Couldnt create status file, you need to manually repair your status file");
+ bb_error_msg_and_die("DANGER: Couldnt create status file, you need to manually repair your status file");
}
}
@@ -976,7 +976,7 @@ int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
}
if (result) {
- error_msg_and_die("Package %s conflicts with %s",
+ bb_error_msg_and_die("Package %s conflicts with %s",
name_hashtable[package_node->name],
name_hashtable[package_edge->name]);
}
@@ -1021,7 +1021,7 @@ int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
}
if (result) {
- error_msg_and_die("Package %s pre-depends on %s, but it is not installed",
+ bb_error_msg_and_die("Package %s pre-depends on %s, but it is not installed",
name_hashtable[package_node->name],
name_hashtable[package_edge->name]);
}
@@ -1038,7 +1038,7 @@ int check_deps(deb_file_t **deb_file, int deb_start, int dep_max_count)
}
/* It must be already installed, or to be installed */
if (result) {
- error_msg_and_die("Package %s depends on %s, but it is not installed, or flaged to be installed",
+ bb_error_msg_and_die("Package %s depends on %s, but it is not installed, or flaged to be installed",
name_hashtable[package_node->name],
name_hashtable[package_edge->name]);
}
@@ -1065,9 +1065,8 @@ char **create_list(const char *filename)
return(NULL);
}
- while ((line = get_line_from_file(list_stream)) != NULL) {
+ while ((line = bb_get_chomped_line_from_file(list_stream)) != NULL) {
file_list = xrealloc(file_list, sizeof(char *) * (count + 2));
- chomp(line);
file_list[count] = line;
count++;
}
@@ -1228,7 +1227,7 @@ void remove_package(const unsigned int package_num)
/* run prerm script */
return_value = run_package_script(package_name, "prerm");
if (return_value == -1) {
- error_msg_and_die("script failed, prerm failure");
+ bb_error_msg_and_die("script failed, prerm failure");
}
/* Create a list of files to remove, and a seperate list of those to keep */
@@ -1245,7 +1244,7 @@ void remove_package(const unsigned int package_num)
/* Create a list of files in /var/lib/dpkg/info/<package>.* to keep */
exclude_files = xmalloc(sizeof(char*) * 3);
- exclude_files[0] = xstrdup(conffile_name);
+ exclude_files[0] = bb_xstrdup(conffile_name);
exclude_files[1] = xmalloc(package_name_length + 27);
sprintf(exclude_files[1], "/var/lib/dpkg/info/%s.postrm", package_name);
exclude_files[2] = NULL;
@@ -1275,7 +1274,7 @@ void purge_package(const unsigned int package_num)
/* run prerm script */
if (run_package_script(package_name, "prerm") != 0) {
- error_msg_and_die("script failed, prerm failure");
+ bb_error_msg_and_die("script failed, prerm failure");
}
/* Create a list of files to remove */
@@ -1297,7 +1296,7 @@ void purge_package(const unsigned int package_num)
/* run postrm script */
if (run_package_script(package_name, "postrm") == -1) {
- error_msg_and_die("postrm fialure.. set status to what?");
+ bb_error_msg_and_die("postrm fialure.. set status to what?");
}
/* Change package status */
@@ -1312,7 +1311,7 @@ static archive_handle_t *init_archive_deb_ar(const char *filename)
/* Setup an ar archive handle that refers to the gzip sub archive */
ar_handle = init_handle();
ar_handle->filter = filter_accept_list_reassign;
- ar_handle->src_fd = xopen(filename, O_RDONLY);
+ ar_handle->src_fd = bb_xopen(filename, O_RDONLY);
return(ar_handle);
}
@@ -1420,7 +1419,7 @@ static void unpack_package(deb_file_t *deb_file)
/* Run the preinst prior to extracting */
if (run_package_script(package_name, "preinst") != 0) {
/* when preinst returns exit code != 0 then quit installation process */
- error_msg_and_die("subprocess pre-installation script returned error.");
+ bb_error_msg_and_die("subprocess pre-installation script returned error.");
}
/* Extract data.tar.gz to the root directory */
@@ -1430,7 +1429,7 @@ static void unpack_package(deb_file_t *deb_file)
/* Create the list file */
strcat(info_prefix, "list");
- out_stream = xfopen(info_prefix, "w");
+ out_stream = bb_xfopen(info_prefix, "w");
while (archive_handle->passed) {
/* blindly skip over the leading '.' */
fputs(archive_handle->passed->data + 1, out_stream);
@@ -1457,7 +1456,7 @@ void configure_package(deb_file_t *deb_file)
/* Run the postinst script */
if (run_package_script(package_name, "postinst") != 0) {
/* TODO: handle failure gracefully */
- error_msg_and_die("postrm failure.. set status to what?");
+ bb_error_msg_and_die("postrm failure.. set status to what?");
}
/* Change status to reflect success */
set_status(status_num, "install", 1);
@@ -1506,12 +1505,12 @@ int dpkg_main(int argc, char **argv)
dpkg_opt |= dpkg_opt_filename;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
/* check for non-otion argument if expected */
if ((dpkg_opt == 0) || ((argc == optind) && !(dpkg_opt && dpkg_opt_list_installed))) {
- show_usage();
+ bb_show_usage();
}
/* puts("(Reading database ... xxxxx files and directories installed.)"); */
@@ -1538,13 +1537,13 @@ int dpkg_main(int argc, char **argv)
init_archive_deb_control(archive_handle);
deb_file[deb_count]->control_file = deb_extract_control_file_to_buffer(archive_handle, control_list);
if (deb_file[deb_count]->control_file == NULL) {
- error_msg_and_die("Couldnt extract control file");
+ bb_error_msg_and_die("Couldnt extract control file");
}
- deb_file[deb_count]->filename = xstrdup(argv[optind]);
+ deb_file[deb_count]->filename = bb_xstrdup(argv[optind]);
package_num = fill_package_struct(deb_file[deb_count]->control_file);
if (package_num == -1) {
- error_msg("Invalid control file in %s", argv[optind]);
+ bb_error_msg("Invalid control file in %s", argv[optind]);
continue;
}
deb_file[deb_count]->package = (unsigned int) package_num;
@@ -1574,7 +1573,7 @@ int dpkg_main(int argc, char **argv)
search_name_hashtable(argv[optind]),
search_name_hashtable("ANY"), VER_ANY);
if (package_hashtable[deb_file[deb_count]->package] == NULL) {
- error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]);
+ bb_error_msg_and_die("Package %s is uninstalled or unknown\n", argv[optind]);
}
state_status = get_status(search_status_hashtable(name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]), 3);
@@ -1582,13 +1581,13 @@ int dpkg_main(int argc, char **argv)
if (dpkg_opt & dpkg_opt_remove) {
if ((strcmp(name_hashtable[state_status], "not-installed") == 0) ||
(strcmp(name_hashtable[state_status], "config-files") == 0)) {
- error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
+ bb_error_msg_and_die("%s is already removed.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
}
}
else if (dpkg_opt & dpkg_opt_purge) {
/* if package status is "conf-files" then its ok */
if (strcmp(name_hashtable[state_status], "not-installed") == 0) {
- error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
+ bb_error_msg_and_die("%s is already purged.", name_hashtable[package_hashtable[deb_file[deb_count]->package]->name]);
}
}
}
@@ -1601,7 +1600,7 @@ int dpkg_main(int argc, char **argv)
/* TODO: check dependencies before removing */
if ((dpkg_opt & dpkg_opt_force_ignore_depends) != dpkg_opt_force_ignore_depends) {
if (!check_deps(deb_file, 0, deb_count)) {
- error_msg_and_die("Dependency check failed");
+ bb_error_msg_and_die("Dependency check failed");
}
}
diff --git a/archival/dpkg_deb.c b/archival/dpkg_deb.c
index 2c338227c..2d7383fd7 100644
--- a/archival/dpkg_deb.c
+++ b/archival/dpkg_deb.c
@@ -82,15 +82,15 @@ extern int dpkg_deb_main(int argc, char **argv)
tar_archive->action_data = data_extract_all;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
if (optind + 2 < argc) {
- show_usage();
+ bb_show_usage();
}
- tar_archive->src_fd = ar_archive->src_fd = xopen(argv[optind++], O_RDONLY);
+ tar_archive->src_fd = ar_archive->src_fd = bb_xopen(argv[optind++], O_RDONLY);
/* Workout where to extract the files */
/* 2nd argument is a dir name */
diff --git a/archival/gunzip.c b/archival/gunzip.c
index e9963a8d2..3350da052 100644
--- a/archival/gunzip.c
+++ b/archival/gunzip.c
@@ -82,7 +82,7 @@ extern int gunzip_main(int argc, char **argv)
int opt;
/* if called as zcat */
- if (strcmp(applet_name, "zcat") == 0) {
+ if (strcmp(bb_applet_name, "zcat") == 0) {
flags |= gunzip_to_stdout;
}
@@ -100,7 +100,7 @@ extern int gunzip_main(int argc, char **argv)
case 'd': /* Used to convert gzip to gunzip. */
break;
default:
- show_usage(); /* exit's inside usage */
+ bb_show_usage(); /* exit's inside usage */
}
}
@@ -118,29 +118,29 @@ extern int gunzip_main(int argc, char **argv)
src_fd = fileno(stdin);
flags |= gunzip_to_stdout;
} else {
- src_fd = xopen(old_path, O_RDONLY);
+ src_fd = bb_xopen(old_path, O_RDONLY);
/* Get the time stamp on the input file. */
if (stat(old_path, &stat_buf) < 0) {
- error_msg_and_die("Couldn't stat file %s", old_path);
+ bb_error_msg_and_die("Couldn't stat file %s", old_path);
}
}
/* Check that the input is sane. */
if (isatty(src_fd) && ((flags & gunzip_force) == 0)) {
- error_msg_and_die
+ bb_error_msg_and_die
("compressed data not read from terminal. Use -f to force it.");
}
/* Set output filename and number */
if (flags & gunzip_test) {
- dst_fd = xopen("/dev/null", O_WRONLY); /* why does test use filenum 2 ? */
+ dst_fd = bb_xopen("/dev/null", O_WRONLY); /* why does test use filenum 2 ? */
} else if (flags & gunzip_to_stdout) {
dst_fd = fileno(stdout);
} else {
char *extension;
- new_path = xstrdup(old_path);
+ new_path = bb_xstrdup(old_path);
extension = strrchr(new_path, '.');
#ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS
@@ -154,11 +154,11 @@ extern int gunzip_main(int argc, char **argv)
extension[2] = 'a';
extension[3] = 'r';
} else {
- error_msg_and_die("Invalid extension");
+ bb_error_msg_and_die("Invalid extension");
}
/* Open output file */
- dst_fd = xopen(new_path, O_WRONLY | O_CREAT);
+ dst_fd = bb_xopen(new_path, O_WRONLY | O_CREAT);
/* Set permissions on the file */
chmod(new_path, stat_buf.st_mode);
@@ -168,10 +168,10 @@ extern int gunzip_main(int argc, char **argv)
}
/* do the decompression, and cleanup */
- if (xread_char(src_fd) == 0x1f) {
+ if (bb_xread_char(src_fd) == 0x1f) {
unsigned char magic2;
- magic2 = xread_char(src_fd);
+ magic2 = bb_xread_char(src_fd);
#ifdef CONFIG_FEATURE_GUNZIP_UNCOMPRESS
if (magic2 == 0x9d) {
status = uncompress(src_fd, dst_fd);
@@ -181,14 +181,14 @@ extern int gunzip_main(int argc, char **argv)
check_header_gzip(src_fd);
status = inflate(src_fd, dst_fd);
if (status != 0) {
- error_msg_and_die("Error inflating");
+ bb_error_msg_and_die("Error inflating");
}
check_trailer_gzip(src_fd);
} else {
- error_msg_and_die("Invalid magic");
+ bb_error_msg_and_die("Invalid magic");
}
} else {
- error_msg_and_die("Invalid magic");
+ bb_error_msg_and_die("Invalid magic");
}
if ((status != EXIT_SUCCESS) && (new_path)) {
@@ -205,7 +205,7 @@ extern int gunzip_main(int argc, char **argv)
/* delete_path will be NULL if in test mode or from stdin */
if (delete_path && (unlink(delete_path) == -1)) {
- error_msg_and_die("Couldn't remove %s", delete_path);
+ bb_error_msg_and_die("Couldn't remove %s", delete_path);
}
free(new_path);
diff --git a/archival/gzip.c b/archival/gzip.c
index 971724d74..cabc4aa2f 100644
--- a/archival/gzip.c
+++ b/archival/gzip.c
@@ -187,7 +187,7 @@ typedef int file_t; /* Do not use stdio */
/* Diagnostic functions */
#ifdef DEBUG
-# define Assert(cond,msg) {if(!(cond)) error_msg(msg);}
+# define Assert(cond,msg) {if(!(cond)) bb_error_msg(msg);}
# define Trace(x) fprintf x
# define Tracev(x) {if (verbose) fprintf x ;}
# define Tracevv(x) {if (verbose>1) fprintf x ;}
@@ -352,10 +352,10 @@ static void clear_bufs(void)
bytes_in = 0L;
}
-static void write_error_msg(void)
+static void write_bb_error_msg(void)
{
fputc('\n', stderr);
- perror_msg("");
+ bb_perror_nomsg();
abort_gzip();
}
@@ -369,7 +369,7 @@ static void write_buf(int fd, void *buf, unsigned cnt)
while ((n = write(fd, buf, cnt)) != cnt) {
if (n == (unsigned) (-1)) {
- write_error_msg();
+ write_bb_error_msg();
}
cnt -= n;
buf = (void *) ((char *) buf + n);
@@ -977,11 +977,11 @@ static void check_match(IPos start, IPos match, int length)
/* check that the match is indeed a match */
if (memcmp((char *) window + match,
(char *) window + start, length) != EQUAL) {
- error_msg(" start %d, match %d, length %d", start, match, length);
- error_msg("invalid match");
+ bb_error_msg(" start %d, match %d, length %d", start, match, length);
+ bb_error_msg("invalid match");
}
if (verbose > 1) {
- error_msg("\\[%d,%d]", start - match, length);
+ bb_error_msg("\\[%d,%d]", start - match, length);
do {
putc(window[start++], stderr);
} while (--length != 0);
@@ -1232,7 +1232,7 @@ int gzip_main(int argc, char **argv)
return gunzip_main(argc, argv);
#endif
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -1282,7 +1282,7 @@ int gzip_main(int argc, char **argv)
} else {
inFileNum = open(argv[i], O_RDONLY);
if (inFileNum < 0 || fstat(inFileNum, &statBuf) < 0)
- perror_msg_and_die("%s", argv[i]);
+ bb_perror_msg_and_die("%s", argv[i]);
time_stamp = statBuf.st_ctime;
ifile_size = statBuf.st_size;
@@ -1299,7 +1299,7 @@ int gzip_main(int argc, char **argv)
outFileNum = open(path, O_RDWR | O_CREAT | O_EXCL);
#endif
if (outFileNum < 0) {
- perror_msg("%s", path);
+ bb_perror_msg("%s", path);
free(path);
continue;
}
@@ -1311,7 +1311,7 @@ int gzip_main(int argc, char **argv)
}
if (path == NULL && isatty(outFileNum) && force == 0) {
- error_msg
+ bb_error_msg
("compressed data not written to a terminal. Use -f to force compression.");
free(path);
continue;
@@ -1330,7 +1330,7 @@ int gzip_main(int argc, char **argv)
delFileName = path;
if (unlink(delFileName) < 0)
- perror_msg("%s", delFileName);
+ bb_perror_msg("%s", delFileName);
}
free(path);
@@ -1655,7 +1655,7 @@ static void set_file_type(void);
#else /* DEBUG */
# define send_code(c, tree) \
- { if (verbose>1) error_msg("\ncd %3d ",(c)); \
+ { if (verbose>1) bb_error_msg("\ncd %3d ",(c)); \
send_bits(tree[c].Code, tree[c].Len); }
#endif
@@ -2035,7 +2035,7 @@ static void build_tree(tree_desc * desc)
tree[n].Dad = tree[m].Dad = (ush) node;
#ifdef DUMP_BL_TREE
if (tree == bl_tree) {
- error_msg("\nnode %d(%d), sons %d(%d) %d(%d)",
+ bb_error_msg("\nnode %d(%d), sons %d(%d) %d(%d)",
node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
}
#endif
@@ -2273,7 +2273,7 @@ static ulg flush_block(char *buf, ulg stored_len, int eof)
if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) {
/* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
if (buf == (char *) 0)
- error_msg("block vanished");
+ bb_error_msg("block vanished");
copy_block(buf, (unsigned) stored_len, 0); /* without header */
compressed_len = stored_len << 3;
@@ -2442,7 +2442,7 @@ static void set_file_type()
bin_freq += dyn_ltree[n++].Freq;
*file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
if (*file_type == BINARY && translate_eol) {
- error_msg("-l used on binary file");
+ bb_error_msg("-l used on binary file");
}
}
diff --git a/archival/libunarchive/archive_copy_file.c b/archival/libunarchive/archive_copy_file.c
index faa8059ef..675bc6ffe 100644
--- a/archival/libunarchive/archive_copy_file.c
+++ b/archival/libunarchive/archive_copy_file.c
@@ -35,7 +35,7 @@ extern void archive_copy_file(const archive_handle_t *archive_handle, const int
size = archive_xread(archive_handle, buffer, size);
if (write(dst_fd, buffer, size) != size) {
- error_msg_and_die ("Short write");
+ bb_error_msg_and_die ("Short write");
}
chunksize -= size;
}
diff --git a/archival/libunarchive/archive_xread.c b/archival/libunarchive/archive_xread.c
index 7fde4c0b1..0b29dbfb9 100644
--- a/archival/libunarchive/archive_xread.c
+++ b/archival/libunarchive/archive_xread.c
@@ -26,7 +26,7 @@ extern ssize_t archive_xread(const archive_handle_t *archive_handle, unsigned ch
size = archive_handle->read(archive_handle->src_fd, buf, count);
if (size == -1) {
- perror_msg_and_die("Read error");
+ bb_perror_msg_and_die("Read error");
}
return(size);
diff --git a/archival/libunarchive/archive_xread_all.c b/archival/libunarchive/archive_xread_all.c
index ef8cc0141..cfe046b27 100644
--- a/archival/libunarchive/archive_xread_all.c
+++ b/archival/libunarchive/archive_xread_all.c
@@ -26,7 +26,7 @@ extern void archive_xread_all(const archive_handle_t *archive_handle, void *buf,
size = archive_xread(archive_handle, buf, count);
if (size != count) {
- error_msg_and_die("Short read");
+ bb_error_msg_and_die("Short read");
}
return;
}
diff --git a/archival/libunarchive/archive_xread_all_eof.c b/archival/libunarchive/archive_xread_all_eof.c
index 3cfbbd8d1..23719cd7b 100644
--- a/archival/libunarchive/archive_xread_all_eof.c
+++ b/archival/libunarchive/archive_xread_all_eof.c
@@ -26,7 +26,7 @@ extern ssize_t archive_xread_all_eof(archive_handle_t *archive_handle, unsigned
size = archive_xread(archive_handle, buf, count);
if ((size != 0) && (size != count)) {
- perror_msg_and_die("Short read, read %d of %d", size, count);
+ bb_perror_msg_and_die("Short read, read %d of %d", size, count);
}
return(size);
}
diff --git a/archival/libunarchive/check_header_gzip.c b/archival/libunarchive/check_header_gzip.c
index d661df7cc..13832c240 100644
--- a/archival/libunarchive/check_header_gzip.c
+++ b/archival/libunarchive/check_header_gzip.c
@@ -15,11 +15,11 @@ extern void check_header_gzip(int src_fd)
} formated;
} header;
- xread_all(src_fd, header.raw, 8);
+ bb_xread_all(src_fd, header.raw, 8);
/* Check the compression method */
if (header.formated.method != 8) {
- error_msg_and_die("Unknown compression method %d",
+ bb_error_msg_and_die("Unknown compression method %d",
header.formated.method);
}
@@ -27,10 +27,10 @@ extern void check_header_gzip(int src_fd)
/* bit 2 set: extra field present */
unsigned char extra_short;
- extra_short = xread_char(src_fd) + (xread_char(src_fd) << 8);
+ extra_short = bb_xread_char(src_fd) + (bb_xread_char(src_fd) << 8);
while (extra_short > 0) {
/* Ignore extra field */
- xread_char(src_fd);
+ bb_xread_char(src_fd);
extra_short--;
}
}
@@ -38,19 +38,19 @@ extern void check_header_gzip(int src_fd)
/* Discard original name if any */
if (header.formated.flags & 0x08) {
/* bit 3 set: original file name present */
- while(xread_char(src_fd) != 0);
+ while(bb_xread_char(src_fd) != 0);
}
/* Discard file comment if any */
if (header.formated.flags & 0x10) {
/* bit 4 set: file comment present */
- while(xread_char(src_fd) != 0);
+ while(bb_xread_char(src_fd) != 0);
}
/* Read the header checksum */
if (header.formated.flags & 0x02) {
- xread_char(src_fd);
- xread_char(src_fd);
+ bb_xread_char(src_fd);
+ bb_xread_char(src_fd);
}
return;
diff --git a/archival/libunarchive/data_extract_all.c b/archival/libunarchive/data_extract_all.c
index 1eb8bb388..77b4de593 100644
--- a/archival/libunarchive/data_extract_all.c
+++ b/archival/libunarchive/data_extract_all.c
@@ -34,8 +34,8 @@ extern void data_extract_all(archive_handle_t *archive_handle)
int res;
if (archive_handle->flags & ARCHIVE_CREATE_LEADING_DIRS) {
- char *name = xstrdup(file_header->name);
- make_directory (dirname(name), 0777, FILEUTILS_RECUR);
+ char *name = bb_xstrdup(file_header->name);
+ bb_make_directory (dirname(name), 0777, FILEUTILS_RECUR);
free(name);
}
@@ -47,13 +47,13 @@ extern void data_extract_all(archive_handle_t *archive_handle)
/* hard link */
res = link(file_header->link_name, file_header->name);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
- perror_msg("Couldnt create hard link");
+ bb_perror_msg("Couldnt create hard link");
}
} else
#endif
{
/* Regular file */
- dst_fd = xopen(file_header->name, O_WRONLY | O_CREAT);
+ dst_fd = bb_xopen(file_header->name, O_WRONLY | O_CREAT);
archive_copy_file(archive_handle, dst_fd);
close(dst_fd);
}
@@ -63,7 +63,7 @@ extern void data_extract_all(archive_handle_t *archive_handle)
unlink(file_header->name);
res = mkdir(file_header->name, file_header->mode);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
- perror_msg("extract_archive: %s", file_header->name);
+ bb_perror_msg("extract_archive: %s", file_header->name);
}
break;
case S_IFLNK:
@@ -71,7 +71,7 @@ extern void data_extract_all(archive_handle_t *archive_handle)
unlink(file_header->name);
res = symlink(file_header->link_name, file_header->name);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
- perror_msg("Cannot create symlink from %s to '%s'", file_header->name, file_header->link_name);
+ bb_perror_msg("Cannot create symlink from %s to '%s'", file_header->name, file_header->link_name);
}
break;
case S_IFSOCK:
@@ -81,11 +81,11 @@ extern void data_extract_all(archive_handle_t *archive_handle)
unlink(file_header->name);
res = mknod(file_header->name, file_header->mode, file_header->device);
if ((res == -1) && !(archive_handle->flags & ARCHIVE_EXTRACT_QUIET)) {
- perror_msg("Cannot create node %s", file_header->name);
+ bb_perror_msg("Cannot create node %s", file_header->name);
}
break;
default:
- error_msg_and_die("Unrecognised file type");
+ bb_error_msg_and_die("Unrecognised file type");
}
chmod(file_header->name, file_header->mode);
diff --git a/archival/libunarchive/decompress_bunzip2.c b/archival/libunarchive/decompress_bunzip2.c
index 4b611b833..0164b77e0 100644
--- a/archival/libunarchive/decompress_bunzip2.c
+++ b/archival/libunarchive/decompress_bunzip2.c
@@ -1548,7 +1548,7 @@ extern ssize_t read_bz2(int fd, void *buf, size_t count)
while (1) {
if (bzf->strm.avail_in == 0) {
- n = xread(bzf->fd, bzf->buf, BZ_MAX_UNUSED);
+ n = bb_xread(bzf->fd, bzf->buf, BZ_MAX_UNUSED);
if (n == 0) {
break;
}
@@ -1560,7 +1560,7 @@ extern ssize_t read_bz2(int fd, void *buf, size_t count)
ret = BZ2_bzDecompress(&(bzf->strm));
if ((ret != BZ_OK) && (ret != BZ_STREAM_END)) {
- error_msg_and_die("Error decompressing");
+ bb_error_msg_and_die("Error decompressing");
}
if (ret == BZ_STREAM_END) {
@@ -1628,12 +1628,12 @@ extern unsigned char uncompressStream(int src_fd, int dst_fd)
while (bzerr == BZ_OK) {
nread = read_bz2(src_fd, obuf, 5000);
if (bzerr == BZ_DATA_ERROR_MAGIC) {
- error_msg_and_die("invalid magic");
+ bb_error_msg_and_die("invalid magic");
}
if (((bzerr == BZ_OK) || (bzerr == BZ_STREAM_END)) && (nread > 0)) {
if (write(dst_fd, obuf, nread) != nread) {
BZ2_bzReadClose();
- perror_msg_and_die("Couldnt write to file");
+ bb_perror_msg_and_die("Couldnt write to file");
}
}
}
diff --git a/archival/libunarchive/decompress_uncompress.c b/archival/libunarchive/decompress_uncompress.c
index 192e98126..9851ca39d 100644
--- a/archival/libunarchive/decompress_uncompress.c
+++ b/archival/libunarchive/decompress_uncompress.c
@@ -121,14 +121,14 @@ extern int uncompress(int fd_in, int fd_out)
insize = 0;
- inbuf[0] = xread_char(fd_in);
+ inbuf[0] = bb_xread_char(fd_in);
maxbits = inbuf[0] & BIT_MASK;
block_mode = inbuf[0] & BLOCK_MODE;
maxmaxcode = MAXCODE(maxbits);
if (maxbits > BITS) {
- error_msg("compressed with %d bits, can only handle %d bits", maxbits,
+ bb_error_msg("compressed with %d bits, can only handle %d bits", maxbits,
BITS);
return -1;
}
@@ -227,11 +227,11 @@ extern int uncompress(int fd_in, int fd_out)
posbits -= n_bits;
p = &inbuf[posbits >> 3];
- error_msg
+ bb_error_msg
("insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)",
insize, posbits, p[-1], p[0], p[1], p[2], p[3],
(posbits & 07));
- error_msg("uncompress: corrupt input");
+ bb_error_msg("uncompress: corrupt input");
return -1;
}
diff --git a/archival/libunarchive/decompress_unzip.c b/archival/libunarchive/decompress_unzip.c
index 3a7334ce9..2401cf831 100644
--- a/archival/libunarchive/decompress_unzip.c
+++ b/archival/libunarchive/decompress_unzip.c
@@ -150,7 +150,7 @@ static void fill_bytebuffer(void)
/* Leave the first 4 bytes empty so we can always unwind the bitbuffer
* to the front of the bytebuffer, leave 4 bytes free at end of tail
* so we can easily top up buffer in check_trailer_gzip() */
- bytebuffer_size = 4 + xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8);
+ bytebuffer_size = 4 + bb_xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8);
bytebuffer_offset = 4;
}
}
@@ -448,7 +448,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
do {
if (e == 99) {
- error_msg_and_die("inflate_codes error 1");;
+ bb_error_msg_and_die("inflate_codes error 1");;
}
b >>= t->b;
k -= t->b;
@@ -484,7 +484,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = td + ((unsigned) b & md))->e) > 16)
do {
if (e == 99)
- error_msg_and_die("inflate_codes error 2");;
+ bb_error_msg_and_die("inflate_codes error 2");;
b >>= t->b;
k -= t->b;
e -= 16;
@@ -821,7 +821,7 @@ static int inflate_block(int *e)
if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
if (i == 1) {
- error_msg_and_die("Incomplete literal tree");
+ bb_error_msg_and_die("Incomplete literal tree");
huft_free(tl);
}
return i; /* incomplete code set */
@@ -830,7 +830,7 @@ static int inflate_block(int *e)
bd = dbits;
if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
if (i == 1) {
- error_msg_and_die("incomplete distance tree");
+ bb_error_msg_and_die("incomplete distance tree");
huft_free(td);
}
huft_free(tl);
@@ -846,7 +846,7 @@ static int inflate_block(int *e)
}
default:
/* bad block type */
- error_msg_and_die("bad block type %d\n", t);
+ bb_error_msg_and_die("bad block type %d\n", t);
}
}
@@ -884,7 +884,7 @@ static int inflate_get_next_window(void)
break;
case -2: ret = inflate_codes(0,0,0,0,0);
break;
- default: error_msg_and_die("inflate error %d", method);
+ default: bb_error_msg_and_die("inflate error %d", method);
}
if (ret == 1) {
@@ -975,16 +975,16 @@ extern void GZ_gzReadClose(void)
ssize_t nread, nwrote;
GZ_gzReadOpen(in, 0, 0);
- while(1) { // Robbed from copyfd.c
+ while(1) { // Robbed from bb_copyfd.c
nread = read_gz(in, buf, sizeof(buf));
if (nread == 0) break; // no data to write
else if (nread == -1) {
- perror_msg("read");
+ bb_perror_msg("read");
return -1;
}
- nwrote = full_write(out, buf, nread);
+ nwrote = bb_full_write(out, buf, nread);
if (nwrote == -1) {
- perror_msg("write");
+ bb_perror_msg("write");
return -1;
}
}
@@ -998,9 +998,9 @@ extern int inflate(int in, int out)
GZ_gzReadOpen(in, 0, 0);
while(1) {
int ret = inflate_get_next_window();
- nwrote = full_write(out, gunzip_window, gunzip_outbuf_count);
+ nwrote = bb_full_write(out, gunzip_window, gunzip_outbuf_count);
if (nwrote == -1) {
- perror_msg("write");
+ bb_perror_msg("write");
return -1;
}
if (ret == 0) break;
@@ -1017,7 +1017,7 @@ extern void check_trailer_gzip(int src_fd)
/* top up the input buffer with the rest of the trailer */
count = bytebuffer_size - bytebuffer_offset;
if (count < 8) {
- xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count);
+ bb_xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count);
bytebuffer_size += 8 - count;
}
for (count = 0; count != 4; count++) {
@@ -1027,14 +1027,14 @@ extern void check_trailer_gzip(int src_fd)
/* Validate decompression - crc */
if (stored_crc != (gunzip_crc ^ 0xffffffffL)) {
- error_msg_and_die("crc error");
+ bb_error_msg_and_die("crc error");
}
/* Validate decompression - size */
if (gunzip_bytes_out !=
(bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) |
(bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) {
- error_msg_and_die("Incorrect length, but crc is correct");
+ bb_error_msg_and_die("Incorrect length, but crc is correct");
}
}
diff --git a/archival/libunarchive/get_header_ar.c b/archival/libunarchive/get_header_ar.c
index 1e0e6c12d..6c576a8da 100644
--- a/archival/libunarchive/get_header_ar.c
+++ b/archival/libunarchive/get_header_ar.c
@@ -41,7 +41,7 @@ extern char get_header_ar(archive_handle_t *archive_handle)
static unsigned int ar_long_name_size;
#endif
- /* dont use xread as we want to handle the error ourself */
+ /* dont use bb_xread as we want to handle the error ourself */
if (read(archive_handle->src_fd, ar.raw, 60) != 60) {
/* End Of File */
return(EXIT_FAILURE);
@@ -51,14 +51,14 @@ extern char get_header_ar(archive_handle_t *archive_handle)
if (ar.raw[0] == '\n') {
/* fix up the header, we started reading 1 byte too early */
memmove(ar.raw, &ar.raw[1], 59);
- ar.raw[59] = xread_char(archive_handle->src_fd);
+ ar.raw[59] = bb_xread_char(archive_handle->src_fd);
archive_handle->offset++;
}
archive_handle->offset += 60;
/* align the headers based on the header magic */
if ((ar.formated.magic[0] != '`') || (ar.formated.magic[1] != '\n')) {
- error_msg_and_die("Invalid ar header");
+ bb_error_msg_and_die("Invalid ar header");
}
typed->mode = strtol(ar.formated.mode, NULL, 8);
@@ -76,7 +76,7 @@ extern char get_header_ar(archive_handle_t *archive_handle)
* in static variable long_names for use in future entries */
ar_long_name_size = typed->size;
ar_long_names = xmalloc(ar_long_name_size);
- xread_all(archive_handle->src_fd, ar_long_names, ar_long_name_size);
+ bb_xread_all(archive_handle->src_fd, ar_long_names, ar_long_name_size);
archive_handle->offset += ar_long_name_size;
/* This ar entries data section only contained filenames for other records
* they are stored in the static ar_long_names for future reference */
@@ -90,16 +90,16 @@ extern char get_header_ar(archive_handle_t *archive_handle)
(saved in variable long_name) that conatains the real filename */
const unsigned int long_offset = atoi(&ar.formated.name[1]);
if (long_offset >= ar_long_name_size) {
- error_msg_and_die("Cant resolve long filename");
+ bb_error_msg_and_die("Cant resolve long filename");
}
- typed->name = xstrdup(ar_long_names + long_offset);
+ typed->name = bb_xstrdup(ar_long_names + long_offset);
}
#else
- error_msg_and_die("long filenames not supported");
+ bb_error_msg_and_die("long filenames not supported");
#endif
} else {
/* short filenames */
- typed->name = xstrndup(ar.formated.name, 16);
+ typed->name = bb_xstrndup(ar.formated.name, 16);
}
typed->name[strcspn(typed->name, " /")] = '\0';
diff --git a/archival/libunarchive/get_header_cpio.c b/archival/libunarchive/get_header_cpio.c
index ea0857840..975e2a4bd 100644
--- a/archival/libunarchive/get_header_cpio.c
+++ b/archival/libunarchive/get_header_cpio.c
@@ -46,7 +46,7 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
oldtmp = NULL;
while (tmp) {
- error_msg_and_die("need to fix this\n");
+ bb_error_msg_and_die("need to fix this\n");
if (tmp->entry->link_name) { /* Found a hardlink ready to be extracted */
file_header = tmp->entry;
if (oldtmp) {
@@ -78,11 +78,11 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
cpio_header[2],
cpio_header[3],
cpio_header[4]);
- error_msg_and_die("Unsupported cpio format");
+ bb_error_msg_and_die("Unsupported cpio format");
}
if ((cpio_header[5] != '1') && (cpio_header[5] != '2')) {
- error_msg_and_die("Unsupported cpio format, use newc or crc");
+ bb_error_msg_and_die("Unsupported cpio format, use newc or crc");
}
{
@@ -109,7 +109,7 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
hardlinks_t *tmp = saved_hardlinks;
hardlinks_t *oldtmp = NULL;
while (tmp) {
- error_msg("%s not created: cannot resolve hardlink", tmp->entry->name);
+ bb_error_msg("%s not created: cannot resolve hardlink", tmp->entry->name);
oldtmp = tmp;
tmp = tmp->next;
free (oldtmp->entry->name);
@@ -142,13 +142,13 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
pending_hardlinks = 1;
while (tmp) {
if (tmp->inode == inode) {
- tmp->entry->link_name = xstrdup(file_header->name);
+ tmp->entry->link_name = bb_xstrdup(file_header->name);
nlink--;
}
tmp = tmp->next;
}
if (nlink > 1) {
- error_msg("error resolving hardlink: did you create the archive with GNU cpio 2.0-2.2?");
+ bb_error_msg("error resolving hardlink: did you create the archive with GNU cpio 2.0-2.2?");
}
}
}
@@ -165,11 +165,11 @@ extern char get_header_cpio(archive_handle_t *archive_handle)
if ((archive_handle->flags & ARCHIVE_EXTRACT_UNCONDITIONAL) || (statbuf.st_mtime < file_header->mtime)) {
/* Remove file if flag set or its older than the file to be extracted */
if (unlink(file_header->name) == -1) {
- perror_msg_and_die("Couldnt remove old file");
+ bb_perror_msg_and_die("Couldnt remove old file");
}
} else {
if (! archive_handle->flags & ARCHIVE_EXTRACT_QUIET) {
- error_msg("%s not created: newer or same age file exists", file_header->name);
+ bb_error_msg("%s not created: newer or same age file exists", file_header->name);
}
extract_flag = FALSE;
}
diff --git a/archival/libunarchive/get_header_tar.c b/archival/libunarchive/get_header_tar.c
index 2cb141ede..365f464dd 100644
--- a/archival/libunarchive/get_header_tar.c
+++ b/archival/libunarchive/get_header_tar.c
@@ -75,7 +75,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
#ifdef CONFIG_FEATURE_TAR_OLDGNU_COMPATABILITY
if (strncmp(tar.formated.magic, "\0\0\0\0\0", 5) != 0)
#endif
- error_msg_and_die("Invalid tar magic");
+ bb_error_msg_and_die("Invalid tar magic");
}
/* Do checksum on headers */
for (i = 0; i < 148 ; i++) {
@@ -86,7 +86,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
sum += tar.raw[i];
}
if (sum != strtol(tar.formated.chksum, NULL, 8)) {
- error_msg("Invalid tar header checksum");
+ bb_error_msg("Invalid tar header checksum");
return(EXIT_FAILURE);
}
@@ -116,7 +116,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
file_header->size = strtol(tar.formated.size, NULL, 8);
file_header->mtime = strtol(tar.formated.mtime, NULL, 8);
file_header->link_name = (tar.formated.linkname[0] != '\0') ?
- xstrdup(tar.formated.linkname) : NULL;
+ bb_xstrdup(tar.formated.linkname) : NULL;
file_header->device = (dev_t) ((strtol(tar.formated.devmajor, NULL, 8) << 8) +
strtol(tar.formated.devminor, NULL, 8));
@@ -129,7 +129,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
file_header->mode |= S_IFREG;
break;
case '1':
- error_msg("Internal hard link not supported");
+ bb_error_msg("Internal hard link not supported");
break;
case '2':
file_header->mode |= S_IFLNK;
@@ -170,7 +170,7 @@ extern char get_header_tar(archive_handle_t *archive_handle)
case 'N':
case 'S':
case 'V':
- error_msg("Ignoring GNU extension type %c", tar.formated.typeflag);
+ bb_error_msg("Ignoring GNU extension type %c", tar.formated.typeflag);
# endif
}
#endif
diff --git a/archival/libunarchive/get_header_tar_gz.c b/archival/libunarchive/get_header_tar_gz.c
index a4355d24c..7792432ae 100644
--- a/archival/libunarchive/get_header_tar_gz.c
+++ b/archival/libunarchive/get_header_tar_gz.c
@@ -25,7 +25,7 @@ extern char get_header_tar_gz(archive_handle_t *archive_handle)
archive_xread_all(archive_handle, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
- error_msg_and_die("Invalid gzip magic");
+ bb_error_msg_and_die("Invalid gzip magic");
}
check_header_gzip(archive_handle->src_fd);
diff --git a/archival/libunarchive/header_verbose_list.c b/archival/libunarchive/header_verbose_list.c
index ff7b3bca2..6739dd393 100644
--- a/archival/libunarchive/header_verbose_list.c
+++ b/archival/libunarchive/header_verbose_list.c
@@ -9,7 +9,7 @@ extern void header_verbose_list(const file_header_t *file_header)
struct tm *mtime = localtime(&file_header->mtime);
printf("%s %d/%d%10u %4u-%02u-%02u %02u:%02u:%02u %s",
- mode_string(file_header->mode),
+ bb_mode_string(file_header->mode),
file_header->uid,
file_header->gid,
(unsigned int) file_header->size,
diff --git a/archival/libunarchive/seek_by_jump.c b/archival/libunarchive/seek_by_jump.c
index 282397616..578870d9b 100644
--- a/archival/libunarchive/seek_by_jump.c
+++ b/archival/libunarchive/seek_by_jump.c
@@ -30,6 +30,6 @@ extern void seek_by_jump(const archive_handle_t *archive_handle, const unsigned
seek_by_char(archive_handle, amount);
} else
#endif
- perror_msg_and_die("Seek failure");
+ bb_perror_msg_and_die("Seek failure");
}
}
diff --git a/archival/libunarchive/uncompress.c b/archival/libunarchive/uncompress.c
index 192e98126..9851ca39d 100644
--- a/archival/libunarchive/uncompress.c
+++ b/archival/libunarchive/uncompress.c
@@ -121,14 +121,14 @@ extern int uncompress(int fd_in, int fd_out)
insize = 0;
- inbuf[0] = xread_char(fd_in);
+ inbuf[0] = bb_xread_char(fd_in);
maxbits = inbuf[0] & BIT_MASK;
block_mode = inbuf[0] & BLOCK_MODE;
maxmaxcode = MAXCODE(maxbits);
if (maxbits > BITS) {
- error_msg("compressed with %d bits, can only handle %d bits", maxbits,
+ bb_error_msg("compressed with %d bits, can only handle %d bits", maxbits,
BITS);
return -1;
}
@@ -227,11 +227,11 @@ extern int uncompress(int fd_in, int fd_out)
posbits -= n_bits;
p = &inbuf[posbits >> 3];
- error_msg
+ bb_error_msg
("insize:%d posbits:%d inbuf:%02X %02X %02X %02X %02X (%d)",
insize, posbits, p[-1], p[0], p[1], p[2], p[3],
(posbits & 07));
- error_msg("uncompress: corrupt input");
+ bb_error_msg("uncompress: corrupt input");
return -1;
}
diff --git a/archival/libunarchive/unpack_ar_archive.c b/archival/libunarchive/unpack_ar_archive.c
index afa3672ad..e8f113bcf 100644
--- a/archival/libunarchive/unpack_ar_archive.c
+++ b/archival/libunarchive/unpack_ar_archive.c
@@ -26,7 +26,7 @@ extern void unpack_ar_archive(archive_handle_t *ar_archive)
archive_xread_all(ar_archive, magic, 7);
if (strncmp(magic, "!<arch>", 7) != 0) {
- error_msg_and_die("Invalid ar magic");
+ bb_error_msg_and_die("Invalid ar magic");
}
ar_archive->offset += 7;
diff --git a/archival/libunarchive/unzip.c b/archival/libunarchive/unzip.c
index 3a7334ce9..2401cf831 100644
--- a/archival/libunarchive/unzip.c
+++ b/archival/libunarchive/unzip.c
@@ -150,7 +150,7 @@ static void fill_bytebuffer(void)
/* Leave the first 4 bytes empty so we can always unwind the bitbuffer
* to the front of the bytebuffer, leave 4 bytes free at end of tail
* so we can easily top up buffer in check_trailer_gzip() */
- bytebuffer_size = 4 + xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8);
+ bytebuffer_size = 4 + bb_xread(gunzip_src_fd, &bytebuffer[4], BYTEBUFFER_MAX - 8);
bytebuffer_offset = 4;
}
}
@@ -448,7 +448,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
do {
if (e == 99) {
- error_msg_and_die("inflate_codes error 1");;
+ bb_error_msg_and_die("inflate_codes error 1");;
}
b >>= t->b;
k -= t->b;
@@ -484,7 +484,7 @@ static int inflate_codes(huft_t * my_tl, huft_t * my_td, const unsigned int my_b
if ((e = (t = td + ((unsigned) b & md))->e) > 16)
do {
if (e == 99)
- error_msg_and_die("inflate_codes error 2");;
+ bb_error_msg_and_die("inflate_codes error 2");;
b >>= t->b;
k -= t->b;
e -= 16;
@@ -821,7 +821,7 @@ static int inflate_block(int *e)
if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
if (i == 1) {
- error_msg_and_die("Incomplete literal tree");
+ bb_error_msg_and_die("Incomplete literal tree");
huft_free(tl);
}
return i; /* incomplete code set */
@@ -830,7 +830,7 @@ static int inflate_block(int *e)
bd = dbits;
if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
if (i == 1) {
- error_msg_and_die("incomplete distance tree");
+ bb_error_msg_and_die("incomplete distance tree");
huft_free(td);
}
huft_free(tl);
@@ -846,7 +846,7 @@ static int inflate_block(int *e)
}
default:
/* bad block type */
- error_msg_and_die("bad block type %d\n", t);
+ bb_error_msg_and_die("bad block type %d\n", t);
}
}
@@ -884,7 +884,7 @@ static int inflate_get_next_window(void)
break;
case -2: ret = inflate_codes(0,0,0,0,0);
break;
- default: error_msg_and_die("inflate error %d", method);
+ default: bb_error_msg_and_die("inflate error %d", method);
}
if (ret == 1) {
@@ -975,16 +975,16 @@ extern void GZ_gzReadClose(void)
ssize_t nread, nwrote;
GZ_gzReadOpen(in, 0, 0);
- while(1) { // Robbed from copyfd.c
+ while(1) { // Robbed from bb_copyfd.c
nread = read_gz(in, buf, sizeof(buf));
if (nread == 0) break; // no data to write
else if (nread == -1) {
- perror_msg("read");
+ bb_perror_msg("read");
return -1;
}
- nwrote = full_write(out, buf, nread);
+ nwrote = bb_full_write(out, buf, nread);
if (nwrote == -1) {
- perror_msg("write");
+ bb_perror_msg("write");
return -1;
}
}
@@ -998,9 +998,9 @@ extern int inflate(int in, int out)
GZ_gzReadOpen(in, 0, 0);
while(1) {
int ret = inflate_get_next_window();
- nwrote = full_write(out, gunzip_window, gunzip_outbuf_count);
+ nwrote = bb_full_write(out, gunzip_window, gunzip_outbuf_count);
if (nwrote == -1) {
- perror_msg("write");
+ bb_perror_msg("write");
return -1;
}
if (ret == 0) break;
@@ -1017,7 +1017,7 @@ extern void check_trailer_gzip(int src_fd)
/* top up the input buffer with the rest of the trailer */
count = bytebuffer_size - bytebuffer_offset;
if (count < 8) {
- xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count);
+ bb_xread_all(src_fd, &bytebuffer[bytebuffer_size], 8 - count);
bytebuffer_size += 8 - count;
}
for (count = 0; count != 4; count++) {
@@ -1027,14 +1027,14 @@ extern void check_trailer_gzip(int src_fd)
/* Validate decompression - crc */
if (stored_crc != (gunzip_crc ^ 0xffffffffL)) {
- error_msg_and_die("crc error");
+ bb_error_msg_and_die("crc error");
}
/* Validate decompression - size */
if (gunzip_bytes_out !=
(bytebuffer[bytebuffer_offset] | (bytebuffer[bytebuffer_offset+1] << 8) |
(bytebuffer[bytebuffer_offset+2] << 16) | (bytebuffer[bytebuffer_offset+3] << 24))) {
- error_msg_and_die("Incorrect length, but crc is correct");
+ bb_error_msg_and_die("Incorrect length, but crc is correct");
}
}
diff --git a/archival/rpm.c b/archival/rpm.c
index 61486cb03..5bde53285 100644
--- a/archival/rpm.c
+++ b/archival/rpm.c
@@ -116,7 +116,7 @@ int rpm_main(int argc, char **argv)
break;
case 'q': // First arg: Query mode
if (!func) func |= rpm_query;
- else show_usage();
+ else bb_show_usage();
break;
case 'p': // Query a package
func |= rpm_query_package;
@@ -133,13 +133,13 @@ int rpm_main(int argc, char **argv)
func |= rpm_query_list_config;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
- if (optind == argc) show_usage();
+ if (optind == argc) bb_show_usage();
while (optind < argc) {
- rpm_fd = xopen(argv[optind], O_RDONLY);
+ rpm_fd = bb_xopen(argv[optind], O_RDONLY);
mytags = rpm_gettags(rpm_fd, (int *) &tagcount);
offset = lseek(rpm_fd, 0, SEEK_CUR);
if (!mytags) { printf("Error reading rpm header\n"); exit(-1); }
@@ -206,9 +206,9 @@ void extract_cpio_gz(int fd) {
archive_handle->src_fd = fd;
archive_handle->offset = 0;
- xread_all(archive_handle->src_fd, &magic, 2);
+ bb_xread_all(archive_handle->src_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
- error_msg_and_die("Invalid gzip magic");
+ bb_error_msg_and_die("Invalid gzip magic");
}
check_header_gzip(archive_handle->src_fd);
chdir("/"); // Install RPM's to root
@@ -314,7 +314,7 @@ void fileaction_dobackup(char *filename, int fileref)
if (rpm_getint(RPMTAG_FILEFLAGS, fileref) & RPMFILE_CONFIG) { /* Only need to backup config files */
stat_res = lstat (filename, &oldfile);
if (stat_res == 0 && S_ISREG(oldfile.st_mode)) { /* File already exists - really should check MD5's etc to see if different */
- newname = xstrdup(filename);
+ newname = bb_xstrdup(filename);
newname = strcat(newname, ".rpmorig");
copy_file(filename, newname, FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS);
remove_file(filename, FILEUTILS_RECUR | FILEUTILS_FORCE);
diff --git a/archival/rpm2cpio.c b/archival/rpm2cpio.c
index 66f680869..bb9f69573 100644
--- a/archival/rpm2cpio.c
+++ b/archival/rpm2cpio.c
@@ -52,12 +52,12 @@ void skip_header(int rpm_fd)
{
struct rpm_header header;
- xread_all(rpm_fd, &header, sizeof(struct rpm_header));
+ bb_xread_all(rpm_fd, &header, sizeof(struct rpm_header));
if (strncmp((char *) &header.magic, RPM_HEADER_MAGIC, 3) != 0) {
- error_msg_and_die("Invalid RPM header magic"); /* Invalid magic */
+ bb_error_msg_and_die("Invalid RPM header magic"); /* Invalid magic */
}
if (header.version != 1) {
- error_msg_and_die("Unsupported RPM header version"); /* This program only supports v1 headers */
+ bb_error_msg_and_die("Unsupported RPM header version"); /* This program only supports v1 headers */
}
header.entries = ntohl(header.entries);
header.size = ntohl(header.size);
@@ -75,12 +75,12 @@ extern int rpm2cpio_main(int argc, char **argv)
if (argc == 1) {
rpm_fd = fileno(stdin);
} else {
- rpm_fd = xopen(argv[1], O_RDONLY);
+ rpm_fd = bb_xopen(argv[1], O_RDONLY);
}
- xread_all(rpm_fd, &lead, sizeof(struct rpm_lead));
+ bb_xread_all(rpm_fd, &lead, sizeof(struct rpm_lead));
if (strncmp((char *) &lead.magic, RPM_MAGIC, 4) != 0) {
- error_msg_and_die("Invalid RPM magic"); /* Just check the magic, the rest is irrelevant */
+ bb_error_msg_and_die("Invalid RPM magic"); /* Just check the magic, the rest is irrelevant */
}
/* Skip the signature header */
@@ -90,14 +90,14 @@ extern int rpm2cpio_main(int argc, char **argv)
/* Skip the main header */
skip_header(rpm_fd);
- xread_all(rpm_fd, &magic, 2);
+ bb_xread_all(rpm_fd, &magic, 2);
if ((magic[0] != 0x1f) || (magic[1] != 0x8b)) {
- error_msg_and_die("Invalid gzip magic");
+ bb_error_msg_and_die("Invalid gzip magic");
}
check_header_gzip(rpm_fd);
if (inflate(rpm_fd, fileno(stdout)) != 0) {
- error_msg("Error inflating");
+ bb_error_msg("Error inflating");
}
check_trailer_gzip(rpm_fd);
diff --git a/archival/tar.c b/archival/tar.c
index fa1c57512..c39d5787f 100644
--- a/archival/tar.c
+++ b/archival/tar.c
@@ -278,7 +278,7 @@ static inline int writeTarHeader(struct TarBallInfo *tbInfo,
header.typeflag = REGTYPE;
putOctal(header.size, sizeof(header.size), statbuf->st_size);
} else {
- error_msg("%s: Unknown file type", real_name);
+ bb_error_msg("%s: Unknown file type", real_name);
return (FALSE);
}
@@ -295,9 +295,9 @@ static inline int writeTarHeader(struct TarBallInfo *tbInfo,
/* Now write the header out to disk */
if ((size =
- full_write(tbInfo->tarFd, (char *) &header,
+ bb_full_write(tbInfo->tarFd, (char *) &header,
sizeof(struct TarHeader))) < 0) {
- error_msg(io_error, real_name);
+ bb_error_msg(bb_msg_io_error, real_name);
return (FALSE);
}
/* Pad the header up to the tar block size */
@@ -368,7 +368,7 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
/* It is against the rules to archive a socket */
if (S_ISSOCK(statbuf->st_mode)) {
- error_msg("%s: socket ignored", fileName);
+ bb_error_msg("%s: socket ignored", fileName);
return (TRUE);
}
@@ -377,7 +377,7 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
* the new tarball */
if (tbInfo->statBuf.st_dev == statbuf->st_dev &&
tbInfo->statBuf.st_ino == statbuf->st_ino) {
- error_msg("%s: file is the archive; skipping", fileName);
+ bb_error_msg("%s: file is the archive; skipping", fileName);
return (TRUE);
}
@@ -386,14 +386,14 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
static int alreadyWarned = FALSE;
if (alreadyWarned == FALSE) {
- error_msg("Removing leading '/' from member names");
+ bb_error_msg("Removing leading '/' from member names");
alreadyWarned = TRUE;
}
header_name++;
}
if (strlen(fileName) >= NAME_SIZE) {
- error_msg(name_longer_than_foo, NAME_SIZE);
+ bb_error_msg(bb_msg_name_longer_than_foo, NAME_SIZE);
return (TRUE);
}
@@ -419,21 +419,21 @@ static int writeFileToTarball(const char *fileName, struct stat *statbuf,
/* open the file we want to archive, and make sure all is well */
if ((inputFileFd = open(fileName, O_RDONLY)) < 0) {
- perror_msg("%s: Cannot open", fileName);
+ bb_perror_msg("%s: Cannot open", fileName);
return (FALSE);
}
/* write the file to the archive */
- while ((size = full_read(inputFileFd, buffer, sizeof(buffer))) > 0) {
- if (full_write(tbInfo->tarFd, buffer, size) != size) {
+ while ((size = bb_full_read(inputFileFd, buffer, sizeof(buffer))) > 0) {
+ if (bb_full_write(tbInfo->tarFd, buffer, size) != size) {
/* Output file seems to have a problem */
- error_msg(io_error, fileName);
+ bb_error_msg(bb_msg_io_error, fileName);
return (FALSE);
}
readSize += size;
}
if (size == -1) {
- error_msg(io_error, fileName);
+ bb_error_msg(bb_msg_io_error, fileName);
return (FALSE);
}
/* Pad the file up to the tar block size */
@@ -464,7 +464,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
/* Make sure there is at least one file to tar up. */
if (include == NULL) {
- error_msg_and_die("Cowardly refusing to create an empty archive");
+ bb_error_msg_and_die("Cowardly refusing to create an empty archive");
}
/* Open the tar file for writing. */
@@ -477,7 +477,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
}
if (tbInfo.tarFd < 0) {
- perror_msg("%s: Cannot open", tarName);
+ bb_perror_msg("%s: Cannot open", tarName);
freeHardLinkInfo(&tbInfo.hlInfoHead);
return (FALSE);
}
@@ -485,12 +485,12 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
/* Store the stat info for the tarball's file, so
* can avoid including the tarball into itself.... */
if (fstat(tbInfo.tarFd, &tbInfo.statBuf) < 0)
- error_msg_and_die(io_error, tarName);
+ bb_error_msg_and_die(bb_msg_io_error, tarName);
#ifdef CONFIG_FEATURE_TAR_GZIP
if (gzip) {
if (pipe(gzipDataPipe) < 0 || pipe(gzipStatusPipe) < 0) {
- perror_msg_and_die("Failed to create gzip pipe");
+ bb_perror_msg_and_die("Failed to create gzip pipe");
}
signal(SIGPIPE, SIG_IGN); /* we only want EPIPE on errors */
@@ -529,7 +529,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
if (n == 0 && vfork_exec_errno != 0) {
errno = vfork_exec_errno;
- perror_msg_and_die("Could not exec gzip process");
+ bb_perror_msg_and_die("Could not exec gzip process");
} else if ((n < 0) && (errno == EAGAIN || errno == EINTR))
continue; /* try it again */
break;
@@ -538,7 +538,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
tbInfo.tarFd = gzipDataPipe[1];
} else {
- perror_msg_and_die("Failed to vfork gzip process");
+ bb_perror_msg_and_die("Failed to vfork gzip process");
}
}
#endif
@@ -567,7 +567,7 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
/* Hang up the tools, close up shop, head home */
close(tbInfo.tarFd);
if (errorFlag)
- error_msg("Error exit delayed from previous errors");
+ bb_error_msg("Error exit delayed from previous errors");
freeHardLinkInfo(&tbInfo.hlInfoHead);
@@ -585,10 +585,9 @@ static inline int writeTarFile(const char *tarName, const int verboseFlag,
#ifdef CONFIG_FEATURE_TAR_EXCLUDE
static llist_t *append_file_list_to_list(const char *filename, llist_t *list)
{
- FILE *src_stream = xfopen(filename, "r");
+ FILE *src_stream = bb_xfopen(filename, "r");
char *line;
- while((line = get_line_from_file(src_stream)) != NULL) {
- chomp(line);
+ while((line = bb_get_chomped_line_from_file(src_stream)) != NULL) {
list = llist_add_to(list, line);
}
fclose(src_stream);
@@ -611,7 +610,7 @@ int tar_main(int argc, char **argv)
unsigned char ctx_flag = 0;
if (argc < 2) {
- show_usage();
+ bb_show_usage();
}
/* Prepend '-' to the first argument if required */
@@ -690,13 +689,13 @@ int tar_main(int argc, char **argv)
break;
#endif
default:
- show_usage();
+ bb_show_usage();
}
}
/* Check one and only one context option was given */
if ((ctx_flag != CTX_CREATE) && (ctx_flag != CTX_TEST) && (ctx_flag != CTX_EXTRACT)) {
- show_usage();
+ bb_show_usage();
}
/* Check if we are reading from stdin */
@@ -740,11 +739,11 @@ int tar_main(int argc, char **argv)
tar_handle->src_fd = fileno(stdin);
tar_handle->seek = seek_by_char;
} else {
- tar_handle->src_fd = xopen(tar_filename, O_RDONLY);
+ tar_handle->src_fd = bb_xopen(tar_filename, O_RDONLY);
}
if ((base_dir) && (chdir(base_dir))) {
- perror_msg_and_die("Couldnt chdir");
+ bb_perror_msg_and_die("Couldnt chdir");
}
while (get_header_ptr(tar_handle) == EXIT_SUCCESS);
@@ -753,7 +752,7 @@ int tar_main(int argc, char **argv)
while (tar_handle->accept) {
if (find_list_entry(tar_handle->reject, tar_handle->accept->data) == NULL) {
if (find_list_entry(tar_handle->passed, tar_handle->accept->data) == NULL) {
- error_msg_and_die("%s: Not found in archive\n", tar_handle->accept->data);
+ bb_error_msg_and_die("%s: Not found in archive\n", tar_handle->accept->data);
}
}
tar_handle->accept = tar_handle->accept->link;
diff --git a/archival/uncompress.c b/archival/uncompress.c
index 877bcc784..2d2145d18 100644
--- a/archival/uncompress.c
+++ b/archival/uncompress.c
@@ -45,7 +45,7 @@ int uncompress_main(int argc, char **argv)
flags |= gunzip_force;
break;
default:
- show_usage(); /* exit's inside usage */
+ bb_show_usage(); /* exit's inside usage */
}
}
@@ -63,17 +63,17 @@ int uncompress_main(int argc, char **argv)
src_fd = fileno(stdin);
flags |= gunzip_to_stdout;
} else {
- src_fd = xopen(old_path, O_RDONLY);
+ src_fd = bb_xopen(old_path, O_RDONLY);
/* Get the time stamp on the input file. */
if (stat(old_path, &stat_buf) < 0) {
- error_msg_and_die("Couldn't stat file %s", old_path);
+ bb_error_msg_and_die("Couldn't stat file %s", old_path);
}
}
/* Check that the input is sane. */
if (isatty(src_fd) && ((flags & gunzip_force) == 0)) {
- error_msg_and_die
+ bb_error_msg_and_die
("compressed data not read from terminal. Use -f to force it.");
}
@@ -83,16 +83,16 @@ int uncompress_main(int argc, char **argv)
} else {
char *extension;
- new_path = xstrdup(old_path);
+ new_path = bb_xstrdup(old_path);
extension = strrchr(new_path, '.');
if (!extension || (strcmp(extension, ".Z") != 0)) {
- error_msg_and_die("Invalid extension");
+ bb_error_msg_and_die("Invalid extension");
}
*extension = '\0';
/* Open output file */
- dst_fd = xopen(new_path, O_WRONLY | O_CREAT);
+ dst_fd = bb_xopen(new_path, O_WRONLY | O_CREAT);
/* Set permissions on the file */
chmod(new_path, stat_buf.st_mode);
@@ -102,10 +102,10 @@ int uncompress_main(int argc, char **argv)
}
/* do the decompression, and cleanup */
- if ((xread_char(src_fd) == 0x1f) && (xread_char(src_fd) == 0x9d)) {
+ if ((bb_xread_char(src_fd) == 0x1f) && (bb_xread_char(src_fd) == 0x9d)) {
status = uncompress(src_fd, dst_fd);
} else {
- error_msg_and_die("Invalid magic");
+ bb_error_msg_and_die("Invalid magic");
}
if ((status != EXIT_SUCCESS) && (new_path)) {
@@ -122,7 +122,7 @@ int uncompress_main(int argc, char **argv)
/* delete_path will be NULL if in test mode or from stdin */
if (delete_path && (unlink(delete_path) == -1)) {
- error_msg_and_die("Couldn't remove %s", delete_path);
+ bb_error_msg_and_die("Couldn't remove %s", delete_path);
}
free(new_path);
diff --git a/archival/unzip.c b/archival/unzip.c
index 86416d327..f2d7f4918 100644
--- a/archival/unzip.c
+++ b/archival/unzip.c
@@ -120,12 +120,12 @@ extern int unzip_main(int argc, char **argv)
break;
#endif
default:
- show_usage();
+ bb_show_usage();
}
}
if (argc == optind) {
- show_usage();
+ bb_show_usage();
}
printf("Archive: %s\n", argv[optind]);
@@ -138,11 +138,11 @@ extern int unzip_main(int argc, char **argv)
archive_handle->src_fd = fileno(stdin);
archive_handle->seek = seek_by_char;
} else {
- archive_handle->src_fd = xopen(argv[optind++], O_RDONLY);
+ archive_handle->src_fd = bb_xopen(argv[optind++], O_RDONLY);
}
if ((base_dir) && (chdir(base_dir))) {
- perror_msg_and_die("Couldnt chdir");
+ bb_perror_msg_and_die("Couldnt chdir");
}
while (optind < argc) {
@@ -163,7 +163,7 @@ extern int unzip_main(int argc, char **argv)
break;
}
else if (magic != ZIP_FILEHEADER_MAGIC) {
- error_msg_and_die("Invlaide zip magic");
+ bb_error_msg_and_die("Invlaide zip magic");
}
/* Read the file header */
@@ -172,7 +172,7 @@ extern int unzip_main(int argc, char **argv)
archive_handle->file_header->mode = S_IFREG | 0777;
if (zip_header.formated.method != 8) {
- error_msg_and_die("Unsupported compression method %d\n", zip_header.formated.method);
+ bb_error_msg_and_die("Unsupported compression method %d\n", zip_header.formated.method);
}
/* Read filename */
@@ -198,19 +198,19 @@ extern int unzip_main(int argc, char **argv)
if (archive_handle->action_data) {
archive_handle->action_data(archive_handle);
} else {
- dst_fd = xopen(archive_handle->file_header->name, O_WRONLY | O_CREAT);
+ dst_fd = bb_xopen(archive_handle->file_header->name, O_WRONLY | O_CREAT);
inflate(archive_handle->src_fd, dst_fd);
close(dst_fd);
chmod(archive_handle->file_header->name, archive_handle->file_header->mode);
/* Validate decompression - crc */
if (zip_header.formated.crc32 != (gunzip_crc ^ 0xffffffffL)) {
- error_msg("Invalid compressed data--crc error");
+ bb_error_msg("Invalid compressed data--crc error");
}
/* Validate decompression - size */
if (gunzip_bytes_out != zip_header.formated.ucmpsize) {
- error_msg("Invalid compressed data--length error");
+ bb_error_msg("Invalid compressed data--length error");
}
}
diff --git a/console-tools/chvt.c b/console-tools/chvt.c
index 8136f1c15..11e1078b7 100644
--- a/console-tools/chvt.c
+++ b/console-tools/chvt.c
@@ -23,13 +23,13 @@ int chvt_main(int argc, char **argv)
int fd, num;
if ((argc != 2) || (**(argv + 1) == '-'))
- show_usage();
+ bb_show_usage();
fd = get_console_fd();
num = atoi(argv[1]);
if (ioctl(fd, VT_ACTIVATE, num))
- perror_msg_and_die("VT_ACTIVATE");
+ bb_perror_msg_and_die("VT_ACTIVATE");
if (ioctl(fd, VT_WAITACTIVE, num))
- perror_msg_and_die("VT_WAITACTIVE");
+ bb_perror_msg_and_die("VT_WAITACTIVE");
return EXIT_SUCCESS;
}
diff --git a/console-tools/deallocvt.c b/console-tools/deallocvt.c
index b7dcc9e22..a4ba851c8 100644
--- a/console-tools/deallocvt.c
+++ b/console-tools/deallocvt.c
@@ -19,23 +19,23 @@ int deallocvt_main(int argc, char *argv[])
//if ((argc > 2) || ((argv == 2) && (**(argv + 1) == '-')))
if (argc > 2)
- show_usage();
+ bb_show_usage();
fd = get_console_fd();
if (argc == 1) {
/* deallocate all unused consoles */
if (ioctl(fd, VT_DISALLOCATE, 0))
- perror_msg_and_die("VT_DISALLOCATE");
+ bb_perror_msg_and_die("VT_DISALLOCATE");
} else {
for (i = 1; i < argc; i++) {
num = atoi(argv[i]);
if (num == 0)
- error_msg("0: illegal VT number");
+ bb_error_msg("0: illegal VT number");
else if (num == 1)
- error_msg("VT 1 cannot be deallocated");
+ bb_error_msg("VT 1 cannot be deallocated");
else if (ioctl(fd, VT_DISALLOCATE, num))
- perror_msg_and_die("VT_DISALLOCATE");
+ bb_perror_msg_and_die("VT_DISALLOCATE");
}
}
diff --git a/console-tools/dumpkmap.c b/console-tools/dumpkmap.c
index d2bb6dcff..85926556c 100644
--- a/console-tools/dumpkmap.c
+++ b/console-tools/dumpkmap.c
@@ -48,12 +48,12 @@ int dumpkmap_main(int argc, char **argv)
char flags[MAX_NR_KEYMAPS], magic[] = "bkeymap";
if (argc>=2 && *argv[1]=='-') {
- show_usage();
+ bb_show_usage();
}
fd = open(CURRENT_VC, O_RDWR);
if (fd < 0) {
- perror_msg("Error opening " CURRENT_VC);
+ bb_perror_msg("Error opening " CURRENT_VC);
return EXIT_FAILURE;
}
@@ -81,7 +81,7 @@ int dumpkmap_main(int argc, char **argv)
ke.kb_table = i;
if (ioctl(fd, KDGKBENT, &ke) < 0) {
- error_msg("ioctl returned: %m, %s, %s, %xqq", (char *)&ke.kb_index,(char *)&ke.kb_table,(int)&ke.kb_value);
+ bb_error_msg("ioctl returned: %m, %s, %s, %xqq", (char *)&ke.kb_index,(char *)&ke.kb_table,(int)&ke.kb_value);
}
else {
write(1,(void*)&ke.kb_value,2);
diff --git a/console-tools/loadacm.c b/console-tools/loadacm.c
index 3fb4e7665..640aa4401 100644
--- a/console-tools/loadacm.c
+++ b/console-tools/loadacm.c
@@ -34,16 +34,16 @@ int loadacm_main(int argc, char **argv)
int fd;
if (argc>=2 && *argv[1]=='-') {
- show_usage();
+ bb_show_usage();
}
fd = open(CURRENT_VC, O_RDWR);
if (fd < 0) {
- perror_msg_and_die("Error opening " CURRENT_VC);
+ bb_perror_msg_and_die("Error opening " CURRENT_VC);
}
if (screen_map_load(fd, stdin)) {
- perror_msg_and_die("Error loading acm");
+ bb_perror_msg_and_die("Error loading acm");
}
write(fd, "\033(K", 3);
@@ -60,7 +60,7 @@ static int screen_map_load(int fd, FILE * fp)
int is_unicode;
if (fstat(fileno(fp), &stbuf))
- perror_msg_and_die("Cannot stat map file");
+ bb_perror_msg_and_die("Cannot stat map file");
/* first try a UTF screen-map: either ASCII (no restriction) or binary (regular file) */
if (!
@@ -70,16 +70,16 @@ static int screen_map_load(int fd, FILE * fp)
if (parse_failed) {
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
- error_msg_and_die("16bit screen-map MUST be a regular file.");
+ bb_error_msg_and_die("16bit screen-map MUST be a regular file.");
else
- perror_msg_and_die("fseek failed reading binary 16bit screen-map");
+ bb_perror_msg_and_die("fseek failed reading binary 16bit screen-map");
}
if (fread(wbuf, sizeof(unicode) * E_TABSZ, 1, fp) != 1)
- perror_msg_and_die("Cannot read [new] map from file");
+ bb_perror_msg_and_die("Cannot read [new] map from file");
#if 0
else
- error_msg("Input screen-map is binary.");
+ bb_error_msg("Input screen-map is binary.");
#endif
}
@@ -87,7 +87,7 @@ static int screen_map_load(int fd, FILE * fp)
/* same if it was binary, ie. if parse_failed */
if (parse_failed || is_unicode) {
if (ioctl(fd, PIO_UNISCRNMAP, wbuf))
- perror_msg_and_die("PIO_UNISCRNMAP ioctl");
+ bb_perror_msg_and_die("PIO_UNISCRNMAP ioctl");
else
return 0;
}
@@ -96,10 +96,10 @@ static int screen_map_load(int fd, FILE * fp)
/* rewind... */
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
- error_msg("Assuming 8bit screen-map - MUST be a regular file."),
+ bb_error_msg("Assuming 8bit screen-map - MUST be a regular file."),
exit(1);
else
- perror_msg_and_die("fseek failed assuming 8bit screen-map");
+ bb_perror_msg_and_die("fseek failed assuming 8bit screen-map");
}
/* ... and try an old 8-bit screen-map */
@@ -109,25 +109,25 @@ static int screen_map_load(int fd, FILE * fp)
if (-1 == fseek(fp, 0, SEEK_SET)) {
if (errno == ESPIPE)
/* should not - it succedeed above */
- error_msg_and_die("fseek() returned ESPIPE !");
+ bb_error_msg_and_die("fseek() returned ESPIPE !");
else
- perror_msg_and_die("fseek for binary 8bit screen-map");
+ bb_perror_msg_and_die("fseek for binary 8bit screen-map");
}
if (fread(buf, E_TABSZ, 1, fp) != 1)
- perror_msg_and_die("Cannot read [old] map from file");
+ bb_perror_msg_and_die("Cannot read [old] map from file");
#if 0
else
- error_msg("Input screen-map is binary.");
+ bb_error_msg("Input screen-map is binary.");
#endif
}
if (ioctl(fd, PIO_SCRNMAP, buf))
- perror_msg_and_die("PIO_SCRNMAP ioctl");
+ bb_perror_msg_and_die("PIO_SCRNMAP ioctl");
else
return 0;
}
- error_msg("Error parsing symbolic map");
+ bb_error_msg("Error parsing symbolic map");
return(1);
}
@@ -172,7 +172,7 @@ static int uni_screen_map_read_ascii(FILE * fp, unicode buf[], int *is_unicode)
if (feof(fp))
break;
else
- perror_msg_and_die("uni_screen_map_read_ascii() can't read line");
+ bb_perror_msg_and_die("uni_screen_map_read_ascii() can't read line");
}
/* get "charset-relative charcode", stripping leading spaces */
diff --git a/console-tools/loadfont.c b/console-tools/loadfont.c
index d66500195..6108151a6 100644
--- a/console-tools/loadfont.c
+++ b/console-tools/loadfont.c
@@ -44,11 +44,11 @@ extern int loadfont_main(int argc, char **argv)
int fd;
if (argc != 1)
- show_usage();
+ bb_show_usage();
fd = open(CURRENT_VC, O_RDWR);
if (fd < 0)
- perror_msg_and_die("Error opening " CURRENT_VC);
+ bb_perror_msg_and_die("Error opening " CURRENT_VC);
loadnewfont(fd);
return EXIT_SUCCESS;
@@ -62,7 +62,7 @@ static void do_loadfont(int fd, char *inbuf, int unit, int fontsize)
memset(buf, 0, sizeof(buf));
if (unit < 1 || unit > 32)
- error_msg_and_die("Bad character size %d", unit);
+ bb_error_msg_and_die("Bad character size %d", unit);
for (i = 0; i < fontsize; i++)
memcpy(buf + (32 * i), inbuf + (unit * i), unit);
@@ -77,11 +77,11 @@ static void do_loadfont(int fd, char *inbuf, int unit, int fontsize)
if (ioctl(fd, PIO_FONTX, &cfd) == 0)
return; /* success */
- perror_msg("PIO_FONTX ioctl error (trying PIO_FONT)");
+ bb_perror_msg("PIO_FONTX ioctl error (trying PIO_FONT)");
}
#endif
if (ioctl(fd, PIO_FONT, buf))
- perror_msg_and_die("PIO_FONT ioctl error");
+ bb_perror_msg_and_die("PIO_FONT ioctl error");
}
static void
@@ -119,11 +119,11 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
if (ioctl(fd, PIO_UNIMAPCLR, &advice)) {
#ifdef ENOIOCTLCMD
if (errno == ENOIOCTLCMD) {
- error_msg("It seems this kernel is older than 1.1.92");
- error_msg_and_die("No Unicode mapping table loaded.");
+ bb_error_msg("It seems this kernel is older than 1.1.92");
+ bb_error_msg_and_die("No Unicode mapping table loaded.");
} else
#endif
- perror_msg_and_die("PIO_UNIMAPCLR");
+ bb_perror_msg_and_die("PIO_UNIMAPCLR");
}
ud.entry_ct = ct;
ud.entries = up;
@@ -133,7 +133,7 @@ do_loadtable(int fd, unsigned char *inbuf, int tailsz, int fontsize)
/* change advice parameters */
}
#endif
- perror_msg_and_die("PIO_UNIMAP");
+ bb_perror_msg_and_die("PIO_UNIMAP");
}
}
@@ -150,13 +150,13 @@ static void loadnewfont(int fd)
*/
inputlth = fread(inbuf, 1, sizeof(inbuf), stdin);
if (ferror(stdin))
- perror_msg_and_die("Error reading input font");
+ bb_perror_msg_and_die("Error reading input font");
/* use malloc/realloc in case of giant files;
maybe these do not occur: 16kB for the font,
and 16kB for the map leaves 32 unicode values
for each font position */
if (!feof(stdin))
- perror_msg_and_die("Font too large");
+ bb_perror_msg_and_die("Font too large");
/* test for psf first */
{
@@ -174,11 +174,11 @@ static void loadnewfont(int fd)
goto no_psf;
if (psfhdr.mode > PSF_MAXMODE)
- error_msg_and_die("Unsupported psf file mode");
+ bb_error_msg_and_die("Unsupported psf file mode");
fontsize = ((psfhdr.mode & PSF_MODE512) ? 512 : 256);
#if !defined( PIO_FONTX ) || defined( __sparc__ )
if (fontsize != 256)
- error_msg_and_die("Only fontsize 256 supported");
+ bb_error_msg_and_die("Only fontsize 256 supported");
#endif
hastable = (psfhdr.mode & PSF_MODEHASTAB);
unit = psfhdr.charsize;
@@ -186,7 +186,7 @@ static void loadnewfont(int fd)
head = head0 + fontsize * unit;
if (head > inputlth || (!hastable && head != inputlth))
- error_msg_and_die("Input file: bad length");
+ bb_error_msg_and_die("Input file: bad length");
do_loadfont(fd, inbuf + head0, unit, fontsize);
if (hastable)
do_loadtable(fd, inbuf + head, inputlth - head, fontsize);
@@ -201,7 +201,7 @@ static void loadnewfont(int fd)
} else {
/* bare font */
if (inputlth & 0377)
- error_msg_and_die("Bad input file size");
+ bb_error_msg_and_die("Bad input file size");
offset = 0;
unit = inputlth / 256;
}
diff --git a/console-tools/loadkmap.c b/console-tools/loadkmap.c
index 4f217d630..f4208df63 100644
--- a/console-tools/loadkmap.c
+++ b/console-tools/loadkmap.c
@@ -51,18 +51,18 @@ int loadkmap_main(int argc, char **argv)
char flags[MAX_NR_KEYMAPS], buff[7];
if (argc != 1)
- show_usage();
+ bb_show_usage();
fd = open(CURRENT_VC, O_RDWR);
if (fd < 0)
- perror_msg_and_die("Error opening " CURRENT_VC);
+ bb_perror_msg_and_die("Error opening " CURRENT_VC);
read(0, buff, 7);
if (0 != strncmp(buff, BINARY_KEYMAP_MAGIC, 7))
- error_msg_and_die("This is not a valid binary keymap.");
+ bb_error_msg_and_die("This is not a valid binary keymap.");
if (MAX_NR_KEYMAPS != read(0, flags, MAX_NR_KEYMAPS))
- perror_msg_and_die("Error reading keymap flags");
+ bb_perror_msg_and_die("Error reading keymap flags");
ibuff = (u_short *) xmalloc(ibuffsz);
@@ -71,7 +71,7 @@ int loadkmap_main(int argc, char **argv)
pos = 0;
while (pos < ibuffsz) {
if ((readsz = read(0, (char *) ibuff + pos, ibuffsz - pos)) < 0)
- perror_msg_and_die("Error reading keymap");
+ bb_perror_msg_and_die("Error reading keymap");
pos += readsz;
}
for (j = 0; j < NR_KEYS; j++) {
diff --git a/console-tools/openvt.c b/console-tools/openvt.c
index 77c897597..519513623 100644
--- a/console-tools/openvt.c
+++ b/console-tools/openvt.c
@@ -43,16 +43,16 @@ int openvt_main(int argc, char **argv)
char * cmd_args = NULL;
if (argc < 3)
- show_usage();
+ bb_show_usage();
if (!isdigit(argv[1][0]))
- show_usage();
+ bb_show_usage();
vtno = (int) atol(argv[1]);
/* if (vtno <= 0 || vtno > 63) */
if (vtno <= 0 || vtno > 12)
- error_msg_and_die("Illegal vt number (%d)", vtno);
+ bb_error_msg_and_die("Illegal vt number (%d)", vtno);
sprintf(vtname, VTNAME, vtno);
@@ -69,13 +69,13 @@ int openvt_main(int argc, char **argv)
if (setsid() < 0) {
#endif
- perror_msg_and_die("Unable to set new session");
+ bb_perror_msg_and_die("Unable to set new session");
}
close(0); /* so that new vt becomes stdin */
/* and grab new one */
if ((fd = open(vtname, O_RDWR)) == -1)
- perror_msg_and_die("could not open %s", vtname);
+ bb_perror_msg_and_die("could not open %s", vtname);
/* Reassign stdout and sterr */
close(1);
diff --git a/console-tools/setkeycodes.c b/console-tools/setkeycodes.c
index 85612c8b1..796bab285 100644
--- a/console-tools/setkeycodes.c
+++ b/console-tools/setkeycodes.c
@@ -43,7 +43,7 @@ setkeycodes_main(int argc, char** argv)
struct kbkeycode a;
if (argc % 2 != 1 || argc < 2) {
- show_usage();
+ bb_show_usage();
}
fd = get_console_fd();
@@ -52,18 +52,18 @@ setkeycodes_main(int argc, char** argv)
a.keycode = atoi(argv[2]);
a.scancode = sc = strtol(argv[1], &ep, 16);
if (*ep) {
- error_msg_and_die("error reading SCANCODE: '%s'", argv[1]);
+ bb_error_msg_and_die("error reading SCANCODE: '%s'", argv[1]);
}
if (a.scancode > 127) {
a.scancode -= 0xe000;
a.scancode += 128;
}
if (a.scancode > 255 || a.keycode > 127) {
- error_msg_and_die("SCANCODE or KEYCODE outside bounds");
+ bb_error_msg_and_die("SCANCODE or KEYCODE outside bounds");
}
if (ioctl(fd,KDSETKEYCODE,&a)) {
perror("KDSETKEYCODE");
- error_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode);
+ bb_error_msg_and_die("failed to set SCANCODE %x to KEYCODE %d", sc, a.keycode);
}
argc -= 2;
argv += 2;
diff --git a/coreutils/Config.in b/coreutils/Config.in
index 5b9996d5b..9f5c379a3 100644
--- a/coreutils/Config.in
+++ b/coreutils/Config.in
@@ -111,17 +111,31 @@ config CONFIG_DOS2UNIX
Please submit a patch to add help text for this item.
config CONFIG_DU
- bool "du"
+ bool "du (default blocksize of 512 bytes)"
default n
help
Please submit a patch to add help text for this item.
+config CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
+ bool " Use a default blocksize of 1024 bytes (1K)"
+ default y
+ depends on CONFIG_DU
+ help
+ Please submit a patch to add help text for this item.
+
config CONFIG_ECHO
- bool "echo"
+ bool "echo (basic SUSv3 version taking no options"
default n
help
Please submit a patch to add help text for this item.
+config CONFIG_FEATURE_FANCY_ECHO
+ bool " Enable echo options (-n and -e)"
+ default y
+ depends on CONFIG_ECHO
+ help
+ Please submit a patch to add help text for this item.
+
config CONFIG_ENV
bool "env"
default n
@@ -154,6 +168,13 @@ config CONFIG_HEAD
help
Please submit a patch to add help text for this item.
+config CONFIG_FEATURE_FANCY_HEAD
+ bool " Enable head options (-c, -q, and -v)"
+ default n
+ depends on CONFIG_HEAD
+ help
+ Please submit a patch to add help text for this item.
+
config CONFIG_HOSTID
bool "hostid"
default n
@@ -313,8 +334,15 @@ config CONFIG_SHA1SUM
Compute and check SHA1 message digest
config CONFIG_SLEEP
- bool "sleep"
+ bool "sleep (single integer arg with no suffix)"
+ default n
+ help
+ Please submit a patch to add help text for this item.
+
+config CONFIG_FEATURE_FANCY_SLEEP
+ bool " Enable multiple integer args and optional time suffixes"
default n
+ depends on CONFIG_SLEEP
help
Please submit a patch to add help text for this item.
@@ -369,6 +397,13 @@ config CONFIG_TEE
help
Please submit a patch to add help text for this item.
+config CONFIG_FEATURE_TEE_USE_BLOCK_IO
+ bool " Enable block i/o (larger/faster) instead of byte i/o."
+ default n
+ depends on CONFIG_TEE
+ help
+ Please submit a patch to add help text for this item.
+
if CONFIG_ASH || CONFIG_HUSH || CONFIG_LASH || CONFIG_MSH
config CONFIG_TEST
default y
diff --git a/coreutils/basename.c b/coreutils/basename.c
index bdbcec17a..71bb9b3bd 100644
--- a/coreutils/basename.c
+++ b/coreutils/basename.c
@@ -21,32 +21,43 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/basename.html */
+
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Changes:
+ * 1) Now checks for too many args. Need at least one and at most two.
+ * 2) Don't check for options, as per SUSv3.
+ * 3) Save some space by using strcmp(). Calling strncmp() here was silly.
+ */
#include <stdlib.h>
-#include "busybox.h"
+#include <stdio.h>
#include <string.h>
+#include "busybox.h"
extern int basename_main(int argc, char **argv)
{
- int m, n;
+ size_t m, n;
char *s;
- if ((argc < 2) || (**(argv + 1) == '-')) {
- show_usage();
+ if (((unsigned int)(argc-2)) >= 2) {
+ bb_show_usage();
}
- argv++;
-
- s = get_last_path_component(*argv);
+ s = bb_get_last_path_component(*++argv);
- if (argc>2) {
- argv++;
+ if (*++argv) {
n = strlen(*argv);
m = strlen(s);
- if (m>n && strncmp(s+m-n, *argv, n)==0)
+ if ((m > n) && ((strcmp)(s+m-n, *argv) == 0)) {
s[m-n] = '\0';
+ }
}
+
puts(s);
- return EXIT_SUCCESS;
+
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/cal.c b/coreutils/cal.c
index ab631576a..ed480dd78 100644
--- a/coreutils/cal.c
+++ b/coreutils/cal.c
@@ -1,3 +1,14 @@
+/* NOTE:
+ *
+ * Apparently, all "Steven J. Merrifield" did was grab the util-linux cal applet,
+ * spend maybe 5 minutes integrating it into busybox, slapped a copyright on it,
+ * and submitted it. I certainly saw no evidence of any attempt at size reduction.
+ * Not only do I consider his copyright below meaningless, I also consider his
+ * actions shameful.
+ *
+ * Manuel Novoa III (mjn3@codepoet.org)
+ */
+
/*
* Calendar implementation for busybox
*
@@ -20,7 +31,16 @@
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
-
+
+/* BB_AUDIT SUSv3 compliant with -j and -y extensions (from util-linux). */
+/* BB_AUDIT BUG: The output of 'cal -j 1752' is incorrect. The upstream
+ * BB_AUDIT BUG: version in util-linux seems to be broken as well. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/cal.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Major size reduction... over 50% (>1.5k) on i386.
+ */
#include <sys/types.h>
#include <ctype.h>
@@ -46,44 +66,30 @@
#define MAXDAYS 42 /* max slots in a month array */
#define SPACE -1 /* used in day array */
-static int days_in_month[2][13] = {
- {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
- {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
+static const char days_in_month[] = {
+ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
-int sep1752[MAXDAYS] = {
- SPACE, SPACE, 1, 2, 14, 15, 16,
+static const char sep1752[] = {
+ 1, 2, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23,
- 24, 25, 26, 27, 28, 29, 30,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
-}, j_sep1752[MAXDAYS] = {
- SPACE, SPACE, 245, 246, 258, 259, 260,
- 261, 262, 263, 264, 265, 266, 267,
- 268, 269, 270, 271, 272, 273, 274,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
-}, empty[MAXDAYS] = {
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
- SPACE, SPACE, SPACE, SPACE, SPACE, SPACE, SPACE,
+ 24, 25, 26, 27, 28, 29, 30
};
-char *month_names[12];
-
-char day_headings[] = " ";
-char j_day_headings[] = " ";
+static int julian;
/* leap year -- account for gregorian reformation in 1752 */
#define leap_year(yr) \
((yr) <= 1752 ? !((yr) % 4) : \
(!((yr) % 4) && ((yr) % 100)) || !((yr) % 400))
+static int is_leap_year(int year)
+{
+ return leap_year(year);
+}
+#undef leap_year
+#define leap_year(yr) is_leap_year(yr)
+
/* number of centuries since 1700, not inclusive */
#define centuries_since_1700(yr) \
((yr) > 1700 ? (yr) / 100 - 17 : 0)
@@ -96,178 +102,129 @@ char j_day_headings[] = " ";
#define leap_years_since_year_1(yr) \
((yr) / 4 - centuries_since_1700(yr) + quad_centuries_since_1700(yr))
-int julian;
-void ascii_day __P((char *, int));
-void center __P((char *, int, int));
-void day_array __P((int, int, int *));
-int day_in_week __P((int, int, int));
-int day_in_year __P((int, int, int));
-void j_yearly __P((int));
-void monthly __P((int, int));
-void trim_trailing_spaces __P((char *));
-void yearly __P((int));
+static void center __P((char *, int, int));
+static void day_array __P((int, int, int *));
+static void trim_trailing_spaces_and_print __P((char *));
+
+static void blank_string(char *buf, size_t buflen);
+static char *build_row(char *p, int *dp);
+
+#define DAY_LEN 3 /* 3 spaces per day */
+#define J_DAY_LEN (DAY_LEN + 1)
+#define WEEK_LEN 20 /* 7 * 3 - one space at the end */
+#define J_WEEK_LEN (WEEK_LEN + 7)
+#define HEAD_SEP 2 /* spaces between day headings */
int cal_main(int argc, char **argv)
{
struct tm *local_time;
- static struct tm zero_tm;
+ struct tm zero_tm;
time_t now;
- int ch, month, year, yflag, i;
+ int month, year, flags, i;
+ char *month_names[12];
+ char day_headings[28]; /* 28 for julian, 21 for nonjulian */
char buf[40];
#ifdef CONFIG_LOCALE_SUPPORT
setlocale(LC_TIME, "");
#endif
- yflag = 0;
- while ((ch = getopt(argc, argv, "jy")) != -1)
- switch(ch) {
- case 'j':
- julian = 1;
- break;
- case 'y':
- yflag = 1;
- break;
- default:
- show_usage();
- }
- argc -= optind;
+ flags = bb_getopt_ulflags(argc, argv, "jy");
+
+ julian = flags & 1;
+
argv += optind;
month = 0;
- switch(argc) {
- case 2:
- if ((month = atoi(*argv++)) < 1 || month > 12)
- error_msg_and_die("Illegal month value: use 1-12");
- /* FALLTHROUGH */
- case 1:
- if ((year = atoi(*argv)) < 1 || year > 9999)
- error_msg_and_die("Illegal year value: use 1-9999");
- break;
- case 0:
+
+ if ((argc -= optind) > 2) {
+ bb_show_usage();
+ }
+
+ if (!argc) {
time(&now);
local_time = localtime(&now);
year = local_time->tm_year + 1900;
- if (!yflag)
+ if (!(flags & 2)) {
month = local_time->tm_mon + 1;
- break;
- default:
- show_usage();
+ }
+ } else {
+ if (argc == 2) {
+ month = bb_xgetularg10_bnd(*argv++, 1, 12);
+ }
+ year = bb_xgetularg10_bnd(*argv, 1, 9999);
}
- for (i = 0; i < 12; i++) {
+ blank_string(day_headings, sizeof(day_headings) - 7 + 7*julian);
+
+ i = 0;
+ do {
zero_tm.tm_mon = i;
strftime(buf, sizeof(buf), "%B", &zero_tm);
- month_names[i] = xstrdup(buf);
- }
- for (i = 0; i < 7; i++) {
- zero_tm.tm_wday = i;
- strftime(buf, sizeof(buf), "%a", &zero_tm);
- strncpy(day_headings + i * 3, buf, 2);
- strncpy(j_day_headings + i * 4 + 1, buf, 2);
- }
-
- if (month)
- monthly(month, year);
- else if (julian)
- j_yearly(year);
- else
- yearly(year);
- exit(0);
-}
+ month_names[i] = bb_xstrdup(buf);
-#define DAY_LEN 3 /* 3 spaces per day */
-#define J_DAY_LEN 4 /* 4 spaces per day */
-#define WEEK_LEN 20 /* 7 * 3 - one space at the end */
-#define J_WEEK_LEN 27 /* 7 * 4 - one space at the end */
-#define HEAD_SEP 2 /* spaces between day headings */
-#define J_HEAD_SEP 2
-
-void monthly(int month, int year)
-{
- int col, row, len, days[MAXDAYS];
- char *p, lineout[30];
-
- day_array(month, year, days);
- len = sprintf(lineout, "%s %d", month_names[month - 1], year);
- printf("%*s%s\n%s\n",
- ((julian ? J_WEEK_LEN : WEEK_LEN) - len) / 2, "",
- lineout, julian ? j_day_headings : day_headings);
- for (row = 0; row < 6; row++) {
- for (col = 0, p = lineout; col < 7; col++,
- p += julian ? J_DAY_LEN : DAY_LEN)
- ascii_day(p, days[row * 7 + col]);
- *p = '\0';
- trim_trailing_spaces(lineout);
- printf("%s\n", lineout);
- }
-}
-
-void j_yearly(int year)
-{
- int col, *dp, i, month, row, which_cal;
- int days[12][MAXDAYS];
- char *p, lineout[80];
-
- sprintf(lineout, "%d", year);
- center(lineout, J_WEEK_LEN * 2 + J_HEAD_SEP, 0);
- printf("\n\n");
- for (i = 0; i < 12; i++)
- day_array(i + 1, year, days[i]);
- memset(lineout, ' ', sizeof(lineout) - 1);
- lineout[sizeof(lineout) - 1] = '\0';
- for (month = 0; month < 12; month += 2) {
- center(month_names[month], J_WEEK_LEN, J_HEAD_SEP);
- center(month_names[month + 1], J_WEEK_LEN, 0);
- printf("\n%s%*s%s\n", j_day_headings, J_HEAD_SEP, "",
- j_day_headings);
- for (row = 0; row < 6; row++) {
- for (which_cal = 0; which_cal < 2; which_cal++) {
- p = lineout + which_cal * (J_WEEK_LEN + 2);
- dp = &days[month + which_cal][row * 7];
- for (col = 0; col < 7; col++, p += J_DAY_LEN)
- ascii_day(p, *dp++);
- }
- *p = '\0';
- trim_trailing_spaces(lineout);
- printf("%s\n", lineout);
+ if (i < 7) {
+ zero_tm.tm_wday = i;
+ strftime(buf, sizeof(buf), "%a", &zero_tm);
+ strncpy(day_headings + i * (3+julian) + julian, buf, 2);
}
- }
- printf("\n");
-}
-
-void yearly(int year)
-{
- int col, *dp, i, month, row, which_cal;
- int days[12][MAXDAYS];
- char *p, lineout[80];
-
- sprintf(lineout, "%d", year);
- center(lineout, WEEK_LEN * 3 + HEAD_SEP * 2, 0);
- printf("\n\n");
- for (i = 0; i < 12; i++)
- day_array(i + 1, year, days[i]);
- memset(lineout, ' ', sizeof(lineout) - 1);
- lineout[sizeof(lineout) - 1] = '\0';
- for (month = 0; month < 12; month += 3) {
- center(month_names[month], WEEK_LEN, HEAD_SEP);
- center(month_names[month + 1], WEEK_LEN, HEAD_SEP);
- center(month_names[month + 2], WEEK_LEN, 0);
- printf("\n%s%*s%s%*s%s\n", day_headings, HEAD_SEP,
- "", day_headings, HEAD_SEP, "", day_headings);
+ } while (++i < 12);
+
+ if (month) {
+ int row, len, days[MAXDAYS];
+ int *dp = days;
+ char lineout[30];
+
+ day_array(month, year, dp);
+ len = sprintf(lineout, "%s %d", month_names[month - 1], year);
+ bb_printf("%*s%s\n%s\n",
+ ((7*julian + WEEK_LEN) - len) / 2, "",
+ lineout, day_headings);
for (row = 0; row < 6; row++) {
- for (which_cal = 0; which_cal < 3; which_cal++) {
- p = lineout + which_cal * (WEEK_LEN + 2);
- dp = &days[month + which_cal][row * 7];
- for (col = 0; col < 7; col++, p += DAY_LEN)
- ascii_day(p, *dp++);
+ build_row(lineout, dp)[0] = '\0';
+ dp += 7;
+ trim_trailing_spaces_and_print(lineout);
+ }
+ } else {
+ int row, which_cal, week_len, days[12][MAXDAYS];
+ int *dp;
+ char lineout[80];
+
+ sprintf(lineout, "%d", year);
+ center(lineout,
+ (WEEK_LEN * 3 + HEAD_SEP * 2)
+ + julian * (J_WEEK_LEN * 2 + HEAD_SEP
+ - (WEEK_LEN * 3 + HEAD_SEP * 2)),
+ 0);
+ puts("\n"); /* two \n's */
+ for (i = 0; i < 12; i++) {
+ day_array(i + 1, year, days[i]);
+ }
+ blank_string(lineout, sizeof(lineout));
+ week_len = WEEK_LEN + julian * (J_WEEK_LEN - WEEK_LEN);
+ for (month = 0; month < 12; month += 3-julian) {
+ center(month_names[month], week_len, HEAD_SEP);
+ if (!julian) {
+ center(month_names[month + 1], week_len, HEAD_SEP);
+ }
+ center(month_names[month + 2 - julian], week_len, 0);
+ bb_printf("\n%s%*s%s", day_headings, HEAD_SEP, "", day_headings);
+ if (!julian) {
+ bb_printf("%*s%s", HEAD_SEP, "", day_headings);
+ }
+ putchar('\n');
+ for (row = 0; row < (6*7); row += 7) {
+ for (which_cal = 0; which_cal < 3-julian; which_cal++) {
+ dp = days[month + which_cal] + row;
+ build_row(lineout + which_cal * (week_len + 2), dp);
+ }
+ /* blank_string took care of nul termination. */
+ trim_trailing_spaces_and_print(lineout);
}
- *p = '\0';
- trim_trailing_spaces(lineout);
- printf("%s\n", lineout);
}
}
- printf("\n");
+
+ bb_fflush_stdout_and_exit(0);
}
/*
@@ -277,118 +234,129 @@ void yearly(int year)
* out end to end. You would have 42 numbers or spaces. This routine
* builds that array for any month from Jan. 1 through Dec. 9999.
*/
-void day_array(int month, int year, int *days)
+static void day_array(int month, int year, int *days)
{
+ long temp;
+ int i;
+ int j_offset;
int day, dw, dm;
+ memset(days, SPACE, MAXDAYS * sizeof(int));
+
if ((month == 9) && (year == 1752)) {
- memmove(days,
- julian ? j_sep1752 : sep1752, MAXDAYS * sizeof(int));
+ j_offset = julian * 244;
+ i = 0;
+ do {
+ days[i+2] = sep1752[i] + j_offset;
+ } while (++i < sizeof(sep1752));
+
return;
}
- memmove(days, empty, MAXDAYS * sizeof(int));
- dm = days_in_month[leap_year(year)][month];
- dw = day_in_week(1, month, year);
- day = julian ? day_in_year(1, month, year) : 1;
- while (dm--)
- days[dw++] = day++;
-}
-/*
- * day_in_year --
- * return the 1 based day number within the year
- */
-int day_in_year(int day, int month, int year)
-{
- int i, leap;
-
- leap = leap_year(year);
- for (i = 1; i < month; i++)
- day += days_in_month[leap][i];
- return (day);
-}
+ /* day_in_year
+ * return the 1 based day number within the year
+ */
+ day = 1;
+ if ((month > 2) && leap_year(year)) {
+ ++day;
+ }
-/*
- * day_in_week
- * return the 0 based day number for any date from 1 Jan. 1 to
- * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
- * 3 Sep. 1752 through 13 Sep. 1752. Returns Thursday for all
- * missing days.
- */
-int day_in_week(int day, int month, int year)
-{
- long temp;
+ i = month;
+ while (i) {
+ day += days_in_month[--i];
+ }
+ /* day_in_week
+ * return the 0 based day number for any date from 1 Jan. 1 to
+ * 31 Dec. 9999. Assumes the Gregorian reformation eliminates
+ * 3 Sep. 1752 through 13 Sep. 1752. Returns Thursday for all
+ * missing days.
+ */
+ dw = THURSDAY;
temp = (long)(year - 1) * 365 + leap_years_since_year_1(year - 1)
- + day_in_year(day, month, year);
- if (temp < FIRST_MISSING_DAY)
- return ((temp - 1 + SATURDAY) % 7);
- if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS))
- return (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
- return (THURSDAY);
+ + day;
+ if (temp < FIRST_MISSING_DAY) {
+ dw = ((temp - 1 + SATURDAY) % 7);
+ } else if (temp >= (FIRST_MISSING_DAY + NUMBER_MISSING_DAYS)) {
+ dw = (((temp - 1 + SATURDAY) - NUMBER_MISSING_DAYS) % 7);
+ }
+
+ if (!julian) {
+ day = 1;
+ }
+
+ dm = days_in_month[month];
+ if ((month == 2) && leap_year(year)) {
+ ++dm;
+ }
+
+ while (dm) {
+ days[dw++] = day++;
+ --dm;
+ }
}
-void ascii_day(char *p, int day)
+static void trim_trailing_spaces_and_print(char *s)
{
- int display, val;
- static char *aday[] = {
- "",
- " 1", " 2", " 3", " 4", " 5", " 6", " 7",
- " 8", " 9", "10", "11", "12", "13", "14",
- "15", "16", "17", "18", "19", "20", "21",
- "22", "23", "24", "25", "26", "27", "28",
- "29", "30", "31",
- };
-
- if (day == SPACE) {
- memset(p, ' ', julian ? J_DAY_LEN : DAY_LEN);
- return;
+ char *p = s;
+
+ while (*p) {
+ ++p;
}
- if (julian) {
- if ((val = day / 100) != 0) {
- day %= 100;
- *p++ = val + '0';
- display = 1;
- } else {
- *p++ = ' ';
- display = 0;
+ while (p > s) {
+ --p;
+ if (!(isspace)(*p)) { /* We want the function... not the inline. */
+ p[1] = '\0';
+ break;
}
- val = day / 10;
- if (val || display)
- *p++ = val + '0';
- else
- *p++ = ' ';
- *p++ = day % 10 + '0';
- } else {
- *p++ = aday[day][0];
- *p++ = aday[day][1];
}
- *p = ' ';
+
+ puts(s);
}
-void trim_trailing_spaces(char *s)
+static void center(char *str, int len, int separate)
{
- char *p;
+ int n = strlen(str);
+ len -= n;
+ bb_printf("%*s%*s", (len/2) + n, str, (len/2) + (len % 2) + separate, "");
+}
- for (p = s; *p; ++p)
- continue;
- while (p > s && (--p, isspace(*p)))
- continue;
- if (p > s)
- ++p;
- *p = '\0';
+static void blank_string(char *buf, size_t buflen)
+{
+ memset(buf, ' ', buflen);
+ buf[buflen-1] = '\0';
}
-void center(char *str, int len, int separate)
+static char *build_row(char *p, int *dp)
{
+ int col, val, day;
+
+ memset(p, ' ', (julian + DAY_LEN) * 7);
+
+ col = 0;
+ do {
+ if ((day = *dp++) != SPACE) {
+ if (julian) {
+ *++p;
+ if (day >= 100) {
+ *p = '0';
+ p[-1] = (day / 100) + '0';
+ day %= 100;
+ }
+ }
+ if ((val = day / 10) > 0) {
+ *p = val + '0';
+ }
+ *++p = day % 10 + '0';
+ p += 2;
+ } else {
+ p += DAY_LEN + julian;
+ }
+ } while (++col < 7);
- len -= strlen(str);
- printf("%*s%s%*s", len / 2, "", str, len / 2 + len % 2, "");
- if (separate)
- printf("%*s", separate, "");
+ return p;
}
-
/*
* Copyright (c) 1989, 1993, 1994
* The Regents of the University of California. All rights reserved.
diff --git a/coreutils/cat.c b/coreutils/cat.c
index 33f15da71..865275767 100644
--- a/coreutils/cat.c
+++ b/coreutils/cat.c
@@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini Cat implementation for busybox
+ * cat implementation for busybox
*
- * Copyright (C) 1999,2000 by Lineo, inc. and Erik Andersen
- * Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,33 +20,48 @@
*
*/
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/cat.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * This is a new implementation of 'cat' which aims to be SUSv3 compliant.
+ *
+ * Changes from the previous implementation include:
+ * 1) Multiple '-' args are accepted as required by SUSv3. The previous
+ * implementation would close stdin and segfault on a subsequent '-'.
+ * 2) The '-u' options is required by SUSv3. Note that the specified
+ * behavior for '-u' is done by default, so all we need do is accept
+ * the option.
+ */
+
#include <stdlib.h>
-#include <string.h>
+#include <stdio.h>
+#include <unistd.h>
#include "busybox.h"
extern int cat_main(int argc, char **argv)
{
- int status = EXIT_SUCCESS;
+ FILE *f;
+ int retval = EXIT_SUCCESS;
- if (argc == 1) {
- print_file(stdin);
- return status;
+ bb_getopt_ulflags(argc, argv, "u");
+
+ argv += optind;
+ if (!*argv) {
+ *--argv = "-";
}
- while (--argc > 0) {
- if(!(strcmp(*++argv, "-"))) {
- print_file(stdin);
- } else if (! print_file_by_name(*argv)) {
- status = EXIT_FAILURE;
+ do {
+ if ((f = bb_wfopen_input(*argv)) != NULL) {
+ int r = bb_copyfd(fileno(f), STDOUT_FILENO, 0);
+ bb_fclose_nonstdin(f);
+ if (r >= 0) {
+ continue;
+ }
}
- }
- return status;
-}
+ retval = EXIT_FAILURE;
+ } while (*++argv);
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
+ return retval;
+}
diff --git a/coreutils/chgrp.c b/coreutils/chgrp.c
index 968b448c0..f5e5d29f1 100644
--- a/coreutils/chgrp.c
+++ b/coreutils/chgrp.c
@@ -21,9 +21,12 @@
*
*/
-#include <stdio.h>
+/* BB_AUDIT SUSv3 defects - unsupported options -h, -H, -L, and -P. */
+/* BB_AUDIT GNU defects - unsupported options -h, -c, -f, -v, and long options. */
+/* BB_AUDIT Note: gnu chgrp does not support -H, -L, or -P. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/chgrp.html */
+
#include <stdlib.h>
-#include <string.h>
#include <unistd.h>
#include "busybox.h"
@@ -32,53 +35,46 @@
#define lchown chown
#endif
-
-static long gid;
-
static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
{
- if (lchown(fileName, statbuf->st_uid, (gid == -1) ? statbuf->st_gid : gid) == 0) {
+ if (lchown(fileName, statbuf->st_uid, *((long *) junk)) == 0) {
return (TRUE);
}
- perror(fileName);
+ bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE);
}
int chgrp_main(int argc, char **argv)
{
- int opt;
- int recursiveFlag = FALSE;
- char *p=NULL;
+ long gid;
+ int recursiveFlag;;
+ int retval = EXIT_SUCCESS;
+ char *p;
- /* do normal option parsing */
- while ((opt = getopt(argc, argv, "R")) > 0) {
- switch (opt) {
- case 'R':
- recursiveFlag = TRUE;
- break;
- default:
- show_usage();
- }
+ recursiveFlag = bb_getopt_ulflags(argc, argv, "R");
+
+ if (argc - optind < 2) {
+ bb_show_usage();
}
- if (argc > optind && argc > 2 && argv[optind]) {
- /* Find the selected group */
- gid = strtoul(argv[optind], &p, 10); /* maybe it's already numeric */
- if (argv[optind] == p)
- gid = my_getgrnam(argv[optind]);
- } else {
- error_msg_and_die(too_few_args);
+ argv += optind;
+
+ /* Find the selected group */
+ gid = strtoul(*argv, &p, 10); /* maybe it's already numeric */
+ if (*p || (p == *argv)) { /* trailing chars or nonnumeric */
+ gid = my_getgrnam(*argv);
}
+ ++argv;
/* Ok, ready to do the deed now */
- while (++optind < argc) {
- if (! recursive_action (argv[optind], recursiveFlag, FALSE, FALSE,
- fileAction, fileAction, NULL)) {
- return EXIT_FAILURE;
+ do {
+ if (! recursive_action (*argv, recursiveFlag, FALSE, FALSE,
+ fileAction, fileAction, &gid)) {
+ retval = EXIT_FAILURE;
}
- }
- return EXIT_SUCCESS;
+ } while (*++argv);
+ return retval;
}
/*
diff --git a/coreutils/chmod.c b/coreutils/chmod.c
index ba80e020a..28c98552a 100644
--- a/coreutils/chmod.c
+++ b/coreutils/chmod.c
@@ -24,67 +24,84 @@
*
*/
+/* BB_AUDIT SUSv3 compliant */
+/* BB_AUDIT GNU defects - unsupported options -c, -f, -v, and long options. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/chmod.html */
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
-#include <getopt.h>
+#include <sys/stat.h>
#include "busybox.h"
static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
{
- if (!parse_mode((char *)junk, &(statbuf->st_mode)))
- error_msg_and_die( "unknown mode: %s", (char *)junk);
+ if (!bb_parse_mode((char *)junk, &(statbuf->st_mode)))
+ bb_error_msg_and_die( "unknown mode: %s", (char *)junk);
if (chmod(fileName, statbuf->st_mode) == 0)
return (TRUE);
- perror(fileName);
+ bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE);
}
int chmod_main(int argc, char **argv)
{
- int opt;
+ int retval = EXIT_SUCCESS;
int recursiveFlag = FALSE;
- int modeind = 0; /* Index of the mode argument in `argv'. */
+ int count;
char *smode;
- static const char chmod_modes[] = "Rrwxstugoa,+-=";
+ char **p;
+ char *p0;
+ char opt = '-';
- /* do normal option parsing */
- while (1) {
- int thisind = optind ? optind : 1;
+ ++argv;
+ count = 0;
- opt = getopt(argc, argv, chmod_modes);
- if (opt == EOF)
- break;
- smode = strchr(chmod_modes, opt);
- if(smode == NULL)
- show_usage();
- if(smode == chmod_modes) { /* 'R' */
- recursiveFlag = TRUE;
- } else {
- if (modeind != 0 && modeind != thisind)
- show_usage();
- modeind = thisind;
+ for (p = argv ; *p ; p++) {
+ p0 = p[0];
+ if (p0[0] == opt) {
+ if ((p0[1] == '-') && !p0[2]) {
+ opt = 0; /* Disable further option processing. */
+ continue;
+ }
+ if (p0[1] == 'R') {
+ char *s = p0 + 2;
+ while (*s == 'R') {
+ ++s;
+ }
+ if (*s) {
+ bb_show_usage();
+ }
+ recursiveFlag = TRUE;
+ continue;
+ }
+ if (count) {
+ bb_show_usage();
+ }
}
+ argv[count] = p0;
+ ++count;
}
- if (modeind == 0)
- modeind = optind++;
+ argv[count] = NULL;
- opt = optind;
- if (opt >= argc) {
- error_msg_and_die(too_few_args);
+ if (count < 2) {
+ bb_show_usage();
}
- smode = argv[modeind];
+ smode = *argv;
+ ++argv;
+
/* Ok, ready to do the deed now */
- for (; opt < argc; opt++) {
- if (! recursive_action (argv[opt], recursiveFlag, FALSE, FALSE, fileAction,
- fileAction, smode)) {
- return EXIT_FAILURE;
+ do {
+ if (! recursive_action (*argv, recursiveFlag, FALSE, FALSE,
+ fileAction, fileAction, smode)) {
+ retval = EXIT_FAILURE;
}
- }
- return EXIT_SUCCESS;
+ } while (*++argv);
+
+ return retval;
}
/*
diff --git a/coreutils/chown.c b/coreutils/chown.c
index 4e766a90b..3e983cfa6 100644
--- a/coreutils/chown.c
+++ b/coreutils/chown.c
@@ -21,10 +21,14 @@
*
*/
-#include <stdio.h>
+/* BB_AUDIT SUSv3 defects - unsupported options -h, -H, -L, and -P. */
+/* BB_AUDIT GNU defects - unsupported options -h, -c, -f, -v, and long options. */
+/* BB_AUDIT Note: gnu chown does not support -H, -L, or -P. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/chown.html */
+
#include <stdlib.h>
-#include <string.h>
#include <unistd.h>
+#include <string.h>
#include "busybox.h"
/* Don't use lchown for libc5 or glibc older then 2.1.x */
@@ -42,65 +46,67 @@ static int fileAction(const char *fileName, struct stat *statbuf, void* junk)
if (chown_func(fileName, uid, (gid == -1) ? statbuf->st_gid : gid) == 0) {
return (TRUE);
}
- perror(fileName);
+ bb_perror_msg("%s", fileName); /* Avoid multibyte problems. */
return (FALSE);
}
+#define FLAG_R 1
+#define FLAG_h 2
+
+static unsigned long get_ug_id(const char *s, long (*my_getxxnam)(const char *))
+{
+ unsigned long r;
+ char *p;
+
+ r = strtoul(s, &p, 10);
+ if (*p || (s == p)) {
+ r = my_getxxnam(s);
+ }
+
+ return r;
+}
+
int chown_main(int argc, char **argv)
{
- int opt;
- int recursiveFlag = FALSE,
- noderefFlag = FALSE;
- char *groupName=NULL;
- char *p=NULL;
-
- /* do normal option parsing */
- while ((opt = getopt(argc, argv, "Rh")) > 0) {
- switch (opt) {
- case 'R':
- recursiveFlag = TRUE;
- break;
- case 'h':
- noderefFlag = TRUE;
- break;
- default:
- show_usage();
- }
+ int flags;
+ int retval = EXIT_SUCCESS;
+ char *groupName;
+
+ flags = bb_getopt_ulflags(argc, argv, "Rh");
+
+ if (flags & FLAG_h) chown_func = lchown;
+
+ if (argc - optind < 2) {
+ bb_show_usage();
}
- if (noderefFlag) chown_func = lchown;
-
- if (argc > optind && argc > 2 && argv[optind]) {
- /* First, check if there is a group name here */
- groupName = strchr(argv[optind], '.');
- if (groupName == NULL)
- groupName = strchr(argv[optind], ':');
- if (groupName) {
- *groupName++ = '\0';
- gid = strtoul(groupName, &p, 10);
- if (groupName == p)
- gid = my_getgrnam(groupName);
- } else {
- gid = -1;
- }
- /* Now check for the username */
- uid = strtoul(argv[optind], &p, 10); /* Is is numeric? */
- if (argv[optind] == p) {
- uid = my_getpwnam(argv[optind]);
- }
- } else {
- error_msg_and_die(too_few_args);
+ argv += optind;
+
+ /* First, check if there is a group name here */
+ if ((groupName = strchr(*argv, '.')) == NULL) {
+ groupName = strchr(*argv, ':');
+ }
+
+ gid = -1;
+ if (groupName) {
+ *groupName++ = '\0';
+ gid = get_ug_id(groupName, my_getgrnam);
}
+ /* Now check for the username */
+ uid = get_ug_id(*argv, my_getpwnam);
+
+ ++argv;
+
/* Ok, ready to do the deed now */
- while (++optind < argc) {
- if (! recursive_action (argv[optind], recursiveFlag, FALSE, FALSE,
- fileAction, fileAction, NULL)) {
- return EXIT_FAILURE;
+ do {
+ if (! recursive_action (*argv, (flags & FLAG_R), FALSE, FALSE,
+ fileAction, fileAction, NULL)) {
+ retval = EXIT_FAILURE;
}
- }
- return EXIT_SUCCESS;
+ } while (*++argv);
+ return retval;
}
/*
diff --git a/coreutils/chroot.c b/coreutils/chroot.c
index ba3e5f864..01e4d564c 100644
--- a/coreutils/chroot.c
+++ b/coreutils/chroot.c
@@ -21,6 +21,8 @@
*
*/
+/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
+
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
@@ -29,46 +31,24 @@
int chroot_main(int argc, char **argv)
{
- char *prog;
-
- if ((argc < 2) || (**(argv + 1) == '-')) {
- show_usage();
+ if (argc < 2) {
+ bb_show_usage();
}
- argc--;
- argv++;
+ ++argv;
if (chroot(*argv) || (chdir("/"))) {
- perror_msg_and_die("cannot change root directory to %s", *argv);
+ bb_perror_msg_and_die("cannot change root directory to %s", *argv);
}
- argc--;
- argv++;
- if (argc >= 1) {
- prog = *argv;
- execvp(*argv, argv);
- } else {
-#if defined shell_main && defined CONFIG_FEATURE_SH_STANDALONE_SHELL
- char shell[] = "/bin/sh";
- char *shell_argv[2] = { shell, NULL };
- applet_name = shell;
- shell_main(1, shell_argv);
- return EXIT_SUCCESS;
-#else
- prog = getenv("SHELL");
- if (!prog)
- prog = "/bin/sh";
- execlp(prog, prog, NULL);
-#endif
+ ++argv;
+ if (argc == 2) {
+ argv -= 2;
+ if (!(*argv = getenv("SHELL"))) {
+ *argv = (char *) "/bin/sh";
+ }
+ argv[1] = (char *) "-i";
}
- perror_msg_and_die("cannot execute %s", prog);
+ execvp(*argv, argv);
+ bb_perror_msg_and_die("cannot execute %s", *argv);
}
-
-
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
diff --git a/coreutils/cmp.c b/coreutils/cmp.c
index 07bf3be92..43dbc842f 100644
--- a/coreutils/cmp.c
+++ b/coreutils/cmp.c
@@ -20,59 +20,133 @@
*
*/
+/* BB_AUDIT SUSv3 (virtually) compliant -- uses nicer GNU format for -l. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/cmp.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Original version majorly reworked for SUSv3 compliance, bug fixes, and
+ * size optimizations. Changes include:
+ * 1) Now correctly distingusishes between errors and actual file differences.
+ * 2) Proper handling of '-' args.
+ * 3) Actual error checking of i/o.
+ * 4) Accept SUSv3 -l option. Note that we use the slightly nicer gnu format
+ * in the '-l' case.
+ */
+
#include <stdio.h>
-#include <string.h>
-#include <errno.h>
#include <stdlib.h>
-#include <getopt.h>
+#include <unistd.h>
#include "busybox.h"
+static FILE *cmp_xfopen_input(const char *filename)
+{
+ FILE *fp;
+
+ if ((fp = bb_wfopen_input(filename)) != NULL) {
+ return fp;
+ }
+
+ exit(bb_default_error_retval); /* We already output an error message. */
+}
+
+static const char fmt_eof[] = "cmp: EOF on %s\n";
+static const char fmt_differ[] = "%s %s differ: char %d, line %d\n";
+#if 0
+static const char fmt_l_opt[] = "%.0s%.0s%d %o %o\n"; /* SUSv3 format */
+#else
+static const char fmt_l_opt[] = "%.0s%.0s%d %3o %3o\n"; /* nicer gnu format */
+#endif
+
+static const char opt_chars[] = "sl";
+
+enum {
+ OPT_s = 1,
+ OPT_l = 2
+};
+
int cmp_main(int argc, char **argv)
{
- FILE *fp1 = NULL, *fp2 = stdin;
- char *filename1, *filename2 = "-";
- int c, c1, c2, char_pos = 1, line_pos = 1, silent = FALSE;
-
- while ((c = getopt(argc, argv, "s")) != EOF) {
- switch (c) {
- case 's':
- silent = TRUE;
- break;
- default:
- show_usage();
- }
+ FILE *fp1, *fp2, *outfile = stdout;
+ const char *filename1, *filename2;
+ const char *fmt;
+ int c1, c2, char_pos, line_pos;
+ int opt_flags;
+ int exit_val = 0;
+
+ bb_default_error_retval = 2; /* 1 is returned if files are different. */
+
+ opt_flags = bb_getopt_ulflags(argc, argv, opt_chars);
+
+ if ((opt_flags == 3) || (((unsigned int)(--argc - optind)) > 1)) {
+ bb_show_usage();
}
- filename1 = argv[optind];
- switch (argc - optind) {
- case 2:
- fp2 = xfopen(filename2 = argv[optind + 1], "r");
- case 1:
- fp1 = xfopen(filename1, "r");
- break;
- default:
- show_usage();
+ fp1 = cmp_xfopen_input(filename1 = *(argv += optind));
+
+ filename2 = "-";
+ if (*++argv) {
+ filename2 = *argv;
}
+ fp2 = cmp_xfopen_input(filename2);
+ if (fp1 == fp2) { /* Paranioa check... stdin == stdin? */
+ /* Note that we don't bother reading stdin. Neither does gnu wc.
+ * But perhaps we should, so that other apps down the chain don't
+ * get the input. Consider 'echo hello | (cmp - - && cat -)'.
+ */
+ return 0;
+ }
+
+ fmt = fmt_differ;
+ if (opt_flags == OPT_l) {
+ fmt = fmt_l_opt;
+ }
+
+ char_pos = 0;
+ line_pos = 1;
do {
- c1 = fgetc(fp1);
- c2 = fgetc(fp2);
- if (c1 != c2) {
- if (silent)
- return EXIT_FAILURE;
- if (c1 == EOF)
- printf("EOF on %s\n", filename1);
- else if (c2 == EOF)
- printf("EOF on %s\n", filename2);
- else
- printf("%s %s differ: char %d, line %d\n", filename1, filename2,
- char_pos, line_pos);
- return EXIT_FAILURE;
+ c1 = getc(fp1);
+ c2 = getc(fp2);
+ ++char_pos;
+ if (c1 != c2) { /* Remember -- a read error may have occurred. */
+ exit_val = 1; /* But assume the files are different for now. */
+ if (c2 == EOF) {
+ /* We know that fp1 isn't at EOF or in an error state. But to
+ * save space below, things are setup to expect an EOF in fp1
+ * if an EOF occurred. So, swap things around.
+ */
+ fp1 = fp2;
+ filename1 = filename2;
+ c1 = c2;
+ }
+ if (c1 == EOF) {
+ bb_xferror(fp1, filename1);
+ fmt = fmt_eof; /* Well, no error, so it must really be EOF. */
+ outfile = stderr;
+ /* There may have been output to stdout (option -l), so
+ * make sure we fflush before writing to stderr. */
+ bb_xfflush_stdout();
+ }
+ if (opt_flags != OPT_s) {
+ if (opt_flags == OPT_l) {
+ line_pos = c1; /* line_pos is unused in the -l case. */
+ }
+ bb_fprintf(outfile, fmt, filename1, filename2, char_pos, line_pos, c2);
+ if (opt_flags) { /* This must be -l since not -s. */
+ /* If we encountered and EOF, the while check will catch it. */
+ continue;
+ }
+ }
+ break;
+ }
+ if (c1 == '\n') {
+ ++line_pos;
}
- char_pos++;
- if (c1 == '\n')
- line_pos++;
} while (c1 != EOF);
- return EXIT_SUCCESS;
+ bb_xferror(fp1, filename1);
+ bb_xferror(fp2, filename2);
+
+ bb_fflush_stdout_and_exit(exit_val);
}
diff --git a/coreutils/cp.c b/coreutils/cp.c
index 8f8fe5ed3..c5dd31ec3 100644
--- a/coreutils/cp.c
+++ b/coreutils/cp.c
@@ -2,7 +2,6 @@
/*
* Mini cp implementation for busybox
*
- *
* Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
*
* This program is free software; you can redistribute it and/or modify
@@ -21,6 +20,15 @@
*
*/
+/* BB_AUDIT SUSv3 defects - unsupported options -H, -L, and -P. */
+/* BB_AUDIT GNU defects - only extension options supported are -a and -d. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/cp.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Size reduction.
+ */
+
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -29,86 +37,76 @@
#include <errno.h>
#include <dirent.h>
#include <stdlib.h>
-
+#include <assert.h>
#include "busybox.h"
+#include "libcoreutils/coreutils.h"
+
+static const char cp_opts[] = "pdRfia"; /* WARNING!! ORDER IS IMPORTANT!! */
extern int cp_main(int argc, char **argv)
{
+ struct stat source_stat;
+ struct stat dest_stat;
+ const char *last;
+ const char *dest;
+ int s_flags;
+ int d_flags;
+ int flags;
int status = 0;
- int opt;
- int flags = FILEUTILS_DEREFERENCE;
- int i;
- while ((opt = getopt(argc, argv, "adfipR")) != -1)
- switch (opt) {
- case 'a':
- flags |= FILEUTILS_PRESERVE_STATUS | FILEUTILS_RECUR;
- /* fallthrough */
- case 'd':
- flags &= ~FILEUTILS_DEREFERENCE;
- break;
- case 'f':
- flags |= FILEUTILS_FORCE;
- break;
- case 'i':
- flags |= FILEUTILS_INTERACTIVE;
- break;
- case 'p':
- flags |= FILEUTILS_PRESERVE_STATUS;
- break;
- case 'R':
- flags |= FILEUTILS_RECUR;
- break;
- default:
- show_usage();
- }
-
- if (optind + 2 > argc)
- show_usage();
+ /* Since these are enums, #if tests will not work. So use assert()s. */
+ assert(FILEUTILS_PRESERVE_STATUS == 1);
+ assert(FILEUTILS_DEREFERENCE == 2);
+ assert(FILEUTILS_RECUR == 4);
+ assert(FILEUTILS_FORCE == 8);
+ assert(FILEUTILS_INTERACTIVE == 16);
- /* If there are only two arguments and... */
- if (optind + 2 == argc) {
- struct stat source_stat;
- struct stat dest_stat;
- int source_exists = 1;
- int dest_exists = 1;
+ flags = bb_getopt_ulflags(argc, argv, cp_opts);
- if ((!(flags & FILEUTILS_DEREFERENCE) &&
- lstat(argv[optind], &source_stat) < 0) ||
- ((flags & FILEUTILS_DEREFERENCE) &&
- stat(argv[optind], &source_stat))) {
- if (errno != ENOENT)
- perror_msg_and_die("unable to stat `%s'", argv[optind]);
- source_exists = 0;
- }
+ if (flags & 32) {
+ flags |= (FILEUTILS_PRESERVE_STATUS | FILEUTILS_RECUR | FILEUTILS_DEREFERENCE);
+ }
+
+ flags ^= FILEUTILS_DEREFERENCE; /* The sense of this flag was reversed. */
+
+ if (optind + 2 > argc) {
+ bb_show_usage();
+ }
+
+ last = argv[argc - 1];
+ argv += optind;
- if (stat(argv[optind + 1], &dest_stat) < 0) {
- if (errno != ENOENT)
- perror_msg_and_die("unable to stat `%s'", argv[optind + 1]);
- dest_exists = 0;
+ /* If there are only two arguments and... */
+ if (optind + 2 == argc) {
+ s_flags = cp_mv_stat2(*argv, &source_stat,
+ (flags & FILEUTILS_DEREFERENCE) ? stat : lstat);
+ if ((s_flags < 0) || ((d_flags = cp_mv_stat(last, &dest_stat)) < 0)) {
+ exit(EXIT_FAILURE);
}
-
/* ...if neither is a directory or... */
- if (((!source_exists || !S_ISDIR(source_stat.st_mode)) &&
- (!dest_exists || !S_ISDIR(dest_stat.st_mode))) ||
- /* ...recursing, the first is a directory, and the
- * second doesn't exist, then... */
- ((flags & FILEUTILS_RECUR) && S_ISDIR(source_stat.st_mode) &&
- !dest_exists)) {
+ if ( !((s_flags | d_flags) & 2) ||
+ /* ...recursing, the 1st is a directory, and the 2nd doesn't exist... */
+ /* ((flags & FILEUTILS_RECUR) && (s_flags & 2) && !d_flags) */
+ /* Simplify the above since FILEUTILS_RECUR >> 1 == 2. */
+ ((((flags & FILEUTILS_RECUR) >> 1) & s_flags) && !d_flags)
+ ) {
/* ...do a simple copy. */
- if (copy_file(argv[optind], argv[optind + 1], flags) < 0)
- status = 1;
- return status;
+ dest = last;
+ goto DO_COPY; /* Note: optind+2==argc implies argv[1]==last below. */
}
}
- for (i = optind; i < argc - 1; i++) {
- char *dest = concat_path_file(argv[argc - 1],
- get_last_path_component(argv[i]));
- if (copy_file(argv[i], dest, flags) < 0)
+ do {
+ dest = concat_path_file(last, bb_get_last_path_component(*argv));
+ DO_COPY:
+ if (copy_file(*argv, dest, flags) < 0) {
status = 1;
- free(dest);
- }
+ }
+ if (*++argv == last) {
+ break;
+ }
+ free((void *) dest);
+ } while (1);
- return status;
+ exit(status);
}
diff --git a/coreutils/cut.c b/coreutils/cut.c
index 3ed264870..c24cf6611 100644
--- a/coreutils/cut.c
+++ b/coreutils/cut.c
@@ -92,7 +92,7 @@ static void parse_lists(char *lists)
} else {
s = strtoul(ntok, &junk, 10);
if(*junk != '\0' || s < 0)
- error_msg_and_die("invalid byte or field list");
+ bb_error_msg_and_die("invalid byte or field list");
/* account for the fact that arrays are zero based, while the user
* expects the first char on the line to be char # 1 */
@@ -109,7 +109,7 @@ static void parse_lists(char *lists)
} else {
e = strtoul(ntok, &junk, 10);
if(*junk != '\0' || e < 0)
- error_msg_and_die("invalid byte or field list");
+ bb_error_msg_and_die("invalid byte or field list");
/* if the user specified and end position of 0, that means "til the
* end of the line */
if (e == 0)
@@ -121,7 +121,7 @@ static void parse_lists(char *lists)
/* if there's something left to tokenize, the user past an invalid list */
if (ltok)
- error_msg_and_die("invalid byte or field list");
+ bb_error_msg_and_die("invalid byte or field list");
/* add the new list */
cut_lists = xrealloc(cut_lists, sizeof(struct cut_list) * (++nlists));
@@ -131,7 +131,7 @@ static void parse_lists(char *lists)
/* make sure we got some cut positions out of all that */
if (nlists == 0)
- error_msg_and_die("missing list of positions");
+ bb_error_msg_and_die("missing list of positions");
/* 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 */
@@ -267,8 +267,7 @@ static void cut_file(FILE *file)
unsigned int linenum = 0; /* keep these zero-based to be consistent */
/* go through every line in the file */
- while ((line = get_line_from_file(file)) != NULL) {
- chomp(line);
+ while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
/* cut based on chars/bytes XXX: only works when sizeof(char) == byte */
if (part == 'c' || part == 'b')
@@ -299,14 +298,14 @@ extern int cut_main(int argc, char **argv)
case 'f':
/* make sure they didn't ask for two types of lists */
if (part != 0) {
- error_msg_and_die("only one type of list may be specified");
+ bb_error_msg_and_die("only one type of list may be specified");
}
part = (char)opt;
parse_lists(optarg);
break;
case 'd':
if (strlen(optarg) > 1) {
- error_msg_and_die("the delimiter must be a single character");
+ bb_error_msg_and_die("the delimiter must be a single character");
}
delim = optarg[0];
break;
@@ -320,17 +319,17 @@ extern int cut_main(int argc, char **argv)
}
if (part == 0) {
- error_msg_and_die("you must specify a list of bytes, characters, or fields");
+ bb_error_msg_and_die("you must specify a list of bytes, characters, or fields");
}
/* non-field (char or byte) cutting has some special handling */
if (part != 'f') {
if (supress_non_delimited_lines) {
- error_msg_and_die("suppressing non-delimited lines makes sense"
+ bb_error_msg_and_die("suppressing non-delimited lines makes sense"
" only when operating on fields");
}
if (delim != '\t' && part != 'f') {
- error_msg_and_die("a delimiter may be specified only when operating on fields");
+ bb_error_msg_and_die("a delimiter may be specified only when operating on fields");
}
}
@@ -344,7 +343,7 @@ extern int cut_main(int argc, char **argv)
int i;
FILE *file;
for (i = optind; i < argc; i++) {
- file = wfopen(argv[i], "r");
+ file = bb_wfopen(argv[i], "r");
if(file) {
cut_file(file);
fclose(file);
diff --git a/coreutils/date.c b/coreutils/date.c
index d68c04a8d..afbedb90d 100644
--- a/coreutils/date.c
+++ b/coreutils/date.c
@@ -53,7 +53,7 @@ static struct tm *date_conv_time(struct tm *tm_time, const char *t_string)
&(tm_time->tm_year));
if (nr < 4 || nr > 5) {
- error_msg_and_die(invalid_date, t_string);
+ bb_error_msg_and_die(bb_msg_invalid_date, t_string);
}
/* correct for century - minor Y2K problem here? */
@@ -108,7 +108,7 @@ static struct tm *date_conv_ftime(struct tm *tm_time, const char *t_string)
t.tm_year -= 1900; /* Adjust years */
t.tm_mon -= 1; /* Adjust dates from 1-12 to 0-11 */
} else {
- error_msg_and_die(invalid_date, t_string);
+ bb_error_msg_and_die(bb_msg_invalid_date, t_string);
}
*tm_time = t;
return (tm_time);
@@ -145,25 +145,25 @@ int date_main(int argc, char **argv)
case 's':
set_time = 1;
if ((date_str != NULL) || ((date_str = optarg) == NULL)) {
- show_usage();
+ bb_show_usage();
}
break;
case 'u':
utc = 1;
if (putenv("TZ=UTC0") != 0)
- error_msg_and_die(memory_exhausted);
+ bb_error_msg_and_die(bb_msg_memory_exhausted);
break;
case 'd':
use_arg = 1;
if ((date_str != NULL) || ((date_str = optarg) == NULL))
- show_usage();
+ bb_show_usage();
break;
#ifdef CONFIG_FEATURE_DATE_ISOFMT
case 'I':
if (!optarg)
ifmt = 1;
else {
- int ifmt_len = xstrlen(optarg);
+ int ifmt_len = bb_strlen(optarg);
if ((ifmt_len <= 4)
&& (strncmp(optarg, "date", ifmt_len) == 0)) {
@@ -180,11 +180,11 @@ int date_main(int argc, char **argv)
}
}
if (ifmt) {
- break; /* else show_usage(); */
+ break; /* else bb_show_usage(); */
}
#endif
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -220,15 +220,15 @@ int date_main(int argc, char **argv)
/* Correct any day of week and day of year etc. fields */
tm = mktime(&tm_time);
if (tm < 0) {
- error_msg_and_die(invalid_date, date_str);
+ bb_error_msg_and_die(bb_msg_invalid_date, date_str);
}
if (utc && (putenv("TZ=UTC0") != 0)) {
- error_msg_and_die(memory_exhausted);
+ bb_error_msg_and_die(bb_msg_memory_exhausted);
}
/* if setting time, set it */
if (set_time && (stime(&tm) < 0)) {
- perror_msg("cannot set date");
+ bb_perror_msg("cannot set date");
}
}
diff --git a/coreutils/dd.c b/coreutils/dd.c
index 8c7272b5c..11508614f 100644
--- a/coreutils/dd.c
+++ b/coreutils/dd.c
@@ -62,19 +62,19 @@ int dd_main(int argc, char **argv)
int ifd;
int ofd;
int i;
- char *infile = NULL;
- char *outfile = NULL;
+ const char *infile = NULL;
+ const char *outfile = NULL;
char *buf;
for (i = 1; i < argc; i++) {
if (strncmp("bs=", argv[i], 3) == 0)
- bs = parse_number(argv[i]+3, dd_suffixes);
+ bs = bb_xparse_number(argv[i]+3, dd_suffixes);
else if (strncmp("count=", argv[i], 6) == 0)
- count = parse_number(argv[i]+6, dd_suffixes);
+ count = bb_xparse_number(argv[i]+6, dd_suffixes);
else if (strncmp("seek=", argv[i], 5) == 0)
- seek = parse_number(argv[i]+5, dd_suffixes);
+ seek = bb_xparse_number(argv[i]+5, dd_suffixes);
else if (strncmp("skip=", argv[i], 5) == 0)
- skip = parse_number(argv[i]+5, dd_suffixes);
+ skip = bb_xparse_number(argv[i]+5, dd_suffixes);
else if (strncmp("if=", argv[i], 3) == 0)
infile = argv[i]+3;
else if (strncmp("of=", argv[i], 3) == 0)
@@ -92,7 +92,7 @@ int dd_main(int argc, char **argv)
noerror = TRUE;
buf += 7;
} else {
- error_msg_and_die("invalid conversion `%s'", argv[i]+5);
+ bb_error_msg_and_die("invalid conversion `%s'", argv[i]+5);
}
if (buf[0] == '\0')
break;
@@ -100,18 +100,18 @@ int dd_main(int argc, char **argv)
buf++;
}
} else
- show_usage();
+ bb_show_usage();
}
buf = xmalloc(bs);
if (infile != NULL) {
if ((ifd = open(infile, O_RDONLY)) < 0) {
- perror_msg_and_die("%s", infile);
+ bb_perror_msg_and_die("%s", infile);
}
} else {
ifd = STDIN_FILENO;
- infile = "standard input";
+ infile = bb_msg_standard_input;
}
if (outfile != NULL) {
@@ -122,7 +122,7 @@ int dd_main(int argc, char **argv)
}
if ((ofd = open(outfile, oflag, 0666)) < 0) {
- perror_msg_and_die("%s", outfile);
+ bb_perror_msg_and_die("%s", outfile);
}
if (seek && trunc) {
@@ -131,24 +131,24 @@ int dd_main(int argc, char **argv)
if (fstat (ofd, &st) < 0 || S_ISREG (st.st_mode) ||
S_ISDIR (st.st_mode)) {
- perror_msg_and_die("%s", outfile);
+ bb_perror_msg_and_die("%s", outfile);
}
}
}
} else {
ofd = STDOUT_FILENO;
- outfile = "standard output";
+ outfile = bb_msg_standard_output;
}
if (skip) {
if (lseek(ifd, skip * bs, SEEK_CUR) < 0) {
- perror_msg_and_die("%s", infile);
+ bb_perror_msg_and_die("%s", infile);
}
}
if (seek) {
if (lseek(ofd, seek * bs, SEEK_CUR) < 0) {
- perror_msg_and_die("%s", outfile);
+ bb_perror_msg_and_die("%s", outfile);
}
}
@@ -161,9 +161,9 @@ int dd_main(int argc, char **argv)
if (n < 0) {
if (noerror) {
n = bs;
- perror_msg("%s", infile);
+ bb_perror_msg("%s", infile);
} else {
- perror_msg_and_die("%s", infile);
+ bb_perror_msg_and_die("%s", infile);
}
}
if (n == 0) {
@@ -178,9 +178,9 @@ int dd_main(int argc, char **argv)
memset(buf + n, '\0', bs - n);
n = bs;
}
- n = full_write(ofd, buf, n);
+ n = bb_full_write(ofd, buf, n);
if (n < 0) {
- perror_msg_and_die("%s", outfile);
+ bb_perror_msg_and_die("%s", outfile);
}
if (n == bs) {
out_full++;
@@ -190,15 +190,16 @@ int dd_main(int argc, char **argv)
}
if (close (ifd) < 0) {
- perror_msg_and_die("%s", infile);
+ bb_perror_msg_and_die("%s", infile);
}
if (close (ofd) < 0) {
- perror_msg_and_die("%s", outfile);
+ bb_perror_msg_and_die("%s", outfile);
}
- fprintf(stderr, "%ld+%ld records in\n", (long)in_full, (long)in_part);
- fprintf(stderr, "%ld+%ld records out\n", (long)out_full, (long)out_part);
+ fprintf(stderr, "%ld+%ld records in\n%ld+%ld records out\n",
+ (long)in_full, (long)in_part,
+ (long)out_full, (long)out_part);
return EXIT_SUCCESS;
}
diff --git a/coreutils/df.c b/coreutils/df.c
index 0e9e5d61a..7d007a003 100644
--- a/coreutils/df.c
+++ b/coreutils/df.c
@@ -22,74 +22,45 @@
*
*/
+/* BB_AUDIT SUSv3 _NOT_ compliant -- options -P and -t missing. Also blocksize. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/df.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Size reduction. Removed floating point dependency. Added error checking
+ * on output. Output stats on 0-sized filesystems if specificly listed on
+ * the command line. Properly round *-blocks, Used, and Available quantities.
+ */
+
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <unistd.h>
#include <mntent.h>
#include <sys/vfs.h>
-#include <getopt.h>
#include "busybox.h"
-extern const char mtab_file[]; /* Defined in utility.c */
-#ifdef CONFIG_FEATURE_HUMAN_READABLE
-static unsigned long df_disp_hr = KILOBYTE;
+#ifndef CONFIG_FEATURE_HUMAN_READABLE
+static long kscale(long b, long bs)
+{
+ return ( b * (long long) bs + KILOBYTE/2 ) / KILOBYTE;
+}
#endif
-static int do_df(char *device, const char *mount_point)
+extern int df_main(int argc, char **argv)
{
- struct statfs s;
long blocks_used;
long blocks_percent_used;
-
- if (statfs(mount_point, &s) != 0) {
- perror_msg("%s", mount_point);
- return FALSE;
- }
-
- if (s.f_blocks > 0) {
- blocks_used = s.f_blocks - s.f_bfree;
- if(blocks_used == 0)
- blocks_percent_used = 0;
- else {
- blocks_percent_used = (long)
- (blocks_used * 100.0 / (blocks_used + s.f_bavail) + 0.5);
- }
- if (strcmp(device, "/dev/root") == 0) {
- /* Adjusts device to be the real root device,
- * or leaves device alone if it can't find it */
- device = find_real_root_device_name(device);
- if(device==NULL)
- return FALSE;
- }
#ifdef CONFIG_FEATURE_HUMAN_READABLE
- printf("%-20s %9s ", device,
- make_human_readable_str(s.f_blocks, s.f_bsize, df_disp_hr));
-
- printf("%9s ",
- make_human_readable_str( (s.f_blocks - s.f_bfree), s.f_bsize, df_disp_hr));
-
- printf("%9s %3ld%% %s\n",
- make_human_readable_str(s.f_bavail, s.f_bsize, df_disp_hr),
- blocks_percent_used, mount_point);
-#else
- printf("%-20s %9ld %9ld %9ld %3ld%% %s\n",
- device,
- (long) (s.f_blocks * (s.f_bsize / (double)KILOBYTE)),
- (long) ((s.f_blocks - s.f_bfree)*(s.f_bsize/(double)KILOBYTE)),
- (long) (s.f_bavail * (s.f_bsize / (double)KILOBYTE)),
- blocks_percent_used, mount_point);
+ unsigned long df_disp_hr = KILOBYTE;
#endif
- }
-
- return TRUE;
-}
-
-extern int df_main(int argc, char **argv)
-{
int status = EXIT_SUCCESS;
- int opt = 0;
- int i = 0;
- char disp_units_hdr[80] = "1k-blocks"; /* default display is kilobytes */
+ int opt;
+ FILE *mount_table;
+ struct mntent *mount_entry;
+ struct statfs s;
+ static const char hdr_1k[] = "1k-blocks"; /* default display is kilobytes */;
+ const char *disp_units_hdr = hdr_1k;
while ((opt = getopt(argc, argv, "k"
#ifdef CONFIG_FEATURE_HUMAN_READABLE
@@ -101,52 +72,106 @@ extern int df_main(int argc, char **argv)
#ifdef CONFIG_FEATURE_HUMAN_READABLE
case 'h':
df_disp_hr = 0;
- strcpy(disp_units_hdr, " Size");
+ disp_units_hdr = " Size";
break;
case 'm':
df_disp_hr = MEGABYTE;
- strcpy(disp_units_hdr, "1M-blocks");
+ disp_units_hdr = "1M-blocks";
break;
#endif
case 'k':
/* default display is kilobytes */
+#ifdef CONFIG_FEATURE_HUMAN_READABLE
+ df_disp_hr = KILOBYTE;
+ disp_units_hdr = hdr_1k;
+#endif
break;
default:
- show_usage();
+ bb_show_usage();
}
}
- printf("%-20s %-14s %s %s %s %s\n", "Filesystem", disp_units_hdr,
- "Used", "Available", "Use%", "Mounted on");
+ bb_printf("Filesystem%11s%-15sUsed Available Use%% Mounted on\n",
+ "", disp_units_hdr);
- if(optind < argc) {
- struct mntent *mount_entry;
- for(i = optind; i < argc; i++)
- {
- if ((mount_entry = find_mount_point(argv[i], mtab_file)) == 0) {
- error_msg("%s: can't find mount point.", argv[i]);
- status = EXIT_FAILURE;
- } else if (!do_df(mount_entry->mnt_fsname, mount_entry->mnt_dir))
- status = EXIT_FAILURE;
+ mount_table = NULL;
+ argv += optind;
+ if (optind >= argc) {
+ if (!(mount_table = setmntent(bb_path_mtab_file, "r"))) {
+ bb_perror_msg_and_die(bb_path_mtab_file);
}
- } else {
- FILE *mount_table;
- struct mntent *mount_entry;
+ }
- mount_table = setmntent(mtab_file, "r");
- if (mount_table == 0) {
- perror_msg("%s", mtab_file);
- return EXIT_FAILURE;
- }
+ do {
+ const char *device;
+ const char *mount_point;
- while ((mount_entry = getmntent(mount_table))) {
- if (!do_df(mount_entry->mnt_fsname, mount_entry->mnt_dir))
+ if (mount_table) {
+ if (!(mount_entry = getmntent(mount_table))) {
+ endmntent(mount_table);
+ break;
+ }
+ } else {
+ if (!(mount_point = *argv++)) {
+ break;
+ }
+ if (!(mount_entry = find_mount_point(mount_point, bb_path_mtab_file))) {
+ bb_error_msg("%s: can't find mount point.", mount_point);
+ SET_ERROR:
status = EXIT_FAILURE;
+ continue;
+ }
}
- endmntent(mount_table);
- }
- return status;
+ device = mount_entry->mnt_fsname;
+ mount_point = mount_entry->mnt_dir;
+
+ if (statfs(mount_point, &s) != 0) {
+ bb_perror_msg("%s", mount_point);
+ goto SET_ERROR;
+ }
+
+ if ((s.f_blocks > 0) || !mount_table){
+ blocks_used = s.f_blocks - s.f_bfree;
+ blocks_percent_used = 0;
+ if (blocks_used + s.f_bavail) {
+ blocks_percent_used = (((long long) blocks_used) * 100
+ + (blocks_used + s.f_bavail)/2
+ ) / (blocks_used + s.f_bavail);
+ }
+
+ if (strcmp(device, "/dev/root") == 0) {
+ /* Adjusts device to be the real root device,
+ * or leaves device alone if it can't find it */
+ if ((device = find_real_root_device_name(device)) != NULL) {
+ goto SET_ERROR;
+ }
+ }
+
+#ifdef CONFIG_FEATURE_HUMAN_READABLE
+ bb_printf("%-21s%9s ", device,
+ make_human_readable_str(s.f_blocks, s.f_bsize, df_disp_hr));
+
+ bb_printf("%9s ",
+ make_human_readable_str( (s.f_blocks - s.f_bfree),
+ s.f_bsize, df_disp_hr));
+
+ bb_printf("%9s %3ld%% %s\n",
+ make_human_readable_str(s.f_bavail, s.f_bsize, df_disp_hr),
+ blocks_percent_used, mount_point);
+#else
+ bb_printf("%-21s%9ld %9ld %9ld %3ld%% %s\n",
+ device,
+ kscale(s.f_blocks, s.f_bsize),
+ kscale(s.f_blocks-s.f_bfree, s.f_bsize),
+ kscale(s.f_bavail, s.f_bsize),
+ blocks_percent_used, mount_point);
+#endif
+ }
+
+ } while (1);
+
+ bb_fflush_stdout_and_exit(status);
}
/*
diff --git a/coreutils/dirname.c b/coreutils/dirname.c
index 387233789..4c6115e66 100644
--- a/coreutils/dirname.c
+++ b/coreutils/dirname.c
@@ -21,20 +21,20 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/dirname.html */
#include <stdio.h>
#include <stdlib.h>
-#include <string.h>
#include "busybox.h"
extern int dirname_main(int argc, char **argv)
{
- if ((argc < 2) || (**(argv + 1) == '-'))
- show_usage();
- argv++;
+ if (argc != 2) {
+ bb_show_usage();
+ }
- puts (dirname (argv[0]));
+ puts(dirname(argv[1]));
- return EXIT_SUCCESS;
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/dos2unix.c b/coreutils/dos2unix.c
index b1d0a9d70..c28e6a8b9 100644
--- a/coreutils/dos2unix.c
+++ b/coreutils/dos2unix.c
@@ -35,6 +35,10 @@
#include <sys/time.h>
#include "busybox.h"
+#define CT_AUTO 0
+#define CT_UNIX2DOS 1
+#define CT_DOS2UNIX 2
+
/* We are making a lame pseudo-random string generator here. in
* convert(), each pass through the while loop will add more and more
* stuff into value, which is _supposed_ to wrap. We don't care about
@@ -55,15 +59,13 @@ static int convert(char *fn, int ConvType)
FILE *in = stdin, *out = stdout;
if (fn != NULL) {
- if ((in = wfopen(fn, "rw")) == NULL) {
- return -1;
- }
+ in = bb_xfopen(fn, "rw");
safe_strncpy(tempFn, fn, sizeof(tempFn));
c = strlen(tempFn);
tempFn[c] = '.';
while(1) {
if (c >=BUFSIZ)
- error_msg_and_die("unique name not found");
+ bb_error_msg_and_die("unique name not found");
/* Get some semi random stuff to try and make a
* random filename based (and in the same dir as)
* the input file... */
@@ -92,7 +94,7 @@ static int convert(char *fn, int ConvType)
// file is alredy in DOS format so it is not necessery to touch it
remove(tempFn);
if (fclose(in) < 0 || fclose(out) < 0) {
- perror_msg(NULL);
+ bb_perror_nomsg();
return -2;
}
return 0;
@@ -106,7 +108,7 @@ static int convert(char *fn, int ConvType)
// file is alredy in UNIX format so it is not necessery to touch it
remove(tempFn);
if ((fclose(in) < 0) || (fclose(out) < 0)) {
- perror_msg(NULL);
+ bb_perror_nomsg();
return -2;
}
return 0;
@@ -137,7 +139,7 @@ static int convert(char *fn, int ConvType)
if (fn != NULL) {
if (fclose(in) < 0 || fclose(out) < 0) {
- perror_msg(NULL);
+ bb_perror_nomsg();
remove(tempFn);
return -2;
}
@@ -146,7 +148,7 @@ static int convert(char *fn, int ConvType)
* should be true since we put them into the same directory
* so we _should_ be ok, but you never know... */
if (rename(tempFn, fn) < 0) {
- perror_msg("unable to rename '%s' as '%s'", tempFn, fn);
+ bb_perror_msg("unable to rename '%s' as '%s'", tempFn, fn);
return -1;
}
}
@@ -177,7 +179,7 @@ int dos2unix_main(int argc, char *argv[])
ConvType = CT_DOS2UNIX;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
diff --git a/coreutils/du.c b/coreutils/du.c
index 2e49b2147..702a9aa14 100644
--- a/coreutils/du.c
+++ b/coreutils/du.c
@@ -22,45 +22,65 @@
*
*/
-#include <sys/types.h>
-#include <fcntl.h>
-#include <dirent.h>
-#include <stdio.h>
+/* BB_AUDIT SUSv3 compliant (unless default blocksize set to 1k) */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/du.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Mostly rewritten for SUSv3 compliance and to fix bugs/defects.
+ * 1) Added support for SUSv3 -a, -H, -L, gnu -c, and (busybox) -d options.
+ * The -d option allows setting of max depth (similar to gnu --max-depth).
+ * 2) Fixed incorrect size calculations for links and directories, especially
+ * when errors occurred. Calculates sizes should now match gnu du output.
+ * 3) Added error checking of output.
+ * 4) Fixed busybox bug #1284 involving long overflow with human_readable.
+ */
+
#include <stdlib.h>
-#include <getopt.h>
-#include <string.h>
-#include <errno.h>
+#include <limits.h>
+#include <unistd.h>
+#include <dirent.h>
+#include <sys/stat.h>
#include "busybox.h"
-
#ifdef CONFIG_FEATURE_HUMAN_READABLE
+# ifdef CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
static unsigned long disp_hr = KILOBYTE;
+# else
+static unsigned long disp_hr = 512;
+# endif
+#elif defined CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
+static unsigned int disp_k = 1;
+#else
+static unsigned int disp_k; /* bss inits to 0 */
#endif
-static int du_depth /*= 0*/;
-static int count_hardlinks /*= 0*/;
-static int one_file_system /*= 0*/;
+static int max_print_depth = INT_MAX;
+static int count_hardlinks = INT_MAX;
+
+static int status
+#if EXIT_SUCCESS == 0
+ = EXIT_SUCCESS
+#endif
+ ;
+static int print_files;
+static int slink_depth;
+static int du_depth;
+static int one_file_system;
static dev_t dir_dev;
-static void (*print) (long, char *);
-static void print_normal(long size, char *filename)
+static void print(long size, char *filename)
{
+ /* TODO - May not want to defer error checking here. */
#ifdef CONFIG_FEATURE_HUMAN_READABLE
- printf("%s\t%s\n", make_human_readable_str(size << 10, 1, disp_hr),
+ bb_printf("%s\t%s\n", make_human_readable_str(size, 512, disp_hr),
filename);
#else
- printf("%ld\t%s\n", size, filename);
+ bb_printf("%ld\t%s\n", size >> disp_k, filename);
#endif
}
-static void print_summary(long size, char *filename)
-{
- if (du_depth == 1) {
- print_normal(size, filename);
- }
-}
-
/* tiny recursive du */
static long du(char *filename)
{
@@ -68,23 +88,43 @@ static long du(char *filename)
long sum;
if ((lstat(filename, &statbuf)) != 0) {
- perror_msg("%s", filename);
+ bb_perror_msg("%s", filename);
+ status = EXIT_FAILURE;
return 0;
}
- if (du_depth == 0)
- dir_dev = statbuf.st_dev;
- else if (one_file_system && dir_dev != statbuf.st_dev)
- return 0;
- du_depth++;
- sum = (statbuf.st_blocks >> 1);
+ if (one_file_system) {
+ if (du_depth == 0) {
+ dir_dev = statbuf.st_dev;
+ } else if (dir_dev != statbuf.st_dev) {
+ return 0;
+ }
+ }
+
+ sum = statbuf.st_blocks;
- /* Don't add in stuff pointed to by symbolic links */
if (S_ISLNK(statbuf.st_mode)) {
- sum = 0L;
- if (du_depth == 1) {
+ if (slink_depth > du_depth) { /* -H or -L */
+ if ((stat(filename, &statbuf)) != 0) {
+ bb_perror_msg("%s", filename);
+ status = EXIT_FAILURE;
+ return 0;
+ }
+ sum = statbuf.st_blocks;
+ if (slink_depth == 1) {
+ slink_depth = INT_MAX; /* Convert -H to -L. */
+ }
}
}
+
+ if (statbuf.st_nlink > count_hardlinks) {
+ /* Add files/directories with links only once */
+ if (is_in_ino_dev_hashtable(&statbuf, NULL)) {
+ return 0;
+ }
+ add_to_ino_dev_hashtable(&statbuf, NULL);
+ }
+
if (S_ISDIR(statbuf.st_mode)) {
DIR *dir;
struct dirent *entry;
@@ -92,8 +132,9 @@ static long du(char *filename)
dir = opendir(filename);
if (!dir) {
- du_depth--;
- return 0;
+ bb_perror_msg("%s", filename);
+ status = EXIT_FAILURE;
+ return sum;
}
newfile = last_char_is(filename, '/');
@@ -103,54 +144,86 @@ static long du(char *filename)
while ((entry = readdir(dir))) {
char *name = entry->d_name;
- if ((strcmp(name, "..") == 0)
- || (strcmp(name, ".") == 0)) {
+ if ((name[0] == '.') && (!name[1] || (name[1] == '.' && !name[2]))) {
continue;
}
newfile = concat_path_file(filename, name);
+ ++du_depth;
sum += du(newfile);
+ --du_depth;
free(newfile);
}
closedir(dir);
+ } else if (du_depth > print_files) {
+ return sum;
+ }
+ if (du_depth <= max_print_depth) {
print(sum, filename);
- } else if (statbuf.st_nlink > 1 && !count_hardlinks) {
- /* Add files with hard links only once */
- if (is_in_ino_dev_hashtable(&statbuf, NULL)) {
- sum = 0L;
- if (du_depth == 1)
- print(sum, filename);
- } else {
- add_to_ino_dev_hashtable(&statbuf, NULL);
- }
}
- du_depth--;
return sum;
}
int du_main(int argc, char **argv)
{
- int status = EXIT_SUCCESS;
- int i;
+ long total;
+ int slink_depth_save;
+ int print_final_total = 0;
int c;
- /* default behaviour */
- print = print_normal;
+#ifdef CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
+ if (getenv("POSIXLY_CORRECT")) { /* TODO - a new libbb function? */
+#ifdef CONFIG_FEATURE_HUMAN_READABLE
+ disp_hr = 512;
+#else
+ disp_k = 0;
+#endif
+ }
+#endif
+
+ /* Note: SUSv3 specifies that -a and -s options can not be used together
+ * in strictly conforming applications. However, it also says that some
+ * du implementations may produce output when -a and -s are used together.
+ * gnu du exits with an error code in this case. We choose to simply
+ * ignore -a. This is consistent with -s being equivalent to -d 0.
+ */
- /* parse argv[] */
- while ((c = getopt(argc, argv, "slx"
+ while ((c = getopt(argc, argv, "aHkLsx" "d:" "lc"
#ifdef CONFIG_FEATURE_HUMAN_READABLE
"hm"
#endif
- "k")) != EOF) {
+ )) > 0) {
switch (c) {
+ case 'a':
+ print_files = INT_MAX;
+ break;
+ case 'H':
+ slink_depth = 1;
+ break;
+ case 'k':
+#ifdef CONFIG_FEATURE_HUMAN_READABLE
+ disp_hr = KILOBYTE;
+#elif !defined CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
+ disp_k = 1;
+#endif
+ break;
+ case 'L':
+ slink_depth = INT_MAX;
+ break;
case 's':
- print = print_summary;
+ max_print_depth = 0;
+ break;
+ case 'x':
+ one_file_system = 1;
+ break;
+
+ case 'd':
+ max_print_depth = bb_xgetularg10_bnd(optarg, 0, INT_MAX);
break;
case 'l':
count_hardlinks = 1;
break;
- case 'x':
- one_file_system = 1;
+ case 'c':
+ print_final_total = 1;
break;
#ifdef CONFIG_FEATURE_HUMAN_READABLE
case 'h':
@@ -160,37 +233,31 @@ int du_main(int argc, char **argv)
disp_hr = MEGABYTE;
break;
#endif
- case 'k':
- break;
default:
- show_usage();
+ bb_show_usage();
}
}
/* go through remaining args (if any) */
+ argv += optind;
if (optind >= argc) {
- if (du(".") == 0)
- status = EXIT_FAILURE;
- } else {
- long sum;
-
- for (i = optind; i < argc; i++) {
- sum = du(argv[i]);
- if (is_directory(argv[i], FALSE, NULL) == FALSE) {
- print_normal(sum, argv[i]);
- }
- reset_ino_dev_hashtable();
+ *--argv = ".";
+ if (slink_depth == 1) {
+ slink_depth = 0;
}
}
- return status;
-}
+ slink_depth_save = slink_depth;
+ total = 0;
+ do {
+ total += du(*argv);
+ slink_depth = slink_depth_save;
+ } while (*++argv);
+ reset_ino_dev_hashtable();
-/* $Id: du.c,v 1.55 2002/08/23 07:28:45 aaronl Exp $ */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
+ if (print_final_total) {
+ print(total, "total");
+ }
+
+ bb_fflush_stdout_and_exit(status);
+}
diff --git a/coreutils/echo.c b/coreutils/echo.c
index 31c031528..b600a1fbd 100644
--- a/coreutils/echo.c
+++ b/coreutils/echo.c
@@ -22,94 +22,107 @@
* Original copyright notice is retained at the end of this file.
*/
+/* BB_AUDIT SUSv3 compliant -- unless configured as fancy echo. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/echo.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Because of behavioral differences, implemented configureable SUSv3
+ * or 'fancy' gnu-ish behaviors. Also, reduced size and fixed bugs.
+ * 1) In handling '\c' escape, the previous version only suppressed the
+ * trailing newline. SUSv3 specifies _no_ output after '\c'.
+ * 2) SUSv3 specifies that octal escapes are of the form \0{#{#{#}}}.
+ * The previous version version did not allow 4-digit octals.
+ */
+
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "busybox.h"
-extern int
-echo_main(int argc, char** argv)
+extern int echo_main(int argc, char** argv)
{
- int nflag = 0;
+#ifndef CONFIG_FEATURE_FANCY_ECHO
+#define eflag '\\'
+ ++argv;
+#else
+ const char *p;
+ int nflag = 1;
int eflag = 0;
- /* Skip argv[0]. */
- argc--;
- argv++;
-
- while (argc > 0 && *argv[0] == '-')
- {
- register char *temp;
- register int ix;
-
- /*
- * If it appears that we are handling options, then make sure
+ while (*++argv && (**argv == '-')) {
+ /* If it appears that we are handling options, then make sure
* that all of the options specified are actually valid.
* Otherwise, the string should just be echoed.
*/
- temp = argv[0] + 1;
-
- for (ix = 0; temp[ix]; ix++)
- {
- if (strrchr("neE", temp[ix]) == 0)
- goto just_echo;
- }
-
- if (!*temp)
+
+ if (!*(p = *argv + 1)) { /* A single '-', so echo it. */
goto just_echo;
+ }
- /*
- * All of the options in temp are valid options to echo.
- * Handle them.
- */
- while (*temp)
- {
- if (*temp == 'n')
- nflag = 1;
- else if (*temp == 'e')
- eflag = 1;
- else if (*temp == 'E')
- eflag = 0;
- else
+ do {
+ if (strrchr("neE", *p) == 0) {
goto just_echo;
+ }
+ } while (*++p);
- temp++;
- }
- argc--;
- argv++;
+ /* All of the options in this arg are valid, so handle them. */
+ p = *argv + 1;
+ do {
+ if (*p == 'n') {
+ nflag = 0;
+ } else if (*p == 'e') {
+ eflag = '\\';
+ } else {
+ eflag = 0;
+ }
+ } while (*++p);
}
just_echo:
- while (argc > 0) {
- const char *arg = argv[0];
+#endif
+ while (*argv) {
register int c;
- while ((c = *arg++)) {
-
- /* Check for escape sequence. */
- if (c == '\\' && eflag && *arg) {
- if (*arg == 'c') {
- /* '\c' means cancel newline. */
- nflag = 1;
- arg++;
- continue;
- } else {
- c = process_escape_sequence(&arg);
+ while ((c = *(*argv)++)) {
+ if (c == eflag) { /* Check for escape seq. */
+ if (**argv == 'c') {
+ /* '\c' means cancel newline and
+ * ignore all subsequent chars. */
+ goto DONE;
+ }
+#ifndef CONFIG_FEATURE_FANCY_ECHO
+ /* SUSv3 specifies that octal escapes must begin with '0'. */
+ if (((unsigned int)(**argv - '1')) >= 7)
+#endif
+ {
+ /* Since SUSv3 mandates a first digit of 0, 4-digit octals
+ * of the form \0### are accepted. */
+ if ((**argv == '0') && (((unsigned int)(argv[0][1] - '0')) < 8)) {
+ (*argv)++;
+ }
+ /* bb_process_escape_sequence can handle nul correctly */
+ c = bb_process_escape_sequence((const char **) argv);
}
}
-
putchar(c);
}
- argc--;
- argv++;
- if (argc > 0)
+
+ if (*++argv) {
putchar(' ');
+ }
}
- if (!nflag)
+
+#ifdef CONFIG_FEATURE_FANCY_ECHO
+ if (nflag) {
putchar('\n');
- fflush(stdout);
+ }
+#else
+ putchar('\n');
+#endif
- return EXIT_SUCCESS;
+DONE:
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
/*-
diff --git a/coreutils/env.c b/coreutils/env.c
index 8bb690b72..db13b3aed 100644
--- a/coreutils/env.c
+++ b/coreutils/env.c
@@ -24,50 +24,66 @@
* Modified for BusyBox by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
*/
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/env.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Fixed bug involving exit return codes if execvp fails. Also added
+ * output error checking.
+ */
+
#include <stdio.h>
#include <string.h>
-#include <getopt.h>
#include <stdlib.h>
+#include <errno.h>
#include <unistd.h>
#include "busybox.h"
extern int env_main(int argc, char** argv)
{
char **ep, *p;
- char *cleanenv[1];
- int ignore_environment = 0;
+ char *cleanenv[1] = { NULL };
int ch;
- while ((ch = getopt(argc, argv, "+iu:")) != -1) {
+ while ((ch = getopt(argc, argv, "iu:")) > 0) {
switch(ch) {
case 'i':
- ignore_environment = 1;
+ environ = cleanenv;
break;
case 'u':
unsetenv(optarg);
break;
default:
- show_usage();
+ bb_show_usage();
}
}
- if (optind != argc && !strcmp(argv[optind], "-")) {
- ignore_environment = 1;
- argv++;
- }
- if (ignore_environment) {
+
+ argv += optind;
+
+ if (*argv && (argv[0][0] == '-') && !argv[0][1]) {
environ = cleanenv;
- cleanenv[0] = NULL;
+ ++argv;
}
- for (argv += optind; *argv && (p = strchr(*argv, '=')); ++argv)
- if (putenv(*argv) < 0)
- perror_msg_and_die("%s", *argv);
+
+ while (*argv && ((p = strchr(*argv, '=')) != NULL)) {
+ if (putenv(*argv) < 0) {
+ bb_perror_msg_and_die("putenv");
+ }
+ ++argv;
+ }
+
if (*argv) {
execvp(*argv, argv);
- perror_msg_and_die("%s", *argv);
+ bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
+ return (errno == ENOENT) ? 127 : 126; /* SUSv3-mandated exit codes. */
}
- for (ep = environ; *ep; ep++)
+
+ for (ep = environ; *ep; ep++) {
puts(*ep);
- return 0;
+ }
+
+ bb_fflush_stdout_and_exit(0);
}
/*
diff --git a/coreutils/expr.c b/coreutils/expr.c
index 55ae3a969..ecba825d5 100644
--- a/coreutils/expr.c
+++ b/coreutils/expr.c
@@ -78,14 +78,14 @@ int expr_main (int argc, char **argv)
VALUE *v;
if (argc == 1) {
- error_msg_and_die("too few arguments");
+ bb_error_msg_and_die("too few arguments");
}
args = argv + 1;
v = eval ();
if (*args)
- error_msg_and_die ("syntax error");
+ bb_error_msg_and_die ("syntax error");
if (v->type == integer)
printf ("%d\n", v->u.i);
@@ -147,7 +147,7 @@ static int null (VALUE *v)
static void tostring (VALUE *v)
{
if (v->type == integer) {
- bb_asprintf (&(v->u.s), "%d", v->u.i);
+ bb_xasprintf (&(v->u.s), "%d", v->u.i);
v->type = string;
}
}
@@ -216,7 +216,7 @@ static \
int name (VALUE *l, VALUE *r) \
{ \
if (!toarith (l) || !toarith (r)) \
- error_msg_and_die ("non-numeric argument"); \
+ bb_error_msg_and_die ("non-numeric argument"); \
return l->u.i op r->u.i; \
}
@@ -224,9 +224,9 @@ int name (VALUE *l, VALUE *r) \
static int name (VALUE *l, VALUE *r) \
{ \
if (!toarith (l) || !toarith (r)) \
- error_msg_and_die ( "non-numeric argument"); \
+ bb_error_msg_and_die ( "non-numeric argument"); \
if (r->u.i == 0) \
- error_msg_and_die ( "division by zero"); \
+ bb_error_msg_and_die ( "division by zero"); \
return l->u.i op r->u.i; \
}
@@ -270,7 +270,7 @@ of a basic regular expression is not portable; it is being ignored",
re_syntax_options = RE_SYNTAX_POSIX_BASIC;
errmsg = re_compile_pattern (pv->u.s, len, &re_buffer);
if (errmsg) {
- error_msg_and_die("%s", errmsg);
+ bb_error_msg_and_die("%s", errmsg);
}
len = re_match (&re_buffer, sv->u.s, strlen (sv->u.s), 0, &re_regs);
@@ -301,19 +301,19 @@ static VALUE *eval7 (void)
VALUE *v;
if (!*args)
- error_msg_and_die ( "syntax error");
+ bb_error_msg_and_die ( "syntax error");
if (nextarg ("(")) {
args++;
v = eval ();
if (!nextarg (")"))
- error_msg_and_die ( "syntax error");
+ bb_error_msg_and_die ( "syntax error");
args++;
return v;
}
if (nextarg (")"))
- error_msg_and_die ( "syntax error");
+ bb_error_msg_and_die ( "syntax error");
return str_value (*args++);
}
@@ -327,7 +327,7 @@ static VALUE *eval6 (void)
if (nextarg ("quote")) {
args++;
if (!*args)
- error_msg_and_die ( "syntax error");
+ bb_error_msg_and_die ( "syntax error");
return str_value (*args++);
}
else if (nextarg ("length")) {
@@ -373,7 +373,7 @@ static VALUE *eval6 (void)
else {
v = xmalloc (sizeof(VALUE));
v->type = string;
- v->u.s = xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
+ v->u.s = bb_xstrndup(l->u.s + i1->u.i - 1, i2->u.i);
}
freev (l);
freev (i1);
diff --git a/coreutils/false.c b/coreutils/false.c
index 96b18498a..c17de7693 100644
--- a/coreutils/false.c
+++ b/coreutils/false.c
@@ -21,7 +21,8 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/false.html */
#include <stdlib.h>
#include "busybox.h"
diff --git a/coreutils/head.c b/coreutils/head.c
index ad21e1b95..dab4de11b 100644
--- a/coreutils/head.c
+++ b/coreutils/head.c
@@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini head implementation for busybox
+ * head implementation for busybox
*
- * Copyright (C) 1999 by Lineo, inc. and John Beppu
- * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,82 +20,119 @@
*
*/
+/* BB_AUDIT SUSv3 compliant */
+/* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/head.html */
+
#include <stdio.h>
-#include <getopt.h>
#include <stdlib.h>
-#include <string.h>
+#include <limits.h>
#include <ctype.h>
+#include <unistd.h>
#include "busybox.h"
-static int head(int len, FILE *fp)
-{
- int i;
- char *input;
+static const char head_opts[] =
+ "n:"
+#ifdef CONFIG_FEATURE_FANCY_HEAD
+ "c:qv"
+#endif
+ ;
- for (i = 0; i < len; i++) {
- if ((input = get_line_from_file(fp)) == NULL)
- break;
- fputs(input, stdout);
- free(input);
- }
- return 0;
-}
+static const char header_fmt_str[] = "\n==> %s <==\n";
-/* BusyBoxed head(1) */
int head_main(int argc, char **argv)
{
+ unsigned long count = 10;
+ unsigned long i;
+#ifdef CONFIG_FEATURE_FANCY_HEAD
+ int count_bytes = 0;
+ int header_threshhold = 1;
+#endif
+
FILE *fp;
- int need_headers, opt, len = 10, status = EXIT_SUCCESS;
+ const char *fmt;
+ char *p;
+ int opt;
+ int c;
+ int retval = EXIT_SUCCESS;
- if (( argc >= 2 ) && ( argv [1][0] == '-' ) && isdigit ( argv [1][1] )) {
- len = atoi ( &argv [1][1] );
- optind = 2;
+ /* Allow legacy syntax of an initial numeric option without -n. */
+ if ((argc > 1) && (argv[1][0] == '-')
+ /* && (isdigit)(argv[1][1]) */
+ && (((unsigned int)(argv[1][1] - '0')) <= 9)
+ ) {
+ --argc;
+ ++argv;
+ p = (*argv) + 1;
+ goto GET_COUNT;
}
- /* parse argv[] */
- while ((opt = getopt(argc, argv, "n:")) > 0) {
- switch (opt) {
- case 'n':
- len = atoi(optarg);
- if (len >= 0)
+ while ((opt = getopt(argc, argv, head_opts)) > 0) {
+ switch(opt) {
+#ifdef CONFIG_FEATURE_FANCY_HEAD
+ case 'q':
+ header_threshhold = INT_MAX;
+ break;
+ case 'v':
+ header_threshhold = -1;
break;
- /* fallthrough */
- default:
- show_usage();
+ case 'c':
+ count_bytes = 1;
+ /* fall through */
+#endif
+ case 'n':
+ p = optarg;
+ GET_COUNT:
+ count = bb_xgetularg10(p);
+ break;
+ default:
+ bb_show_usage();
}
}
- /* get rest of argv[] or stdin if nothing's left */
- if (argv[optind] == NULL) {
- head(len, stdin);
- return status;
- }
+ argv += optind;
+ if (!*argv) {
+ *--argv = "-";
+ }
- need_headers = optind != (argc - 1);
- while (argv[optind]) {
- if (strcmp(argv[optind], "-") == 0) {
- fp = stdin;
- argv[optind] = "standard input";
- } else {
- if ((fp = wfopen(argv[optind], "r")) == NULL)
- status = EXIT_FAILURE;
- }
- if (fp) {
- if (need_headers) {
- printf("==> %s <==\n", argv[optind]);
+ fmt = header_fmt_str + 1;
+#ifdef CONFIG_FEATURE_FANCY_HEAD
+ if (argc - optind <= header_threshhold) {
+ header_threshhold = 0;
+ }
+#else
+ if (argc <= optind + 1) {
+ fmt += 11;
+ }
+ /* Now define some things here to avoid #ifdefs in the code below.
+ * These should optimize out of the if conditions below. */
+#define header_threshhold 1
+#define count_bytes 0
+#endif
+
+ do {
+ if ((fp = bb_wfopen_input(*argv)) != NULL) {
+ if (fp == stdin) {
+ *argv = (char *) bb_msg_standard_input;
}
- head(len, fp);
- if (ferror(fp)) {
- perror_msg("%s", argv[optind]);
- status = EXIT_FAILURE;
+ if (header_threshhold) {
+ bb_printf(fmt, *argv);
}
- if (optind < argc - 1)
- putchar('\n');
- if (fp != stdin)
- fclose(fp);
+ i = count;
+ while (i && ((c = getc(fp)) != EOF)) {
+ if (count_bytes || (c == '\n')) {
+ --i;
+ }
+ putchar(c);
+ }
+ if (bb_fclose_nonstdin(fp)) {
+ bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
+ retval = EXIT_FAILURE;
+ }
+ bb_xferror_stdout();
}
- optind++;
- }
+ fmt = header_fmt_str;
+ } while (*++argv);
- return status;
+ bb_fflush_stdout_and_exit(retval);
}
diff --git a/coreutils/hostid.c b/coreutils/hostid.c
index 68a2cc659..917dc223e 100644
--- a/coreutils/hostid.c
+++ b/coreutils/hostid.c
@@ -20,13 +20,19 @@
*
*/
-#include <stdio.h>
+/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
+
#include <stdlib.h>
#include <unistd.h>
#include "busybox.h"
extern int hostid_main(int argc, char **argv)
{
- printf("%lx\n", gethostid());
- return EXIT_SUCCESS;
+ if (argc > 1) {
+ bb_show_usage();
+ }
+
+ bb_printf("%lx\n", gethostid());
+
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/id.c b/coreutils/id.c
index c7f61532d..9b2d60dc7 100644
--- a/coreutils/id.c
+++ b/coreutils/id.c
@@ -20,6 +20,8 @@
*
*/
+/* BB_AUDIT SUSv3 _NOT_ compliant -- option -G is not currently supported. */
+
#include "busybox.h"
#include <stdio.h>
#include <unistd.h>
@@ -27,70 +29,58 @@
#include <string.h>
#include <sys/types.h>
+#define NO_GROUP 1
+#define NO_USER 2
+#define PRINT_REAL 4
+#define NAME_NOT_NUMBER 8
+
extern int id_main(int argc, char **argv)
{
- int no_user = 0, no_group = 0, print_real = 0;
- int name_not_number = 0;
char user[9], group[9];
- long gid;
long pwnam, grnam;
- int opt;
+ int uid, gid;
+ int flags;
- gid = 0;
+ flags = bb_getopt_ulflags(argc, argv, "ugrn");
- while ((opt = getopt(argc, argv, "ugrn")) > 0) {
- switch (opt) {
- case 'u':
- no_group++;
- break;
- case 'g':
- no_user++;
- break;
- case 'r':
- print_real++;
- break;
- case 'n':
- name_not_number++;
- break;
- default:
- show_usage();
- }
+ if (((flags & (NO_USER | NO_GROUP)) == (NO_USER | NO_GROUP))
+ || (argc > optind + 1)
+ ) {
+ bb_show_usage();
}
- if (no_user && no_group) show_usage();
-
if (argv[optind] == NULL) {
- if (print_real) {
- my_getpwuid(user, getuid());
- my_getgrgid(group, getgid());
+ if (flags & PRINT_REAL) {
+ uid = getuid();
+ gid = getgid();
} else {
- my_getpwuid(user, geteuid());
- my_getgrgid(group, getegid());
+ uid = geteuid();
+ gid = getegid();
}
+ my_getpwuid(user, uid);
} else {
safe_strncpy(user, argv[optind], sizeof(user));
gid = my_getpwnamegid(user);
- my_getgrgid(group, gid);
}
+ my_getgrgid(group, gid);
pwnam=my_getpwnam(user);
grnam=my_getgrnam(group);
- if (no_group) {
- if(name_not_number)
- puts(user);
- else
- printf("%ld\n", pwnam);
- } else if (no_user) {
- if(name_not_number)
- puts(group);
- else
+ if (flags & (NO_GROUP | NO_USER)) {
+ char *s = group;
+ if (flags & NO_GROUP) {
+ s = user;
+ grnam = pwnam;
+ }
+ if (flags & NAME_NOT_NUMBER) {
+ puts(s);
+ } else {
printf("%ld\n", grnam);
+ }
} else {
printf("uid=%ld(%s) gid=%ld(%s)\n", pwnam, user, grnam, group);
}
- return(0);
-}
-
-/* END CODE */
+ bb_fflush_stdout_and_exit(0);
+}
diff --git a/coreutils/length.c b/coreutils/length.c
index 73becd28a..bce43ab3f 100644
--- a/coreutils/length.c
+++ b/coreutils/length.c
@@ -1,4 +1,7 @@
/* vi: set sw=4 ts=4: */
+
+/* BB_AUDIT SUSv3 N/A -- Apparently a busybox (obsolete?) extension. */
+
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
@@ -6,8 +9,11 @@
extern int length_main(int argc, char **argv)
{
- if (argc != 2 || **(argv + 1) == '-')
- show_usage();
- printf("%lu\n", (long)strlen(argv[1]));
- return EXIT_SUCCESS;
+ if ((argc != 2) || (**(++argv) == '-')) {
+ bb_show_usage();
+ }
+
+ bb_printf("%lu\n", (unsigned long)strlen(*argv));
+
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/libcoreutils/Makefile b/coreutils/libcoreutils/Makefile
new file mode 100644
index 000000000..59ec24ed9
--- /dev/null
+++ b/coreutils/libcoreutils/Makefile
@@ -0,0 +1,30 @@
+# Makefile for busybox
+#
+# Copyright (C) 1999-2002 Erik Andersen <andersee@debian.org>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+
+TOPDIR:= ../../
+LIBCOREUTILS_DIR:=./
+include $(TOPDIR).config
+include $(TOPDIR)Rules.mak
+include Makefile.in
+all: $(libraries-y)
+-include $(TOPDIR).depend
+
+clean:
+ rm -f *.o *.a $(AR_TARGET)
+
diff --git a/coreutils/libcoreutils/Makefile.in b/coreutils/libcoreutils/Makefile.in
new file mode 100644
index 000000000..47391dd49
--- /dev/null
+++ b/coreutils/libcoreutils/Makefile.in
@@ -0,0 +1,32 @@
+# Makefile for busybox
+#
+# Copyright (C) 1999-2002 Erik Andersen <andersee@debian.org>
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+
+LIBCOREUTILS_AR:=libcoreutils.a
+ifndef $(LIBCOREUTILS_DIR)
+LIBCOREUTILS_DIR:=$(TOPDIR)coreutils/libcoreutils/
+endif
+
+LIBCOREUTILS_SRC:= cp_mv_stat.c getopt_mk_fifo_nod.c xgetoptfile_sort_uniq.c
+
+LIBCOREUTILS_OBJS=$(patsubst %.c,$(LIBCOREUTILS_DIR)%.o, $(LIBCOREUTILS_SRC))
+
+libraries-y+=$(LIBCOREUTILS_DIR)$(LIBCOREUTILS_AR)
+
+$(LIBCOREUTILS_DIR)$(LIBCOREUTILS_AR): $(LIBCOREUTILS_OBJS)
+ $(AR) -ro $@ $(LIBCOREUTILS_OBJS)
diff --git a/coreutils/libcoreutils/coreutils.h b/coreutils/libcoreutils/coreutils.h
new file mode 100644
index 000000000..eabca8204
--- /dev/null
+++ b/coreutils/libcoreutils/coreutils.h
@@ -0,0 +1,12 @@
+#ifndef COREUTILS_H
+#define COREUTILS_H 1
+
+typedef int (*stat_func)(const char *fn, struct stat *ps);
+
+extern int cp_mv_stat2(const char *fn, struct stat *fn_stat, stat_func sf);
+extern int cp_mv_stat(const char *fn, struct stat *fn_stat);
+
+extern mode_t getopt_mk_fifo_nod(int argc, char **argv);
+extern FILE *xgetoptfile_sort_uniq(char **argv, const char *mode);
+
+#endif
diff --git a/coreutils/libcoreutils/cp_mv_stat.c b/coreutils/libcoreutils/cp_mv_stat.c
new file mode 100644
index 000000000..5a70b0221
--- /dev/null
+++ b/coreutils/libcoreutils/cp_mv_stat.c
@@ -0,0 +1,45 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * coreutils utility routine
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+#include <errno.h>
+#include <sys/stat.h>
+#include "libbb.h"
+#include "coreutils.h"
+
+extern int cp_mv_stat2(const char *fn, struct stat *fn_stat, stat_func sf)
+{
+ if (sf(fn, fn_stat) < 0) {
+ if (errno != ENOENT) {
+ bb_perror_msg("unable to stat `%s'", fn);
+ return -1;
+ }
+ return 0;
+ } else if (S_ISDIR(fn_stat->st_mode)) {
+ return 3;
+ }
+ return 1;
+}
+
+extern int cp_mv_stat(const char *fn, struct stat *fn_stat)
+{
+ return cp_mv_stat2(fn, fn_stat, stat);
+}
diff --git a/coreutils/libcoreutils/getopt_mk_fifo_nod.c b/coreutils/libcoreutils/getopt_mk_fifo_nod.c
new file mode 100644
index 000000000..0872bdcf0
--- /dev/null
+++ b/coreutils/libcoreutils/getopt_mk_fifo_nod.c
@@ -0,0 +1,45 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * coreutils utility routine
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include "libbb.h"
+#include "coreutils.h"
+
+extern mode_t getopt_mk_fifo_nod(int argc, char **argv)
+{
+ mode_t mode = 0666;
+ int opt;
+
+ while ((opt = getopt(argc, argv, "m:")) > 0) {
+ if (opt == 'm') {
+ mode = 0666;
+ if (bb_parse_mode(optarg, &mode)) {
+ umask(0);
+ continue;
+ }
+ }
+ bb_show_usage();
+ }
+ return mode;
+}
diff --git a/coreutils/libcoreutils/xgetoptfile_sort_uniq.c b/coreutils/libcoreutils/xgetoptfile_sort_uniq.c
new file mode 100644
index 000000000..a63daf97b
--- /dev/null
+++ b/coreutils/libcoreutils/xgetoptfile_sort_uniq.c
@@ -0,0 +1,38 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * coreutils utility routine
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+#include <stdio.h>
+#include <unistd.h>
+#include "libbb.h"
+#include "coreutils.h"
+
+extern FILE *xgetoptfile_sort_uniq(char **argv, const char *mode)
+{
+ const char *n;
+
+ if ((n = *argv) != NULL) {
+ if ((*n != '-') || n[1]) {
+ return bb_xfopen(n, mode);
+ }
+ }
+ return (*mode == 'r') ? stdin : stdout;
+}
diff --git a/coreutils/ln.c b/coreutils/ln.c
index 427ffcc6e..2edece104 100644
--- a/coreutils/ln.c
+++ b/coreutils/ln.c
@@ -21,113 +21,86 @@
*
*/
-#include <stdio.h>
-#include <dirent.h>
-#include <string.h>
+/* BB_AUDIT SUSv3 compliant */
+/* BB_AUDIT GNU options missing: -b, -d, -F, -i, -S, and -v. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/ln.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Fixed bug involving -n option. Essentially, -n was always in effect.
+ */
+
#include <stdlib.h>
-#include <errno.h>
#include <unistd.h>
#include "busybox.h"
+#define LN_SYMLINK 1
+#define LN_FORCE 2
+#define LN_NODEREFERENCE 4
-static const int LN_SYMLINK = 1;
-static const int LN_FORCE = 2;
-static const int LN_NODEREFERENCE = 4;
-
-/*
- * linkDestName is where the link points to,
- * linkSrcName is the name of the link to be created.
- */
-static int fs_link(const char *link_destname, const char *link_srcname,
- const int flag)
+extern int ln_main(int argc, char **argv)
{
- int status;
- int src_is_dir;
- char *src_name = 0;
+ int status = EXIT_SUCCESS;
+ int flag;
+ char *last;
+ char *src_name;
const char *src;
+ int (*link_func)(const char *, const char *);
- if (link_destname==NULL)
- return(FALSE);
-
- if (link_srcname==NULL)
- src = link_destname;
- else
- src = link_srcname;
-
- if (flag&LN_NODEREFERENCE)
- src_is_dir = is_directory(src, TRUE, NULL);
- else
- src_is_dir = is_directory(src, FALSE, NULL);
-
- if ((src_is_dir==TRUE)&&((flag&LN_NODEREFERENCE)==0)) {
- char* srcdir_name;
-
- srcdir_name = xstrdup(link_destname);
- src_name = concat_path_file(src, get_last_path_component(srcdir_name));
- src = src_name;
- free(srcdir_name);
+ flag = bb_getopt_ulflags(argc, argv, "sfn");
+
+ if (argc == optind) {
+ bb_show_usage();
}
-
- if (flag&LN_FORCE)
- unlink(src);
-
- if (flag&LN_SYMLINK)
- status = symlink(link_destname, src);
- else
- status = link(link_destname, src);
-
- if (status != 0) {
- perror_msg(src);
- status = FALSE;
- } else {
- status = TRUE;
+
+ last = argv[argc - 1];
+ argv += optind;
+
+ if (argc == optind + 1) {
+ *--argv = last;
+ last = bb_get_last_path_component(bb_xstrdup(last));
}
- free(src_name);
- return status;
-}
-extern int ln_main(int argc, char **argv)
-{
- int status = EXIT_SUCCESS;
- int flag = 0;
- int opt;
-
- /* Parse any options */
- while ((opt=getopt(argc, argv, "sfn")) != -1) {
- switch(opt) {
- case 's':
- flag |= LN_SYMLINK;
- break;
- case 'f':
- flag |= LN_FORCE;
- break;
- case 'n':
- flag |= LN_NODEREFERENCE;
- break;
- default:
- show_usage();
+ do {
+ src_name = 0;
+ src = last;
+
+ if (is_directory(src,
+ (flag & LN_NODEREFERENCE) ^ LN_NODEREFERENCE,
+ NULL)) {
+ src_name = bb_xstrdup(*argv);
+ src = concat_path_file(src, bb_get_last_path_component(src_name));
+ free(src_name);
+ src_name = (char *)src;
}
- }
- if (optind > (argc-1)) {
- show_usage();
- }
- if (optind == (argc-1)) {
- if (fs_link(argv[optind],
- get_last_path_component(argv[optind]), flag)==FALSE)
- status = EXIT_FAILURE;
- }
- while(optind<(argc-1)) {
- if (fs_link(argv[optind], argv[argc-1], flag)==FALSE)
- status = EXIT_FAILURE;
- optind++;
- }
+
+ if (flag & LN_FORCE) {
+ unlink(src);
+ }
+
+ link_func = link;
+ if (flag & LN_SYMLINK) {
+ link_func = symlink;
+ }
+
+ if (link_func(*argv, src) != 0) {
+ bb_perror_msg(src);
+ status = EXIT_FAILURE;;
+ }
+
+ free(src_name);
+
+ } while ((++argv)[1]);
+
return status;
}
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
+
+
+
+
+
+
+
+
+
diff --git a/coreutils/logname.c b/coreutils/logname.c
index 3e10fba6f..9cedff027 100644
--- a/coreutils/logname.c
+++ b/coreutils/logname.c
@@ -20,6 +20,19 @@
*
*/
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/logname.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * SUSv3 specifies the string used is that returned from getlogin().
+ * The previous implementation used getpwuid() for geteuid(), which
+ * is _not_ the same. Erik apparently made this change almost 3 years
+ * ago to avoid failing when no utmp was available. However, the
+ * correct course of action wrt SUSv3 for a failing getlogin() is
+ * a dianostic message and an error return.
+ */
+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
@@ -27,14 +40,16 @@
extern int logname_main(int argc, char **argv)
{
- char user[9];
+ const char *p;
- if (argc > 1)
- show_usage();
+ if (argc > 1) {
+ bb_show_usage();
+ }
- if (my_getpwuid(user, geteuid())) {
- puts(user);
- return EXIT_SUCCESS;
+ if ((p = getlogin()) != NULL) {
+ puts(p);
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
- error_msg_and_die("no login name");
+
+ bb_perror_msg_and_die("getlogin");
}
diff --git a/coreutils/ls.c b/coreutils/ls.c
index 64ec0fee6..4a4956611 100644
--- a/coreutils/ls.c
+++ b/coreutils/ls.c
@@ -73,58 +73,76 @@ enum {
#endif
/* what is the overall style of the listing */
-enum {
- STYLE_AUTO = 0,
- STYLE_LONG = 1, /* one record per line, extended info */
- STYLE_SINGLE = 2, /* one record per line */
- STYLE_COLUMNS = 3 /* fill columns */
-};
+#define STYLE_AUTO (0)
+#define STYLE_COLUMNS (1U<<21) /* fill columns */
+#define STYLE_LONG (2U<<21) /* one record per line, extended info */
+#define STYLE_SINGLE (3U<<21) /* one record per line */
+
+#define STYLE_MASK STYLE_SINGLE
+#define STYLE_ONE_RECORD_FLAG STYLE_LONG
/* 51306 lrwxrwxrwx 1 root root 2 May 11 01:43 /bin/view -> vi* */
/* what file information will be listed */
-#define LIST_INO (1<<0)
-#define LIST_BLOCKS (1<<1)
-#define LIST_MODEBITS (1<<2)
-#define LIST_NLINKS (1<<3)
-#define LIST_ID_NAME (1<<4)
-#define LIST_ID_NUMERIC (1<<5)
-#define LIST_SIZE (1<<6)
-#define LIST_DEV (1<<7)
-#define LIST_DATE_TIME (1<<8)
-#define LIST_FULLTIME (1<<9)
-#define LIST_FILENAME (1<<10)
-#define LIST_SYMLINK (1<<11)
-#define LIST_FILETYPE (1<<12)
-#define LIST_EXEC (1<<13)
+#define LIST_INO (1U<<0)
+#define LIST_BLOCKS (1U<<1)
+#define LIST_MODEBITS (1U<<2)
+#define LIST_NLINKS (1U<<3)
+#define LIST_ID_NAME (1U<<4)
+#define LIST_ID_NUMERIC (1U<<5)
+#define LIST_SIZE (1U<<6)
+#define LIST_DEV (1U<<7)
+#define LIST_DATE_TIME (1U<<8)
+#define LIST_FULLTIME (1U<<9)
+#define LIST_FILENAME (1U<<10)
+#define LIST_SYMLINK (1U<<11)
+#define LIST_FILETYPE (1U<<12)
+#define LIST_EXEC (1U<<13)
+
+#define LIST_MASK ((LIST_EXEC << 1) - 1)
/* what files will be displayed */
-#define DISP_NORMAL (0) /* show normal filenames */
-#define DISP_DIRNAME (1<<0) /* 2 or more items? label directories */
-#define DISP_HIDDEN (1<<1) /* show filenames starting with . */
-#define DISP_DOT (1<<2) /* show . and .. */
-#define DISP_NOLIST (1<<3) /* show directory as itself, not contents */
-#define DISP_RECURSIVE (1<<4) /* show directory and everything below it */
-#define DISP_ROWS (1<<5) /* print across rows */
+/* TODO -- We may be able to make DISP_NORMAL 0 to save a bit slot. */
+#define DISP_NORMAL (1U<<14) /* show normal filenames */
+#define DISP_DIRNAME (1U<<15) /* 2 or more items? label directories */
+#define DISP_HIDDEN (1U<<16) /* show filenames starting with . */
+#define DISP_DOT (1U<<17) /* show . and .. */
+#define DISP_NOLIST (1U<<18) /* show directory as itself, not contents */
+#define DISP_RECURSIVE (1U<<19) /* show directory and everything below it */
+#define DISP_ROWS (1U<<20) /* print across rows */
+
+#define DISP_MASK (((DISP_ROWS << 1) - 1) & ~(DISP_NORMAL - 1))
#ifdef CONFIG_FEATURE_LS_SORTFILES
/* how will the files be sorted */
-static const int SORT_FORWARD = 0; /* sort in reverse order */
-static const int SORT_REVERSE = 1; /* sort in reverse order */
-static const int SORT_NAME = 2; /* sort by file name */
-static const int SORT_SIZE = 3; /* sort by file size */
-static const int SORT_ATIME = 4; /* sort by last access time */
-static const int SORT_CTIME = 5; /* sort by last change time */
-static const int SORT_MTIME = 6; /* sort by last modification time */
-static const int SORT_VERSION = 7; /* sort by version */
-static const int SORT_EXT = 8; /* sort by file name extension */
-static const int SORT_DIR = 9; /* sort by file or directory */
+#define SORT_ORDER_FORWARD 0 /* sort in reverse order */
+#define SORT_ORDER_REVERSE (1U<<27) /* sort in reverse order */
+
+#define SORT_NAME 0 /* sort by file name */
+#define SORT_SIZE (1U<<28) /* sort by file size */
+#define SORT_ATIME (2U<<28) /* sort by last access time */
+#define SORT_CTIME (3U<<28) /* sort by last change time */
+#define SORT_MTIME (4U<<28) /* sort by last modification time */
+#define SORT_VERSION (5U<<28) /* sort by version */
+#define SORT_EXT (6U<<28) /* sort by file name extension */
+#define SORT_DIR (7U<<28) /* sort by file or directory */
+
+#define SORT_MASK (7U<<28)
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
/* which of the three times will be used */
-static const int TIME_MOD = 0;
-static const int TIME_CHANGE = 1;
-static const int TIME_ACCESS = 2;
+#define TIME_MOD 0
+#define TIME_CHANGE (1U<<23)
+#define TIME_ACCESS (1U<<24)
+
+#define TIME_MASK (3U<<23)
+#endif
+
+#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
+#define FOLLOW_LINKS (1U<<25)
+#endif
+#ifdef CONFIG_FEATURE_HUMAN_READABLE
+#define LS_DISP_HR (1U<<26)
#endif
#define LIST_SHORT (LIST_FILENAME)
@@ -133,9 +151,9 @@ static const int TIME_ACCESS = 2;
LIST_DATE_TIME | LIST_FILENAME | LIST_SYMLINK)
#define LIST_ILONG (LIST_INO | LIST_LONG)
-static const int SPLIT_DIR = 0;
-static const int SPLIT_FILE = 1;
-static const int SPLIT_SUBDIR = 2;
+#define SPLIT_DIR 1
+#define SPLIT_FILE 0
+#define SPLIT_SUBDIR 2
#define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
#define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
@@ -169,20 +187,7 @@ static struct dnode **list_dir(const char *);
static struct dnode **dnalloc(int);
static int list_single(struct dnode *);
-static unsigned int disp_opts;
-static unsigned int style_fmt;
-static unsigned int list_fmt;
-
-#ifdef CONFIG_FEATURE_LS_SORTFILES
-static unsigned int sort_opts;
-static unsigned int sort_order;
-#endif
-#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
-static unsigned int time_fmt;
-#endif
-#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
-static unsigned int follow_links = FALSE;
-#endif
+static unsigned int all_fmt;
#ifdef CONFIG_FEATURE_AUTOWIDTH
static unsigned short terminal_width = TERMINAL_WIDTH;
@@ -194,26 +199,22 @@ static unsigned short tabstops = COLUMN_GAP;
static int status = EXIT_SUCCESS;
-#ifdef CONFIG_FEATURE_HUMAN_READABLE
-static unsigned long ls_disp_hr = 0;
-#endif
-
static struct dnode *my_stat(char *fullname, char *name)
{
struct stat dstat;
struct dnode *cur;
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
- if (follow_links) {
+ if (all_fmt & FOLLOW_LINKS) {
if (stat(fullname, &dstat)) {
- perror_msg("%s", fullname);
+ bb_perror_msg("%s", fullname);
status = EXIT_FAILURE;
return 0;
}
} else
#endif
if (lstat(fullname, &dstat)) {
- perror_msg("%s", fullname);
+ bb_perror_msg("%s", fullname);
status = EXIT_FAILURE;
return 0;
}
@@ -253,9 +254,9 @@ static char bgcolor(mode_t mode)
#if defined(CONFIG_FEATURE_LS_FILETYPES) || defined(CONFIG_FEATURE_LS_COLOR)
static char append_char(mode_t mode)
{
- if (!(list_fmt & LIST_FILETYPE))
+ if (!(all_fmt & LIST_FILETYPE))
return '\0';
- if ((list_fmt & LIST_EXEC) && S_ISREG(mode)
+ if ((all_fmt & LIST_EXEC) && S_ISREG(mode)
&& (mode & (S_IXUSR | S_IXGRP | S_IXOTH)))
return '*';
return APPCHAR(mode);
@@ -263,13 +264,11 @@ static char append_char(mode_t mode)
#endif
/*----------------------------------------------------------------------*/
-static int is_subdir(struct dnode *dn)
-{
- return (S_ISDIR(dn->dstat.st_mode) && strcmp(dn->name, ".") != 0 &&
- strcmp(dn->name, "..") != 0);
-}
-static int countdirs(struct dnode **dn, int nfiles)
+#define countdirs(A,B) count_dirs((A), (B), 1)
+#define countsubdirs(A,B) count_dirs((A), (B), 0)
+
+static int count_dirs(struct dnode **dn, int nfiles, int notsubdirs)
{
int i, dirs;
@@ -277,25 +276,17 @@ static int countdirs(struct dnode **dn, int nfiles)
return (0);
dirs = 0;
for (i = 0; i < nfiles; i++) {
- if (S_ISDIR(dn[i]->dstat.st_mode))
+ if (S_ISDIR(dn[i]->dstat.st_mode)
+ && (notsubdirs
+ || ((dn[i]->name[0] != '.')
+ || (dn[i]->name[1]
+ && ((dn[i]->name[1] != '.')
+ || dn[i]->name[2])))))
dirs++;
}
return (dirs);
}
-static int countsubdirs(struct dnode **dn, int nfiles)
-{
- int i, subdirs;
-
- if (dn == NULL || nfiles < 1)
- return 0;
- subdirs = 0;
- for (i = 0; i < nfiles; i++)
- if (is_subdir(dn[i]))
- subdirs++;
- return subdirs;
-}
-
static int countfiles(struct dnode **dnp)
{
int nfiles;
@@ -364,18 +355,18 @@ static struct dnode **splitdnarray(struct dnode **dn, int nfiles, int which)
/* copy the entrys into the file or dir array */
for (d = i = 0; i < nfiles; i++) {
- if (which == SPLIT_DIR) {
- if (S_ISDIR(dn[i]->dstat.st_mode)) {
- dnp[d++] = dn[i];
- } /* else skip the file */
- } else if (which == SPLIT_SUBDIR) {
- if (is_subdir(dn[i])) {
- dnp[d++] = dn[i];
- } /* else skip the file or dir */
- } else {
- if (!(S_ISDIR(dn[i]->dstat.st_mode))) {
- dnp[d++] = dn[i];
- } /* else skip the dir */
+ if (S_ISDIR(dn[i]->dstat.st_mode)) {
+ if (which & (SPLIT_DIR|SPLIT_SUBDIR)) {
+ if ((which & SPLIT_DIR)
+ || ((dn[i]->name[0] != '.')
+ || (dn[i]->name[1]
+ && ((dn[i]->name[1] != '.')
+ || dn[i]->name[2])))) {
+ dnp[d++] = dn[i];
+ }
+ }
+ } else if (!(which & (SPLIT_DIR|SPLIT_SUBDIR))) {
+ dnp[d++] = dn[i];
}
}
return (dnp);
@@ -385,29 +376,24 @@ static struct dnode **splitdnarray(struct dnode **dn, int nfiles, int which)
#ifdef CONFIG_FEATURE_LS_SORTFILES
static int sortcmp(struct dnode *d1, struct dnode *d2)
{
- int cmp, dif;
+ unsigned int sort_opts = all_fmt & SORT_MASK;
+ int dif;
- cmp = 0;
+ dif = 0; /* assume SORT_NAME */
if (sort_opts == SORT_SIZE) {
- dif = (int) (d1->dstat.st_size - d2->dstat.st_size);
+ dif = (int) (d2->dstat.st_size - d1->dstat.st_size);
} else if (sort_opts == SORT_ATIME) {
- dif = (int) (d1->dstat.st_atime - d2->dstat.st_atime);
+ dif = (int) (d2->dstat.st_atime - d1->dstat.st_atime);
} else if (sort_opts == SORT_CTIME) {
- dif = (int) (d1->dstat.st_ctime - d2->dstat.st_ctime);
+ dif = (int) (d2->dstat.st_ctime - d1->dstat.st_ctime);
} else if (sort_opts == SORT_MTIME) {
- dif = (int) (d1->dstat.st_mtime - d2->dstat.st_mtime);
+ dif = (int) (d2->dstat.st_mtime - d1->dstat.st_mtime);
} else if (sort_opts == SORT_DIR) {
- dif = S_ISDIR(d1->dstat.st_mode) - S_ISDIR(d2->dstat.st_mode);
+ dif = S_ISDIR(d2->dstat.st_mode) - S_ISDIR(d1->dstat.st_mode);
/* } else if (sort_opts == SORT_VERSION) { */
/* } else if (sort_opts == SORT_EXT) { */
- } else { /* assume SORT_NAME */
- dif = 0;
}
- if (dif > 0)
- cmp = -1;
- if (dif < 0)
- cmp = 1;
if (dif == 0) {
/* sort by name- may be a tie_breaker for time or size cmp */
#ifdef CONFIG_LOCALE_SUPPORT
@@ -415,16 +401,12 @@ static int sortcmp(struct dnode *d1, struct dnode *d2)
#else
dif = strcmp(d1->name, d2->name);
#endif
- if (dif > 0)
- cmp = 1;
- if (dif < 0)
- cmp = -1;
}
- if (sort_order == SORT_REVERSE) {
- cmp = -1 * cmp;
+ if (all_fmt & SORT_ORDER_REVERSE) {
+ dif = -dif;
}
- return (cmp);
+ return (dif);
}
/*----------------------------------------------------------------------*/
@@ -463,20 +445,17 @@ static void showfiles(struct dnode **dn, int nfiles)
if (dn == NULL || nfiles < 1)
return;
- switch (style_fmt) {
- case STYLE_LONG: /* one record per line, extended info */
- case STYLE_SINGLE: /* one record per line */
+ if (all_fmt & STYLE_ONE_RECORD_FLAG) {
ncols = 1;
- break;
- default:
- /* find the longest file name- use that as the column width */
- for (i = 0; i < nfiles; i++) {
+ } else {
+ /* find the longest file name- use that as the column width */
+ for (i = 0; i < nfiles; i++) {
int len = strlen(dn[i]->name) +
- ((list_fmt & LIST_INO) ? 8 : 0) +
- ((list_fmt & LIST_BLOCKS) ? 5 : 0);
- if (column_width < len)
- column_width = len;
- }
+ ((all_fmt & LIST_INO) ? 8 : 0) +
+ ((all_fmt & LIST_BLOCKS) ? 5 : 0);
+ if (column_width < len)
+ column_width = len;
+ }
column_width += tabstops;
ncols = (int) (terminal_width / column_width);
}
@@ -494,7 +473,7 @@ static void showfiles(struct dnode **dn, int nfiles)
for (nc = 0; nc < ncols; nc++) {
/* reach into the array based on the column and row */
i = (nc * nrows) + row; /* assume display by column */
- if (disp_opts & DISP_ROWS)
+ if (all_fmt & DISP_ROWS)
i = (row * ncols) + nc; /* display across row */
if (i < nfiles) {
if (column > 0) {
@@ -528,7 +507,7 @@ static void showdirs(struct dnode **dn, int ndirs)
return;
for (i = 0; i < ndirs; i++) {
- if (disp_opts & (DISP_DIRNAME | DISP_RECURSIVE)) {
+ if (all_fmt & (DISP_DIRNAME | DISP_RECURSIVE)) {
printf("\n%s:\n", dn[i]->fullname);
}
subdnp = list_dir(dn[i]->fullname);
@@ -540,7 +519,7 @@ static void showdirs(struct dnode **dn, int ndirs)
#endif
showfiles(subdnp, nfiles);
#ifdef CONFIG_FEATURE_LS_RECURSIVE
- if (disp_opts & DISP_RECURSIVE) {
+ if (all_fmt & DISP_RECURSIVE) {
/* recursive- list the sub-dirs */
dnd = splitdnarray(subdnp, nfiles, SPLIT_SUBDIR);
dndirs = countsubdirs(subdnp, nfiles);
@@ -573,7 +552,7 @@ static struct dnode **list_dir(const char *path)
nfiles = 0;
dir = opendir(path);
if (dir == NULL) {
- perror_msg("%s", path);
+ bb_perror_msg("%s", path);
status = EXIT_FAILURE;
return (NULL); /* could not open the dir */
}
@@ -585,9 +564,9 @@ static struct dnode **list_dir(const char *path)
if ((entry->d_name[1] == 0 || (
entry->d_name[1] == '.'
&& entry->d_name[2] == 0))
- && !(disp_opts & DISP_DOT))
+ && !(all_fmt & DISP_DOT))
continue;
- if (!(disp_opts & DISP_HIDDEN))
+ if (!(all_fmt & DISP_HIDDEN))
continue;
}
fullname = concat_path_file(path, entry->d_name);
@@ -636,9 +615,9 @@ static int list_single(struct dnode *dn)
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
ttime = dn->dstat.st_mtime; /* the default time */
- if (time_fmt & TIME_ACCESS)
+ if (all_fmt & TIME_ACCESS)
ttime = dn->dstat.st_atime;
- if (time_fmt & TIME_CHANGE)
+ if (all_fmt & TIME_CHANGE)
ttime = dn->dstat.st_ctime;
filetime = ctime(&ttime);
#endif
@@ -647,7 +626,7 @@ static int list_single(struct dnode *dn)
#endif
for (i = 0; i <= 31; i++) {
- switch (list_fmt & (1 << i)) {
+ switch (all_fmt & (1 << i)) {
case LIST_INO:
column += printf("%7ld ", (long int) dn->dstat.st_ino);
break;
@@ -659,7 +638,7 @@ static int list_single(struct dnode *dn)
#endif
break;
case LIST_MODEBITS:
- column += printf("%-10s ", (char *) mode_string(dn->dstat.st_mode));
+ column += printf("%-10s ", (char *) bb_mode_string(dn->dstat.st_mode));
break;
case LIST_NLINKS:
column += printf("%4ld ", (long) dn->dstat.st_nlink);
@@ -683,7 +662,7 @@ static int list_single(struct dnode *dn)
(int) MINOR(dn->dstat.st_rdev));
} else {
#ifdef CONFIG_FEATURE_HUMAN_READABLE
- if (ls_disp_hr == TRUE) {
+ if (all_fmt & LS_DISP_HR) {
column += printf("%9s ",
make_human_readable_str(dn->dstat.st_size, 1, 0));
} else
@@ -700,7 +679,7 @@ static int list_single(struct dnode *dn)
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
case LIST_FULLTIME:
case LIST_DATE_TIME:
- if (list_fmt & LIST_FULLTIME) {
+ if (all_fmt & LIST_FULLTIME) {
printf("%24.24s ", filetime);
column += 25;
break;
@@ -774,47 +753,8 @@ static int list_single(struct dnode *dn)
}
/*----------------------------------------------------------------------*/
-extern int ls_main(int argc, char **argv)
-{
- struct dnode **dnf, **dnd;
- int dnfiles, dndirs;
- struct dnode *dn, *cur, **dnp;
- int i, nfiles;
- int opt;
- int oi, ac;
- char **av;
-
-#ifdef CONFIG_FEATURE_AUTOWIDTH
- struct winsize win = { 0, 0, 0, 0 };
-#endif
-
- disp_opts = DISP_NORMAL;
- style_fmt = STYLE_AUTO;
- list_fmt = LIST_SHORT;
-#ifdef CONFIG_FEATURE_LS_SORTFILES
- sort_opts = SORT_NAME;
- sort_order = SORT_FORWARD;
-#endif
-#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
- time_fmt = TIME_MOD;
-#endif
-#ifdef CONFIG_FEATURE_AUTOWIDTH
- ioctl(fileno(stdout), TIOCGWINSZ, &win);
- if (win.ws_col > 0)
- terminal_width = win.ws_col - 1;
-#endif
- nfiles = 0;
-#ifdef CONFIG_FEATURE_LS_COLOR
- if (isatty(fileno(stdout)))
- show_color = 1;
-#endif
-
- /* process options */
- while ((opt = getopt(argc, argv, "1AaCdgilnsx"
-#ifdef CONFIG_FEATURE_AUTOWIDTH
- "T:w:"
-#endif
+static const char ls_opts[] = "1AaCdgilnsx"
#ifdef CONFIG_FEATURE_LS_FILETYPES
"Fp"
#endif
@@ -825,7 +765,7 @@ extern int ls_main(int argc, char **argv)
"rSvX"
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
- "cetu"
+ "ecut"
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
"L"
@@ -833,141 +773,180 @@ extern int ls_main(int argc, char **argv)
#ifdef CONFIG_FEATURE_HUMAN_READABLE
"h"
#endif
- "k")) > 0) {
- switch (opt) {
- case '1':
- style_fmt = STYLE_SINGLE;
- list_fmt = LIST_SHORT;
- break;
- case 'A':
- disp_opts |= DISP_HIDDEN;
- break;
- case 'a':
- disp_opts |= DISP_HIDDEN | DISP_DOT;
- break;
- case 'C':
- style_fmt = STYLE_COLUMNS;
- list_fmt = LIST_SHORT;
- break;
- case 'd':
- disp_opts |= DISP_NOLIST;
- break;
- case 'g': /* ignore -- for ftp servers */
- break;
- case 'i':
- list_fmt |= LIST_INO;
- break;
- case 'l':
- style_fmt = STYLE_LONG;
- list_fmt |= LIST_LONG;
-#ifdef CONFIG_FEATURE_HUMAN_READABLE
- ls_disp_hr = FALSE;
+ "k"
+#ifdef CONFIG_FEATURE_AUTOWIDTH
+ "T:w:"
#endif
- break;
- case 'n':
- list_fmt |= LIST_ID_NUMERIC;
- break;
- case 's':
- list_fmt |= LIST_BLOCKS;
- break;
- case 'x':
- disp_opts = DISP_ROWS;
- break;
+ ;
+
+#define LIST_MASK_TRIGGER LIST_SHORT
+#define STYLE_MASK_TRIGGER STYLE_MASK
+#define SORT_MASK_TRIGGER SORT_MASK
+#define DISP_MASK_TRIGGER DISP_ROWS
+#define TIME_MASK_TRIGGER TIME_MASK
+
+static const unsigned opt_flags[] = {
+ LIST_SHORT | STYLE_SINGLE, /* 1 */
+ DISP_HIDDEN, /* A */
+ DISP_HIDDEN | DISP_DOT, /* a */
+ LIST_SHORT | STYLE_COLUMNS, /* C */
+ DISP_NOLIST, /* d */
+ 0, /* g - ingored */
+ LIST_INO, /* i */
+ LIST_LONG | STYLE_LONG, /* l - remember LS_DISP_HR in mask! */
+ LIST_ID_NUMERIC, /* n */
+ LIST_BLOCKS, /* s */
+ DISP_ROWS, /* x */
#ifdef CONFIG_FEATURE_LS_FILETYPES
- case 'F':
- list_fmt |= LIST_FILETYPE | LIST_EXEC;
- break;
- case 'p':
- list_fmt |= LIST_FILETYPE;
- break;
+ LIST_FILETYPE | LIST_EXEC, /* F */
+ LIST_FILETYPE, /* p */
#endif
#ifdef CONFIG_FEATURE_LS_RECURSIVE
- case 'R':
- disp_opts |= DISP_RECURSIVE;
- break;
+ DISP_RECURSIVE, /* R */
#endif
#ifdef CONFIG_FEATURE_LS_SORTFILES
- case 'r':
- sort_order |= SORT_REVERSE;
- break;
- case 'S':
- sort_opts = SORT_SIZE;
- break;
- case 'v':
- sort_opts = SORT_VERSION;
- break;
- case 'X':
- sort_opts = SORT_EXT;
- break;
+ SORT_ORDER_REVERSE, /* r */
+ SORT_SIZE, /* S */
+ SORT_VERSION, /* v */
+ SORT_EXT, /* v */
#endif
#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
- case 'e':
- list_fmt |= LIST_FULLTIME;
- break;
- case 'c':
- time_fmt = TIME_CHANGE;
+ LIST_FULLTIME, /* e */
#ifdef CONFIG_FEATURE_LS_SORTFILES
- sort_opts = SORT_CTIME;
+ TIME_CHANGE | SORT_CTIME, /* c */
+#else
+ TIME_CHANGE, /* c */
#endif
- break;
- case 'u':
- time_fmt = TIME_ACCESS;
#ifdef CONFIG_FEATURE_LS_SORTFILES
- sort_opts = SORT_ATIME;
+ TIME_ACCESS | SORT_ATIME, /* u */
+#else
+ TIME_ACCESS, /* u */
#endif
- break;
- case 't':
#ifdef CONFIG_FEATURE_LS_SORTFILES
- sort_opts = SORT_MTIME;
+ SORT_MTIME, /* t */
+#else
+ 0, /* t - ignored -- is this correct? */
#endif
- break;
#endif
#ifdef CONFIG_FEATURE_LS_FOLLOWLINKS
- case 'L':
- follow_links = TRUE;
- break;
+ FOLLOW_LINKS, /* L */
+#endif
+#ifdef CONFIG_FEATURE_HUMAN_READABLE
+LS_DISP_HR, /* h */
+#endif
+ 0, /* k - ingored */
+};
+
+
+/*----------------------------------------------------------------------*/
+
+extern int ls_main(int argc, char **argv)
+{
+ struct dnode **dnf, **dnd;
+ int dnfiles, dndirs;
+ struct dnode *dn, *cur, **dnp;
+ int i, nfiles;
+ int opt;
+ int oi, ac;
+ char **av;
+
+#ifdef CONFIG_FEATURE_AUTOWIDTH
+ struct winsize win = { 0, 0, 0, 0 };
+#endif
+
+ all_fmt = LIST_SHORT | DISP_NORMAL | STYLE_AUTO
+#ifdef CONFIG_FEATURE_LS_TIMESTAMPS
+ | TIME_MOD
+#endif
+#ifdef CONFIG_FEATURE_LS_SORTFILES
+ | SORT_NAME | SORT_ORDER_FORWARD
+#endif
+ ;
+#ifdef CONFIG_FEATURE_AUTOWIDTH
+ ioctl(fileno(stdout), TIOCGWINSZ, &win);
+ if (win.ws_col > 0)
+ terminal_width = win.ws_col - 1;
+#endif
+ nfiles = 0;
+
+#ifdef CONFIG_FEATURE_LS_COLOR
+ if (isatty(fileno(stdout)))
+ show_color = 1;
#endif
+
+ /* process options */
+ while ((opt = getopt(argc, argv, ls_opts)) > 0) {
#ifdef CONFIG_FEATURE_AUTOWIDTH
- case 'T':
+ if (opt == 'T') {
tabstops = atoi(optarg);
- break;
- case 'w':
+ continue;
+ }
+ if (opt == 'w') {
terminal_width = atoi(optarg);
- break;
+ continue;
+ }
+ if (opt == ':') {
+ goto print_usage_message;
+ }
#endif
+ {
+ unsigned int flags;
+ const char *p = strchr(ls_opts, opt);
+ if (!p) { /* shouldn't be necessary */
+ goto print_usage_message;
+ }
+ flags = opt_flags[(int)(p - ls_opts)];
+ if (flags & LIST_MASK_TRIGGER) {
+ all_fmt &= ~LIST_MASK;
+ }
+ if (flags & STYLE_MASK_TRIGGER) {
+ all_fmt &= ~STYLE_MASK;
+ }
+ if (flags & SORT_MASK_TRIGGER) {
+ all_fmt &= ~SORT_MASK;
+ }
+ if (flags & DISP_MASK_TRIGGER) {
+ all_fmt &= ~DISP_MASK;
+ }
+ if (flags & TIME_MASK_TRIGGER) {
+ all_fmt &= ~TIME_MASK;
+ }
#ifdef CONFIG_FEATURE_HUMAN_READABLE
- case 'h':
- ls_disp_hr = TRUE;
- break;
+ if (opt == 'l') {
+ all_fmt &= ~LS_DISP_HR;
+ }
#endif
- case 'k':
- break;
- default:
- goto print_usage_message;
+ all_fmt |= flags;
}
}
+
/* sort out which command line options take precedence */
#ifdef CONFIG_FEATURE_LS_RECURSIVE
- if (disp_opts & DISP_NOLIST)
- disp_opts &= ~DISP_RECURSIVE; /* no recurse if listing only dir */
+ if (all_fmt & DISP_NOLIST)
+ all_fmt &= ~DISP_RECURSIVE; /* no recurse if listing only dir */
#endif
#if defined (CONFIG_FEATURE_LS_TIMESTAMPS) && defined (CONFIG_FEATURE_LS_SORTFILES)
- if (time_fmt & TIME_CHANGE)
- sort_opts = SORT_CTIME;
- if (time_fmt & TIME_ACCESS)
- sort_opts = SORT_ATIME;
+ if (all_fmt & TIME_CHANGE)
+ all_fmt = (all_fmt & ~SORT_MASK) | SORT_CTIME;
+ if (all_fmt & TIME_ACCESS)
+ all_fmt = (all_fmt & ~SORT_MASK) | SORT_ATIME;
#endif
- if (style_fmt != STYLE_LONG) /* only for long list */
- list_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
+ if ((all_fmt & STYLE_MASK) != STYLE_LONG) /* only for long list */
+ all_fmt &= ~(LIST_ID_NUMERIC|LIST_FULLTIME|LIST_ID_NAME|LIST_ID_NUMERIC);
#ifdef CONFIG_FEATURE_LS_USERNAME
- if (style_fmt == STYLE_LONG && (list_fmt & LIST_ID_NUMERIC))
- list_fmt &= ~LIST_ID_NAME; /* don't list names if numeric uid */
+ if ((all_fmt & STYLE_MASK) == STYLE_LONG && (all_fmt & LIST_ID_NUMERIC))
+ all_fmt &= ~LIST_ID_NAME; /* don't list names if numeric uid */
#endif
-
+
/* choose a display format */
- if (style_fmt == STYLE_AUTO)
- style_fmt = isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE;
+ if ((all_fmt & STYLE_MASK) == STYLE_AUTO)
+#if STYLE_AUTO != 0
+ all_fmt = (all_fmt & ~STYLE_MASK)
+ | (isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE);
+#else
+ all_fmt |= (isatty(fileno(stdout)) ? STYLE_COLUMNS : STYLE_SINGLE);
+#endif
/*
* when there are no cmd line args we have to supply a default "." arg.
@@ -979,7 +958,7 @@ extern int ls_main(int argc, char **argv)
ac = argc - optind; /* how many cmd line args are left */
if (ac < 1) {
av = (char **) xcalloc((size_t) 1, (size_t) (sizeof(char *)));
- av[0] = xstrdup(".");
+ av[0] = bb_xstrdup(".");
ac = 1;
} else {
av = (char **) xcalloc((size_t) ac, (size_t) (sizeof(char *)));
@@ -990,12 +969,12 @@ extern int ls_main(int argc, char **argv)
/* now, everything is in the av array */
if (ac > 1)
- disp_opts |= DISP_DIRNAME; /* 2 or more items? label directories */
+ all_fmt |= DISP_DIRNAME; /* 2 or more items? label directories */
/* stuff the command line file names into an dnode array */
dn = NULL;
for (oi = 0; oi < ac; oi++) {
- char *fullname = xstrdup(av[oi]);
+ char *fullname = bb_xstrdup(av[oi]);
cur = my_stat(fullname, fullname);
if (!cur)
@@ -1015,7 +994,7 @@ extern int ls_main(int argc, char **argv)
}
- if (disp_opts & DISP_NOLIST) {
+ if (all_fmt & DISP_NOLIST) {
#ifdef CONFIG_FEATURE_LS_SORTFILES
shellsort(dnp, nfiles);
#endif
@@ -1042,5 +1021,5 @@ extern int ls_main(int argc, char **argv)
return (status);
print_usage_message:
- show_usage();
+ bb_show_usage();
}
diff --git a/coreutils/md5sum.c b/coreutils/md5sum.c
index f5be4486c..c1480cd32 100644
--- a/coreutils/md5sum.c
+++ b/coreutils/md5sum.c
@@ -770,13 +770,13 @@ static int md5_file(const char *filename,
have_read_stdin = 1;
fp = stdin;
} else {
- fp = wfopen(filename, "r");
+ fp = bb_wfopen(filename, "r");
if (fp == NULL)
return FALSE;
}
if (md5_stream(fp, md5_result)) {
- perror_msg("%s", filename);
+ bb_perror_msg("%s", filename);
if (fp != stdin)
fclose(fp);
@@ -784,7 +784,7 @@ static int md5_file(const char *filename,
}
if (fp != stdin && fclose(fp) == EOF) {
- perror_msg("%s", filename);
+ bb_perror_msg("%s", filename);
return FALSE;
}
@@ -805,7 +805,7 @@ static int md5_check(const char *checkfile_name)
have_read_stdin = 1;
checkfile_stream = stdin;
} else {
- checkfile_stream = wfopen(checkfile_name, "r");
+ checkfile_stream = bb_wfopen(checkfile_name, "r");
if (checkfile_stream == NULL)
return FALSE;
}
@@ -836,7 +836,7 @@ static int md5_check(const char *checkfile_name)
if (split_3(line, line_length, &md5num, &filename)
|| !hex_digits(md5num)) {
if (warn) {
- error_msg("%s: %lu: improperly formatted MD5 checksum line",
+ bb_error_msg("%s: %lu: improperly formatted MD5 checksum line",
checkfile_name, (unsigned long) line_number);
}
} else {
@@ -881,18 +881,18 @@ static int md5_check(const char *checkfile_name)
while (!feof(checkfile_stream) && !ferror(checkfile_stream));
if (ferror(checkfile_stream)) {
- error_msg("%s: read error", checkfile_name);
+ bb_error_msg("%s: read error", checkfile_name);
return FALSE;
}
if (checkfile_stream != stdin && fclose(checkfile_stream) == EOF) {
- perror_msg("md5sum: %s", checkfile_name);
+ bb_perror_msg("md5sum: %s", checkfile_name);
return FALSE;
}
if (n_properly_formated_lines == 0) {
/* Warn if no tests are found. */
- error_msg("%s: no properly formatted MD5 checksum lines found",
+ bb_error_msg("%s: no properly formatted MD5 checksum lines found",
checkfile_name);
return FALSE;
} else {
@@ -901,13 +901,13 @@ static int md5_check(const char *checkfile_name)
- n_open_or_read_failures);
if (n_open_or_read_failures > 0) {
- error_msg("WARNING: %d of %d listed files could not be read",
+ bb_error_msg("WARNING: %d of %d listed files could not be read",
n_open_or_read_failures, n_properly_formated_lines);
return FALSE;
}
if (n_mismatched_checksums > 0) {
- error_msg("WARNING: %d of %d computed checksums did NOT match",
+ bb_error_msg("WARNING: %d of %d computed checksums did NOT match",
n_mismatched_checksums, n_computed_checkums);
return FALSE;
}
@@ -965,31 +965,31 @@ int md5sum_main(int argc,
break;
default:
- show_usage();
+ bb_show_usage();
}
}
if (file_type_specified && do_check) {
- error_msg_and_die("the -b and -t options are meaningless when verifying checksums");
+ bb_error_msg_and_die("the -b and -t options are meaningless when verifying checksums");
}
if (n_strings > 0 && do_check) {
- error_msg_and_die("the -g and -c options are mutually exclusive");
+ bb_error_msg_and_die("the -g and -c options are mutually exclusive");
}
if (status_only && !do_check) {
- error_msg_and_die("the -s option is meaningful only when verifying checksums");
+ bb_error_msg_and_die("the -s option is meaningful only when verifying checksums");
}
if (warn && !do_check) {
- error_msg_and_die("the -w option is meaningful only when verifying checksums");
+ bb_error_msg_and_die("the -w option is meaningful only when verifying checksums");
}
if (n_strings > 0) {
size_t i;
if (optind < argc) {
- error_msg_and_die("no files may be specified when using -g");
+ bb_error_msg_and_die("no files may be specified when using -g");
}
for (i = 0; i < n_strings; ++i) {
size_t cnt;
@@ -1002,7 +1002,7 @@ int md5sum_main(int argc,
}
} else if (do_check) {
if (optind + 1 < argc) {
- error_msg("only one argument may be specified when using -c");
+ bb_error_msg("only one argument may be specified when using -c");
}
err = md5_check ((optind == argc) ? "-" : argv[optind]);
@@ -1060,11 +1060,11 @@ int md5sum_main(int argc,
}
if (fclose (stdout) == EOF) {
- error_msg_and_die("write error");
+ bb_error_msg_and_die("write error");
}
if (have_read_stdin && fclose (stdin) == EOF) {
- error_msg_and_die("standard input");
+ bb_error_msg_and_die(bb_msg_standard_input);
}
if (err == 0)
diff --git a/coreutils/mkdir.c b/coreutils/mkdir.c
index f003db99f..b018ac181 100644
--- a/coreutils/mkdir.c
+++ b/coreutils/mkdir.c
@@ -20,46 +20,50 @@
*
*/
-#include <errno.h>
-#include <getopt.h>
-#include <sys/stat.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <string.h>
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/mkdir.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Fixed broken permission setting when -p was used; especially in
+ * conjunction with -m.
+ */
+#include <stdlib.h>
+#include <unistd.h>
#include "busybox.h"
extern int mkdir_main (int argc, char **argv)
{
- mode_t mode = -1;
+ mode_t mode = (mode_t)(-1);
+ int status = EXIT_SUCCESS;
int flags = 0;
- int i, opt;
+ int opt;
- while ((opt = getopt (argc, argv, "m:p")) != -1) {
- switch (opt) {
- case 'm':
+ while ((opt = getopt (argc, argv, "m:p")) > 0) {
+ if (opt == 'm') {
mode = 0777;
- if (!parse_mode (optarg, &mode)) {
- error_msg_and_die ("invalid mode `%s'", optarg);
+ if (!bb_parse_mode (optarg, &mode)) {
+ bb_error_msg_and_die ("invalid mode `%s'", optarg);
}
- umask(0);
- break;
- case 'p':
+ } else if (opt == 'p') {
flags |= FILEUTILS_RECUR;
- break;
- default:
- show_usage ();
+ } else {
+ bb_show_usage();
}
}
- if (optind == argc)
- show_usage ();
-
- for (i = optind; i < argc; i++) {
- make_directory (argv[i], mode, flags);
+ if (optind == argc) {
+ bb_show_usage();
}
- return(EXIT_SUCCESS);
+ argv += optind;
+
+ do {
+ if (bb_make_directory(*argv, mode, flags)) {
+ status = EXIT_FAILURE;
+ }
+ } while (*++argv);
+
+ return status;
}
diff --git a/coreutils/mkfifo.c b/coreutils/mkfifo.c
index ca217fa23..77e0e6dd8 100644
--- a/coreutils/mkfifo.c
+++ b/coreutils/mkfifo.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini mkfifo implementation for busybox
+ * mkfifo implementation for busybox
*
- * Copyright (C) 1999 by Randolph Chung <tausq@debian.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,41 +20,32 @@
*
*/
-#include <stdio.h>
-#include <sys/types.h>
-#include <errno.h>
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/mkfifo.html */
+
#include <stdlib.h>
+#include <unistd.h>
+#include <sys/types.h>
#include "busybox.h"
+#include "libcoreutils/coreutils.h"
extern int mkfifo_main(int argc, char **argv)
{
- char *thisarg;
- mode_t mode = 0666;
+ mode_t mode;
+ int retval = EXIT_SUCCESS;
- argc--;
- argv++;
+ mode = getopt_mk_fifo_nod(argc, argv);
- /* Parse any options */
- while (argc > 1) {
- if (**argv != '-')
- show_usage();
- thisarg = *argv;
- thisarg++;
- switch (*thisarg) {
- case 'm':
- argc--;
- argv++;
- parse_mode(*argv, &mode);
- break;
- default:
- show_usage();
- }
- argc--;
- argv++;
+ if (!*(argv += optind)) {
+ bb_show_usage();
}
- if (argc < 1 || *argv[0] == '-')
- show_usage();
- if (mkfifo(*argv, mode) < 0)
- perror_msg_and_die("mkfifo");
- return EXIT_SUCCESS;
+
+ do {
+ if (mkfifo(*argv, mode) < 0) {
+ bb_perror_msg("%s", *argv); /* Avoid multibyte problems. */
+ retval = EXIT_FAILURE;
+ }
+ } while (*++argv);
+
+ return retval;
}
diff --git a/coreutils/mknod.c b/coreutils/mknod.c
index 432ec2b25..59294e9cb 100644
--- a/coreutils/mknod.c
+++ b/coreutils/mknod.c
@@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini mknod implementation for busybox
+ * mknod implementation for busybox
*
- * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
- * Copyright (C) 1999-2002 by Erik Andersen <andersee@debian.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,73 +20,44 @@
*
*/
-#include <stdio.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <unistd.h>
-#include <string.h>
+/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
+
#include <stdlib.h>
-#include <sys/types.h>
+#include <string.h>
#include <sys/stat.h>
+#include <unistd.h>
#include "busybox.h"
+#include "libcoreutils/coreutils.h"
+
+static const char modes_chars[] = { 'p', 'c', 'u', 'b', 0, 1, 1, 2 };
+static const mode_t modes_cubp[] = { S_IFIFO, S_IFCHR, S_IFBLK };
-int mknod_main(int argc, char **argv)
+extern int mknod_main(int argc, char **argv)
{
- char *thisarg;
- mode_t mode = 0;
- mode_t perm = 0666;
- dev_t dev = (dev_t) 0;
+ mode_t mode;
+ dev_t dev;
+ const char *name;
+
+ mode = getopt_mk_fifo_nod(argc, argv);
+ argv += optind;
+ argc -= optind;
- argc--;
- argv++;
+ if ((argc >= 2) && ((name = strchr(modes_chars, argv[1][0])) != NULL)) {
+ mode |= modes_cubp[(int)(name[4])];
- /* Parse any options */
- while (argc > 1) {
- if (**argv != '-')
- break;
- thisarg = *argv;
- thisarg++;
- switch (*thisarg) {
- case 'm':
- argc--;
- argv++;
- parse_mode(*argv, &perm);
- umask(0);
- break;
- default:
- show_usage();
+ dev = 0;
+ if ((*name != 'p') && ((argc -= 2) == 0)) {
+ dev = (bb_xgetularg10_bnd(argv[2], 0, 255) << 8)
+ + bb_xgetularg10_bnd(argv[3], 0, 255);
}
- argc--;
- argv++;
- }
- if (argc != 4 && argc != 2) {
- show_usage();
- }
- switch (argv[1][0]) {
- case 'c':
- case 'u':
- mode = S_IFCHR;
- break;
- case 'b':
- mode = S_IFBLK;
- break;
- case 'p':
- mode = S_IFIFO;
- if (argc != 2) {
- show_usage();
+
+ if (argc == 2) {
+ name = *argv;
+ if (mknod(name, mode, dev) == 0) {
+ return EXIT_SUCCESS;
+ }
+ bb_perror_msg_and_die("%s", name);
}
- break;
- default:
- show_usage();
- }
-
- if (mode == S_IFCHR || mode == S_IFBLK) {
- dev = (dev_t) ((atoi(argv[2]) << 8) | atoi(argv[3]));
}
-
- mode |= perm;
-
- if (mknod(argv[0], mode, dev) != 0)
- perror_msg_and_die("%s", argv[0]);
- return EXIT_SUCCESS;
+ bb_show_usage();
}
diff --git a/coreutils/mv.c b/coreutils/mv.c
index 1c4a34788..ae0ee92e4 100644
--- a/coreutils/mv.c
+++ b/coreutils/mv.c
@@ -2,7 +2,6 @@
/*
* Mini mv implementation for busybox
*
- *
* Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
*
* This program is free software; you can redistribute it and/or modify
@@ -21,148 +20,122 @@
*
*/
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Size reduction and improved error checking.
+ */
+
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <stdlib.h>
-
#include "busybox.h"
+#include "libcoreutils/coreutils.h"
-static int flags;
+static const char *fmt = "cannot overwrite %sdirectory with %sdirectory";
-static int manual_rename(const char *source, const char *dest)
+extern int mv_main(int argc, char **argv)
{
struct stat source_stat;
struct stat dest_stat;
- int source_exists = 1;
- int dest_exists = 1;
+ const char *last;
+ const char *dest;
+ int dest_exists;
+ int source_exists;
+ int opt;
+ int flags = 0;
+ int status = 0;
- if (stat(source, &source_stat) < 0) {
- if (errno != ENOENT) {
- perror_msg("unable to stat `%s'", source);
- return -1;
+ while ((opt = getopt(argc, argv, "fi")) > 0) {
+ flags &= ~(FILEUTILS_INTERACTIVE | FILEUTILS_FORCE);
+ if (opt == 'i') {
+ flags |= FILEUTILS_INTERACTIVE;
+ } else if (opt == 'f') {
+ flags |= FILEUTILS_FORCE;
+ } else {
+ bb_show_usage();
}
- source_exists = 0;
}
- if (stat(dest, &dest_stat) < 0) {
- if (errno != ENOENT) {
- perror_msg("unable to stat `%s'", dest);
- return -1;
- }
- dest_exists = 0;
- }
+ if (optind + 2 > argc)
+ bb_show_usage();
- if (dest_exists) {
- if (S_ISDIR(dest_stat.st_mode) &&
- (!source_exists || !S_ISDIR(source_stat.st_mode))) {
- error_msg("cannot overwrite directory with non-directory");
- return -1;
- }
+ last = argv[argc - 1];
+ argv += optind;
- if (!S_ISDIR(dest_stat.st_mode) && source_exists &&
- S_ISDIR(source_stat.st_mode)) {
- error_msg("cannot overwrite non-directory with directory");
- return -1;
+ if (optind + 2 == argc) {
+ if ((dest_exists = cp_mv_stat(last, &dest_stat)) < 0) {
+ return 1;
}
- if (unlink(dest) < 0) {
- perror_msg("cannot remove `%s'", dest);
- return -1;
+ if (!(dest_exists & 2)) {
+ dest = last;
+ goto DO_MOVE;
}
}
+
+ do {
+ dest = concat_path_file(last,
+ bb_get_last_path_component(*argv));
- if (copy_file(source, dest,
- FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS) < 0)
- return -1;
-
- if (remove_file(source, FILEUTILS_RECUR | FILEUTILS_FORCE) < 0)
- return -1;
-
- return 0;
-}
-
-static int move_file(const char *source, const char *dest)
-{
- struct stat dest_stat;
- int dest_exists = 1;
-
- if (stat(dest, &dest_stat) < 0) {
- if (errno != ENOENT) {
- perror_msg("unable to stat `%s'", dest);
- return -1;
+ if ((dest_exists = cp_mv_stat(dest, &dest_stat)) < 0) {
+ goto RET_1;
}
- dest_exists = 0;
- }
- if (dest_exists && !(flags & FILEUTILS_FORCE) &&
+ DO_MOVE:
+
+ if (dest_exists && !(flags & FILEUTILS_FORCE) &&
((access(dest, W_OK) < 0 && isatty(0)) ||
(flags & FILEUTILS_INTERACTIVE))) {
- fprintf(stderr, "mv: overwrite `%s'? ", dest);
- if (!ask_confirmation())
- return 0;
- }
-
- if (rename(source, dest) < 0) {
- if (errno == EXDEV)
- return manual_rename(source, dest);
-
- perror_msg("unable to rename `%s'", source);
- return -1;
- }
-
- return 0;
-}
-
-extern int mv_main(int argc, char **argv)
-{
- int status = 0;
- int opt;
- int i;
-
- while ((opt = getopt(argc, argv, "fi")) != -1)
- switch (opt) {
- case 'f':
- flags &= ~FILEUTILS_INTERACTIVE;
- flags |= FILEUTILS_FORCE;
- break;
- case 'i':
- flags &= ~FILEUTILS_FORCE;
- flags |= FILEUTILS_INTERACTIVE;
- break;
- default:
- show_usage();
- }
-
- if (optind + 2 > argc)
- show_usage();
-
- if (optind + 2 == argc) {
- struct stat dest_stat;
- int dest_exists = 1;
-
- if (stat(argv[optind + 1], &dest_stat) < 0) {
- if (errno != ENOENT)
- perror_msg_and_die("unable to stat `%s'", argv[optind + 1]);
- dest_exists = 0;
+ if (fprintf(stderr, "mv: overwrite `%s'? ", dest) < 0) {
+ goto RET_1; /* Ouch! fprintf failed! */
+ }
+ if (!bb_ask_confirmation())
+ goto RET_0;
+ }
+
+ if (rename(*argv, dest) < 0) {
+ if (errno != EXDEV) {
+ bb_perror_msg("unable to rename `%s'", *argv);
+ } else if ((source_exists = cp_mv_stat(*argv, &source_stat)) >= 0) {
+ if (dest_exists) {
+ if (dest_exists & 2) {
+ if (!(source_exists & 2)) {
+ bb_error_msg(fmt, "", "non-");
+ goto RET_1;
+ }
+ } else {
+ if (source_exists & 2) {
+ bb_error_msg(fmt, "non-", "");
+ goto RET_1;
+ }
+ }
+ if (unlink(dest) < 0) {
+ bb_perror_msg("cannot remove `%s'", dest);
+ goto RET_1;
+ }
+ }
+
+ if ((copy_file(*argv, dest,
+ FILEUTILS_RECUR | FILEUTILS_PRESERVE_STATUS) >= 0)
+ && (remove_file(*argv, FILEUTILS_RECUR | FILEUTILS_FORCE) >= 0)
+ ) {
+ goto RET_0;
+ }
+
+ }
+ RET_1:
+ status = 1;
}
- if (!dest_exists || !S_ISDIR(dest_stat.st_mode)) {
- if (move_file(argv[optind], argv[optind + 1]) < 0)
- status = 1;
- return status;
+ RET_0:
+ if (dest != last) {
+ free((void *) dest);
}
- }
-
- for (i = optind; i < argc - 1; i++) {
- char *dest = concat_path_file(argv[argc - 1],
- get_last_path_component(argv[i]));
- if (move_file(argv[i], dest) < 0)
- status = 1;
- free(dest);
- }
-
- return status;
+
+ } while (*++argv != last);
+
+ exit(status);
}
diff --git a/coreutils/od.c b/coreutils/od.c
index 6187cadf2..5eaaf5024 100644
--- a/coreutils/od.c
+++ b/coreutils/od.c
@@ -23,22 +23,18 @@
*/
#include <ctype.h>
+#include <string.h>
#include <getopt.h>
#include <stdlib.h>
-#include "dump.h"
#include "busybox.h"
+#include "dump.h"
-extern FS *fshead; /* head of format strings */
-extern int blocksize; /* data block size */
-extern int length; /* max bytes to read */
-
-#define ishexdigit(c) \
- ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'))
+#define isdecdigit(c) (isdigit)(c)
+#define ishexdigit(c) (isxdigit)(c)
static void
odoffset(int argc, char ***argvp)
{
- extern off_t skip;
register char *num, *p;
int base;
char *end;
@@ -62,13 +58,15 @@ odoffset(int argc, char ***argvp)
return;
}
- if (*p != '+' && (argc < 2 ||
- (!isdigit(p[0]) && (p[0] != 'x' || !ishexdigit(p[1])))))
+ if ((*p != '+')
+ && (argc < 2
+ || (!isdecdigit(p[0])
+ && ((p[0] != 'x') || !ishexdigit(p[1])))))
return;
base = 0;
/*
- * skip over leading '+', 'x[0-9a-fA-f]' or '0x', and
+ * bb_dump_skip over leading '+', 'x[0-9a-fA-f]' or '0x', and
* set base.
*/
if (p[0] == '+')
@@ -81,11 +79,11 @@ odoffset(int argc, char ***argvp)
base = 16;
}
- /* skip over the number */
+ /* bb_dump_skip over the number */
if (base == 16)
for (num = p; ishexdigit(*p); ++p);
else
- for (num = p; isdigit(*p); ++p);
+ for (num = p; isdecdigit(*p); ++p);
/* check for no number */
if (num == p)
@@ -98,21 +96,23 @@ odoffset(int argc, char ***argvp)
base = 10;
}
- skip = strtol(num, &end, base ? base : 8);
+ bb_dump_skip = strtol(num, &end, base ? base : 8);
/* if end isn't the same as p, we got a non-octal digit */
if (end != p)
- skip = 0;
+ bb_dump_skip = 0;
else {
if (*p) {
- if (*p == 'b')
- skip *= 512;
- else if (*p == 'B')
- skip *= 1024;
- ++p;
+ if (*p == 'b') {
+ bb_dump_skip *= 512;
+ ++p;
+ } else if (*p == 'B') {
+ bb_dump_skip *= 1024;
+ ++p;
+ }
}
if (*p)
- skip = 0;
+ bb_dump_skip = 0;
else {
++*argvp;
/*
@@ -121,117 +121,76 @@ odoffset(int argc, char ***argvp)
* but it's easy.
*/
#define TYPE_OFFSET 7
- if (base == 16) {
- fshead->nextfu->fmt[TYPE_OFFSET] = 'x';
- fshead->nextfs->nextfu->fmt[TYPE_OFFSET] = 'x';
- } else if (base == 10) {
- fshead->nextfu->fmt[TYPE_OFFSET] = 'd';
- fshead->nextfs->nextfu->fmt[TYPE_OFFSET] = 'd';
+ {
+ char x_or_d;
+ if (base == 16) {
+ x_or_d = 'x';
+ goto DO_X_OR_D;
+ }
+ if (base == 10) {
+ x_or_d = 'd';
+ DO_X_OR_D:
+ bb_dump_fshead->nextfu->fmt[TYPE_OFFSET]
+ = bb_dump_fshead->nextfs->nextfu->fmt[TYPE_OFFSET]
+ = x_or_d;
+ }
}
}
}
}
-static void odprecede(void)
-{
- static int first = 1;
-
- if (first) {
- first = 0;
- add("\"%07.7_Ao\n\"");
- add("\"%07.7_ao \"");
- } else
- add("\" \"");
-}
+static const char * const add_strings[] = {
+ "16/1 \"%3_u \" \"\\n\"", /* a */
+ "8/2 \" %06o \" \"\\n\"", /* B, o */
+ "16/1 \"%03o \" \"\\n\"", /* b */
+ "16/1 \"%3_c \" \"\\n\"", /* c */
+ "8/2 \" %05u \" \"\\n\"", /* d */
+ "4/4 \" %010u \" \"\\n\"", /* D */
+ "2/8 \" %21.14e \" \"\\n\"", /* e (undocumented in od), F */
+ "4/4 \" %14.7e \" \"\\n\"", /* f */
+ "4/4 \" %08x \" \"\\n\"", /* H, X */
+ "8/2 \" %04x \" \"\\n\"", /* h, x */
+ "4/4 \" %11d \" \"\\n\"", /* I, L, l */
+ "8/2 \" %6d \" \"\\n\"", /* i */
+ "4/4 \" %011o \" \"\\n\"", /* O */
+};
+
+static const signed char od_opts[] = "aBbcDdeFfHhIiLlOovXx";
+
+static const signed char od_o2si[] = {
+ 0, 1, 2, 3, 5,
+ 4, 6, 6, 7, 8,
+ 9, 0xa, 0xb, 0xa, 0xa,
+ 0xb, 1, -1, 8, 9,
+};
int od_main(int argc, char **argv)
{
int ch;
- extern enum _vflag vflag;
- vflag = FIRST;
- length = -1;
-
- while ((ch = getopt(argc, argv, "aBbcDdeFfHhIiLlOoPpswvXx")) != EOF)
- switch (ch) {
- case 'a':
- odprecede();
- add("16/1 \"%3_u \" \"\\n\"");
- break;
- case 'B':
- case 'o':
- odprecede();
- add("8/2 \" %06o \" \"\\n\"");
- break;
- case 'b':
- odprecede();
- add("16/1 \"%03o \" \"\\n\"");
- break;
- case 'c':
- odprecede();
- add("16/1 \"%3_c \" \"\\n\"");
- break;
- case 'd':
- odprecede();
- add("8/2 \" %05u \" \"\\n\"");
- break;
- case 'D':
- odprecede();
- add("4/4 \" %010u \" \"\\n\"");
- break;
- case 'e': /* undocumented in od */
- case 'F':
- odprecede();
- add("2/8 \" %21.14e \" \"\\n\"");
- break;
-
- case 'f':
- odprecede();
- add("4/4 \" %14.7e \" \"\\n\"");
- break;
- case 'H':
- case 'X':
- odprecede();
- add("4/4 \" %08x \" \"\\n\"");
- break;
- case 'h':
- case 'x':
- odprecede();
- add("8/2 \" %04x \" \"\\n\"");
- break;
- case 'I':
- case 'L':
- case 'l':
- odprecede();
- add("4/4 \" %11d \" \"\\n\"");
- break;
- case 'i':
- odprecede();
- add("8/2 \" %6d \" \"\\n\"");
- break;
- case 'O':
- odprecede();
- add("4/4 \" %011o \" \"\\n\"");
- break;
- case 'v':
- vflag = ALL;
- break;
- case 'P':
- case 'p':
- case 's':
- case 'w':
- case '?':
- default:
- error_msg("od: od(1) has been deprecated for hexdump(1).\n");
- if (ch != '?') {
- error_msg("od: hexdump(1) compatibility doesn't support the -%c option%s\n",
- ch, ch == 's' ? "; see strings(1)." : ".");
+ bb_dump_vflag = FIRST;
+ bb_dump_length = -1;
+ int first = 1;
+ signed char *p;
+
+ while ((ch = getopt(argc, argv, od_opts)) > 0) {
+ if (((p = strchr(od_opts, ch)) != NULL) && (*p >= 0)) {
+ if (first) {
+ first = 0;
+ bb_dump_add("\"%07.7_Ao\n\"");
+ bb_dump_add("\"%07.7_ao \"");
+ } else {
+ bb_dump_add("\" \"");
}
- show_usage();
+ bb_dump_add(add_strings[od_o2si[(int)(p-od_opts)]]);
+ } else if (ch == 'v') {
+ bb_dump_vflag = ALL;
+ } else { /* P, p, s, w, or other unhandled */
+ bb_show_usage();
}
-
- if (!fshead) {
- add("\"%07.7_Ao\n\"");
- add("\"%07.7_ao \" 8/2 \"%06o \" \"\\n\"");
+ }
+ if (!bb_dump_fshead) {
+ bb_dump_add("\"%07.7_Ao\n\"");
+ bb_dump_add("\"%07.7_ao \" 8/2 \"%06o \" \"\\n\"");
}
argc -= optind;
@@ -239,7 +198,7 @@ int od_main(int argc, char **argv)
odoffset(argc, &argv);
- return(dump(argv));
+ return(bb_dump_dump(argv));
}
/*-
diff --git a/coreutils/printf.c b/coreutils/printf.c
index d579a9b4e..9602788de 100644
--- a/coreutils/printf.c
+++ b/coreutils/printf.c
@@ -124,7 +124,7 @@ int printf_main(int argc, char **argv)
exit_status = 0;
if (argc <= 1 || **(argv + 1) == '-') {
- show_usage();
+ bb_show_usage();
}
format = argv[1];
diff --git a/coreutils/pwd.c b/coreutils/pwd.c
index 9c5d70cef..7e0dc056a 100644
--- a/coreutils/pwd.c
+++ b/coreutils/pwd.c
@@ -20,24 +20,18 @@
*
*/
-/* getopt not needed */
-
#include <stdio.h>
-#include <dirent.h>
-#include <errno.h>
-#include <unistd.h>
#include <stdlib.h>
#include "busybox.h"
extern int pwd_main(int argc, char **argv)
{
- static char *buf;
-
- buf = xgetcwd(buf);
-
- if (buf != NULL) {
+ char *buf;
+
+ if ((buf = xgetcwd(NULL)) != NULL) {
puts(buf);
- return EXIT_SUCCESS;
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
+
return EXIT_FAILURE;
}
diff --git a/coreutils/realpath.c b/coreutils/realpath.c
index f89e0a274..ec98221ad 100644
--- a/coreutils/realpath.c
+++ b/coreutils/realpath.c
@@ -14,17 +14,26 @@
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
+/* BB_AUDIT SUSv3 N/A -- Apparently a busybox extension. */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Now does proper error checking on output and returns a failure exit code
+ * if one or more paths can not be resolved.
+ */
+
#include <limits.h>
#include <stdlib.h>
-
#include "busybox.h"
int realpath_main(int argc, char **argv)
{
+ int retval = EXIT_SUCCESS;
+
RESERVE_CONFIG_BUFFER(resolved_path, PATH_MAX);
if (--argc == 0) {
- show_usage();
+ bb_show_usage();
}
do {
@@ -32,11 +41,14 @@ int realpath_main(int argc, char **argv)
if (realpath(*argv, resolved_path) != NULL) {
puts(resolved_path);
} else {
- perror_msg("%s", *argv);
+ retval = EXIT_FAILURE;
+ bb_perror_msg("%s", *argv);
}
} while (--argc);
+#ifdef CONFIG_FEATURE_CLEAN_UP
RELEASE_CONFIG_BUFFER(resolved_path);
+#endif
- return(EXIT_SUCCESS);
+ bb_fflush_stdout_and_exit(retval);
}
diff --git a/coreutils/rm.c b/coreutils/rm.c
index 51c9f4ceb..5489350e5 100644
--- a/coreutils/rm.c
+++ b/coreutils/rm.c
@@ -2,7 +2,6 @@
/*
* Mini rm implementation for busybox
*
- *
* Copyright (C) 2001 Matt Kraai <kraai@alumni.carnegiemellon.edu>
*
*
@@ -22,55 +21,51 @@
*
*/
-#include <stdio.h>
-#include <time.h>
-#include <utime.h>
-#include <dirent.h>
-#include <errno.h>
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/rm.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Size reduction.
+ */
+
#include <unistd.h>
-#include <stdlib.h>
-#include <string.h>
-#include <getopt.h>
#include "busybox.h"
extern int rm_main(int argc, char **argv)
{
int status = 0;
- int opt;
int flags = 0;
- int i;
+ int opt;
- while ((opt = getopt(argc, argv, "fiRr")) != -1) {
- switch (opt) {
- case 'f':
- flags &= ~FILEUTILS_INTERACTIVE;
- flags |= FILEUTILS_FORCE;
- break;
- case 'i':
- flags &= ~FILEUTILS_FORCE;
- flags |= FILEUTILS_INTERACTIVE;
- break;
- case 'R':
- case 'r':
+ while ((opt = getopt(argc, argv, "fiRr")) > 0) {
+ if ((opt == 'r') || (opt == 'R')) {
flags |= FILEUTILS_RECUR;
- break;
+ } else {
+ flags &= ~(FILEUTILS_INTERACTIVE | FILEUTILS_FORCE);
+ if (opt == 'i') {
+ flags |= FILEUTILS_INTERACTIVE;
+ } else if (opt == 'f') {
+ flags |= FILEUTILS_FORCE;
+ } else {
+ bb_show_usage();
+ }
}
}
- if (!(flags & FILEUTILS_FORCE) && optind == argc)
- show_usage();
-
- for (i = optind; i < argc; i++) {
- char *base = get_last_path_component(argv[i]);
-
- if (strcmp(base, ".") == 0 || strcmp(base, "..") == 0) {
- error_msg("cannot remove `.' or `..'");
- status = 1;
- continue;
- }
+ if (*(argv += optind) != NULL) {
+ do {
+ const char *base = bb_get_last_path_component(*argv);
- if (remove_file(argv[i], flags) < 0)
+ if ((base[0] == '.') && (!base[1] || ((base[1] == '.') && !base[2]))) {
+ bb_error_msg("cannot remove `.' or `..'");
+ } else if (remove_file(*argv, flags) >= 0) {
+ continue;
+ }
status = 1;
+ } while (*++argv);
+ } else if (!(flags & FILEUTILS_FORCE)) {
+ bb_show_usage();
}
return status;
diff --git a/coreutils/rmdir.c b/coreutils/rmdir.c
index 83b27c9bd..3f6037170 100644
--- a/coreutils/rmdir.c
+++ b/coreutils/rmdir.c
@@ -1,9 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini rmdir implementation for busybox
+ * rmdir implementation for busybox
*
- * Copyright (C) 1999,2000 by Lineo, inc. and Erik Andersen
- * Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -21,76 +20,54 @@
*
*/
-#include <getopt.h>
-#include <unistd.h>
-#include <stdlib.h>
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/rmdir.html */
+#include <stdlib.h>
+#include <unistd.h>
+#include <libgen.h>
#include "busybox.h"
-
-/* Return true if a path is composed of multiple components. */
-
-static int
-multiple_components_p (const char *path)
-{
- const char *s = path;
-
- while (s[0] != '\0' && s[0] != '/')
- s++;
-
- while (s[0] == '/')
- s++;
-
- return (s[0] != '\0');
-}
-
-
-/* Remove a directory. Returns 0 if successful, -1 on error. */
-
-static int
-remove_directory (char *path, int flags)
-{
- if (!(flags & FILEUTILS_RECUR)) {
- if (rmdir (path) < 0) {
- perror_msg ("unable to remove `%s'", path);
- return -1;
- }
- } else {
- if (remove_directory (path, 0) < 0)
- return -1;
-
- if (multiple_components_p (path))
- if (remove_directory (dirname (path), flags) < 0)
- return -1;
- }
-
- return 0;
-}
-
-
-extern int
-rmdir_main (int argc, char **argv)
+extern int rmdir_main(int argc, char **argv)
{
int status = EXIT_SUCCESS;
- int flags = 0;
- int i, opt;
+ int flags;
+ int do_dot;
+ char *path;
- while ((opt = getopt (argc, argv, "p")) != -1)
- switch (opt) {
- case 'p':
- flags |= FILEUTILS_RECUR;
- break;
+ flags = bb_getopt_ulflags(argc, argv, "p");
- default:
- show_usage ();
- }
+ argv += optind;
- if (optind == argc)
- show_usage();
+ if (!*argv) {
+ bb_show_usage();
+ }
- for (i = optind; i < argc; i++)
- if (remove_directory (argv[i], flags) < 0)
- status = EXIT_FAILURE;
+ do {
+ path = *argv;
+
+ /* Record if the first char was a '.' so we can use dirname later. */
+ do_dot = (*path == '.');
+
+ do {
+ if (rmdir(path) < 0) {
+ bb_perror_msg("`%s'", path); /* Match gnu rmdir msg. */
+ status = EXIT_FAILURE;
+ } else if (flags) {
+ /* Note: path was not empty or null since rmdir succeeded. */
+ path = dirname(path);
+ /* Path is now just the parent component. Note that dirname
+ * returns "." if there are no parents. We must distinguish
+ * this from the case of the original path starting with '.'.
+ */
+ if (do_dot || (*path != '.') || path[1]) {
+ continue;
+ }
+ }
+ break;
+ } while (1);
+
+ } while (*++argv);
return status;
}
diff --git a/coreutils/sha1sum.c b/coreutils/sha1sum.c
index 03009f76f..d94cb4b53 100644
--- a/coreutils/sha1sum.c
+++ b/coreutils/sha1sum.c
@@ -187,7 +187,7 @@ extern int authenticate(const int argc, char **argv, void (*hash_ptr)(FILE *stre
break;
#endif
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -204,7 +204,7 @@ extern int authenticate(const int argc, char **argv, void (*hash_ptr)(FILE *stre
hash_ptr(stdin, hashval);
print_hash(hash_length, hashval, NULL);
} else {
- FILE *stream = xfopen(argv[i], "r");
+ FILE *stream = bb_xfopen(argv[i], "r");
hash_ptr(stream, hashval);
fclose(stream);
print_hash(hash_length, hashval, argv[i]);
diff --git a/coreutils/sleep.c b/coreutils/sleep.c
index 7bc98d8e8..506192dd3 100644
--- a/coreutils/sleep.c
+++ b/coreutils/sleep.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini sleep implementation for busybox
+ * sleep implementation for busybox
*
- * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,18 +20,67 @@
*
*/
-#include <stdio.h>
-#include <unistd.h>
+/* BB_AUDIT SUSv3 compliant */
+/* BB_AUDIT GNU issues -- fancy version matches except args must be ints. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/sleep.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Rewritten to do proper arg and error checking.
+ * Also, added a 'fancy' configuration to accept multiple args with
+ * time suffixes for seconds, minutes, hours, and days.
+ */
+
#include <stdlib.h>
+#include <limits.h>
+#include <unistd.h>
#include "busybox.h"
+#ifdef CONFIG_FEATURE_FANCY_SLEEP
+static const struct suffix_mult sleep_suffixes[] = {
+ { "s", 1 },
+ { "m", 60 },
+ { "h", 60*60 },
+ { "d", 24*60*60 },
+ { NULL, 0 }
+};
+#endif
+
extern int sleep_main(int argc, char **argv)
{
- if ((argc < 2) || (**(argv + 1) == '-')) {
- show_usage();
+ unsigned int duration;
+
+#ifdef CONFIG_FEATURE_FANCY_SLEEP
+
+ if (argc < 2) {
+ bb_show_usage();
+ }
+
+ ++argv;
+ duration = 0;
+ do {
+ duration += bb_xgetularg_bnd_sfx(*argv, 10,
+ 0, UINT_MAX-duration,
+ sleep_suffixes);
+ } while (*++argv);
+
+#else /* CONFIG_FEATURE_FANCY_SLEEP */
+
+ if (argc != 2) {
+ bb_show_usage();
+ }
+
+#if UINT_MAX == ULONG_MAX
+ duration = bb_xgetularg10(argv[1]);
+#else
+ duration = bb_xgetularg10_bnd(argv[1], 0, UINT_MAX);
+#endif
+
+#endif /* CONFIG_FEATURE_FANCY_SLEEP */
+
+ if (sleep(duration)) {
+ bb_perror_nomsg_and_die();
}
- if (sleep(atoi(*(++argv))) != 0)
- perror_msg_and_die("sleep");
return EXIT_SUCCESS;
}
diff --git a/coreutils/sort.c b/coreutils/sort.c
index fc12dfb01..8cc4d8886 100644
--- a/coreutils/sort.c
+++ b/coreutils/sort.c
@@ -2,7 +2,6 @@
/*
* Mini sort implementation for busybox
*
- *
* Copyright (C) 2000 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
*
* This program is free software; you can redistribute it and/or modify
@@ -21,10 +20,20 @@
*
*/
-#include <getopt.h>
-#include <string.h>
+/* BB_AUDIT SUSv3 _NOT_ compliant -- a number of options are not supported. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/sort.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Now does proper error checking on i/o. Plus some space savings.
+ */
+
+#include <stdio.h>
#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
#include "busybox.h"
+#include "libcoreutils/coreutils.h"
static int compare_ascii(const void *x, const void *y)
{
@@ -41,66 +50,51 @@ int sort_main(int argc, char **argv)
{
FILE *fp;
char *line, **lines = NULL;
- int i, opt, nlines = 0;
+ int i, nlines = 0, inc;
int (*compare)(const void *, const void *) = compare_ascii;
-#ifdef CONFIG_FEATURE_SORT_REVERSE
- int reverse = FALSE;
-#endif
-#ifdef CONFIG_FEATURE_SORT_UNIQUE
- int unique = FALSE;
-#endif
- while ((opt = getopt(argc, argv, "nru")) != -1) {
- switch (opt) {
- case 'n':
- compare = compare_numeric;
- break;
-#ifdef CONFIG_FEATURE_SORT_REVERSE
- case 'r':
- reverse = TRUE;
- break;
-#endif
-#ifdef CONFIG_FEATURE_SORT_UNIQUE
- case 'u':
- unique = TRUE;
- break;
-#endif
- default:
- show_usage();
- }
+ int flags;
+
+ bb_default_error_retval = 2;
+
+ flags = bb_getopt_ulflags(argc, argv, "nru");
+ if (flags & 1) {
+ compare = compare_numeric;
}
- /* read the input */
- for (i = optind; i == optind || i < argc; i++) {
- if (argv[i] == NULL)
- fp = stdin;
- else
- fp = xfopen(argv[i], "r");
+ argv += optind;
+ if (!*argv) {
+ *--argv = "-";
+ }
- while ((line = get_line_from_file(fp)) != NULL) {
+ do {
+ fp = xgetoptfile_sort_uniq(argv, "r");
+ while ((line = bb_get_chomped_line_from_file(fp)) != NULL) {
lines = xrealloc(lines, sizeof(char *) * (nlines + 1));
- chomp(line);
lines[nlines++] = line;
}
- }
+ bb_xferror(fp, *argv);
+ bb_fclose_nonstdin(fp);
+ } while (*++argv);
/* sort it */
qsort(lines, nlines, sizeof(char *), compare);
/* print it */
-#ifdef CONFIG_FEATURE_SORT_REVERSE
- if (reverse) {
- for (i = --nlines; 0 <= i; i--)
-#ifdef CONFIG_FEATURE_SORT_UNIQUE
- if((!unique) || (i == nlines) || (strcmp(lines[i + 1], lines[i])))
-#endif
- puts(lines[i]);
- } else
-#endif
- for (i = 0; i < nlines; i++)
-#ifdef CONFIG_FEATURE_SORT_UNIQUE
- if((!unique) || (!i) || (strcmp(lines[i - 1], lines[i])))
-#endif
- puts(lines[i]);
- return EXIT_SUCCESS;
+ i = 0;
+ --nlines;
+ if ((inc = 1 - (flags & 2)) < 0) { /* reverse */
+ i = nlines;
+ }
+ flags &= 4;
+
+ while (nlines >= 0) {
+ if (!flags || !nlines || strcmp(lines[i+inc], lines[i])) {
+ puts(lines[i]);
+ }
+ i += inc;
+ --nlines;
+ }
+
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/stty.c b/coreutils/stty.c
index a67a17c0f..a3a98d9ef 100644
--- a/coreutils/stty.c
+++ b/coreutils/stty.c
@@ -30,9 +30,9 @@
//#define TEST
+#include <stddef.h>
#include <termios.h>
#include <sys/ioctl.h>
-#include <getopt.h>
#include <sys/param.h>
#include <unistd.h>
@@ -155,13 +155,10 @@ enum speed_setting {
input_speed, output_speed, both_speeds
};
-/* What to output and how. */
-enum output_type {
- changed, all, recoverable /* Default, -a, -g. */
-};
-
/* Which member(s) of `struct termios' a mode uses. */
enum mode_type {
+ /* Do NOT change the order or values, as mode_type_flag()
+ * depends on them. */
control, input, output, local, combination
};
@@ -199,156 +196,159 @@ static const char stty_dec [] = "dec";
/* Each mode. */
struct mode_info {
const char *name; /* Name given on command line. */
- enum mode_type type; /* Which structure element to change. */
+ /* enum mode_type type; */
+ char type; /* Which structure element to change. */
char flags; /* Setting and display options. */
+ unsigned short mask; /* Other bits to turn off for this mode. */
unsigned long bits; /* Bits to set for this mode. */
- unsigned long mask; /* Other bits to turn off for this mode. */
};
+#define MI_ENTRY(N,T,F,B,M) { N, T, F, M, B }
+
static const struct mode_info mode_info[] = {
- {"parenb", control, REV, PARENB, 0 },
- {"parodd", control, REV, PARODD, 0 },
- {"cs5", control, 0, CS5, CSIZE},
- {"cs6", control, 0, CS6, CSIZE},
- {"cs7", control, 0, CS7, CSIZE},
- {"cs8", control, 0, CS8, CSIZE},
- {"hupcl", control, REV, HUPCL, 0 },
- {"hup", control, REV | OMIT, HUPCL, 0 },
- {"cstopb", control, REV, CSTOPB, 0 },
- {"cread", control, SANE_SET | REV, CREAD, 0 },
- {"clocal", control, REV, CLOCAL, 0 },
+ MI_ENTRY("parenb", control, REV, PARENB, 0 ),
+ MI_ENTRY("parodd", control, REV, PARODD, 0 ),
+ MI_ENTRY("cs5", control, 0, CS5, CSIZE),
+ MI_ENTRY("cs6", control, 0, CS6, CSIZE),
+ MI_ENTRY("cs7", control, 0, CS7, CSIZE),
+ MI_ENTRY("cs8", control, 0, CS8, CSIZE),
+ MI_ENTRY("hupcl", control, REV, HUPCL, 0 ),
+ MI_ENTRY("hup", control, REV | OMIT, HUPCL, 0 ),
+ MI_ENTRY("cstopb", control, REV, CSTOPB, 0 ),
+ MI_ENTRY("cread", control, SANE_SET | REV, CREAD, 0 ),
+ MI_ENTRY("clocal", control, REV, CLOCAL, 0 ),
#ifdef CRTSCTS
- {"crtscts", control, REV, CRTSCTS, 0 },
-#endif
- {"ignbrk", input, SANE_UNSET | REV, IGNBRK, 0 },
- {"brkint", input, SANE_SET | REV, BRKINT, 0 },
- {"ignpar", input, REV, IGNPAR, 0 },
- {"parmrk", input, REV, PARMRK, 0 },
- {"inpck", input, REV, INPCK, 0 },
- {"istrip", input, REV, ISTRIP, 0 },
- {"inlcr", input, SANE_UNSET | REV, INLCR, 0 },
- {"igncr", input, SANE_UNSET | REV, IGNCR, 0 },
- {"icrnl", input, SANE_SET | REV, ICRNL, 0 },
- {"ixon", input, REV, IXON, 0 },
- {"ixoff", input, SANE_UNSET | REV, IXOFF, 0 },
- {"tandem", input, REV | OMIT, IXOFF, 0 },
+ MI_ENTRY("crtscts", control, REV, CRTSCTS, 0 ),
+#endif
+ MI_ENTRY("ignbrk", input, SANE_UNSET | REV, IGNBRK, 0 ),
+ MI_ENTRY("brkint", input, SANE_SET | REV, BRKINT, 0 ),
+ MI_ENTRY("ignpar", input, REV, IGNPAR, 0 ),
+ MI_ENTRY("parmrk", input, REV, PARMRK, 0 ),
+ MI_ENTRY("inpck", input, REV, INPCK, 0 ),
+ MI_ENTRY("istrip", input, REV, ISTRIP, 0 ),
+ MI_ENTRY("inlcr", input, SANE_UNSET | REV, INLCR, 0 ),
+ MI_ENTRY("igncr", input, SANE_UNSET | REV, IGNCR, 0 ),
+ MI_ENTRY("icrnl", input, SANE_SET | REV, ICRNL, 0 ),
+ MI_ENTRY("ixon", input, REV, IXON, 0 ),
+ MI_ENTRY("ixoff", input, SANE_UNSET | REV, IXOFF, 0 ),
+ MI_ENTRY("tandem", input, REV | OMIT, IXOFF, 0 ),
#ifdef IUCLC
- {"iuclc", input, SANE_UNSET | REV, IUCLC, 0 },
+ MI_ENTRY("iuclc", input, SANE_UNSET | REV, IUCLC, 0 ),
#endif
#ifdef IXANY
- {"ixany", input, SANE_UNSET | REV, IXANY, 0 },
+ MI_ENTRY("ixany", input, SANE_UNSET | REV, IXANY, 0 ),
#endif
#ifdef IMAXBEL
- {"imaxbel", input, SANE_SET | REV, IMAXBEL, 0 },
+ MI_ENTRY("imaxbel", input, SANE_SET | REV, IMAXBEL, 0 ),
#endif
- {"opost", output, SANE_SET | REV, OPOST, 0 },
+ MI_ENTRY("opost", output, SANE_SET | REV, OPOST, 0 ),
#ifdef OLCUC
- {"olcuc", output, SANE_UNSET | REV, OLCUC, 0 },
+ MI_ENTRY("olcuc", output, SANE_UNSET | REV, OLCUC, 0 ),
#endif
#ifdef OCRNL
- {"ocrnl", output, SANE_UNSET | REV, OCRNL, 0 },
+ MI_ENTRY("ocrnl", output, SANE_UNSET | REV, OCRNL, 0 ),
#endif
#ifdef ONLCR
- {"onlcr", output, SANE_SET | REV, ONLCR, 0 },
+ MI_ENTRY("onlcr", output, SANE_SET | REV, ONLCR, 0 ),
#endif
#ifdef ONOCR
- {"onocr", output, SANE_UNSET | REV, ONOCR, 0 },
+ MI_ENTRY("onocr", output, SANE_UNSET | REV, ONOCR, 0 ),
#endif
#ifdef ONLRET
- {"onlret", output, SANE_UNSET | REV, ONLRET, 0 },
+ MI_ENTRY("onlret", output, SANE_UNSET | REV, ONLRET, 0 ),
#endif
#ifdef OFILL
- {"ofill", output, SANE_UNSET | REV, OFILL, 0 },
+ MI_ENTRY("ofill", output, SANE_UNSET | REV, OFILL, 0 ),
#endif
#ifdef OFDEL
- {"ofdel", output, SANE_UNSET | REV, OFDEL, 0 },
+ MI_ENTRY("ofdel", output, SANE_UNSET | REV, OFDEL, 0 ),
#endif
#ifdef NLDLY
- {"nl1", output, SANE_UNSET, NL1, NLDLY},
- {"nl0", output, SANE_SET, NL0, NLDLY},
+ MI_ENTRY("nl1", output, SANE_UNSET, NL1, NLDLY),
+ MI_ENTRY("nl0", output, SANE_SET, NL0, NLDLY),
#endif
#ifdef CRDLY
- {"cr3", output, SANE_UNSET, CR3, CRDLY},
- {"cr2", output, SANE_UNSET, CR2, CRDLY},
- {"cr1", output, SANE_UNSET, CR1, CRDLY},
- {"cr0", output, SANE_SET, CR0, CRDLY},
+ MI_ENTRY("cr3", output, SANE_UNSET, CR3, CRDLY),
+ MI_ENTRY("cr2", output, SANE_UNSET, CR2, CRDLY),
+ MI_ENTRY("cr1", output, SANE_UNSET, CR1, CRDLY),
+ MI_ENTRY("cr0", output, SANE_SET, CR0, CRDLY),
#endif
#ifdef TABDLY
- {"tab3", output, SANE_UNSET, TAB3, TABDLY},
- {"tab2", output, SANE_UNSET, TAB2, TABDLY},
- {"tab1", output, SANE_UNSET, TAB1, TABDLY},
- {"tab0", output, SANE_SET, TAB0, TABDLY},
+ MI_ENTRY("tab3", output, SANE_UNSET, TAB3, TABDLY),
+ MI_ENTRY("tab2", output, SANE_UNSET, TAB2, TABDLY),
+ MI_ENTRY("tab1", output, SANE_UNSET, TAB1, TABDLY),
+ MI_ENTRY("tab0", output, SANE_SET, TAB0, TABDLY),
#else
# ifdef OXTABS
- {"tab3", output, SANE_UNSET, OXTABS, 0 },
+ MI_ENTRY("tab3", output, SANE_UNSET, OXTABS, 0 ),
# endif
#endif
#ifdef BSDLY
- {"bs1", output, SANE_UNSET, BS1, BSDLY},
- {"bs0", output, SANE_SET, BS0, BSDLY},
+ MI_ENTRY("bs1", output, SANE_UNSET, BS1, BSDLY),
+ MI_ENTRY("bs0", output, SANE_SET, BS0, BSDLY),
#endif
#ifdef VTDLY
- {"vt1", output, SANE_UNSET, VT1, VTDLY},
- {"vt0", output, SANE_SET, VT0, VTDLY},
+ MI_ENTRY("vt1", output, SANE_UNSET, VT1, VTDLY),
+ MI_ENTRY("vt0", output, SANE_SET, VT0, VTDLY),
#endif
#ifdef FFDLY
- {"ff1", output, SANE_UNSET, FF1, FFDLY},
- {"ff0", output, SANE_SET, FF0, FFDLY},
+ MI_ENTRY("ff1", output, SANE_UNSET, FF1, FFDLY),
+ MI_ENTRY("ff0", output, SANE_SET, FF0, FFDLY),
#endif
- {"isig", local, SANE_SET | REV, ISIG, 0 },
- {"icanon", local, SANE_SET | REV, ICANON, 0 },
+ MI_ENTRY("isig", local, SANE_SET | REV, ISIG, 0 ),
+ MI_ENTRY("icanon", local, SANE_SET | REV, ICANON, 0 ),
#ifdef IEXTEN
- {"iexten", local, SANE_SET | REV, IEXTEN, 0 },
-#endif
- {"echo", local, SANE_SET | REV, ECHO, 0 },
- {"echoe", local, SANE_SET | REV, ECHOE, 0 },
- {"crterase", local, REV | OMIT, ECHOE, 0 },
- {"echok", local, SANE_SET | REV, ECHOK, 0 },
- {"echonl", local, SANE_UNSET | REV, ECHONL, 0 },
- {"noflsh", local, SANE_UNSET | REV, NOFLSH, 0 },
+ MI_ENTRY("iexten", local, SANE_SET | REV, IEXTEN, 0 ),
+#endif
+ MI_ENTRY("echo", local, SANE_SET | REV, ECHO, 0 ),
+ MI_ENTRY("echoe", local, SANE_SET | REV, ECHOE, 0 ),
+ MI_ENTRY("crterase", local, REV | OMIT, ECHOE, 0 ),
+ MI_ENTRY("echok", local, SANE_SET | REV, ECHOK, 0 ),
+ MI_ENTRY("echonl", local, SANE_UNSET | REV, ECHONL, 0 ),
+ MI_ENTRY("noflsh", local, SANE_UNSET | REV, NOFLSH, 0 ),
#ifdef XCASE
- {"xcase", local, SANE_UNSET | REV, XCASE, 0 },
+ MI_ENTRY("xcase", local, SANE_UNSET | REV, XCASE, 0 ),
#endif
#ifdef TOSTOP
- {"tostop", local, SANE_UNSET | REV, TOSTOP, 0 },
+ MI_ENTRY("tostop", local, SANE_UNSET | REV, TOSTOP, 0 ),
#endif
#ifdef ECHOPRT
- {"echoprt", local, SANE_UNSET | REV, ECHOPRT, 0 },
- {"prterase", local, REV | OMIT, ECHOPRT, 0 },
+ MI_ENTRY("echoprt", local, SANE_UNSET | REV, ECHOPRT, 0 ),
+ MI_ENTRY("prterase", local, REV | OMIT, ECHOPRT, 0 ),
#endif
#ifdef ECHOCTL
- {"echoctl", local, SANE_SET | REV, ECHOCTL, 0 },
- {"ctlecho", local, REV | OMIT, ECHOCTL, 0 },
+ MI_ENTRY("echoctl", local, SANE_SET | REV, ECHOCTL, 0 ),
+ MI_ENTRY("ctlecho", local, REV | OMIT, ECHOCTL, 0 ),
#endif
#ifdef ECHOKE
- {"echoke", local, SANE_SET | REV, ECHOKE, 0 },
- {"crtkill", local, REV | OMIT, ECHOKE, 0 },
-#endif
- {evenp, combination, REV | OMIT, 0, 0 },
- {parity, combination, REV | OMIT, 0, 0 },
- {stty_oddp, combination, REV | OMIT, 0, 0 },
- {stty_nl, combination, REV | OMIT, 0, 0 },
- {stty_ek, combination, OMIT, 0, 0 },
- {stty_sane, combination, OMIT, 0, 0 },
- {cooked, combination, REV | OMIT, 0, 0 },
- {raw, combination, REV | OMIT, 0, 0 },
- {stty_pass8, combination, REV | OMIT, 0, 0 },
- {litout, combination, REV | OMIT, 0, 0 },
- {cbreak, combination, REV | OMIT, 0, 0 },
+ MI_ENTRY("echoke", local, SANE_SET | REV, ECHOKE, 0 ),
+ MI_ENTRY("crtkill", local, REV | OMIT, ECHOKE, 0 ),
+#endif
+ MI_ENTRY(evenp, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(parity, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(stty_oddp, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(stty_nl, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(stty_ek, combination, OMIT, 0, 0 ),
+ MI_ENTRY(stty_sane, combination, OMIT, 0, 0 ),
+ MI_ENTRY(cooked, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(raw, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(stty_pass8, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(litout, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(cbreak, combination, REV | OMIT, 0, 0 ),
#ifdef IXANY
- {decctlq, combination, REV | OMIT, 0, 0 },
+ MI_ENTRY(decctlq, combination, REV | OMIT, 0, 0 ),
#endif
#if defined (TABDLY) || defined (OXTABS)
- {stty_tabs, combination, REV | OMIT, 0, 0 },
+ MI_ENTRY(stty_tabs, combination, REV | OMIT, 0, 0 ),
#endif
#if defined(XCASE) && defined(IUCLC) && defined(OLCUC)
- {stty_lcase, combination, REV | OMIT, 0, 0 },
- {stty_LCASE, combination, REV | OMIT, 0, 0 },
+ MI_ENTRY(stty_lcase, combination, REV | OMIT, 0, 0 ),
+ MI_ENTRY(stty_LCASE, combination, REV | OMIT, 0, 0 ),
#endif
- {stty_crt, combination, OMIT, 0, 0 },
- {stty_dec, combination, OMIT, 0, 0 },
+ MI_ENTRY(stty_crt, combination, OMIT, 0, 0 ),
+ MI_ENTRY(stty_dec, combination, OMIT, 0, 0 ),
};
static const int NUM_mode_info =
@@ -359,7 +359,7 @@ static const int NUM_mode_info =
struct control_info {
const char *name; /* Name given on command line. */
unsigned char saneval; /* Value to set for `stty sane'. */
- int offset; /* Offset in c_cc. */
+ unsigned char offset; /* Offset in c_cc. */
};
/* Control characters. */
@@ -408,7 +408,6 @@ static const int NUM_control_info =
static const char * visible(unsigned int ch);
-static unsigned long baud_to_value(speed_t speed);
static int recover_mode(char *arg, struct termios *mode);
static int screen_columns(void);
static int set_mode(const struct mode_info *info,
@@ -416,12 +415,11 @@ static int set_mode(const struct mode_info *info,
static speed_t string_to_baud(const char *arg);
static tcflag_t* mode_type_flag(enum mode_type type, struct termios *mode);
static void display_all(struct termios *mode, int fd,
- const char *device_name);
-static void display_changed(struct termios *mode);
-static void display_recoverable(struct termios *mode);
-static void display_settings(enum output_type output_type,
- struct termios *mode, int fd,
- const char *device_name);
+ const char *device_name);
+static void display_changed(struct termios *mode, int fd,
+ const char *device_name);
+static void display_recoverable(struct termios *mode, int fd,
+ const char *device_name);
static void display_speed(struct termios *mode, int fancy);
static void display_window_size(int fancy, int fd,
const char *device_name);
@@ -479,7 +477,7 @@ extern int main(int argc, char **argv)
#endif
{
struct termios mode;
- enum output_type output_type;
+ void (*output_func)(struct termios *, int, const char *);
int optc;
int require_set_attr;
int speed_was_set;
@@ -491,7 +489,7 @@ extern int main(int argc, char **argv)
int fd;
const char *device_name;
- output_type = changed;
+ output_func = display_changed;
verbose_output = 0;
recoverable_output = 0;
@@ -502,17 +500,17 @@ extern int main(int argc, char **argv)
switch (optc) {
case 'a':
verbose_output = 1;
- output_type = all;
+ output_func = display_all;
break;
case 'g':
recoverable_output = 1;
- output_type = recoverable;
+ output_func = display_recoverable;
break;
case 'F':
if (file_name)
- error_msg_and_die("only one device may be specified");
+ bb_error_msg_and_die("only one device may be specified");
file_name = optarg;
break;
@@ -529,12 +527,12 @@ extern int main(int argc, char **argv)
noargs = 0;
/* Specifying both -a and -g gets an error. */
- if (verbose_output && recoverable_output)
- error_msg_and_die ("verbose and stty-readable output styles are mutually exclusive");
+ if (verbose_output & recoverable_output)
+ bb_error_msg_and_die ("verbose and stty-readable output styles are mutually exclusive");
/* Specifying any other arguments with -a or -g gets an error. */
- if (!noargs && (verbose_output || recoverable_output))
- error_msg_and_die ("modes may not be set when specifying an output style");
+ if (~noargs & (verbose_output | recoverable_output))
+ bb_error_msg_and_die ("modes may not be set when specifying an output style");
/* FIXME: it'd be better not to open the file until we've verified
that all arguments are valid. Otherwise, we could end up doing
@@ -547,26 +545,26 @@ extern int main(int argc, char **argv)
device_name = file_name;
fd = open(device_name, O_RDONLY | O_NONBLOCK);
if (fd < 0)
- perror_msg_and_die("%s", device_name);
+ bb_perror_msg_and_die("%s", device_name);
if ((fdflags = fcntl(fd, F_GETFL)) == -1
|| fcntl(fd, F_SETFL, fdflags & ~O_NONBLOCK) < 0)
- perror_msg_and_die("%s: couldn't reset non-blocking mode",
+ bb_perror_msg_and_die("%s: couldn't reset non-blocking mode",
device_name);
} else {
fd = 0;
- device_name = "standard input";
+ device_name = bb_msg_standard_input;
}
/* Initialize to all zeroes so there is no risk memcmp will report a
spurious difference in an uninitialized portion of the structure. */
memset(&mode, 0, sizeof(mode));
if (tcgetattr(fd, &mode))
- perror_msg_and_die("%s", device_name);
+ bb_perror_msg_and_die("%s", device_name);
- if (verbose_output || recoverable_output || noargs) {
+ if (verbose_output | recoverable_output | noargs) {
max_col = screen_columns();
current_col = 0;
- display_settings(output_type, &mode, fd, device_name);
+ output_func(&mode, fd, device_name);
return EXIT_SUCCESS;
}
@@ -610,13 +608,13 @@ extern int main(int argc, char **argv)
}
if (match_found == 0 && reversed)
- error_msg_and_die("invalid argument `%s'", --argv[k]);
+ bb_error_msg_and_die("invalid argument `%s'", --argv[k]);
if (match_found == 0)
for (i = 0; i < NUM_control_info; ++i)
if (STREQ(argv[k], control_info[i].name)) {
if (k == argc - 1)
- error_msg_and_die("missing argument to `%s'", argv[k]);
+ bb_error_msg_and_die("missing argument to `%s'", argv[k]);
match_found = 1;
++k;
set_control_char(&control_info[i], argv[k], &mode);
@@ -627,14 +625,14 @@ extern int main(int argc, char **argv)
if (match_found == 0) {
if (STREQ(argv[k], "ispeed")) {
if (k == argc - 1)
- error_msg_and_die("missing argument to `%s'", argv[k]);
+ bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k;
set_speed(input_speed, argv[k], &mode);
speed_was_set = 1;
require_set_attr = 1;
} else if (STREQ(argv[k], "ospeed")) {
if (k == argc - 1)
- error_msg_and_die("missing argument to `%s'", argv[k]);
+ bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k;
set_speed(output_speed, argv[k], &mode);
speed_was_set = 1;
@@ -643,16 +641,16 @@ extern int main(int argc, char **argv)
#ifdef TIOCGWINSZ
else if (STREQ(argv[k], "rows")) {
if (k == argc - 1)
- error_msg_and_die("missing argument to `%s'", argv[k]);
+ bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k;
- set_window_size((int) parse_number(argv[k], stty_suffixes),
+ set_window_size((int) bb_xparse_number(argv[k], stty_suffixes),
-1, fd, device_name);
} else if (STREQ(argv[k], "cols") || STREQ(argv[k], "columns")) {
if (k == argc - 1)
- error_msg_and_die("missing argument to `%s'", argv[k]);
+ bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k;
set_window_size(-1,
- (int) parse_number(argv[k], stty_suffixes),
+ (int) bb_xparse_number(argv[k], stty_suffixes),
fd, device_name);
} else if (STREQ(argv[k], "size")) {
max_col = screen_columns();
@@ -663,9 +661,9 @@ extern int main(int argc, char **argv)
#ifdef HAVE_C_LINE
else if (STREQ(argv[k], "line")) {
if (k == argc - 1)
- error_msg_and_die("missing argument to `%s'", argv[k]);
+ bb_error_msg_and_die("missing argument to `%s'", argv[k]);
++k;
- mode.c_line = parse_number(argv[k], stty_suffixes);
+ mode.c_line = bb_xparse_number(argv[k], stty_suffixes);
require_set_attr = 1;
}
#endif
@@ -679,7 +677,7 @@ extern int main(int argc, char **argv)
speed_was_set = 1;
require_set_attr = 1;
} else
- error_msg_and_die("invalid argument `%s'", argv[k]);
+ bb_error_msg_and_die("invalid argument `%s'", argv[k]);
}
}
@@ -687,7 +685,7 @@ extern int main(int argc, char **argv)
struct termios new_mode;
if (tcsetattr(fd, TCSADRAIN, &mode))
- perror_msg_and_die("%s", device_name);
+ bb_perror_msg_and_die("%s", device_name);
/* POSIX (according to Zlotnick's book) tcsetattr returns zero if
it performs *any* of the requested operations. This means it
@@ -700,7 +698,7 @@ extern int main(int argc, char **argv)
spurious difference in an uninitialized portion of the structure. */
memset(&new_mode, 0, sizeof(new_mode));
if (tcgetattr(fd, &new_mode))
- perror_msg_and_die("%s", device_name);
+ bb_perror_msg_and_die("%s", device_name);
/* Normally, one shouldn't use memcmp to compare structures that
may have `holes' containing uninitialized data, but we have been
@@ -723,7 +721,7 @@ extern int main(int argc, char **argv)
new_mode.c_cflag &= (~CIBAUD);
if (speed_was_set || memcmp(&mode, &new_mode, sizeof(mode)) != 0)
#endif
- error_msg_and_die ("%s: unable to perform all requested operations",
+ bb_error_msg_and_die ("%s: unable to perform all requested operations",
device_name);
}
}
@@ -896,9 +894,9 @@ set_mode(const struct mode_info *info, int reversed, struct termios *mode)
#endif
}
} else if (reversed)
- *bitsp = *bitsp & ~info->mask & ~info->bits;
+ *bitsp = *bitsp & ~((unsigned long)info->mask) & ~info->bits;
else
- *bitsp = (*bitsp & ~info->mask) | info->bits;
+ *bitsp = (*bitsp & ~((unsigned long)info->mask)) | info->bits;
return 1;
}
@@ -910,7 +908,7 @@ set_control_char(const struct control_info *info, const char *arg,
unsigned char value;
if (info->name == stty_min || info->name == stty_time)
- value = parse_number(arg, stty_suffixes);
+ value = bb_xparse_number(arg, stty_suffixes);
else if (arg[0] == '\0' || arg[1] == '\0')
value = arg[0];
else if (STREQ(arg, "^-") || STREQ(arg, "undef"))
@@ -921,7 +919,7 @@ set_control_char(const struct control_info *info, const char *arg,
else
value = arg[1] & ~0140; /* Non-letters get weird results. */
} else
- value = parse_number(arg, stty_suffixes);
+ value = bb_xparse_number(arg, stty_suffixes);
mode->c_cc[info->offset] = value;
}
@@ -931,10 +929,13 @@ set_speed(enum speed_setting type, const char *arg, struct termios *mode)
speed_t baud;
baud = string_to_baud(arg);
- if (type == input_speed || type == both_speeds)
+
+ if (type != output_speed) { /* either input or both */
cfsetispeed(mode, baud);
- if (type == output_speed || type == both_speeds)
+ }
+ if (type != input_speed) { /* either output or both */
cfsetospeed(mode, baud);
+ }
}
#ifdef TIOCGWINSZ
@@ -953,7 +954,7 @@ set_window_size(int rows, int cols, int fd, const char *device_name)
if (get_win_size(fd, &win)) {
if (errno != EINVAL)
- perror_msg_and_die("%s", device_name);
+ bb_perror_msg_and_die("%s", device_name);
memset(&win, 0, sizeof(win));
}
@@ -975,32 +976,28 @@ set_window_size(int rows, int cols, int fd, const char *device_name)
ttysz.ts_lines = win.ws_row;
ttysz.ts_cols = win.ws_col;
- win.ws_row = 1;
- win.ws_col = 1;
-
- if (ioctl(fd, TIOCSWINSZ, (char *) &win))
- perror_msg_and_die("%s", device_name);
+ win.ws_row = win.ws_col = 1;
- if (ioctl(fd, TIOCSSIZE, (char *) &ttysz))
- perror_msg_and_die("%s", device_name);
+ if ((ioctl(fd, TIOCSWINSZ, (char *) &win) != 0)
+ || (ioctl(fd, TIOCSSIZE, (char *) &ttysz) != 0)) {
+ bb_perror_msg_and_die("%s", device_name);
return;
}
# endif
if (ioctl(fd, TIOCSWINSZ, (char *) &win))
- perror_msg_and_die("%s", device_name);
+ bb_perror_msg_and_die("%s", device_name);
}
static void display_window_size(int fancy, int fd, const char *device_name)
{
+ const char *fmt_str = "%s" "\0" "%s: no size information for this device";
struct winsize win;
if (get_win_size(fd, &win)) {
- if (errno != EINVAL)
- perror_msg_and_die("%s", device_name);
- if (!fancy)
- perror_msg_and_die("%s: no size information for this device",
- device_name);
+ if ((errno != EINVAL) || ((fmt_str += 2), !fancy)) {
+ bb_perror_msg_and_die(fmt_str, device_name);
+ }
} else {
wrapf(fancy ? "rows %d; columns %d;" : "%d %d\n",
win.ws_row, win.ws_col);
@@ -1012,6 +1009,9 @@ static void display_window_size(int fancy, int fd, const char *device_name)
static int screen_columns(void)
{
+ int columns;
+ const char *s;
+
#ifdef TIOCGWINSZ
struct winsize win;
@@ -1025,51 +1025,29 @@ static int screen_columns(void)
return win.ws_col;
#endif
- if (getenv("COLUMNS"))
- return atoi(getenv("COLUMNS"));
- return 80;
-}
-
-static tcflag_t *mode_type_flag(enum mode_type type, struct termios *mode)
-{
- switch (type) {
- case control:
- return &mode->c_cflag;
-
- case input:
- return &mode->c_iflag;
-
- case output:
- return &mode->c_oflag;
-
- case local:
- return &mode->c_lflag;
-
- default: /* combination: */
- return NULL;
+ columns = 80;
+ if ((s = getenv("COLUMNS"))) {
+ columns = atoi(s);
}
+ return columns;
}
-static void
-display_settings(enum output_type output_type, struct termios *mode,
- int fd, const char *device_name)
+static tcflag_t *mode_type_flag(enum mode_type type, struct termios *mode)
{
- switch (output_type) {
- case changed:
- display_changed(mode);
- break;
-
- case all:
- display_all(mode, fd, device_name);
- break;
-
- case recoverable:
- display_recoverable(mode);
- break;
+ static const unsigned char tcflag_offsets[] = {
+ offsetof(struct termios, c_cflag), /* control */
+ offsetof(struct termios, c_iflag), /* input */
+ offsetof(struct termios, c_oflag), /* output */
+ offsetof(struct termios, c_lflag) /* local */
+ };
+
+ if (((unsigned int) type) <= local) {
+ return (tcflag_t *)(((char *) mode) + tcflag_offsets[(int)type]);
}
+ return NULL;
}
-static void display_changed(struct termios *mode)
+static void display_changed(struct termios *mode, int fd, const char *device_name)
{
int i;
int empty_line;
@@ -1206,18 +1184,25 @@ display_all(struct termios *mode, int fd, const char *device_name)
static void display_speed(struct termios *mode, int fancy)
{
- if (cfgetispeed(mode) == 0 || cfgetispeed(mode) == cfgetospeed(mode))
- wrapf(fancy ? "speed %lu baud;" : "%lu\n",
- baud_to_value(cfgetospeed(mode)));
- else
- wrapf(fancy ? "ispeed %lu baud; ospeed %lu baud;" : "%lu %lu\n",
- baud_to_value(cfgetispeed(mode)),
- baud_to_value(cfgetospeed(mode)));
+ unsigned long ispeed, ospeed;
+ const char *fmt_str =
+ "%lu %lu\n\0" "ispeed %lu baud; ospeed %lu baud;\0"
+ "%lu\n\0" "\0\0\0\0" "speed %lu baud;";
+
+ ospeed = ispeed = cfgetispeed(mode);
+ if (ispeed == 0 || ispeed == (ospeed = cfgetospeed(mode))) {
+ ispeed = ospeed; /* in case ispeed was 0 */
+ fmt_str += 43;
+ }
+ if (fancy) {
+ fmt_str += 9;
+ }
+ wrapf(fmt_str, bb_baud_to_value(ispeed), bb_baud_to_value(ospeed));
if (!fancy)
current_col = 0;
}
-static void display_recoverable(struct termios *mode)
+static void display_recoverable(struct termios *mode, int fd, const char *device_name)
{
int i;
@@ -1259,62 +1244,9 @@ static int recover_mode(char *arg, struct termios *mode)
return 1;
}
-struct speed_map {
- speed_t speed; /* Internal form. */
- unsigned long value; /* Numeric value. */
-};
-
-static const struct speed_map speeds[] = {
- {B0, 0},
- {B50, 50},
- {B75, 75},
- {B110, 110},
- {B134, 134},
- {B150, 150},
- {B200, 200},
- {B300, 300},
- {B600, 600},
- {B1200, 1200},
- {B1800, 1800},
- {B2400, 2400},
- {B4800, 4800},
- {B9600, 9600},
- {B19200, 19200},
- {B38400, 38400},
-#ifdef B57600
- {B57600, 57600},
-#endif
-#ifdef B115200
- {B115200, 115200},
-#endif
-#ifdef B230400
- {B230400, 230400},
-#endif
-#ifdef B460800
- {B460800, 460800},
-#endif
-};
-
-static const int NUM_SPEEDS = (sizeof(speeds) / sizeof(struct speed_map));
-
static speed_t string_to_baud(const char *arg)
{
- int i;
-
- for (i = 0; i < NUM_SPEEDS; ++i)
- if (parse_number(arg, 0) == speeds[i].value)
- return speeds[i].speed;
- return (speed_t) - 1;
-}
-
-static unsigned long baud_to_value(speed_t speed)
-{
- int i;
-
- for (i = 0; i < NUM_SPEEDS; ++i)
- if (speed == speeds[i].speed)
- return speeds[i].value;
- return 0;
+ return bb_value_to_baud(bb_xparse_number(arg, 0));
}
static void sane_mode(struct termios *mode)
@@ -1333,10 +1265,12 @@ static void sane_mode(struct termios *mode)
for (i = 0; i < NUM_mode_info; ++i) {
if (mode_info[i].flags & SANE_SET) {
bitsp = mode_type_flag(mode_info[i].type, mode);
- *bitsp = (*bitsp & ~mode_info[i].mask) | mode_info[i].bits;
+ *bitsp = (*bitsp & ~((unsigned long)mode_info[i].mask))
+ | mode_info[i].bits;
} else if (mode_info[i].flags & SANE_UNSET) {
bitsp = mode_type_flag(mode_info[i].type, mode);
- *bitsp = *bitsp & ~mode_info[i].mask & ~mode_info[i].bits;
+ *bitsp = *bitsp & ~((unsigned long)mode_info[i].mask)
+ & ~mode_info[i].bits;
}
}
}
@@ -1349,47 +1283,32 @@ static const char *visible(unsigned int ch)
static char buf[10];
char *bpout = buf;
- if (ch == _POSIX_VDISABLE)
+ if (ch == _POSIX_VDISABLE) {
return "<undef>";
+ }
- if (ch >= 32) {
- if (ch < 127)
- *bpout++ = ch;
- else if (ch == 127) {
- *bpout++ = '^';
- *bpout++ = '?';
- } else {
- *bpout++ = 'M', *bpout++ = '-';
- if (ch >= 128 + 32) {
- if (ch < 128 + 127)
- *bpout++ = ch - 128;
- else {
- *bpout++ = '^';
- *bpout++ = '?';
- }
- } else {
- *bpout++ = '^';
- *bpout++ = ch - 128 + 64;
- }
- }
- } else {
+ if (ch >= 128) {
+ ch -= 128;
+ *bpout++ = 'M';
+ *bpout++ = '-';
+ }
+
+ if (ch < 32) {
*bpout++ = '^';
*bpout++ = ch + 64;
+ } else if (ch < 127) {
+ *bpout++ = ch;
+ } else {
+ *bpout++ = '^';
+ *bpout++ = '?';
}
+
*bpout = '\0';
return (const char *) buf;
}
#ifdef TEST
-const char *applet_name = "stty";
+const char *bb_applet_name = "stty";
#endif
-
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
diff --git a/coreutils/sync.c b/coreutils/sync.c
index d58168065..84746311f 100644
--- a/coreutils/sync.c
+++ b/coreutils/sync.c
@@ -20,15 +20,17 @@
*
*/
-#include <stdio.h>
+/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
+
#include <stdlib.h>
#include <unistd.h>
#include "busybox.h"
extern int sync_main(int argc, char **argv)
{
- if (argc > 1 && **(argv + 1) == '-')
- show_usage();
+ bb_warn_ignoring_args(argc - 1);
+
sync();
+
return(EXIT_SUCCESS);
}
diff --git a/coreutils/tail.c b/coreutils/tail.c
index 1703eefc6..8e0adf5b5 100644
--- a/coreutils/tail.c
+++ b/coreutils/tail.c
@@ -2,7 +2,6 @@
/*
* Mini tail implementation for busybox
*
- *
* Copyright (C) 2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
*
* This program is free software; you can redistribute it and/or modify
@@ -21,14 +20,30 @@
*
*/
+/* BB_AUDIT SUSv3 compliant (need fancy for -c) */
+/* BB_AUDIT GNU compatible -c, -q, and -v options in 'fancy' configuration. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/tail.html */
-#include <fcntl.h>
-#include <getopt.h>
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Pretty much rewritten to fix numerous bugs and reduce realloc() calls.
+ * Bugs fixed (although I may have forgotten one or two... it was pretty bad)
+ * 1) mixing printf/write without fflush()ing stdout
+ * 2) no check that any open files are present
+ * 3) optstring had -q taking an arg
+ * 4) no error checking on write in some cases, and a warning even then
+ * 5) q and s interaction bug
+ * 6) no check for lseek error
+ * 7) lseek attempted when count==0 even if arg was +0 (from top)
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
#include <string.h>
#include <ctype.h>
-#include <stdlib.h>
#include <unistd.h>
-#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/stat.h>
#include "busybox.h"
static const struct suffix_mult tail_suffixes[] = {
@@ -38,234 +53,287 @@ static const struct suffix_mult tail_suffixes[] = {
{ NULL, 0 }
};
-static const int BYTES = 0;
-static const int LINES = 1;
-
-static char *tailbuf;
-static int taillen;
-static int newline;
+static int status
+#if EXIT_SUCCESS != 0
+ = EXIT_SUCCESS /* If it is 0 (paranoid check), let bss initialize it. */
+#endif
+ ;
-static void tailbuf_append(char *buf, int len)
+static void tail_xprint_header(const char *fmt, const char *filename)
{
- tailbuf = xrealloc(tailbuf, taillen + len);
- memcpy(tailbuf + taillen, buf, len);
- taillen += len;
+ /* If we get an output error, there is really no sense in continuing. */
+ if (dprintf(STDOUT_FILENO, fmt, filename) < 0) {
+ bb_perror_nomsg_and_die();
+ }
}
-static void tailbuf_trunc(void)
+/* len should probably be size_t */
+static void tail_xbb_full_write(const char *buf, size_t len)
{
- char *s;
- s = memchr(tailbuf, '\n', taillen);
- memmove(tailbuf, s + 1, taillen - ((s + 1) - tailbuf));
- taillen -= (s + 1) - tailbuf;
- newline = 0;
+ /* If we get a write error, there is really no sense in continuing. */
+ if (bb_full_write(STDOUT_FILENO, buf, len) < 0) {
+ bb_perror_nomsg_and_die();
+ }
}
-int tail_main(int argc, char **argv)
+static ssize_t tail_read(int fd, char *buf, size_t count)
{
- int from_top = 0, units = LINES, count = 10, sleep_period = 1;
- int show_headers = 0, hide_headers = 0, follow = 0;
- int *fds, nfiles = 0, status = EXIT_SUCCESS, nread, nwrite, seen = 0;
- char *s, *start, *end, buf[BUFSIZ];
- int i, opt;
-
- if (argc >= 2) {
- int line_num;
- switch (argv[1][0]) {
- case '+':
- from_top = 1;
- /* FALLS THROUGH */
- case '-':
- line_num = atoi(&argv[1][1]);
- if (line_num != 0) {
- optind = 2;
- count = line_num;
- }
- break;
- }
+ ssize_t r;
+
+ if ((r = safe_read(fd, buf, count)) < 0) {
+ bb_perror_msg("read");
+ status = EXIT_FAILURE;
}
+ return r;
+}
+
+static const char tail_opts[] =
+ "fn:"
+#ifdef CONFIG_FEATURE_FANCY_TAIL
+ "c:qs:v"
+#endif
+ ;
+
+static const char header_fmt[] = "\n==> %s <==\n";
+
+int tail_main(int argc, char **argv)
+{
+ long count = 10;
+ unsigned int sleep_period = 1;
+ int from_top = 0;
+ int follow = 0;
+ int header_threshhold = 1;
#ifdef CONFIG_FEATURE_FANCY_TAIL
- while ((opt = getopt(argc, argv, "c:fn:q:s:v")) > 0) {
-#else
- while ((opt = getopt(argc, argv, "fn:")) > 0) {
+ int count_bytes = 0;
#endif
+
+ char *tailbuf;
+ size_t tailbufsize;
+ int taillen = 0;
+ int newline = 0;
+
+ int *fds, nfiles, nread, nwrite, seen, i, opt;
+ char *s, *buf;
+ const char *fmt;
+
+ /* Allow legacy syntax of an initial numeric option without -n. */
+ if ((argv[1][0] == '+')
+ || ((argv[1][0] == '-')
+ /* && (isdigit)(argv[1][1]) */
+ && (((unsigned int)(argv[1][1] - '0')) <= 9))
+ ) {
+ optind = 2;
+ optarg = argv[1];
+ goto GET_COUNT;
+ }
+
+ while ((opt = getopt(argc, argv, tail_opts)) > 0) {
switch (opt) {
case 'f':
follow = 1;
break;
#ifdef CONFIG_FEATURE_FANCY_TAIL
case 'c':
- units = BYTES;
+ count_bytes = 1;
/* FALLS THROUGH */
#endif
case 'n':
- count = parse_number(optarg, tail_suffixes);
- if (count < 0)
- count = -count;
- if (optarg[0] == '+')
+ GET_COUNT:
+ count = bb_xgetlarg10_sfx(optarg, tail_suffixes);
+ /* Note: Leading whitespace is an error trapped above. */
+ if (*optarg == '+') {
from_top = 1;
+ } else {
+ from_top = 0;
+ }
+ if (count < 0) {
+ count = -count;
+ }
break;
#ifdef CONFIG_FEATURE_FANCY_TAIL
case 'q':
- hide_headers = 1;
+ header_threshhold = INT_MAX;
break;
case 's':
- sleep_period = parse_number(optarg, 0);
+ sleep_period =bb_xgetularg10_bnd(optarg, 0, UINT_MAX);
break;
case 'v':
- show_headers = 1;
+ header_threshhold = 0;
break;
#endif
default:
- show_usage();
+ bb_show_usage();
}
}
/* open all the files */
fds = (int *)xmalloc(sizeof(int) * (argc - optind + 1));
- if (argc == optind) {
- fds[nfiles++] = STDIN_FILENO;
- argv[optind] = "standard input";
- } else {
- for (i = optind; i < argc; i++) {
- if (strcmp(argv[i], "-") == 0) {
- fds[nfiles++] = STDIN_FILENO;
- argv[i] = "standard input";
- } else if ((fds[nfiles++] = open(argv[i], O_RDONLY)) < 0) {
- perror_msg("%s", argv[i]);
- status = EXIT_FAILURE;
- }
+
+ argv += optind;
+ nfiles = i = 0;
+
+ if ((argc -= optind) == 0) {
+ struct stat statbuf;
+
+ if (!fstat(STDIN_FILENO, &statbuf) && S_ISFIFO(statbuf.st_mode)) {
+ follow = 0;
}
+ /* --argv; */
+ *argv = (char *) bb_msg_standard_input;
+ goto DO_STDIN;
+ }
+
+ do {
+ if ((argv[i][0] == '-') && !argv[i][1]) {
+ DO_STDIN:
+ fds[nfiles] = STDIN_FILENO;
+ } else if ((fds[nfiles] = open(argv[i], O_RDONLY)) < 0) {
+ bb_perror_msg("%s", argv[i]);
+ status = EXIT_FAILURE;
+ continue;
+ }
+ argv[nfiles] = argv[i];
+ ++nfiles;
+ } while (++i < argc);
+
+ if (!nfiles) {
+ bb_error_msg_and_die("no files");
}
-
+
+ tailbufsize = BUFSIZ;
#ifdef CONFIG_FEATURE_FANCY_TAIL
/* tail the files */
- if (!from_top && units == BYTES)
- tailbuf = xmalloc(count);
+ if (from_top < count_bytes) { /* Each is 0 or 1, so true iff 0 < 1. */
+ /* Hence, !from_top && count_bytes */
+ if (tailbufsize < count) {
+ tailbufsize = count + BUFSIZ;
+ }
+ }
#endif
+ buf = tailbuf = xmalloc(tailbufsize);
- for (i = 0; i < nfiles; i++) {
- if (fds[i] == -1)
- continue;
- if (!count) {
- lseek(fds[i], 0, SEEK_END);
+ fmt = header_fmt + 1; /* Skip header leading newline on first output. */
+ i = 0;
+ do {
+ /* Be careful. It would be possible to optimize the count-bytes
+ * case if the file is seekable. If you do though, remember that
+ * starting file position may not be the beginning of the file.
+ * Beware of backing up too far. See example in wc.c.
+ */
+ if ((!(count|from_top)) && (lseek(fds[i], 0, SEEK_END) >= 0)) {
continue;
}
- seen = 0;
- if (show_headers || (!hide_headers && nfiles > 1))
- printf("%s==> %s <==\n", i == 0 ? "" : "\n", argv[optind + i]);
- while ((nread = safe_read(fds[i], buf, sizeof(buf))) > 0) {
+
+ if (nfiles > header_threshhold) {
+ tail_xprint_header(fmt, argv[i]);
+ fmt = header_fmt;
+ }
+
+ buf = tailbuf;
+ taillen = 0;
+ seen = 1;
+
+ while ((nread = tail_read(fds[i], buf, tailbufsize-taillen)) > 0) {
if (from_top) {
+ nwrite = nread;
+ if (seen < count) {
#ifdef CONFIG_FEATURE_FANCY_TAIL
- if (units == BYTES) {
- if (count - 1 <= seen)
- nwrite = nread;
- else if (count - 1 <= seen + nread)
- nwrite = nread + seen - (count - 1);
- else
- nwrite = 0;
- seen += nread;
- } else {
-#else
- {
+ if (count_bytes) {
+ nwrite -= (count - seen);
+ seen = count;
+ } else
#endif
- if (count - 1 <= seen)
- nwrite = nread;
- else {
- nwrite = 0;
- for (s = memchr(buf, '\n', nread); s != NULL;
- s = memchr(s+1, '\n', nread - (s + 1 - buf))) {
- if (count - 1 <= ++seen) {
- nwrite = nread - (s + 1 - buf);
+ {
+ s = buf;
+ do {
+ --nwrite;
+ if ((*s++ == '\n') && (++seen == count)) {
break;
}
- }
+ } while (nwrite);
}
}
- if (full_write(STDOUT_FILENO, buf + nread - nwrite,
- nwrite) < 0) {
- perror_msg("write");
- status = EXIT_FAILURE;
- break;
- }
- } else {
+ tail_xbb_full_write(buf + nread - nwrite, nwrite);
+ } else if (count) {
#ifdef CONFIG_FEATURE_FANCY_TAIL
- if (units == BYTES) {
- if (nread < count) {
- memmove(tailbuf, tailbuf + nread, count - nread);
- memcpy(tailbuf + count - nread, buf, nread);
- } else {
- memcpy(tailbuf, buf + nread - count, count);
+ if (count_bytes) {
+ taillen += nread;
+ if (taillen > count) {
+ memmove(tailbuf, tailbuf + taillen - count, count);
+ taillen = count;
}
- seen += nread;
- } else {
-#else
- {
+ } else
#endif
- for (start = buf, end = memchr(buf, '\n', nread);
- end != NULL; start = end+1,
- end = memchr(start, '\n', nread - (start - buf))) {
- if (newline && count <= seen)
- tailbuf_trunc();
- tailbuf_append(start, end - start + 1);
- seen++;
- newline = 1;
+ {
+ int k = nread;
+ int nbuf = 0;
+
+ while (k) {
+ --k;
+ if (buf[k] == '\n') {
+ ++nbuf;
+ }
}
- if (newline && count <= seen && nread - (start - buf) > 0)
- tailbuf_trunc();
- tailbuf_append(start, nread - (start - buf));
- }
- }
- }
- if (nread < 0) {
- perror_msg("read");
- status = EXIT_FAILURE;
- }
+ if (newline + nbuf < count) {
+ newline += nbuf;
+ taillen += nread;
-#ifdef CONFIG_FEATURE_FANCY_TAIL
- if (!from_top && units == BYTES) {
- if (count < seen)
- seen = count;
- if (full_write(STDOUT_FILENO, tailbuf + count - seen, seen) < 0) {
- perror_msg("write");
- status = EXIT_FAILURE;
+ } else {
+ int extra = 0;
+ if (buf[nread-1] != '\n') {
+ extra = 1;
+ }
+
+ k = newline + nbuf + extra - count;
+ s = tailbuf;
+ while (k) {
+ if (*s == '\n') {
+ --k;
+ }
+ ++s;
+ }
+
+ taillen += nread - (s - tailbuf);
+ memmove(tailbuf, s, taillen);
+ newline = count - extra;
+ }
+ if (tailbufsize < taillen + BUFSIZ) {
+ tailbufsize = taillen + BUFSIZ;
+ tailbuf = xrealloc(tailbuf, tailbufsize);
+ }
+ }
+ buf = tailbuf + taillen;
}
}
-#endif
- if (!from_top && units == LINES) {
- if (full_write(STDOUT_FILENO, tailbuf, taillen) < 0) {
- perror_msg("write");
- status = EXIT_FAILURE;
- }
+ if (!from_top) {
+ tail_xbb_full_write(tailbuf, taillen);
}
taillen = 0;
- }
-
- while (follow) {
- sleep(sleep_period);
+ } while (++i < nfiles);
- for (i = 0; i < nfiles; i++) {
- if (fds[i] == -1)
- continue;
+ buf = xrealloc(tailbuf, BUFSIZ);
- if ((nread = safe_read(fds[i], buf, sizeof(buf))) > 0) {
- if (show_headers || (!hide_headers && nfiles > 1))
- printf("\n==> %s <==\n", argv[optind + i]);
+ fmt = NULL;
- do {
- full_write(STDOUT_FILENO, buf, nread);
- } while ((nread = safe_read(fds[i], buf, sizeof(buf))) > 0);
+ while (follow) {
+ sleep(sleep_period);
+ i = 0;
+ do {
+ if (nfiles > header_threshhold) {
+ fmt = header_fmt;
}
-
- if (nread < 0) {
- perror_msg("read");
- status = EXIT_FAILURE;
+ while ((nread = tail_read(fds[i], buf, sizeof(buf))) > 0) {
+ if (fmt) {
+ tail_xprint_header(fmt, argv[i]);
+ fmt = NULL;
+ }
+ tail_xbb_full_write(buf, nread);
}
- }
+ } while (++i < nfiles);
}
return status;
diff --git a/coreutils/tee.c b/coreutils/tee.c
index 1c145426a..7e86f2e29 100644
--- a/coreutils/tee.c
+++ b/coreutils/tee.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini tee implementation for busybox
+ * tee implementation for busybox
*
- * Copyright (C) 2000,2001 by Matt Kraai <kraai@alumni.carnegiemellon.edu>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,47 +20,96 @@
*
*/
-#include "busybox.h"
-#include <getopt.h>
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/tee.html */
+
#include <stdio.h>
+#include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>
+#include "busybox.h"
-int
-tee_main(int argc, char **argv)
+int tee_main(int argc, char **argv)
{
- char *mode = "w";
- int c, i, status = 0, nfiles = 0;
+ const char *mode = "w\0a";
FILE **files;
+ FILE **p;
+ char **filenames;
+ int flags;
+ int retval = EXIT_SUCCESS;
+#ifdef CONFIG_FEATURE_TEE_USE_BLOCK_IO
+ size_t c;
+ RESERVE_CONFIG_BUFFER(buf, BUFSIZ);
+#else
+ int c;
+#endif
+
+ flags = bb_getopt_ulflags(argc, argv, "ia"); /* 'a' must be 2nd */
+
+ mode += (flags & 2); /* Since 'a' is the 2nd option... */
+
+ if (flags & 1) {
+ signal(SIGINT, SIG_IGN); /* TODO - switch to sigaction.*/
+ }
+
+ /* gnu tee ignores SIGPIPE in case one of the output files is a pipe
+ * that doesn't consume all its input. Good idea... */
+ signal(SIGPIPE, SIG_IGN); /* TODO - switch to sigaction.*/
- while ((c = getopt(argc, argv, "a")) != EOF) {
- switch (c) {
- case 'a':
- mode = "a";
- break;
- default:
- show_usage();
+ /* Allocate an array of FILE *'s, with one extra for a sentinal. */
+ p = files = (FILE **)xmalloc(sizeof(FILE *) * (argc - optind + 2));
+ *p = stdout;
+ argv += optind - 1;
+ filenames = argv - 1;
+ *filenames = (char *) bb_msg_standard_input; /* for later */
+ goto GOT_NEW_FILE;
+
+ do {
+ if ((*p = bb_wfopen(*argv, mode)) == NULL) {
+ retval = EXIT_FAILURE;
+ continue;
+ }
+ filenames[(int)(p - files)] = *argv;
+ GOT_NEW_FILE:
+ setbuf(*p, NULL); /* tee must not buffer output. */
+ ++p;
+ } while (*++argv);
+
+ *p = NULL; /* Store the sentinal value. */
+
+#ifdef CONFIG_FEATURE_TEE_USE_BLOCK_IO
+ while ((c = fread(buf, 1, BUFSIZ, stdin)) != 0) {
+ for (p=files ; *p ; p++) {
+ fwrite(buf, 1, c, *p);
}
}
- files = (FILE **)xmalloc(sizeof(FILE *) * (argc - optind + 1));
- files[nfiles++] = stdout;
- while (optind < argc) {
- if ((files[nfiles++] = wfopen(argv[optind++], mode)) == NULL) {
- nfiles--;
- status = 1;
+#ifdef CONFIG_FEATURE_CLEAN_UP
+ RELEASE_CONFIG_BUFFER(buf);
+#endif
+
+#else
+ while ((c = getchar()) != EOF) {
+ for (p=files ; *p ; p++) {
+ putc(c, *p);
}
}
+#endif
- while ((c = getchar()) != EOF)
- for (i = 0; i < nfiles; i++)
- putc(c, files[i]);
+ /* Now we need to check for i/o errors on stdin and the various
+ * output files. Since we know that the first entry in the output
+ * file table is stdout, we can save one "if ferror" test by
+ * setting the first entry to stdin and checking stdout error
+ * status with bb_fflush_stdout_and_exit()... although fflush()ing
+ * is unnecessary here. */
- return status;
-}
+ p = files;
+ *p = stdin;
+ do { /* Now check for (input and) output errors. */
+ /* Checking ferror should be sufficient, but we may want to fclose.
+ * If we do, remember not to close stdin! */
+ bb_xferror(*p, filenames[(int)(p - files)]);
+ } while (*++p);
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
+ bb_fflush_stdout_and_exit(retval);
+}
diff --git a/coreutils/test.c b/coreutils/test.c
index 83e31ea5c..0bce66e6f 100644
--- a/coreutils/test.c
+++ b/coreutils/test.c
@@ -180,9 +180,9 @@ extern int test_main(int argc, char **argv)
{
int res;
- if (strcmp(applet_name, "[") == 0) {
+ if (strcmp(bb_applet_name, "[") == 0) {
if (strcmp(argv[--argc], "]"))
- error_msg_and_die("missing ]");
+ bb_error_msg_and_die("missing ]");
argv[argc] = NULL;
}
/* Implement special cases from POSIX.2, section 4.62.4 */
@@ -226,9 +226,9 @@ extern int test_main(int argc, char **argv)
static void syntax(const char *op, const char *msg)
{
if (op && *op) {
- error_msg_and_die("%s: %s", op, msg);
+ bb_error_msg_and_die("%s: %s", op, msg);
} else {
- error_msg_and_die("%s", msg);
+ bb_error_msg_and_die("%s", msg);
}
}
@@ -450,13 +450,13 @@ static int getn(const char *s)
r = strtol(s, &p, 10);
if (errno != 0)
- error_msg_and_die("%s: out of range", s);
+ bb_error_msg_and_die("%s: out of range", s);
while (isspace(*p))
p++;
if (*p)
- error_msg_and_die("%s: bad number", s);
+ bb_error_msg_and_die("%s: bad number", s);
return (int) r;
}
diff --git a/coreutils/touch.c b/coreutils/touch.c
index f1c6dc484..c66f26e0d 100644
--- a/coreutils/touch.c
+++ b/coreutils/touch.c
@@ -21,6 +21,16 @@
*
*/
+/* BB_AUDIT SUSv3 _NOT_ compliant -- options -a, -m, -r, -t not supported. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/touch.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Previous version called open() and then utime(). While this will be
+ * be necessary to implement -r and -t, it currently only makes things bigger.
+ * Also, exiting on a failure was a bug. All args should be processed.
+ */
+
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
@@ -33,44 +43,35 @@
extern int touch_main(int argc, char **argv)
{
int fd;
- int create = TRUE;
+ int flags;
+ int status = EXIT_SUCCESS;
- /* Parse options */
- while (--argc > 0 && **(++argv) == '-') {
- while (*(++(*argv))) {
- switch (**argv) {
- case 'c':
- create = FALSE;
- break;
- default:
- show_usage();
- }
- }
- }
+ flags = bb_getopt_ulflags(argc, argv, "c");
+
+ argv += optind;
- if (argc < 1) {
- show_usage();
+ if (!*argv) {
+ bb_show_usage();
}
- while (argc > 0) {
- fd = open(*argv, create ? O_RDWR | O_CREAT : O_RDWR,
- S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
- if (fd < 0) {
- if (! create && errno == ENOENT) {
- argc--;
- argv++;
- continue;
- } else {
- perror_msg_and_die("%s", *argv);
- }
- }
- close(fd);
+ do {
if (utime(*argv, NULL)) {
- perror_msg_and_die("%s", *argv);
+ if (errno == ENOENT) { /* no such file*/
+ if (flags & 1) { /* Creation is disabled, so ignore. */
+ continue;
+ }
+ /* Try to create the file. */
+ fd = open(*argv, O_RDWR | O_CREAT,
+ S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH
+ );
+ if ((fd >= 0) && !close(fd)) {
+ continue;
+ }
+ }
+ status = EXIT_FAILURE;
+ bb_perror_msg("%s", *argv);
}
- argc--;
- argv++;
- }
+ } while (*++argv);
- return EXIT_SUCCESS;
+ return status;
}
diff --git a/coreutils/tr.c b/coreutils/tr.c
index e2a4ef6c5..a00e36134 100644
--- a/coreutils/tr.c
+++ b/coreutils/tr.c
@@ -54,7 +54,7 @@ static void convert(void)
if (in_index == read_chars) {
if ((read_chars = read(0, (char *) pinput, BUFSIZ)) <= 0) {
if (write(1, (char *) poutput, out_index) != out_index)
- error_msg("%s", write_error);
+ bb_error_msg(bb_msg_write_error);
exit(0);
}
in_index = 0;
@@ -68,7 +68,7 @@ static void convert(void)
poutput[out_index++] = last = coded;
if (out_index == BUFSIZ) {
if (write(1, (char *) poutput, out_index) != out_index)
- error_msg_and_die("%s", write_error);
+ bb_error_msg_and_die(bb_msg_write_error);
out_index = 0;
}
}
@@ -102,7 +102,7 @@ static unsigned int expand(const char *arg, register unsigned char *buffer)
while (*arg) {
if (*arg == '\\') {
arg++;
- *buffer++ = process_escape_sequence(&arg);
+ *buffer++ = bb_process_escape_sequence(&arg);
} else if (*(arg+1) == '-') {
ac = *(arg+2);
if(ac == 0) {
@@ -181,7 +181,7 @@ extern int tr_main(int argc, char **argv)
sq_fl = TRUE;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
idx++;
@@ -197,7 +197,7 @@ extern int tr_main(int argc, char **argv)
input_length = complement(input, input_length);
if (argv[idx] != NULL) {
if (*argv[idx] == '\0')
- error_msg_and_die("STRING2 cannot be empty");
+ bb_error_msg_and_die("STRING2 cannot be empty");
output_length = expand(argv[idx], output);
map(input, input_length, output, output_length);
}
diff --git a/coreutils/true.c b/coreutils/true.c
index 9644aad4a..0fbe1023d 100644
--- a/coreutils/true.c
+++ b/coreutils/true.c
@@ -21,7 +21,8 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/true.html */
#include <stdlib.h>
#include "busybox.h"
diff --git a/coreutils/tty.c b/coreutils/tty.c
index 4510c2996..cd2c784fd 100644
--- a/coreutils/tty.c
+++ b/coreutils/tty.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini tty implementation for busybox
+ * tty implementation for busybox
*
- * Copyright (C) 2000 Edward Betts <edward@debian.org>.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,25 +20,39 @@
*
*/
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/tty.html */
+
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
-#include <sys/types.h>
#include "busybox.h"
extern int tty_main(int argc, char **argv)
{
- char *tty;
-
- if (argc > 1) {
- if (argv[1][0] != '-' || argv[1][1] != 's')
- show_usage();
- } else {
- tty = ttyname(0);
- if (tty)
- puts(tty);
- else
- puts("not a tty");
+ const char *s;
+ int silent; /* Note: No longer relevant in SUSv3. */
+ int retval;
+
+ bb_default_error_retval = 2; /* SUSv3 requires > 1 for error. */
+
+ silent = bb_getopt_ulflags(argc, argv, "s");
+
+ /* gnu tty outputs a warning that it is ignoring all args. */
+ bb_warn_ignoring_args(argc - optind);
+
+ retval = 0;
+
+ if ((s = ttyname(0)) == NULL) {
+ /* According to SUSv3, ttyname can on fail with EBADF or ENOTTY.
+ * We know the file descriptor is good, so failure means not a tty. */
+ s = "not a tty";
+ retval = 1;
+ }
+
+ if (!silent) {
+ puts(s);
}
- return(isatty(0) ? EXIT_SUCCESS : EXIT_FAILURE);
+
+ bb_fflush_stdout_and_exit(retval);
}
diff --git a/coreutils/uname.c b/coreutils/uname.c
index df4f14ea0..a3e52e39f 100644
--- a/coreutils/uname.c
+++ b/coreutils/uname.c
@@ -16,6 +16,9 @@
along with this program; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/uname.html */
+
/* Option Example
-s, --sysname SunOS
@@ -33,13 +36,18 @@
/* Further size reductions by Glenn McGrath and Manuel Novoa III. */
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Now does proper error checking on i/o. Plus some further space savings.
+ */
+
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
+#include <unistd.h>
#include <sys/types.h>
#include <sys/utsname.h>
-#include <getopt.h>
#include "busybox.h"
typedef struct {
@@ -48,7 +56,6 @@ typedef struct {
} uname_info_t;
static const char options[] = "snrvmpa";
-static const char flags[] = "\x01\x02\x04\x08\x10\x20\x3f";
static const unsigned short int utsname_offset[] = {
offsetof(uname_info_t,name.sysname),
offsetof(uname_info_t,name.nodename),
@@ -61,29 +68,28 @@ static const unsigned short int utsname_offset[] = {
int uname_main(int argc, char **argv)
{
uname_info_t uname_info;
-
#if defined(__sparc__) && defined(__linux__)
char *fake_sparc = getenv("FAKE_SPARC");
#endif
-
const unsigned short int *delta;
- int opt;
- char toprint = 0;
+ char toprint;
- while ((opt = getopt(argc, argv, options)) != -1) {
- const char *p = strchr(options,opt);
- if (p == NULL) {
- show_usage();
- }
- toprint |= flags[(int)(p-options)];
+ toprint = bb_getopt_ulflags(argc, argv, options);
+
+ if (argc != optind) {
+ bb_show_usage();
+ }
+
+ if (toprint & (1 << 6)) {
+ toprint = 0x3f;
}
if (toprint == 0) {
- toprint = flags[0]; /* sysname */
+ toprint = 1; /* sysname */
}
if (uname(&uname_info.name) == -1) {
- error_msg_and_die("cannot get system name");
+ bb_error_msg_and_die("cannot get system name");
}
#if defined(__sparc__) && defined(__linux__)
@@ -99,7 +105,7 @@ int uname_main(int argc, char **argv)
delta=utsname_offset;
do {
if (toprint & 1) {
- printf(((char *)(&uname_info)) + *delta);
+ bb_printf(((char *)(&uname_info)) + *delta);
if (toprint > 1) {
putchar(' ');
}
@@ -108,5 +114,5 @@ int uname_main(int argc, char **argv)
} while (toprint >>= 1);
putchar('\n');
- return EXIT_SUCCESS;
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/uniq.c b/coreutils/uniq.c
index cb63c4277..90686c9af 100644
--- a/coreutils/uniq.c
+++ b/coreutils/uniq.c
@@ -1,10 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini uniq implementation for busybox
+ * uniq implementation for busybox
*
- * Copyright (C) 1999 by Lineo, inc. and John Beppu
- * Copyright (C) 1999,2000,2001 by John Beppu <beppu@codepoet.org>
- * Rewritten by Matt Kraai <kraai@alumni.carnegiemellon.edu>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -22,67 +20,93 @@
*
*/
+/* BB_AUDIT SUSv3 compliant */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/uniq.html */
+
#include <stdio.h>
-#include <string.h>
-#include <getopt.h>
-#include <errno.h>
#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <unistd.h>
#include "busybox.h"
+#include "libcoreutils/coreutils.h"
-static int print_count;
-static int print_uniq = 1;
-static int print_duplicates = 1;
-
-static void print_line(char *line, int count, FILE *fp)
-{
- if ((print_duplicates && count > 1) || (print_uniq && count == 1)) {
- if (print_count)
- fprintf(fp, "%7d\t%s", count, line);
- else
- fputs(line, fp);
- }
-}
+static const char uniq_opts[] = "f:s:cdu\0\7\3\5\1\2\4";
int uniq_main(int argc, char **argv)
{
- FILE *in = stdin, *out = stdout;
- char *lastline = NULL, *input;
- int opt, count = 0;
+ FILE *in, *out;
+ /* Note: Ignore the warning about dups and e0 possibly being uninitialized.
+ * They will be initialized on the fist pass of the loop (since s0 is NULL). */
+ unsigned long dups, skip_fields, skip_chars, i;
+ const char *s0, *e0, *s1, *e1, *input_filename;
+ int opt;
+ int uniq_flags = 6; /* -u */
- /* parse argv[] */
- while ((opt = getopt(argc, argv, "cdu")) > 0) {
- switch (opt) {
- case 'c':
- print_count = 1;
- break;
- case 'd':
- print_duplicates = 1;
- print_uniq = 0;
- break;
- case 'u':
- print_duplicates = 0;
- print_uniq = 1;
- break;
+ skip_fields = skip_chars = 0;
+
+ while ((opt = getopt(argc, argv, uniq_opts)) > 0) {
+ if (opt == 'f') {
+ skip_fields = bb_xgetularg10(optarg);
+ } else if (opt == 's') {
+ skip_chars = bb_xgetularg10(optarg);
+ } else if ((s0 = strchr(uniq_opts, opt)) != NULL) {
+ uniq_flags &= s0[4];
+ uniq_flags |= s0[7];
+ } else {
+ bb_show_usage();
}
}
- if (argv[optind] != NULL) {
- in = xfopen(argv[optind], "r");
- if (argv[optind+1] != NULL)
- out = xfopen(argv[optind+1], "w");
+ input_filename = *(argv += optind);
+
+ in = xgetoptfile_sort_uniq(argv, "r");
+ if (*argv) {
+ ++argv;
}
+ out = xgetoptfile_sort_uniq(argv, "w");
+ if (*argv && argv[1]) {
+ bb_show_usage();
+ }
+
+ s0 = NULL;
- while ((input = get_line_from_file(in)) != NULL) {
- if (lastline == NULL || strcmp(input, lastline) != 0) {
- print_line(lastline, count, out);
- free(lastline);
- lastline = input;
- count = 0;
+ /* gnu uniq ignores newlines */
+ while ((s1 = bb_get_chomped_line_from_file(in)) != NULL) {
+ e1 = s1;
+ for (i=skip_fields ; i ; i--) {
+ e1 = bb_skip_whitespace(e1);
+ while (*e1 && !isspace(*e1)) {
+ ++e1;
+ }
+ }
+ for (i = skip_chars ; *e1 && i ; i--) {
+ ++e1;
+ }
+ if (s0) {
+ if (strcmp(e0, e1) == 0) {
+ ++dups; /* Note: Testing for overflow seems excessive. */
+ continue;
+ }
+ DO_LAST:
+ if ((dups && (uniq_flags & 2)) || (!dups && (uniq_flags & 4))) {
+ bb_fprintf(out, "\0%7d\t" + (uniq_flags & 1), dups + 1);
+ bb_fprintf(out, "%s\n", s0);
+ }
+ free((void *)s0);
}
- count++;
+
+ s0 = s1;
+ e0 = e1;
+ dups = 0;
+ }
+
+ if (s0) {
+ e1 = NULL;
+ goto DO_LAST;
}
- print_line(lastline, count, out);
- free(lastline);
- return EXIT_SUCCESS;
+ bb_xferror(in, input_filename);
+
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/usleep.c b/coreutils/usleep.c
index ac268b485..f570f2734 100644
--- a/coreutils/usleep.c
+++ b/coreutils/usleep.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini usleep implementation for busybox
+ * usleep implementation for busybox
*
- * Copyright (C) 1995, 1996 by Bruce Perens <bruce@pixar.com>.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,18 +20,22 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 N/A -- Apparently a busybox extension. */
#include <stdlib.h>
+#include <limits.h>
#include <unistd.h>
#include "busybox.h"
extern int usleep_main(int argc, char **argv)
{
- if ((argc < 2) || (**(argv + 1) == '-')) {
- show_usage();
+ if (argc != 2) {
+ bb_show_usage();
+ }
+
+ if (usleep(bb_xgetularg10_bnd(argv[1], 0, UINT_MAX))) {
+ bb_perror_nomsg_and_die();
}
- usleep(atoi(*(++argv))); /* return void */
return EXIT_SUCCESS;
}
diff --git a/coreutils/uudecode.c b/coreutils/uudecode.c
index a5ac002e9..4f9270c18 100644
--- a/coreutils/uudecode.c
+++ b/coreutils/uudecode.c
@@ -46,7 +46,7 @@ static int read_stduu (const char *inname)
char *p;
if (fgets (buf, sizeof(buf), stdin) == NULL) {
- error_msg("%s: Short file", inname);
+ bb_error_msg("%s: Short file", inname);
return FALSE;
}
p = buf;
@@ -81,7 +81,7 @@ static int read_stduu (const char *inname)
if (fgets (buf, sizeof(buf), stdin) == NULL
|| strcmp (buf, "end\n")) {
- error_msg("%s: No `end' line", inname);
+ bb_error_msg("%s: No `end' line", inname);
return FALSE;
}
@@ -131,7 +131,7 @@ static int read_base64 (const char *inname)
unsigned char *p;
if (fgets (buf, sizeof(buf), stdin) == NULL) {
- error_msg("%s: Short file", inname);
+ bb_error_msg("%s: Short file", inname);
return FALSE;
}
p = buf;
@@ -139,7 +139,7 @@ static int read_base64 (const char *inname)
if (memcmp (buf, "====", 4) == 0)
break;
if (last_data != 0) {
- error_msg("%s: data following `=' padding character", inname);
+ bb_error_msg("%s: data following `=' padding character", inname);
return FALSE;
}
@@ -161,14 +161,14 @@ static int read_base64 (const char *inname)
while ((b64_tab[*p] & '\100') != 0)
if (*p == '\n' || *p++ == '=') {
- error_msg("%s: illegal line", inname);
+ bb_error_msg("%s: illegal line", inname);
return FALSE;
}
c2 = b64_tab[*p++];
while (b64_tab[*p] == '\177')
if (*p++ == '\n') {
- error_msg("%s: illegal line", inname);
+ bb_error_msg("%s: illegal line", inname);
return FALSE;
}
if (*p == '=') {
@@ -180,7 +180,7 @@ static int read_base64 (const char *inname)
while (b64_tab[*p] == '\177')
if (*p++ == '\n') {
- error_msg("%s: illegal line", inname);
+ bb_error_msg("%s: illegal line", inname);
return FALSE;
}
putchar (c1 << 2 | c2 >> 4);
@@ -213,7 +213,7 @@ static int decode (const char *inname,
while (1) {
if (fgets (buf, sizeof (buf), stdin) == NULL) {
- error_msg("%s: No `begin' line", inname);
+ bb_error_msg("%s: No `begin' line", inname);
return FALSE;
}
@@ -239,13 +239,13 @@ static int decode (const char *inname,
while (*p != '/')
++p;
if (*p == '\0') {
- error_msg("%s: Illegal ~user", inname);
+ bb_error_msg("%s: Illegal ~user", inname);
return FALSE;
}
*p++ = '\0';
pw = getpwnam (buf + 1);
if (pw == NULL) {
- error_msg("%s: No user `%s'", inname, buf + 1);
+ bb_error_msg("%s: No user `%s'", inname, buf + 1);
return FALSE;
}
outname = concat_path_file(pw->pw_dir, p);
@@ -258,7 +258,7 @@ static int decode (const char *inname,
&& (freopen (outname, "w", stdout) == NULL
|| chmod (outname, mode & (S_IRWXU | S_IRWXG | S_IRWXO))
)) {
- perror_msg("%s", outname); /* */
+ bb_perror_msg("%s", outname); /* */
if (dofre)
free(outname);
return FALSE;
@@ -295,7 +295,7 @@ int uudecode_main (int argc,
break;
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -308,7 +308,7 @@ int uudecode_main (int argc,
if (decode (argv[optind], outname) != 0)
exit_status = FALSE;
} else {
- perror_msg("%s", argv[optind]);
+ bb_perror_msg("%s", argv[optind]);
exit_status = EXIT_FAILURE;
}
optind++;
diff --git a/coreutils/uuencode.c b/coreutils/uuencode.c
index 49b2d9189..fd3326d80 100644
--- a/coreutils/uuencode.c
+++ b/coreutils/uuencode.c
@@ -29,7 +29,7 @@
#include "busybox.h"
/* Conversion table. for base 64 */
-static char tbl_base64[65] = {
+static const char tbl_base64[65] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
@@ -41,7 +41,7 @@ static char tbl_base64[65] = {
'=' /* termination character */
};
-static char tbl_std[65] = {
+static const char tbl_std[65] = {
'`', '!', '"', '#', '$', '%', '&', '\'',
'(', ')', '*', '+', ',', '-', '.', '/',
'0', '1', '2', '3', '4', '5', '6', '7',
@@ -92,40 +92,36 @@ int uuencode_main(int argc, char **argv)
int write_size = dst_buf_size;
struct stat stat_buf;
FILE *src_stream = stdin;
- char *tbl = tbl_std;
+ const char *tbl;
size_t size;
mode_t mode;
- int opt;
RESERVE_CONFIG_BUFFER(src_buf, SRC_BUF_SIZE + 1);
RESERVE_CONFIG_BUFFER(dst_buf, DST_BUF_SIZE + 1);
- while ((opt = getopt(argc, argv, "m")) != -1) {
- switch (opt) {
- case 'm':
- tbl = tbl_base64;
- break;
- default:
- show_usage();
- }
+ tbl = tbl_std;
+ if (bb_getopt_ulflags(argc, argv, "m") & 1) {
+ tbl = tbl_base64;
}
switch (argc - optind) {
case 2:
- src_stream = xfopen(argv[optind], "r");
- stat(argv[optind], &stat_buf);
+ src_stream = bb_xfopen(argv[optind], "r");
+ if (stat(argv[optind], &stat_buf) < 0) {
+ bb_perror_msg_and_die("stat");
+ }
mode = stat_buf.st_mode & (S_IRWXU | S_IRWXG | S_IRWXO);
if (src_stream == stdout) {
- printf("NULL\n");
+ puts("NULL");
}
break;
case 1:
mode = 0666 & ~umask(0666);
break;
default:
- show_usage();
+ bb_show_usage();
}
- printf("begin%s %o %s", tbl == tbl_std ? "" : "-base64", mode, argv[argc - 1]);
+ bb_printf("begin%s %o %s", tbl == tbl_std ? "" : "-base64", mode, argv[argc - 1]);
while ((size = fread(src_buf, 1, src_buf_size, src_stream)) > 0) {
if (size != src_buf_size) {
@@ -142,10 +138,12 @@ int uuencode_main(int argc, char **argv)
putchar(tbl[size]);
}
if (fwrite(dst_buf, 1, write_size, stdout) != write_size) {
- perror("Couldnt finish writing");
+ bb_perror_msg_and_die(bb_msg_write_error);
}
}
- printf(tbl == tbl_std ? "\n`\nend\n" : "\n====\n");
+ bb_printf(tbl == tbl_std ? "\n`\nend\n" : "\n====\n");
+
+ bb_xferror(src_stream, "source"); /* TODO - Fix this! */
- return(EXIT_SUCCESS);
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
diff --git a/coreutils/watch.c b/coreutils/watch.c
index c275f3bb3..f9f40189e 100644
--- a/coreutils/watch.c
+++ b/coreutils/watch.c
@@ -20,67 +20,76 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 N/A */
+/* BB_AUDIT GNU defects -- only option -n is supported. */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Removed dependency on date_main(), added proper error checking, and
+ * reduced size.
+ */
#include <stdio.h>
-#include <errno.h>
-#include <unistd.h>
#include <stdlib.h>
#include <string.h>
+#include <limits.h>
+#include <time.h>
+#include <assert.h>
+#include <unistd.h>
#include <sys/wait.h>
#include "busybox.h"
extern int watch_main(int argc, char **argv)
{
- const char date_argv[2][10] = { "date", "" };
const int header_len = 40;
- char header[header_len + 1];
- int period = 2;
- char **cargv;
- int cargc;
+ time_t t;
pid_t pid;
+ unsigned period = 2;
int old_stdout;
- int i;
+ int len, len2;
+ char **watched_argv;
+ char header[header_len + 1];
if (argc < 2) {
- show_usage();
- } else {
- cargv = argv + 1;
- cargc = argc - 1;
-
- /* don't use getopt, because it permutes the arguments */
- if (argc >= 3 && !strcmp(argv[1], "-n")) {
- period = strtol(argv[2], NULL, 10);
- if (period < 1)
- show_usage();
- cargv += 2;
- cargc -= 2;
- }
+ bb_show_usage();
}
-
- /* create header */
- snprintf(header, header_len, "Every %ds: ", period);
- for (i = 0; i < cargc && (strlen(header) + strlen(cargv[i]) < header_len);
- i++) {
- strcat(header, cargv[i]);
- strcat(header, " ");
+ /* don't use getopt, because it permutes the arguments */
+ ++argv;
+ if ((argc > 3) && !strcmp(*argv, "-n")
+ ) {
+ period = bb_xgetularg10_bnd(argv[1], 1, UINT_MAX);
+ argv += 2;
}
+ watched_argv = argv;
- /* fill with blanks */
- for (i = strlen(header); i < header_len; i++)
- header[i] = ' ';
+ /* create header */
- header[header_len - 1] = '\0';
+ len = snprintf(header, header_len, "Every %ds:", period);
+ /* Don't bother checking for len < 0, as it should never happen.
+ * But, just to be prepared... */
+ assert(len >= 0);
+ do {
+ len2 = strlen(*argv);
+ if (len + len2 >= header_len-1) {
+ break;
+ }
+ header[len] = ' ';
+ memcpy(header+len+1, *argv, len2);
+ len += len2+1;
+ } while (*++argv);
+ header[len] = 0;
/* thanks to lye, who showed me how to redirect stdin/stdout */
old_stdout = dup(1);
while (1) {
- printf("\033[H\033[J%s", header);
- date_main(1, (char **) date_argv);
- printf("\n");
+ time(&t);
+ /* Use dprintf to avoid fflush()ing stdout. */
+ if (dprintf(1, "\033[H\033[J%-*s%s\n", header_len, header, ctime(&t)) < 0) {
+ bb_perror_msg_and_die("printf");
+ }
pid = vfork(); /* vfork, because of ucLinux */
if (pid > 0) {
@@ -91,13 +100,11 @@ extern int watch_main(int argc, char **argv)
//child
close(1);
dup(old_stdout);
- if (execvp(*cargv, cargv))
- error_msg_and_die("Couldn't run command\n");
+ if (execvp(*watched_argv, watched_argv)) {
+ bb_error_msg_and_die("Couldn't run command\n");
+ }
} else {
- error_msg_and_die("Couldn't vfork\n");
+ bb_error_msg_and_die("Couldn't vfork\n");
}
}
-
-
- return EXIT_SUCCESS;
}
diff --git a/coreutils/wc.c b/coreutils/wc.c
index 8e3b5bbf4..779901524 100644
--- a/coreutils/wc.c
+++ b/coreutils/wc.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini wc implementation for busybox
+ * wc implementation for busybox
*
- * Copyright (C) 2000 Edward Betts <edward@debian.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,159 +20,208 @@
*
*/
+/* BB_AUDIT SUSv3 _NOT_ compliant -- option -m is not currently supported. */
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/wc.html */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Rewritten to fix a number of problems and do some size optimizations.
+ * Problems in the previous busybox implementation (besides bloat) included:
+ * 1) broken 'wc -c' optimization (read note below)
+ * 2) broken handling of '-' args
+ * 3) no checking of ferror on EOF returns
+ * 4) isprint() wasn't considered when word counting.
+ *
+ * TODO:
+ *
+ * When locale support is enabled, count multibyte chars in the '-m' case.
+ *
+ * NOTES:
+ *
+ * The previous busybox wc attempted an optimization using stat for the
+ * case of counting chars only. I omitted that because it was broken.
+ * It didn't take into account the possibility of input coming from a
+ * pipe, or input from a file with file pointer not at the beginning.
+ *
+ * To implement such a speed optimization correctly, not only do you
+ * need the size, but also the file position. Note also that the
+ * file position may be past the end of file. Consider the example
+ * (adapted from example in gnu wc.c)
+ *
+ * echo hello > /tmp/testfile &&
+ * (dd ibs=1k skip=1 count=0 &> /dev/null ; wc -c) < /tmp/testfile
+ *
+ * for which 'wc -c' should output '0'.
+ */
+
#include <stdio.h>
-#include <getopt.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
#include "busybox.h"
-enum print_e {
- print_lines = 1,
- print_words = 2,
- print_chars = 4,
- print_length = 8
+#ifdef CONFIG_LOCALE_SUPPORT
+#include <locale.h>
+#include <ctype.h>
+#define isspace_given_isprint(c) isspace(c)
+#else
+#undef isspace
+#undef isprint
+#define isspace(c) ((((c) == ' ') || (((unsigned int)((c) - 9)) <= (13 - 9))))
+#define isprint(c) (((unsigned int)((c) - 0x20)) <= (0x7e - 0x20))
+#define isspace_given_isprint(c) ((c) == ' ')
+#endif
+
+enum {
+ WC_LINES = 0,
+ WC_WORDS = 1,
+ WC_CHARS = 2,
+ WC_LENGTH = 3
};
-static unsigned int total_lines = 0;
-static unsigned int total_words = 0;
-static unsigned int total_chars = 0;
-static unsigned int max_length = 0;
-static char print_type = 0;
+/* Note: If this changes, remember to change the initialization of
+ * 'name' in wc_main. It needs to point to the terminating nul. */
+static const char wc_opts[] = "lwcL"; /* READ THE WARNING ABOVE! */
-static void print_counts(const unsigned int lines, const unsigned int words,
- const unsigned int chars, const unsigned int length, const char *name)
-{
- int output = 0;
+enum {
+ OP_INC_LINE = 1, /* OP_INC_LINE must be 1. */
+ OP_SPACE = 2,
+ OP_NEWLINE = 4,
+ OP_TAB = 8,
+ OP_NUL = 16,
+};
- if (print_type & print_lines) {
- printf("%7d", lines);
- output++;
- }
- if (print_type & print_words) {
- if (output++)
- putchar(' ');
- printf("%7d", words);
- }
- if (print_type & print_chars) {
- if (output++)
- putchar(' ');
- printf("%7d", chars);
- }
- if (print_type & print_length) {
- if (output++)
- putchar(' ');
- printf("%7d", length);
- }
- if (*name) {
- printf(" %s", name);
- }
- putchar('\n');
-}
+/* Note: If fmt_str changes, the offsets to 's' in the OUTPUT section
+ * will need to be updated. */
+static const char fmt_str[] = " %7u\0 %s\n";
+static const char total_str[] = "total";
-static void wc_file(FILE * file, const char *name)
+int wc_main(int argc, char **argv)
{
- unsigned int lines = 0;
- unsigned int words = 0;
- unsigned int chars = 0;
- unsigned int length = 0;
- unsigned int linepos = 0;
- char in_word = 0;
+ FILE *fp;
+ const char *s;
+ unsigned int *pcounts;
+ unsigned int counts[4];
+ unsigned int totals[4];
+ unsigned int linepos;
+ unsigned int u;
+ int num_files = 0;
int c;
-
- while ((c = getc(file)) != EOF) {
- chars++;
- switch (c) {
- case '\n':
- lines++;
- case '\r':
- case '\f':
- if (linepos > length)
- length = linepos;
- linepos = 0;
- goto word_separator;
- case '\t':
- linepos += 8 - (linepos % 8);
- goto word_separator;
- case ' ':
- linepos++;
- case '\v':
-word_separator:
- if (in_word) {
- in_word = 0;
- words++;
- }
- break;
- default:
- linepos++;
- in_word = 1;
- break;
- }
- }
- if (linepos > length) {
- length = linepos;
- }
- if (in_word) {
- words++;
+ char status = EXIT_SUCCESS;
+ char in_word;
+ char print_type;
+
+ print_type = bb_getopt_ulflags(argc, argv, wc_opts);
+
+ if (print_type == 0) {
+ print_type = (1 << WC_LINES) | (1 << WC_WORDS) | (1 << WC_CHARS);
}
- print_counts(lines, words, chars, length, name);
- total_lines += lines;
- total_words += words;
- total_chars += chars;
- if (length > max_length) {
- max_length = length;
+
+ argv += optind;
+ if (!*argv) {
+ *--argv = (char *) bb_msg_standard_input;
}
-}
-
-int wc_main(int argc, char **argv)
-{
- int opt;
-
- while ((opt = getopt(argc, argv, "clLw")) > 0) {
- switch (opt) {
- case 'c':
- print_type |= print_chars;
- break;
- case 'l':
- print_type |= print_lines;
- break;
- case 'L':
- print_type |= print_length;
- break;
- case 'w':
- print_type |= print_words;
- break;
- default:
- show_usage();
+
+ memset(totals, 0, sizeof(totals));
+
+ pcounts = counts;
+
+ do {
+ ++num_files;
+ if (!(fp = bb_wfopen_input(*argv))) {
+ status = EXIT_FAILURE;
+ continue;
}
- }
-
- if (print_type == 0) {
- print_type = print_lines | print_words | print_chars;
- }
-
- if (argv[optind] == NULL || strcmp(argv[optind], "-") == 0) {
- wc_file(stdin, "");
- } else {
- unsigned short num_files_counted = 0;
- while (optind < argc) {
- if (print_type == print_chars) {
- struct stat statbuf;
- stat(argv[optind], &statbuf);
- print_counts(0, 0, statbuf.st_size, 0, argv[optind]);
- total_chars += statbuf.st_size;
+
+ memset(counts, 0, sizeof(counts));
+ linepos = 0;
+ in_word = 0;
+
+ do {
+ ++counts[WC_CHARS];
+ c = getc(fp);
+ if (isprint(c)) {
+ ++linepos;
+ if (!isspace_given_isprint(c)) {
+ in_word = 1;
+ continue;
+ }
+ } else if (((unsigned int)(c - 9)) <= 4) {
+ /* \t 9
+ * \n 10
+ * \v 11
+ * \f 12
+ * \r 13
+ */
+ if (c == '\t') {
+ linepos = (linepos | 7) + 1;
+ } else { /* '\n', '\r', '\f', or '\v' */
+ DO_EOF:
+ if (linepos > counts[WC_LENGTH]) {
+ counts[WC_LENGTH] = linepos;
+ }
+ if (c == '\n') {
+ ++counts[WC_LINES];
+ }
+ if (c != '\v') {
+ linepos = 0;
+ }
+ }
+ } else if (c == EOF) {
+ if (ferror(fp)) {
+ bb_perror_msg("%s", *argv);
+ status = EXIT_FAILURE;
+ }
+ --counts[WC_CHARS];
+ goto DO_EOF; /* Treat an EOF as '\r'. */
} else {
- FILE *file;
- file = xfopen(argv[optind], "r");
- wc_file(file, argv[optind]);
- fclose(file);
+ continue;
+ }
+
+ counts[WC_WORDS] += in_word;
+ in_word = 0;
+ if (c == EOF) {
+ break;
}
- optind++;
- num_files_counted++;
+ } while (1);
+
+ if (totals[WC_LENGTH] < counts[WC_LENGTH]) {
+ totals[WC_LENGTH] = counts[WC_LENGTH];
}
- if (num_files_counted > 1) {
- print_counts(total_lines, total_words, total_chars, max_length, "total");
+ totals[WC_LENGTH] -= counts[WC_LENGTH];
+
+ bb_fclose_nonstdin(fp);
+
+ OUTPUT:
+ s = fmt_str + 1; /* Skip the leading space on 1st pass. */
+ u = 0;
+ do {
+ if (print_type & (1 << u)) {
+ bb_printf(s, pcounts[u]);
+ s = fmt_str; /* Ok... restore the leading space. */
+ }
+ totals[u] += pcounts[u];
+ } while (++u < 4);
+
+ s += 8; /* Set the format to the empty string. */
+
+ if (*argv != bb_msg_standard_input) {
+ s -= 3; /* We have a name, so do %s conversion. */
}
+ bb_printf(s, *argv);
+
+ } while (*++argv);
+
+ /* If more than one file was processed, we want the totals. To save some
+ * space, we set the pcounts ptr to the totals array. This has the side
+ * effect of trashing the totals array after outputting it, but that's
+ * irrelavent since we no longer need it. */
+ if (num_files > 1) {
+ num_files = 0; /* Make sure we don't get here again. */
+ *--argv = (char *) total_str;
+ pcounts = totals;
+ goto OUTPUT;
}
-
- return(EXIT_SUCCESS);
+
+ bb_fflush_stdout_and_exit(status);
}
diff --git a/coreutils/who.c b/coreutils/who.c
index 3da7ed1c7..1bf552056 100644
--- a/coreutils/who.c
+++ b/coreutils/who.c
@@ -23,7 +23,7 @@
#include <errno.h>
#include <string.h>
#include <time.h>
-#include <busybox.h>
+#include "busybox.h"
extern int who_main(int argc, char **argv)
{
@@ -33,7 +33,7 @@ extern int who_main(int argc, char **argv)
time_t now, idle;
if (argc > 1)
- show_usage();
+ bb_show_usage();
setutent();
devlen = sizeof("/dev/") - 1;
@@ -81,5 +81,3 @@ extern int who_main(int argc, char **argv)
return 0;
}
-
-
diff --git a/coreutils/whoami.c b/coreutils/whoami.c
index a9d6ecf26..f93034d3a 100644
--- a/coreutils/whoami.c
+++ b/coreutils/whoami.c
@@ -20,7 +20,7 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
#include <stdio.h>
#include <stdlib.h>
@@ -30,14 +30,15 @@
extern int whoami_main(int argc, char **argv)
{
char user[9];
- uid_t uid = geteuid();
+ uid_t uid;
if (argc > 1)
- show_usage();
+ bb_show_usage();
+ uid = geteuid();
if (my_getpwuid(user, uid)) {
puts(user);
- return EXIT_SUCCESS;
+ bb_fflush_stdout_and_exit(EXIT_SUCCESS);
}
- error_msg_and_die("cannot find username for UID %u", (unsigned) uid);
+ bb_error_msg_and_die("cannot find username for UID %u", (unsigned) uid);
}
diff --git a/coreutils/yes.c b/coreutils/yes.c
index 7d9596d0b..74f7571cf 100644
--- a/coreutils/yes.c
+++ b/coreutils/yes.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini yes implementation for busybox
+ * yes implementation for busybox
*
- * Copyright (C) 2000 Edward Betts <edward@debian.org>.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -20,7 +20,12 @@
*
*/
-/* getopt not needed */
+/* BB_AUDIT SUSv3 N/A -- Matches GNU behavior. */
+
+/* Mar 16, 2003 Manuel Novoa III (mjn3@codepoet.org)
+ *
+ * Size reductions and removed redundant applet name prefix from error messages.
+ */
#include <stdio.h>
#include <stdlib.h>
@@ -28,26 +33,24 @@
extern int yes_main(int argc, char **argv)
{
- int i;
-
- if (argc >= 2 && *argv[1] == '-')
- show_usage();
+ static const char fmt_str[] = " %s";
+ const char *fmt;
+ char **first_arg;
- if (argc == 1) {
- while (1)
- if (puts("y") == EOF) {
- perror("yes");
- return EXIT_FAILURE;
- }
+ *argv = "y";
+ if (argc != 1) {
+ ++argv;
}
- while (1)
- for (i = 1; i < argc; i++)
- if (fputs(argv[i], stdout) == EOF
- || putchar(i == argc - 1 ? '\n' : ' ') == EOF) {
- perror("yes");
- return EXIT_FAILURE;
- }
+ first_arg = argv;
+ do {
+ fmt = fmt_str + 1;
+ do {
+ bb_printf(fmt, *argv);
+ fmt = fmt_str;
+ } while (*++argv);
+ argv = first_arg;
+ } while (putchar('\n') != EOF);
- return EXIT_SUCCESS;
+ bb_perror_nomsg_and_die();
}
diff --git a/debianutils/mktemp.c b/debianutils/mktemp.c
index bc47d0af0..9d8de2174 100644
--- a/debianutils/mktemp.c
+++ b/debianutils/mktemp.c
@@ -32,7 +32,7 @@
extern int mktemp_main(int argc, char **argv)
{
if (argc != 2 && (argc != 3 || strcmp(argv[1], "-q")))
- show_usage();
+ bb_show_usage();
if(mkstemp(argv[argc-1]) < 0)
return EXIT_FAILURE;
(void) puts(argv[argc-1]);
diff --git a/debianutils/readlink.c b/debianutils/readlink.c
index da5259038..d8d7e8c2d 100644
--- a/debianutils/readlink.c
+++ b/debianutils/readlink.c
@@ -32,7 +32,7 @@ int readlink_main(int argc, char **argv)
/* no options, no getopt */
if (argc != 2)
- show_usage();
+ bb_show_usage();
buf = xreadlink(argv[1]);
if (!buf)
diff --git a/debianutils/run_parts.c b/debianutils/run_parts.c
index a6ad81096..a941e1fc8 100644
--- a/debianutils/run_parts.c
+++ b/debianutils/run_parts.c
@@ -78,7 +78,7 @@ int run_parts_main(int argc, char **argv)
{
const unsigned int mask = (unsigned int) strtol(optarg, NULL, 8);
if (mask > 07777) {
- perror_msg_and_die("bad umask value");
+ bb_perror_msg_and_die("bad umask value");
}
umask(mask);
}
@@ -90,13 +90,13 @@ int run_parts_main(int argc, char **argv)
args[argcount++] = optarg;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
/* We require exactly one argument: the directory name */
if (optind != (argc - 1)) {
- show_usage();
+ bb_show_usage();
}
args[0] = argv[optind];
diff --git a/debianutils/start_stop_daemon.c b/debianutils/start_stop_daemon.c
index 576526183..a1c2c21c2 100644
--- a/debianutils/start_stop_daemon.c
+++ b/debianutils/start_stop_daemon.c
@@ -74,7 +74,7 @@ parse_options(int argc, char * const *argv)
break;
case 's':
if (sscanf(optarg, "%d", &signal_nr) != 1)
- error_msg_and_die ("-s takes a numeric argument");
+ bb_error_msg_and_die ("-s takes a numeric argument");
break;
case 'u':
userspec = optarg;
@@ -86,21 +86,21 @@ parse_options(int argc, char * const *argv)
fork_before_exec = 1;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
if (start == stop)
- error_msg_and_die ("need one of -S or -K");
+ bb_error_msg_and_die ("need one of -S or -K");
if (!execname && !userspec)
- error_msg_and_die ("need at least one of -x or -u");
+ bb_error_msg_and_die ("need at least one of -x or -u");
if (!startas)
startas = execname;
if (start && !startas)
- error_msg_and_die ("-S needs -x or -a");
+ bb_error_msg_and_die ("-S needs -x or -a");
}
@@ -185,7 +185,7 @@ do_procfs(void)
procdir = opendir("/proc");
if (!procdir)
- perror_msg_and_die ("opendir /proc");
+ bb_perror_msg_and_die ("opendir /proc");
foundany = 0;
while ((entry = readdir(procdir)) != NULL) {
@@ -196,7 +196,7 @@ do_procfs(void)
}
closedir(procdir);
if (!foundany)
- error_msg_and_die ("nothing in /proc - not mounted?");
+ bb_error_msg_and_die ("nothing in /proc - not mounted?");
}
@@ -214,7 +214,7 @@ do_stop(void)
else if (userspec)
sprintf(what, "process(es) owned by `%s'", userspec);
else
- error_msg_and_die ("internal error, please report");
+ bb_error_msg_and_die ("internal error, please report");
if (!found) {
printf("no %s found; none killed.\n", what);
@@ -225,7 +225,7 @@ do_stop(void)
p->pid = -p->pid;
killed++;
} else {
- perror_msg("warning: failed to kill %d:", p->pid);
+ bb_perror_msg("warning: failed to kill %d:", p->pid);
}
}
if (killed) {
@@ -262,10 +262,10 @@ start_stop_daemon_main(int argc, char **argv)
*--argv = startas;
if (fork_before_exec) {
if (daemon(0, 0) == -1)
- perror_msg_and_die ("unable to fork");
+ bb_perror_msg_and_die ("unable to fork");
}
setsid();
execv(startas, argv);
- perror_msg_and_die ("unable to start %s", startas);
+ bb_perror_msg_and_die ("unable to start %s", startas);
}
diff --git a/debianutils/which.c b/debianutils/which.c
index b2af5a8ea..fbcfb371b 100644
--- a/debianutils/which.c
+++ b/debianutils/which.c
@@ -34,7 +34,7 @@ extern int which_main(int argc, char **argv)
int i, count=1, found, status = EXIT_SUCCESS;
if (argc <= 1 || **(argv + 1) == '-')
- show_usage();
+ bb_show_usage();
argc--;
path_list = getenv("PATH");
diff --git a/editors/awk.c b/editors/awk.c
index 44c2f45b2..0f8cf94f4 100644
--- a/editors/awk.c
+++ b/editors/awk.c
@@ -463,7 +463,7 @@ static const char EMSG_NO_MATH[] = "Math support is not compiled in";
static void syntax_error(const char * const message)
{
- error_msg("%s:%i: %s", programname, lineno, message);
+ bb_error_msg("%s:%i: %s", programname, lineno, message);
awk_exit(1);
}
@@ -546,7 +546,7 @@ static void *hash_find(xhash *hash, char *name) {
if (++hash->nel / hash->csize > 10)
hash_rebuild(hash);
- l = xstrlen(name) + 1;
+ l = bb_strlen(name) + 1;
hi = xcalloc(sizeof(hash_item) + l, 1);
memcpy(hi->name, name, l);
@@ -571,7 +571,7 @@ static void hash_remove(xhash *hash, char *name) {
while (*phi) {
hi = *phi;
if (strcmp(hi->name, name) == 0) {
- hash->glen -= (xstrlen(name) + 1);
+ hash->glen -= (bb_strlen(name) + 1);
hash->nel--;
*phi = hi->next;
free(hi);
@@ -609,7 +609,7 @@ static char nextchar(char **s) {
c = *((*s)++);
pps = *s;
- if (c == '\\') c = process_escape_sequence((const char**)s);
+ if (c == '\\') c = bb_process_escape_sequence((const char**)s);
if (c == '\\' && *s == pps) c = *((*s)++);
return c;
}
@@ -621,7 +621,7 @@ static inline int isalnum_(int c) {
static FILE *afopen(const char *path, const char *mode) {
- return (*path == '-' && *(path+1) == '\0') ? stdin : xfopen(path, mode);
+ return (*path == '-' && *(path+1) == '\0') ? stdin : bb_xfopen(path, mode);
}
/* -------- working with variables (set/get/copy/etc) -------- */
@@ -683,7 +683,7 @@ static var *setvar_p(var *v, char *value) {
/* same as setvar_p but make a copy of string */
static var *setvar_s(var *v, char *value) {
- return setvar_p(v, (value && *value) ? xstrdup(value) : NULL);
+ return setvar_p(v, (value && *value) ? bb_xstrdup(value) : NULL);
}
/* same as setvar_s but set USER flag */
@@ -720,7 +720,7 @@ static char *getvar_s(var *v) {
/* if v is numeric and has no cached string, convert it to string */
if ((v->type & (VF_NUMBER | VF_CACHED)) == VF_NUMBER) {
fmt_num(buf, MAXVARFMT, getvar_s(V[CONVFMT]), v->number, TRUE);
- v->string = xstrdup(buf);
+ v->string = bb_xstrdup(buf);
v->type |= VF_CACHED;
}
return (v->string == NULL) ? "" : v->string;
@@ -755,7 +755,7 @@ static var *copyvar(var *dest, var *src) {
dest->type |= (src->type & ~VF_DONTTOUCH);
dest->number = src->number;
if (src->string)
- dest->string = xstrdup(src->string);
+ dest->string = bb_xstrdup(src->string);
}
handle_special(dest);
return dest;
@@ -903,7 +903,7 @@ static unsigned long next_token(unsigned long expected) {
syntax_error(EMSG_UNEXP_EOS);
if ((*s++ = *p++) == '\\') {
pp = p;
- *(s-1) = process_escape_sequence((const char **)&p);
+ *(s-1) = bb_process_escape_sequence((const char **)&p);
if (*pp == '\\') *s++ = '\\';
if (p == pp) *s++ = *p++;
}
@@ -1153,7 +1153,7 @@ static node *chain_node(unsigned long info) {
if (seq->programname != programname) {
seq->programname = programname;
n = chain_node(OC_NEWSOURCE);
- n->l.s = xstrdup(programname);
+ n->l.s = bb_xstrdup(programname);
}
n = seq->last;
@@ -1373,7 +1373,7 @@ static node *mk_splitter(char *s, tsplitter *spl) {
regfree(re);
regfree(ire);
}
- if (xstrlen(s) > 1) {
+ if (bb_strlen(s) > 1) {
mk_re_node(s, n, re);
} else {
n->info = (unsigned long) *s;
@@ -1441,7 +1441,7 @@ static int awk_split(char *s, node *spl, char **slist) {
regmatch_t pmatch[2];
/* in worst case, each char would be a separate field */
- *slist = s1 = xstrndup(s, xstrlen(s) * 2 + 3);
+ *slist = s1 = bb_xstrndup(s, bb_strlen(s) * 2 + 3);
c[0] = c[1] = (char)spl->info;
c[2] = c[3] = '\0';
@@ -1536,12 +1536,12 @@ static void handle_special(var *v) {
/* recalculate $0 */
sep = getvar_s(V[OFS]);
- sl = xstrlen(sep);
+ sl = bb_strlen(sep);
b = NULL;
len = 0;
for (i=0; i<n; i++) {
s = getvar_s(&Fields[i]);
- l = xstrlen(s);
+ l = bb_strlen(s);
if (b) {
memcpy(b+len, sep, sl);
len += sl;
@@ -1744,7 +1744,7 @@ static char *awk_printf(node *n) {
var *v, *arg;
v = nvalloc(1);
- fmt = f = xstrdup(getvar_s(evaluate(nextarg(&n), v)));
+ fmt = f = bb_xstrdup(getvar_s(evaluate(nextarg(&n), v)));
i = 0;
while (*f) {
@@ -1767,7 +1767,7 @@ static char *awk_printf(node *n) {
} else if (c == 's') {
s1 = getvar_s(arg);
- qrealloc(&b, incr+i+xstrlen(s1), &bsize);
+ qrealloc(&b, incr+i+bb_strlen(s1), &bsize);
i += sprintf(b+i, s, s1);
} else {
@@ -1807,7 +1807,7 @@ static int awk_sub(node *rn, char *repl, int nm, var *src, var *dest, int ex) {
i = di = 0;
sp = getvar_s(src);
- rl = xstrlen(repl);
+ rl = bb_strlen(repl);
while (regexec(re, sp, 10, pmatch, sp==getvar_s(src) ? 0:REG_NOTBOL) == 0) {
so = pmatch[0].rm_so;
eo = pmatch[0].rm_eo;
@@ -1920,7 +1920,7 @@ static var *exec_builtin(node *op, var *res) {
break;
case B_ss:
- l = xstrlen(as[0]);
+ l = bb_strlen(as[0]);
i = getvar_i(av[1]) - 1;
if (i>l) i=l; if (i<0) i=0;
n = (nargs > 2) ? getvar_i(av[2]) : l-i;
@@ -1938,7 +1938,7 @@ static var *exec_builtin(node *op, var *res) {
case B_up:
to_xxx = toupper;
lo_cont:
- s1 = s = xstrdup(as[0]);
+ s1 = s = bb_xstrdup(as[0]);
while (*s1) {
*s1 = (*to_xxx)(*s1);
s1++;
@@ -1948,8 +1948,8 @@ lo_cont:
case B_ix:
n = 0;
- ll = xstrlen(as[1]);
- l = xstrlen(as[0]) - ll;
+ ll = bb_strlen(as[1]);
+ l = bb_strlen(as[0]) - ll;
if (ll > 0 && l >= 0) {
if (! icase) {
s = strstr(as[0], as[1]);
@@ -2112,10 +2112,10 @@ static var *evaluate(node *op, var *res) {
if (! X.rsm->F) {
if (opn == '|') {
if((X.rsm->F = popen(R.s, "w")) == NULL)
- perror_msg_and_die("popen");
+ bb_perror_msg_and_die("popen");
X.rsm->is_pipe = 1;
} else {
- X.rsm->F = xfopen(R.s, opn=='w' ? "w" : "a");
+ X.rsm->F = bb_xfopen(R.s, opn=='w' ? "w" : "a");
}
}
X.F = X.rsm->F;
@@ -2269,7 +2269,7 @@ re_cont:
X.rsm->F = popen(L.s, "r");
X.rsm->is_pipe = TRUE;
} else {
- X.rsm->F = fopen(L.s, "r"); /* not xfopen! */
+ X.rsm->F = fopen(L.s, "r"); /* not bb_xfopen! */
}
}
} else {
@@ -2351,7 +2351,7 @@ re_cont:
case F_le:
if (! op1)
L.s = getvar_s(V[F0]);
- R.d = xstrlen(L.s);
+ R.d = bb_strlen(L.s);
break;
case F_sy:
@@ -2439,12 +2439,12 @@ re_cont:
/* concatenation (" ") and index joining (",") */
case XC( OC_CONCAT ):
case XC( OC_COMMA ):
- opn = xstrlen(L.s) + xstrlen(R.s) + 2;
+ opn = bb_strlen(L.s) + bb_strlen(R.s) + 2;
X.s = (char *)xmalloc(opn);
strcpy(X.s, L.s);
if ((opinfo & OPCLSMASK) == OC_COMMA) {
L.s = getvar_s(V[SUBSEP]);
- X.s = (char *)xrealloc(X.s, opn + xstrlen(L.s));
+ X.s = (char *)xrealloc(X.s, opn + bb_strlen(L.s));
strcat(X.s, L.s);
}
strcat(X.s, R.s);
@@ -2554,7 +2554,7 @@ static int is_assignment(char *expr) {
char *exprc, *s, *s0, *s1;
- exprc = xstrdup(expr);
+ exprc = bb_xstrdup(expr);
if (!isalnum_(*exprc) || (s = strchr(exprc, '=')) == NULL) {
free(exprc);
return FALSE;
@@ -2649,7 +2649,7 @@ extern int awk_main(int argc, char **argv) {
}
for (envp=environ; *envp; envp++) {
- s = xstrdup(*envp);
+ s = bb_xstrdup(*envp);
s1 = strchr(s, '=');
*(s1++) = '\0';
setvar_u(findvar(iamarray(V[ENVIRON]), s), s1);
@@ -2663,7 +2663,7 @@ extern int awk_main(int argc, char **argv) {
break;
case 'v':
if (! is_assignment(optarg))
- show_usage();
+ bb_show_usage();
break;
case 'f':
from_file = TRUE;
@@ -2680,17 +2680,17 @@ extern int awk_main(int argc, char **argv) {
free(s);
break;
case 'W':
- error_msg("Warning: unrecognized option '-W %s' ignored\n", optarg);
+ bb_error_msg("Warning: unrecognized option '-W %s' ignored\n", optarg);
break;
default:
- show_usage();
+ bb_show_usage();
}
}
if (!from_file) {
if (argc == optind)
- show_usage();
+ bb_show_usage();
programname="cmd. line";
parse_program(argv[optind++]);
diff --git a/editors/sed.c b/editors/sed.c
index 8bd627a9c..2ff028498 100644
--- a/editors/sed.c
+++ b/editors/sed.c
@@ -200,7 +200,7 @@ static int get_address(char *delimiter, char *my_str, int *linenum, regex_t **re
}
idx = index_of_next_unescaped_regexp_delim(*delimiter, my_str, ++idx);
if (idx == -1) {
- error_msg_and_die("unterminated match expression");
+ bb_error_msg_and_die("unterminated match expression");
}
my_str[idx] = '\0';
*regex = (regex_t *)xmalloc(sizeof(regex_t));
@@ -230,7 +230,7 @@ static int parse_subst_cmd(sed_cmd_t * const sed_cmd, const char *substr)
/* verify that the 's' is followed by something. That something
* (typically a 'slash') is now our regexp delimiter... */
if (substr[idx] == '\0')
- error_msg_and_die("bad format in substitution expression");
+ bb_error_msg_and_die("bad format in substitution expression");
else
sed_cmd->delimiter=substr[idx];
@@ -238,8 +238,8 @@ static int parse_subst_cmd(sed_cmd_t * const sed_cmd, const char *substr)
oldidx = idx+1;
idx = index_of_next_unescaped_regexp_delim(sed_cmd->delimiter, substr, ++idx);
if (idx == -1)
- error_msg_and_die("bad format in substitution expression");
- match = xstrndup(substr + oldidx, idx - oldidx);
+ bb_error_msg_and_die("bad format in substitution expression");
+ match = bb_xstrndup(substr + oldidx, idx - oldidx);
/* determine the number of back references in the match string */
/* Note: we compute this here rather than in the do_subst_command()
@@ -257,8 +257,8 @@ static int parse_subst_cmd(sed_cmd_t * const sed_cmd, const char *substr)
oldidx = idx+1;
idx = index_of_next_unescaped_regexp_delim(sed_cmd->delimiter, substr, ++idx);
if (idx == -1)
- error_msg_and_die("bad format in substitution expression");
- sed_cmd->replace = xstrndup(substr + oldidx, idx - oldidx);
+ bb_error_msg_and_die("bad format in substitution expression");
+ sed_cmd->replace = bb_xstrndup(substr + oldidx, idx - oldidx);
/* process the flags */
while (substr[++idx]) {
@@ -278,7 +278,7 @@ static int parse_subst_cmd(sed_cmd_t * const sed_cmd, const char *substr)
if (strchr(semicolon_whitespace, substr[idx]))
goto out;
/* else */
- error_msg_and_die("bad option in substitution expression");
+ bb_error_msg_and_die("bad option in substitution expression");
}
}
@@ -317,7 +317,7 @@ static int parse_edit_cmd(sed_cmd_t *sed_cmd, const char *editstr)
*
*/
if ((*editstr != '\\') || ((editstr[1] != '\n') && (editstr[1] != '\r'))) {
- error_msg_and_die("bad format in edit expression");
+ bb_error_msg_and_die("bad format in edit expression");
}
/* store the edit line text */
@@ -390,20 +390,20 @@ static char *parse_cmd_str(sed_cmd_t * const sed_cmd, char *cmdstr)
/* handle edit cmds: (a)ppend, (i)nsert, and (c)hange */
else if (strchr("aic", sed_cmd->cmd)) {
if ((sed_cmd->end_line || sed_cmd->end_match) && sed_cmd->cmd != 'c')
- error_msg_and_die("only a beginning address can be specified for edit commands");
+ bb_error_msg_and_die("only a beginning address can be specified for edit commands");
cmdstr += parse_edit_cmd(sed_cmd, cmdstr);
}
/* handle file cmds: (r)ead */
else if (sed_cmd->cmd == 'r') {
if (sed_cmd->end_line || sed_cmd->end_match)
- error_msg_and_die("Command only uses one address");
+ bb_error_msg_and_die("Command only uses one address");
cmdstr += parse_file_cmd(sed_cmd, cmdstr);
}
/* if it wasnt a single-letter command that takes no arguments
* then it must be an invalid command.
*/
else if (strchr("nNpPqd=", sed_cmd->cmd) == 0) {
- error_msg_and_die("Unsupported command %c", sed_cmd->cmd);
+ bb_error_msg_and_die("Unsupported command %c", sed_cmd->cmd);
}
/* give back whatever's left over */
@@ -442,7 +442,7 @@ static char *add_cmd(sed_cmd_t *sed_cmd, char *cmdstr)
cmdstr++;
idx = get_address(&(sed_cmd->delimiter), cmdstr, &sed_cmd->end_line, &sed_cmd->end_match);
if (idx == 0) {
- error_msg_and_die("get_address: no address found in string\n"
+ bb_error_msg_and_die("get_address: no address found in string\n"
"\t(you probably didn't check the string you passed me)");
}
cmdstr += idx;
@@ -465,7 +465,7 @@ static char *add_cmd(sed_cmd_t *sed_cmd, char *cmdstr)
* with <blank>s.
*/
if (isblank(cmdstr[idx]) {
- error_msg_and_die("blank follows '!'");
+ bb_error_msg_and_die("blank follows '!'");
}
#else
/* skip whitespace before the command */
@@ -478,7 +478,7 @@ static char *add_cmd(sed_cmd_t *sed_cmd, char *cmdstr)
/* last part (mandatory) will be a command */
if (*cmdstr == '\0')
- error_msg_and_die("missing command");
+ bb_error_msg_and_die("missing command");
sed_cmd->cmd = *cmdstr;
cmdstr++;
@@ -517,14 +517,16 @@ static void load_cmd_file(char *filename)
FILE *cmdfile;
char *line;
char *nextline;
+ char *e;
- cmdfile = xfopen(filename, "r");
+ cmdfile = bb_xfopen(filename, "r");
- while ((line = get_line_from_file(cmdfile)) != NULL) {
+ while ((line = bb_get_line_from_file(cmdfile)) != NULL) {
/* if a line ends with '\' it needs the next line appended to it */
- while (line[strlen(line)-2] == '\\' &&
- (nextline = get_line_from_file(cmdfile)) != NULL) {
- line = xrealloc(line, strlen(line) + strlen(nextline) + 1);
+ while (((e = last_char_is(line, '\n')) != NULL)
+ && (e > line) && (e[-1] == '\\')
+ && ((nextline = bb_get_line_from_file(cmdfile)) != NULL)) {
+ line = xrealloc(line, (e - line) + 1 + strlen(nextline) + 1);
strcat(line, nextline);
free(nextline);
}
@@ -677,20 +679,18 @@ static void process_file(FILE *file)
int altered;
int i;
- line = get_line_from_file(file);
+ line = bb_get_chomped_line_from_file(file);
if (line == NULL) {
return;
}
- chomp(line);
/* go through every line in the file */
do {
char *next_line;
/* Read one line in advance so we can act on the last line, the '$' address */
- next_line = get_line_from_file(file);
+ next_line = bb_get_chomped_line_from_file(file);
- chomp(next_line);
linenum++;
altered = 0;
@@ -805,7 +805,7 @@ static void process_file(FILE *file)
puts(line);
outfile = fopen(sed_cmd->filename, "r");
if (outfile)
- print_file(outfile);
+ bb_xprint_and_close_file(outfile);
/* else if we couldn't open the output file,
* no biggie, just don't print anything */
altered++;
@@ -817,16 +817,14 @@ static void process_file(FILE *file)
case 'n': /* Read next line from input */
free(line);
line = next_line;
- next_line = get_line_from_file(file);
- chomp(next_line);
+ next_line = bb_get_chomped_line_from_file(file);
linenum++;
break;
case 'N': /* Append the next line to the current line */
line = realloc(line, strlen(line) + strlen(next_line) + 2);
strcat(line, "\n");
strcat(line, next_line);
- next_line = get_line_from_file(file);
- chomp(next_line);
+ next_line = bb_get_chomped_line_from_file(file);
linenum++;
}
}
@@ -880,7 +878,7 @@ extern int sed_main(int argc, char **argv)
#ifdef CONFIG_FEATURE_CLEAN_UP
/* destroy command strings on exit */
if (atexit(destroy_cmd_strs) == -1)
- perror_msg_and_die("atexit");
+ bb_perror_msg_and_die("atexit");
#endif
/* do normal option parsing */
@@ -896,7 +894,7 @@ extern int sed_main(int argc, char **argv)
load_cmd_file(optarg);
break;
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -904,7 +902,7 @@ extern int sed_main(int argc, char **argv)
* argv[optind] should be the pattern. no pattern, no worky */
if (ncmds == 0) {
if (argv[optind] == NULL)
- show_usage();
+ bb_show_usage();
else {
add_cmd_str(argv[optind]);
optind++;
@@ -921,7 +919,7 @@ extern int sed_main(int argc, char **argv)
int i;
FILE *file;
for (i = optind; i < argc; i++) {
- file = wfopen(argv[i], "r");
+ file = bb_wfopen(argv[i], "r");
if (file) {
process_file(file);
fclose(file);
diff --git a/editors/vi.c b/editors/vi.c
index cda17db1a..144e9d760 100644
--- a/editors/vi.c
+++ b/editors/vi.c
@@ -19,7 +19,7 @@
*/
static const char vi_Version[] =
- "$Id: vi.c,v 1.27 2002/12/03 21:48:15 bug1 Exp $";
+ "$Id: vi.c,v 1.28 2003/03/19 09:11:45 mjn3 Exp $";
/*
* To compile for standalone use:
@@ -403,7 +403,7 @@ extern int vi_main(int argc, char **argv)
for (; optind < argc; optind++) {
editing = 1; // 0=exit, 1=one file, 2+ =many files
free(cfn);
- cfn = (Byte *) xstrdup(argv[optind]);
+ cfn = (Byte *) bb_xstrdup(argv[optind]);
edit_file(cfn);
}
}
@@ -597,7 +597,7 @@ static Byte *get_one_address(Byte * p, int *addr) // get colon addr, if present
*q++ = *p;
*q = '\0';
}
- pat = (Byte *) xstrdup((char *) buf); // save copy of pattern
+ pat = (Byte *) bb_xstrdup((char *) buf); // save copy of pattern
if (*p == '/')
p++;
q = char_search(dot, pat, FORWARD, FULL);
@@ -811,7 +811,7 @@ static void colon(Byte * buf)
// There is a read-able regular file
// make this the current file
- q = (Byte *) xstrdup((char *) fn); // save the cfn
+ q = (Byte *) bb_xstrdup((char *) fn); // save the cfn
free(cfn); // free the old name
cfn = q; // remember new cfn
@@ -862,7 +862,7 @@ static void colon(Byte * buf)
if (strlen((char *) args) > 0) {
// user wants a new filename
free(cfn);
- cfn = (Byte *) xstrdup((char *) args);
+ cfn = (Byte *) bb_xstrdup((char *) args);
} else {
// user wants file status info
edit_status();
@@ -2432,7 +2432,7 @@ static Byte *get_input_line(Byte * prompt) // get input line- use "status line"
}
refresh(FALSE);
free(obufp);
- obufp = (Byte *) xstrdup((char *) buf);
+ obufp = (Byte *) bb_xstrdup((char *) buf);
return (obufp);
}
@@ -3263,7 +3263,7 @@ key_cmd_mode:
// Stuff the last_modifying_cmd back into stdin
// and let it be re-executed.
if (last_modifying_cmd != 0) {
- ioq = ioq_start = (Byte *) xstrdup((char *) last_modifying_cmd);
+ ioq = ioq_start = (Byte *) bb_xstrdup((char *) last_modifying_cmd);
}
break;
#endif /* CONFIG_FEATURE_VI_DOT_CMD */
@@ -3278,7 +3278,7 @@ key_cmd_mode:
if (strlen((char *) q) > 1) { // new pat- save it and find
// there is a new pat
free(last_search_pattern);
- last_search_pattern = (Byte *) xstrdup((char *) q);
+ last_search_pattern = (Byte *) bb_xstrdup((char *) q);
goto dc3; // now find the pattern
}
// user changed mind and erased the "/"- do nothing
diff --git a/findutils/find.c b/findutils/find.c
index 048aac503..58bc8bf9c 100644
--- a/findutils/find.c
+++ b/findutils/find.c
@@ -167,7 +167,7 @@ static int find_type(char *type)
}
if (mask == 0 || type[1] != '\0')
- error_msg_and_die(msg_invalid_arg, type, "-type");
+ bb_error_msg_and_die(msg_invalid_arg, type, "-type");
return mask;
}
@@ -192,22 +192,22 @@ int find_main(int argc, char **argv)
}
else if (strcmp(argv[i], "-name") == 0) {
if (++i == argc)
- error_msg_and_die(msg_req_arg, "-name");
+ bb_error_msg_and_die(msg_req_arg, "-name");
pattern = argv[i];
#ifdef CONFIG_FEATURE_FIND_TYPE
} else if (strcmp(argv[i], "-type") == 0) {
if (++i == argc)
- error_msg_and_die(msg_req_arg, "-type");
+ bb_error_msg_and_die(msg_req_arg, "-type");
type_mask = find_type(argv[i]);
#endif
#ifdef CONFIG_FEATURE_FIND_PERM
} else if (strcmp(argv[i], "-perm") == 0) {
char *end;
if (++i == argc)
- error_msg_and_die(msg_req_arg, "-perm");
+ bb_error_msg_and_die(msg_req_arg, "-perm");
perm_mask = strtol(argv[i], &end, 8);
if ((end[0] != '\0') || (perm_mask > 07777))
- error_msg_and_die(msg_invalid_arg, argv[i], "-perm");
+ bb_error_msg_and_die(msg_invalid_arg, argv[i], "-perm");
if ((perm_char = argv[i][0]) == '-')
perm_mask = -perm_mask;
#endif
@@ -215,10 +215,10 @@ int find_main(int argc, char **argv)
} else if (strcmp(argv[i], "-mtime") == 0) {
char *end;
if (++i == argc)
- error_msg_and_die(msg_req_arg, "-mtime");
+ bb_error_msg_and_die(msg_req_arg, "-mtime");
mtime_days = strtol(argv[i], &end, 10);
if (end[0] != '\0')
- error_msg_and_die(msg_invalid_arg, argv[i], "-mtime");
+ bb_error_msg_and_die(msg_invalid_arg, argv[i], "-mtime");
if ((mtime_char = argv[i][0]) == '-')
mtime_days = -mtime_days;
#endif
@@ -231,14 +231,14 @@ int find_main(int argc, char **argv)
if ( firstopt == 1 ) {
if ( stat ( ".", &stbuf ) < 0 )
- error_msg_and_die("could not stat '.'" );
+ bb_error_msg_and_die("could not stat '.'" );
xdev_dev [0] = stbuf. st_dev;
}
else {
for (i = 1; i < firstopt; i++) {
if ( stat ( argv [i], &stbuf ) < 0 )
- error_msg_and_die("could not stat '%s'", argv [i] );
+ bb_error_msg_and_die("could not stat '%s'", argv [i] );
xdev_dev [i-1] = stbuf. st_dev;
}
}
@@ -247,22 +247,22 @@ int find_main(int argc, char **argv)
} else if (strcmp(argv[i], "-newer") == 0) {
struct stat stat_newer;
if (++i == argc)
- error_msg_and_die(msg_req_arg, "-newer");
+ bb_error_msg_and_die(msg_req_arg, "-newer");
if (stat (argv[i], &stat_newer) != 0)
- error_msg_and_die("file %s not found", argv[i]);
+ bb_error_msg_and_die("file %s not found", argv[i]);
newer_mtime = stat_newer.st_mtime;
#endif
#ifdef CONFIG_FEATURE_FIND_INUM
} else if (strcmp(argv[i], "-inum") == 0) {
char *end;
if (++i == argc)
- error_msg_and_die(msg_req_arg, "-inum");
+ bb_error_msg_and_die(msg_req_arg, "-inum");
inode_num = strtol(argv[i], &end, 10);
if (end[0] != '\0')
- error_msg_and_die(msg_invalid_arg, argv[i], "-inum");
+ bb_error_msg_and_die(msg_invalid_arg, argv[i], "-inum");
#endif
} else
- show_usage();
+ bb_show_usage();
}
if (firstopt == 1) {
diff --git a/findutils/grep.c b/findutils/grep.c
index cc2b697e8..b4a25923e 100644
--- a/findutils/grep.c
+++ b/findutils/grep.c
@@ -88,8 +88,7 @@ static void grep_file(FILE *file)
int idx = 0; /* used for iteration through the circular buffer */
#endif /* CONFIG_FEATURE_GREP_CONTEXT */
- while ((line = get_line_from_file(file)) != NULL) {
- chomp(line);
+ while ((line = bb_get_chomped_line_from_file(file)) != NULL) {
linenum++;
for (i = 0; i < nregexes; i++) {
@@ -154,7 +153,7 @@ static void grep_file(FILE *file)
/* Add the line to the circular 'before' buffer */
if(lines_before) {
free(before_buf[curpos]);
- before_buf[curpos] = xstrdup(line);
+ before_buf[curpos] = bb_xstrdup(line);
curpos = (curpos + 1) % lines_before;
}
}
@@ -205,9 +204,8 @@ static void add_regex(const char *restr)
static void load_regexes_from_file(const char *filename)
{
char *line;
- FILE *f = xfopen(filename, "r");
- while ((line = get_line_from_file(f)) != NULL) {
- chomp(line);
+ FILE *f = bb_xfopen(filename, "r");
+ while ((line = bb_get_chomped_line_from_file(f)) != NULL) {
add_regex(line);
free(line);
}
@@ -242,7 +240,7 @@ extern int grep_main(int argc, char **argv)
#endif
#ifdef CONFIG_FEATURE_GREP_EGREP_ALIAS
- if (strcmp(get_last_path_component(argv[0]), "egrep") == 0)
+ if (strcmp(bb_get_last_path_component(argv[0]), "egrep") == 0)
reflags |= REG_EXTENDED;
#endif
@@ -298,23 +296,23 @@ extern int grep_main(int argc, char **argv)
case 'A':
lines_after = strtoul(optarg, &junk, 10);
if(*junk != '\0')
- error_msg_and_die("invalid context length argument");
+ bb_error_msg_and_die("invalid context length argument");
break;
case 'B':
lines_before = strtoul(optarg, &junk, 10);
if(*junk != '\0')
- error_msg_and_die("invalid context length argument");
+ bb_error_msg_and_die("invalid context length argument");
before_buf = (char **)xcalloc(lines_before, sizeof(char *));
break;
case 'C':
lines_after = lines_before = strtoul(optarg, &junk, 10);
if(*junk != '\0')
- error_msg_and_die("invalid context length argument");
+ bb_error_msg_and_die("invalid context length argument");
before_buf = (char **)xcalloc(lines_before, sizeof(char *));
break;
#endif /* CONFIG_FEATURE_GREP_CONTEXT */
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -322,7 +320,7 @@ extern int grep_main(int argc, char **argv)
* argv[optind] should be the pattern. no pattern, no worky */
if (nregexes == 0) {
if (argv[optind] == NULL)
- show_usage();
+ bb_show_usage();
else {
add_regex(argv[optind]);
optind++;
@@ -356,7 +354,7 @@ extern int grep_main(int argc, char **argv)
file = fopen(cur_file, "r");
if (file == NULL) {
if (!suppress_err_msgs)
- perror_msg("%s", cur_file);
+ bb_perror_msg("%s", cur_file);
}
else {
grep_file(file);
diff --git a/findutils/xargs.c b/findutils/xargs.c
index 677618dc0..d4bed57f0 100644
--- a/findutils/xargs.c
+++ b/findutils/xargs.c
@@ -53,11 +53,11 @@ static void xargs_exec(char * const * args)
wait(NULL);
if(common[0]) {
errno = common[0];
- perror_msg_and_die("%s", args[0]);
+ bb_perror_msg_and_die("%s", args[0]);
}
}
} else {
- perror_msg_and_die("vfork");
+ bb_perror_msg_and_die("vfork");
}
}
@@ -81,7 +81,7 @@ int xargs_main(int argc, char **argv)
flg_no_empty = 1;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
@@ -101,9 +101,7 @@ int xargs_main(int argc, char **argv)
/* Now, read in one line at a time from stdin, and store this
* line to be used later as an argument to the command */
- while ((file_to_act_on = get_line_from_file(stdin)) != NULL) {
- /* eat the newline off the filename. */
- chomp(file_to_act_on);
+ while ((file_to_act_on = bb_get_chomped_line_from_file(stdin)) != NULL) {
if(file_to_act_on[0] != 0 || flg_no_empty == 0) {
args[a] = file_to_act_on[0] ? file_to_act_on : NULL;
if(flg_vi) {
@@ -114,7 +112,7 @@ int xargs_main(int argc, char **argv)
}
fprintf(stderr, "%s", ((flg_vi & 2) ? " ?..." : "\n"));
}
- if((flg_vi & 2) == 0 || ask_confirmation() != 0 ) {
+ if((flg_vi & 2) == 0 || bb_ask_confirmation() != 0 ) {
xargs_exec(args);
}
}
diff --git a/include/dump.h b/include/dump.h
index 0e8dbe07f..3f4b480b2 100644
--- a/include/dump.h
+++ b/include/dump.h
@@ -38,5 +38,12 @@ typedef struct _fs { /* format strings */
int bcnt;
} FS;
-void add(char *fmt);
-int dump (char **argv);
+extern void bb_dump_add(const char *fmt);
+extern int bb_dump_dump (char **argv);
+extern int bb_dump_size(FS * fs);
+
+extern FS *bb_dump_fshead; /* head of format strings */
+extern int bb_dump_blocksize; /* data block size */
+extern int bb_dump_length; /* max bytes to read */
+extern enum _vflag bb_dump_vflag;
+extern off_t bb_dump_skip; /* bytes to skip */
diff --git a/include/libbb.h b/include/libbb.h
index 8cb72de8b..f79def321 100644
--- a/include/libbb.h
+++ b/include/libbb.h
@@ -28,6 +28,7 @@
#include <stdarg.h>
#include <sys/stat.h>
#include <sys/types.h>
+#include <termios.h>
#include <netdb.h>
@@ -86,84 +87,132 @@ char *strtok_r(char *s, const char *delim, char **ptrptr);
#define MAX(a,b) (((a)>(b))?(a):(b))
#endif
-extern void show_usage(void) __attribute__ ((noreturn));
-extern void error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
-extern void error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
-extern void perror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
-extern void perror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
-extern void vherror_msg(const char *s, va_list p);
-extern void herror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
-extern void herror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
+extern void bb_show_usage(void) __attribute__ ((noreturn));
+extern void bb_error_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
+extern void bb_error_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
+extern void bb_perror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
+extern void bb_perror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
+extern void bb_vherror_msg(const char *s, va_list p);
+extern void bb_herror_msg(const char *s, ...) __attribute__ ((format (printf, 1, 2)));
+extern void bb_herror_msg_and_die(const char *s, ...) __attribute__ ((noreturn, format (printf, 1, 2)));
+
+extern void bb_perror_nomsg_and_die(void) __attribute__ ((noreturn));
+extern void bb_perror_nomsg(void);
/* These two are used internally -- you shouldn't need to use them */
-extern void verror_msg(const char *s, va_list p);
-extern void vperror_msg(const char *s, va_list p);
-
-const char *mode_string(int mode);
-const char *time_string(time_t timeVal);
-int is_directory(const char *name, int followLinks, struct stat *statBuf);
-int isDevice(const char *name);
-
-int remove_file(const char *path, int flags);
-int copy_file(const char *source, const char *dest, int flags);
-int copy_file_chunk(FILE *src_file, FILE *dst_file, unsigned long long chunksize);
-char *buildName(const char *dirName, const char *fileName);
-int makeString(int argc, const char **argv, char *buf, int bufLen);
-char *getChunk(int size);
-char *chunkstrdup(const char *str);
-void freeChunks(void);
-ssize_t safe_read(int fd, void *buf, size_t count);
-int full_write(int fd, const char *buf, int len);
-int full_read(int fd, char *buf, int len);
-int recursive_action(const char *fileName, int recurse, int followLinks, int depthFirst,
+extern void bb_verror_msg(const char *s, va_list p) __attribute__ ((format (printf, 1, 0)));
+extern void bb_vperror_msg(const char *s, va_list p) __attribute__ ((format (printf, 1, 0)));
+
+extern const char *bb_mode_string(int mode);
+extern int is_directory(const char *name, int followLinks, struct stat *statBuf);
+
+extern int remove_file(const char *path, int flags);
+extern int copy_file(const char *source, const char *dest, int flags);
+extern ssize_t safe_read(int fd, void *buf, size_t count);
+extern ssize_t bb_full_write(int fd, const void *buf, size_t len);
+extern ssize_t bb_full_read(int fd, void *buf, size_t len);
+extern int recursive_action(const char *fileName, int recurse,
+ int followLinks, int depthFirst,
int (*fileAction) (const char *fileName, struct stat* statbuf, void* userData),
int (*dirAction) (const char *fileName, struct stat* statbuf, void* userData),
void* userData);
-extern int parse_mode( const char* s, mode_t* theMode);
+extern int bb_parse_mode( const char* s, mode_t* theMode);
extern long bb_xgetlarg(char *arg, int base, long lower, long upper);
+extern unsigned long bb_baud_to_value(speed_t speed);
+extern speed_t bb_value_to_baud(unsigned long value);
+
extern int get_kernel_revision(void);
extern int get_console_fd(void);
extern struct mntent *find_mount_point(const char *name, const char *table);
extern void write_mtab(char* blockDevice, char* directory,
- char* filesystemType, long flags, char* string_flags);
+ char* filesystemType, long flags, char* string_flags);
extern void erase_mtab(const char * name);
-extern long atoi_w_units (const char *cp);
-extern long* find_pid_by_name( const char* pidName);
+extern long *find_pid_by_name( const char* pidName);
extern char *find_real_root_device_name(const char* name);
-extern char *get_line_from_file(FILE *file);
-extern void print_file(FILE *file);
-extern int copyfd(int fd1, int fd2, const off_t chunksize);
-extern int print_file_by_name(char *filename);
-extern char process_escape_sequence(const char **ptr);
-extern char *get_last_path_component(char *path);
-extern FILE *wfopen(const char *path, const char *mode);
-extern FILE *xfopen(const char *path, const char *mode);
+extern char *bb_get_line_from_file(FILE *file);
+extern char *bb_get_chomped_line_from_file(FILE *file);
+extern int bb_copyfd(int fd1, int fd2, const off_t chunksize);
+extern void bb_xprint_and_close_file(FILE *file);
+extern int bb_xprint_file_by_name(const char *filename);
+extern char bb_process_escape_sequence(const char **ptr);
+extern char *bb_get_last_path_component(char *path);
+extern FILE *bb_wfopen(const char *path, const char *mode);
+extern FILE *bb_xfopen(const char *path, const char *mode);
+
+//#warning rename?
+extern int bb_fclose_nonstdin(FILE *f);
+extern void bb_fflush_stdout_and_exit(int retval) __attribute__ ((noreturn));
+extern unsigned long bb_getopt_ulflags(int argc, char **argv, const char *applet_opts);
+//#warning rename?
+extern FILE *bb_wfopen_input(const char *filename);
+
+extern int bb_vfprintf(FILE * __restrict stream, const char * __restrict format,
+ va_list arg) __attribute__ ((format (printf, 2, 0)));
+extern int bb_vprintf(const char * __restrict format, va_list arg)
+ __attribute__ ((format (printf, 1, 0)));
+extern int bb_fprintf(FILE * __restrict stream, const char * __restrict format, ...)
+ __attribute__ ((format (printf, 2, 3)));
+extern int bb_printf(const char * __restrict format, ...)
+ __attribute__ ((format (printf, 1, 2)));
+
+//#warning rename to xferror_filename?
+extern void bb_xferror(FILE *fp, const char *fn);
+extern void bb_xferror_stdout(void);
+extern void bb_xfflush_stdout(void);
+
+extern void bb_warn_ignoring_args(int n);
+
extern void chomp(char *s);
extern void trim(char *s);
+extern const char *bb_skip_whitespace(const char *);
+
extern struct BB_applet *find_applet_by_name(const char *name);
void run_applet_by_name(const char *name, int argc, char **argv);
+//#warning is this needed anymore?
#ifndef DMALLOC
extern void *xmalloc (size_t size);
extern void *xrealloc(void *old, size_t size);
extern void *xcalloc(size_t nmemb, size_t size);
-extern char *xstrdup (const char *s);
+extern char *bb_xstrdup (const char *s);
#endif
-extern char *xstrndup (const char *s, int n);
+extern char *bb_xstrndup (const char *s, int n);
extern char * safe_strncpy(char *dst, const char *src, size_t size);
struct suffix_mult {
const char *suffix;
- int mult;
+ unsigned int mult;
};
-extern unsigned long parse_number(const char *numstr,
+extern unsigned long bb_xgetularg_bnd_sfx(const char *arg, int base,
+ unsigned long lower,
+ unsigned long upper,
+ const struct suffix_mult *suffixes);
+extern unsigned long bb_xgetularg_bnd(const char *arg, int base,
+ unsigned long lower,
+ unsigned long upper);
+extern unsigned long bb_xgetularg10_bnd(const char *arg,
+ unsigned long lower,
+ unsigned long upper);
+extern unsigned long bb_xgetularg10(const char *arg);
+
+extern long bb_xgetlarg_bnd_sfx(const char *arg, int base,
+ long lower,
+ long upper,
+ const struct suffix_mult *suffixes);
+extern long bb_xgetlarg10_sfx(const char *arg, const struct suffix_mult *suffixes);
+
+
+//#warning pitchable now?
+extern unsigned long bb_xparse_number(const char *numstr,
const struct suffix_mult *suffixes);
+//#warning change names?
+
/* These parse entries in /etc/passwd and /etc/group. This is desirable
* for BusyBox since we want to avoid using the glibc NSS stuff, which
* increases target size and is often not needed embedded systems. */
@@ -217,7 +266,7 @@ enum {
};
const char *make_human_readable_str(unsigned long size, unsigned long block_size, unsigned long display_unit);
-int ask_confirmation(void);
+int bb_ask_confirmation(void);
int klogctl(int type, char * b, int len);
char *xgetcwd(char *cwd);
@@ -228,6 +277,7 @@ char *last_char_is(const char *s, int c);
extern long arith (const char *startbuf, int *errcode);
int read_package_field(const char *package_buffer, char **field_name, char **field_value);
+//#warning yuk!
char *fgets_str(FILE *file, const char *terminating_string);
extern int uncompress(int fd_in, int fd_out);
@@ -239,19 +289,15 @@ extern int create_icmp_socket(void);
extern int create_icmp6_socket(void);
extern int xconnect(const char *host, const char *port);
+//#warning wrap this?
char *dirname (char *path);
-int make_directory (char *path, long mode, int flags);
+int bb_make_directory (char *path, long mode, int flags);
const char *u_signal_names(const char *str_sig, int *signo, int startnum);
-char *simplify_path(const char *path);
-
-#define CT_AUTO 0
-#define CT_UNIX2DOS 1
-#define CT_DOS2UNIX 2
-/* extern int convert(char *fn, int ConvType); */
+char *bb_simplify_path(const char *path);
-enum {
+enum { /* DO NOT CHANGE THESE VALUES! cp.c depends on them. */
FILEUTILS_PRESERVE_STATUS = 1,
FILEUTILS_DEREFERENCE = 2,
FILEUTILS_RECUR = 4,
@@ -259,29 +305,31 @@ enum {
FILEUTILS_INTERACTIVE = 16
};
-extern const char *applet_name;
-extern const char * const full_version;
-extern const char * const name_too_long;
-extern const char * const omitting_directory;
-extern const char * const not_a_directory;
-extern const char * const memory_exhausted;
-extern const char * const invalid_date;
-extern const char * const invalid_option;
-extern const char * const io_error;
-extern const char * const dash_dash_help;
-extern const char * const write_error;
-extern const char * const too_few_args;
-extern const char * const name_longer_than_foo;
-extern const char * const unknown;
-extern const char * const can_not_create_raw_socket;
-extern const char * const nologin_file;
-extern const char * const passwd_file;
-extern const char * const shadow_file;
-extern const char * const gshadow_file;
-extern const char * const group_file;
-extern const char * const securetty_file;
-extern const char * const motd_file;
-extern const char * const _path_login;
+extern const char *bb_applet_name;
+
+extern const char * const bb_msg_full_version;
+extern const char * const bb_msg_memory_exhausted;
+extern const char * const bb_msg_invalid_date;
+extern const char * const bb_msg_io_error;
+extern const char * const bb_msg_write_error;
+extern const char * const bb_msg_name_longer_than_foo;
+extern const char * const bb_msg_unknown;
+extern const char * const bb_msg_can_not_create_raw_socket;
+extern const char * const bb_msg_perm_denied_are_you_root;
+extern const char * const bb_msg_standard_input;
+extern const char * const bb_msg_standard_output;
+
+extern const char * const bb_path_nologin_file;
+extern const char * const bb_path_passwd_file;
+extern const char * const bb_path_shadow_file;
+extern const char * const bb_path_gshadow_file;
+extern const char * const bb_path_group_file;
+extern const char * const bb_path_securetty_file;
+extern const char * const bb_path_motd_file;
+
+extern const char bb_path_mtab_file[];
+
+extern int bb_default_error_retval;
#ifdef CONFIG_FEATURE_DEVFS
# define CURRENT_VC "/dev/vc/0"
@@ -309,6 +357,8 @@ extern const char * const _path_login;
# define LOOP_FORMAT "/dev/loop%d"
#endif
+//#warning put these in .o files
+
/* The following devices are the same on devfs and non-devfs systems. */
#define CURRENT_TTY "/dev/tty"
#define CONSOLE_DEV "/dev/console"
@@ -318,10 +368,10 @@ void add_to_ino_dev_hashtable(const struct stat *statbuf, const char *name);
void reset_ino_dev_hashtable(void);
/* Stupid gcc always includes its own builtin strlen()... */
-extern size_t xstrlen(const char *string);
-#define strlen(x) xstrlen(x)
+extern size_t bb_strlen(const char *string);
+#define strlen(x) bb_strlen(x)
-void bb_asprintf(char **string_ptr, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
+void bb_xasprintf(char **string_ptr, const char *format, ...) __attribute__ ((format (printf, 2, 3)));
#define FAIL_DELAY 3
@@ -335,10 +385,10 @@ extern char *pw_encrypt(const char *clear, const char *salt);
extern struct spwd *pwd_to_spwd(const struct passwd *pw);
extern int obscure(const char *old, const char *newval, const struct passwd *pwdp);
-extern int xopen(const char *pathname, int flags);
-extern ssize_t xread(int fd, void *buf, size_t count);
-extern void xread_all(int fd, void *buf, size_t count);
-extern unsigned char xread_char(int fd);
+extern int bb_xopen(const char *pathname, int flags);
+extern ssize_t bb_xread(int fd, void *buf, size_t count);
+extern void bb_xread_all(int fd, void *buf, size_t count);
+extern unsigned char bb_xread_char(int fd);
typedef struct {
int pid;
diff --git a/include/usage.h b/include/usage.h
index 8fc12f151..bbc0babfc 100644
--- a/include/usage.h
+++ b/include/usage.h
@@ -98,9 +98,11 @@
"\t-y\tDisplay the entire year."
#define cat_trivial_usage \
- "[FILE]..."
+ "[-u] [FILE]..."
#define cat_full_usage \
- "Concatenates FILE(s) and prints them to stdout."
+ "Concatenates FILE(s) and prints them to stdout.\n\n" \
+ "Options:\n" \
+ "\t-u\tignored since unbuffered i/o is always used"
#define cat_example_usage \
"$ cat /proc/uptime\n" \
"110716.72 17.67"
@@ -397,20 +399,34 @@
#define dpkg_deb_example_usage \
"$ dpkg-deb -X ./busybox_0.48-1_i386.deb /tmp\n"
+#ifdef CONFIG_FEATURE_DU_DEFALT_BLOCKSIZE_1K
+#define USAGE_DU_DEFALT_BLOCKSIZE_1k(a) a
+#define USAGE_NOT_DU_DEFALT_BLOCKSIZE_1k(a)
+#else
+#define USAGE_DU_DEFALT_BLOCKSIZE_1k(a)
+#define USAGE_NOT_DU_DEFALT_BLOCKSIZE_1k(a) a
+#endif
+
#define du_trivial_usage \
- "[-lsx" USAGE_HUMAN_READABLE("hm") USAGE_NOT_HUMAN_READABLE("") "k] [FILE]..."
+ "[-aHLdclsx" USAGE_HUMAN_READABLE("hm") "k] [FILE]..."
#define du_full_usage \
"Summarizes disk space used for each FILE and/or directory.\n" \
- "Disk space is printed in units of 1024 bytes.\n\n" \
- "Options:\n" \
+ "Disk space is printed in units of " \
+ USAGE_DU_DEFALT_BLOCKSIZE_1k("1024") USAGE_NOT_DU_DEFALT_BLOCKSIZE_1k("512") \
+ " bytes.\n\n" \
+ "Options:\n" \
+ "\t-a\tshow sizes of files in addition to directories\n" \
+ "\t-H\tfollow symbolic links that are FILE command line args\n" \
+ "\t-L\tfollow all symbolic links encountered\n" \
+ "\t-d N\tlimit output to directories (and files with -a) of depth < N\n" \
+ "\t-c\toutput a grand total\n" \
"\t-l\tcount sizes many times if hard linked\n" \
- "\t-s\tdisplay only a total for each argument" \
- USAGE_HUMAN_READABLE( \
- "\n\t-h\tprint sizes in human readable format (e.g., 1K 243M 2G )\n" \
- "\t-m\tprint sizes in megabytes\n" \
+ "\t-s\tdisplay only a total for each argument\n" \
"\t-x\tskip directories on different filesystems\n" \
- "\t-k\tprint sizes in kilobytes(default)") USAGE_NOT_HUMAN_READABLE( \
- "\n\t-k\tprint sizes in kilobytes(compatibility)")
+ USAGE_HUMAN_READABLE( \
+ "\t-h\tprint sizes in human readable format (e.g., 1K 243M 2G )\n" \
+ "\t-m\tprint sizes in megabytes\n" ) \
+ "\t-k\tprint sizes in kilobytes" USAGE_DU_DEFALT_BLOCKSIZE_1k("(default)")
#define du_example_usage \
"$ du\n" \
"16 ./CVS\n" \
@@ -451,25 +467,31 @@
"8|125||l4|||0|0|0|955637629|998367|0\n" \
"6|245|tty1|1|LOGIN||0|0|0|955637630|998974|0\n" \
"6|246|tty2|2|LOGIN||0|0|0|955637630|999498|0\n" \
- "7|336|pts/0|vt00andersen|andersen|:0.0|0|0|0|955637763|0|0\n"
+ "7|336|pts/0|vt00|andersen|:0.0|0|0|0|955637763|0|0\n"
+
+#ifdef CONFIG_FEATURE_FANCY_ECHO
+ #define USAGE_FANCY_ECHO(a) a
+#else
+ #define USAGE_FANCY_ECHO(a)
+#endif
#define echo_trivial_usage \
- "[-neE] [ARG ...]"
+ USAGE_FANCY_ECHO("[-neE] ") "[ARG ...]"
#define echo_full_usage \
"Prints the specified ARGs to stdout\n\n" \
- "Options:\n" \
+ USAGE_FANCY_ECHO("Options:\n" \
"\t-n\tsuppress trailing newline\n" \
"\t-e\tinterpret backslash-escaped characters (i.e., \\t=tab)\n" \
- "\t-E\tdisable interpretation of backslash-escaped characters"
+ "\t-E\tdisable interpretation of backslash-escaped characters")
#define echo_example_usage \
"$ echo "Erik is cool"\n" \
"Erik is cool\n" \
- "$ echo -e "Erik\\nis\\ncool"\n" \
+ USAGE_FANCY_ECHO("$ echo -e "Erik\\nis\\ncool"\n" \
"Erik\n" \
"is\n" \
"cool\n" \
"$ echo "Erik\\nis\\ncool"\n" \
- "Erik\\nis\\ncool\n"
+ "Erik\\nis\\ncool\n")
#define env_trivial_usage \
"[-iu] [-] [name=value]... [command]"
@@ -757,6 +779,12 @@
#define halt_full_usage \
"Halt the system."
+#ifdef CONFIG_FEATURE_FANCY_HEAD
+#define USAGE_FANCY_HEAD(a) a
+#else
+#define USAGE_FANCY_HEAD(a)
+#endif
+
#define head_trivial_usage \
"[OPTION] [FILE]..."
#define head_full_usage \
@@ -764,7 +792,11 @@
"With more than one FILE, precede each with a header giving the\n" \
"file name. With no FILE, or when FILE is -, read standard input.\n\n" \
"Options:\n" \
- "\t-n NUM\t\tPrint first NUM lines instead of first 10"
+ "\t-n NUM\t\tPrint first NUM lines instead of first 10" \
+ USAGE_FANCY_HEAD( \
+ "\n\t-c NUM\t\toutput the first NUM bytes\n" \
+ "\t-q\t\tnever output headers giving file names\n" \
+ "\t-v\t\talways output headers giving file names" )
#define head_example_usage \
"$ head -n 2 /etc/passwd\n" \
"root:x:0:0:root:/root:/bin/bash\n" \
@@ -1762,7 +1794,7 @@
"Remove (unlink) the FILE(s). You may use '--' to\n" \
"indicate that all following arguments are non-options.\n\n" \
"Options:\n" \
- "\t-i\t\talways prompt before removing each destination" \
+ "\t-i\t\talways prompt before removing each destination\n" \
"\t-f\t\tremove existing destinations, never prompt\n" \
"\t-r or -R\tremove the contents of directories recursively"
#define rm_example_usage \
@@ -1864,14 +1896,26 @@
#define sha1sum_full_usage \
"[OPTION] [FILE]"
+#ifdef CONFIG_FEATURE_FANCY_SLEEP
+ #define USAGE_FANCY_SLEEP(a) a
+ #define USAGE_NOT_FANCY_SLEEP(a)
+#else
+ #define USAGE_FANCY_SLEEP(a)
+ #define USAGE_NOT_FANCY_SLEEP(a) a
+#endif
+
#define sleep_trivial_usage \
- "N"
+ USAGE_FANCY_SLEEP("[") "N" USAGE_FANCY_SLEEP("]...")
#define sleep_full_usage \
- "Pause for N seconds."
+ USAGE_NOT_FANCY_SLEEP("Pause for N seconds.") \
+ USAGE_FANCY_SLEEP( \
+"Pause for a time equal to the total of the args given, where each arg can\n" \
+"have an optional suffix of (s)econds, (m)inutes, (h)ours, or (d)ays.")
#define sleep_example_usage \
"$ sleep 2\n" \
- "[2 second delay results]\n"
-
+ "[2 second delay results]\n" \
+ USAGE_FANCY_SLEEP("$ sleep 1d 3h 22m 8s\n" \
+ "[98528 second delay results]\n")
#ifdef CONFIG_FEATURE_SORT_UNIQUE
#define USAGE_SORT_UNIQUE(a) a
@@ -2077,7 +2121,8 @@
#define tee_full_usage \
"Copy standard input to each FILE, and also to standard output.\n\n" \
"Options:\n" \
- "\t-a\tappend to the given FILEs, do not overwrite"
+ "\t-a\tappend to the given FILEs, do not overwrite\n" \
+ "\t-i\tignore interrupt signals (SIGINT)"
#define tee_example_usage \
"$ echo "Hello" | tee /tmp/foo\n" \
"$ cat /tmp/foo\n" \
@@ -2312,7 +2357,9 @@
"Options:\n" \
"\t-c\tprefix lines by the number of occurrences\n" \
"\t-d\tonly print duplicate lines\n" \
- "\t-u\tonly print unique lines"
+ "\t-u\tonly print unique lines\n" \
+ "\t-f N\tskip the first N fields\n" \
+ "\t-s N\tskip the first N chars (after any skipped fields)"
#define uniq_example_usage \
"$ echo -e \"a\\na\\nb\\nc\\nc\\na\" | sort | uniq\n" \
"a\n" \
diff --git a/init/halt.c b/init/halt.c
index 3d4725f09..7e663227c 100644
--- a/init/halt.c
+++ b/init/halt.c
@@ -32,7 +32,7 @@ extern int halt_main(int argc, char **argv)
if (!pid || *pid<=0) {
pid = find_pid_by_name("linuxrc");
if (!pid || *pid<=0)
- error_msg_and_die("no process killed");
+ bb_error_msg_and_die("no process killed");
}
return(kill(*pid, SIGUSR1));
#else
diff --git a/init/init.c b/init/init.c
index 258a7fa6b..be91d6a8f 100644
--- a/init/init.c
+++ b/init/init.c
@@ -247,14 +247,14 @@ static void message(int device, const char *fmt, ...)
if (log_fd < 0) {
if ((log_fd = device_open(log, O_RDWR | O_NDELAY | O_NOCTTY)) < 0) {
log_fd = -2;
- error_msg("Bummer, can't write to log on %s!", log);
+ bb_error_msg("Bummer, can't write to log on %s!", log);
device = CONSOLE;
} else {
fcntl(log_fd, F_SETFD, FD_CLOEXEC);
}
}
if ((device & LOG) && (log_fd >= 0)) {
- full_write(log_fd, msg, l);
+ bb_full_write(log_fd, msg, l);
}
#endif
@@ -263,12 +263,12 @@ static void message(int device, const char *fmt, ...)
O_WRONLY | O_NOCTTY | O_NDELAY);
/* Always send console messages to /dev/console so people will see them. */
if (fd >= 0) {
- full_write(fd, msg, l);
+ bb_full_write(fd, msg, l);
close(fd);
#ifdef DEBUG_INIT
/* all descriptors may be closed */
} else {
- error_msg("Bummer, can't print: ");
+ bb_error_msg("Bummer, can't print: ");
va_start(arguments, fmt);
vfprintf(stderr, fmt, arguments);
va_end(arguments);
@@ -323,7 +323,7 @@ static int check_free_memory(void)
unsigned int result, u, s = 10;
if (sysinfo(&info) != 0) {
- perror_msg("Error checking free memory");
+ bb_perror_msg("Error checking free memory");
return -1;
}
@@ -564,11 +564,11 @@ static pid_t run(const struct init_action *a)
++cmdpath;
/* find the last component in the command pathname */
- s = get_last_path_component(cmdpath);
+ s = bb_get_last_path_component(cmdpath);
/* make a new argv[0] */
if ((cmd[0] = malloc(strlen(s) + 2)) == NULL) {
- message(LOG | CONSOLE, memory_exhausted);
+ message(LOG | CONSOLE, bb_msg_memory_exhausted);
cmd[0] = cmdpath;
} else {
cmd[0][0] = '-';
@@ -589,7 +589,7 @@ static pid_t run(const struct init_action *a)
messageD(LOG, "Waiting for enter to start '%s'"
"(pid %d, terminal %s)\n",
cmdpath, getpid(), a->terminal);
- full_write(1, press_enter, sizeof(press_enter) - 1);
+ bb_full_write(1, press_enter, sizeof(press_enter) - 1);
while(read(0, &c, 1) == 1 && c != '\n')
;
}
@@ -1017,7 +1017,7 @@ extern int init_main(int argc, char **argv)
if (!pid || *pid <= 0) {
pid = find_pid_by_name("linuxrc");
if (!pid || *pid <= 0)
- error_msg_and_die("no process killed");
+ bb_error_msg_and_die("no process killed");
}
return kill(*pid, SIGHUP);
}
@@ -1025,10 +1025,10 @@ extern int init_main(int argc, char **argv)
/* Expect to be invoked as init with PID=1 or be invoked as linuxrc */
if (getpid() != 1
#ifdef CONFIG_FEATURE_INITRD
- && strstr(applet_name, "linuxrc") == NULL
+ && strstr(bb_applet_name, "linuxrc") == NULL
#endif
) {
- show_usage();
+ bb_show_usage();
}
/* Set up sig handlers -- be sure to
* clear all of these in run() */
@@ -1068,10 +1068,10 @@ extern int init_main(int argc, char **argv)
const char * const *e;
/* Make sure environs is set to something sane */
for(e = environment; *e; e++)
- putenv(*e);
+ putenv((char *) *e);
}
/* Hello world */
- message(MAYBE_CONSOLE | LOG, "init started: %s", full_version);
+ message(MAYBE_CONSOLE | LOG, "init started: %s", bb_msg_full_version);
/* Make sure there is enough memory to do something useful. */
check_memory();
diff --git a/init/mesg.c b/init/mesg.c
index f9b46e029..7b8acf657 100644
--- a/init/mesg.c
+++ b/init/mesg.c
@@ -52,7 +52,7 @@ extern int mesg_main(int argc, char *argv[])
return EXIT_SUCCESS;
}
}
- perror_msg_and_die("%s", tty);
+ bb_perror_msg_and_die("%s", tty);
}
- show_usage();
+ bb_show_usage();
}
diff --git a/init/poweroff.c b/init/poweroff.c
index 27468bac0..aca6e2f25 100644
--- a/init/poweroff.c
+++ b/init/poweroff.c
@@ -32,7 +32,7 @@ extern int poweroff_main(int argc, char **argv)
if (!pid || *pid<=0) {
pid = find_pid_by_name("linuxrc");
if (!pid || *pid<=0)
- error_msg_and_die("no process killed");
+ bb_error_msg_and_die("no process killed");
}
return(kill(*pid, SIGUSR2));
#else
diff --git a/init/reboot.c b/init/reboot.c
index 872d9e741..8c380fa6a 100644
--- a/init/reboot.c
+++ b/init/reboot.c
@@ -52,7 +52,7 @@ extern int reboot_main(int argc, char **argv)
break;
default:
- show_usage();
+ bb_show_usage();
break;
}
}
@@ -99,7 +99,7 @@ extern int reboot_main(int argc, char **argv)
if (!pid || *pid<=0)
pid = find_pid_by_name("linuxrc");
if (!pid || *pid<=0)
- error_msg_and_die("no process killed");
+ bb_error_msg_and_die("no process killed");
fflush(stdout);
return(kill(*pid, SIGTERM));
}
diff --git a/init/start_stop_daemon.c b/init/start_stop_daemon.c
index 576526183..a1c2c21c2 100644
--- a/init/start_stop_daemon.c
+++ b/init/start_stop_daemon.c
@@ -74,7 +74,7 @@ parse_options(int argc, char * const *argv)
break;
case 's':
if (sscanf(optarg, "%d", &signal_nr) != 1)
- error_msg_and_die ("-s takes a numeric argument");
+ bb_error_msg_and_die ("-s takes a numeric argument");
break;
case 'u':
userspec = optarg;
@@ -86,21 +86,21 @@ parse_options(int argc, char * const *argv)
fork_before_exec = 1;
break;
default:
- show_usage();
+ bb_show_usage();
}
}
if (start == stop)
- error_msg_and_die ("need one of -S or -K");
+ bb_error_msg_and_die ("need one of -S or -K");
if (!execname && !userspec)
- error_msg_and_die ("need at least one of -x or -u");
+ bb_error_msg_and_die ("need at least one of -x or -u");
if (!startas)
startas = execname;
if (start && !startas)
- error_msg_and_die ("-S needs -x or -a");
+ bb_error_msg_and_die ("-S needs -x or -a");
}
@@ -185,7 +185,7 @@ do_procfs(void)
procdir = opendir("/proc");
if (!procdir)
- perror_msg_and_die ("opendir /proc");
+ bb_perror_msg_and_die ("opendir /proc");
foundany = 0;
while ((entry = readdir(procdir)) != NULL) {
@@ -196,7 +196,7 @@ do_procfs(void)
}
closedir(procdir);
if (!foundany)
- error_msg_and_die ("nothing in /proc - not mounted?");
+ bb_error_msg_and_die ("nothing in /proc - not mounted?");
}
@@ -214,7 +214,7 @@ do_stop(void)
else if (userspec)
sprintf(what, "process(es) owned by `%s'", userspec);
else
- error_msg_and_die ("internal error, please report");
+ bb_error_msg_and_die ("internal error, please report");
if (!found) {
printf("no %s found; none killed.\n", what);
@@ -225,7 +225,7 @@ do_stop(void)
p->pid = -p->pid;
killed++;
} else {
- perror_msg("warning: failed to kill %d:", p->pid);
+ bb_perror_msg("warning: failed to kill %d:", p->pid);
}
}
if (killed) {
@@ -262,10 +262,10 @@ start_stop_daemon_main(int argc, char **argv)
*--argv = startas;
if (fork_before_exec) {
if (daemon(0, 0) == -1)
- perror_msg_and_die ("unable to fork");
+ bb_perror_msg_and_die ("unable to fork");
}
setsid();
execv(startas, argv);
- perror_msg_and_die ("unable to start %s", startas);
+ bb_perror_msg_and_die ("unable to start %s", startas);
}
diff --git a/libbb/Makefile.in b/libbb/Makefile.in
index 6d2475bcf..c7916f108 100644
--- a/libbb/Makefile.in
+++ b/libbb/Makefile.in
@@ -42,26 +42,59 @@ LIBBB_SRC:= \
restricted_shell.c run_parts.c run_shell.c safe_read.c safe_strncpy.c \
setup_environment.c simplify_path.c syscalls.c syslog_msg_with_name.c \
time_string.c trim.c u_signal_names.c vdprintf.c verror_msg.c \
- vherror_msg.c vperror_msg.c wfopen.c xconnect.c xgetcwd.c xfuncs.c \
- xgethostbyname.c xgethostbyname2.c xreadlink.c xregcomp.c xgetlarg.c
-
+ vherror_msg.c vperror_msg.c wfopen.c xconnect.c xgetcwd.c \
+ xgethostbyname.c xgethostbyname2.c xreadlink.c xregcomp.c xgetlarg.c \
+ \
+ fclose_nonstdin.c fflush_stdout_and_exit.c getopt_ulflags.c \
+ default_error_retval.c wfopen_input.c speed_table.c \
+ perror_nomsg_and_die.c perror_nomsg.c skip_whitespace.c \
+ warn_ignoring_args.c
LIBBB_OBJS=$(patsubst %.c,$(LIBBB_DIR)%.o, $(LIBBB_SRC))
-LIBBB_MSRC:=$(LIBBB_DIR)messages.c
-LIBBB_MOBJ:=full_version.o name_too_long.o omitting_directory.o not_a_directory.o \
- memory_exhausted.o invalid_date.o invalid_option.o io_error.o dash_dash_help.o \
- write_error.o too_few_args.o name_longer_than_foo.o unknown.o can_not_create_raw_socket.o \
- shadow_file.o passwd_file.o group_file.o gshadow_file.o nologin_file.o securetty_file.o \
- motd_file.o
-LIBBB_MOBJS=$(patsubst %,$(LIBBB_DIR)%, $(LIBBB_MOBJ))
+LIBBB_MSRC0:=$(LIBBB_DIR)messages.c
+LIBBB_MOBJ0:=full_version.o \
+ memory_exhausted.o invalid_date.o io_error.o \
+ write_error.o name_longer_than_foo.o unknown.o \
+ can_not_create_raw_socket.o perm_denied_are_you_root.o \
+ shadow_file.o passwd_file.o group_file.o gshadow_file.o nologin_file.o \
+ securetty_file.o motd_file.o \
+ msg_standard_input.o msg_standard_output.o
+
+LIBBB_MSRC1:=$(LIBBB_DIR)xfuncs.c
+LIBBB_MOBJ1:=xmalloc.o xrealloc.o xcalloc.o xstrdup.o xstrndup.o \
+ xfopen.o xopen.o xread.o xread_all.o xread_char.o \
+ xferror.o xferror_stdout.o xfflush_stdout.o strlen.o
+
+LIBBB_MSRC2:=$(LIBBB_DIR)printf.c
+LIBBB_MOBJ2:=vfprintf.o vprintf.o fprintf.o printf.o
+
+LIBBB_MSRC3:=$(LIBBB_DIR)xgetularg.c
+LIBBB_MOBJ3:=xgetularg_bnd_sfx.o xgetlarg_bnd_sfx.o getlarg10_sfx.o \
+ xgetularg_bnd.o xgetularg10_bnd.o xgetularg10.o
+
+LIBBB_MOBJS0=$(patsubst %,$(LIBBB_DIR)%, $(LIBBB_MOBJ0))
+LIBBB_MOBJS1=$(patsubst %,$(LIBBB_DIR)%, $(LIBBB_MOBJ1))
+LIBBB_MOBJS2=$(patsubst %,$(LIBBB_DIR)%, $(LIBBB_MOBJ2))
+LIBBB_MOBJS3=$(patsubst %,$(LIBBB_DIR)%, $(LIBBB_MOBJ3))
libraries-y+=$(LIBBB_DIR)$(LIBBB_AR)
-$(LIBBB_DIR)$(LIBBB_AR): $(LIBBB_OBJS) $(LIBBB_MOBJS)
- $(AR) -ro $@ $(LIBBB_OBJS) $(LIBBB_MOBJS)
+$(LIBBB_DIR)$(LIBBB_AR): $(LIBBB_OBJS) $(LIBBB_MOBJS0) $(LIBBB_MOBJS1) \
+ $(LIBBB_MOBJS2) $(LIBBB_MOBJS3)
+ $(AR) -ro $@ $(LIBBB_OBJS) $(LIBBB_MOBJS0) $(LIBBB_MOBJS1) \
+ $(LIBBB_MOBJS2) $(LIBBB_MOBJS3)
+
+$(LIBBB_MOBJS0): $(LIBBB_MSRC0)
+ $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -DL_$(notdir $*) -c $< -o $@
+
+$(LIBBB_MOBJS1): $(LIBBB_MSRC1)
+ $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -DL_$(notdir $*) -c $< -o $@
+
+$(LIBBB_MOBJS2): $(LIBBB_MSRC2)
+ $(CC) $(CFLAGS) $(EXTRA_CFLAGS) -DL_$(notdir $*) -c $< -o $@
-$(LIBBB_MOBJS): $(LIBBB_MSRC)
+$(LIBBB_MOBJS3): $(LIBBB_MSRC3)
$(CC) $(CFLAGS) $(EXTRA_CFLAGS) -DL_$(notdir $*) -c $< -o $@
$(LIBBB_DIR)loop.o: $(LIBBB_DIR)loop.h
diff --git a/libbb/ask_confirmation.c b/libbb/ask_confirmation.c
index d4d943ad7..a99a4e733 100644
--- a/libbb/ask_confirmation.c
+++ b/libbb/ask_confirmation.c
@@ -1,49 +1,49 @@
/* vi: set sw=4 ts=4: */
/*
- * Utility routines.
+ * bb_ask_confirmation implementation for busybox
*
- * Copyright (C) many different people. If you wrote this, please
- * acknowledge your work.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/* Read a line from stdin. If the first non-whitespace char is 'y' or 'Y',
+ * return 1. Otherwise return 0.
*/
#include <stdio.h>
+#include <ctype.h>
#include "libbb.h"
-
-int ask_confirmation()
+int bb_ask_confirmation(void)
{
- int c = '\0';
- int ret = 0;
+ int retval = 0;
+ int first = 1;
+ int c;
- while (c != '\n') {
- c = getchar();
- if ( c != '\n' ) {
- ret = ((c=='y')||(c=='Y')) ? 1 : 0;
+ while (((c = getchar()) != EOF) && (c != '\n')) {
+ /* Make sure we get the actual function call for isspace,
+ * as speed is not critical here. */
+ if (first && !(isspace)(c)) {
+ --first;
+ if ((c == 'y') || (c == 'Y')) {
+ ++retval;
+ }
}
}
- return ret;
-}
-/* END CODE */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
+ return retval;
+}
diff --git a/libbb/bb_asprintf.c b/libbb/bb_asprintf.c
index 9a71be7f5..7075b46de 100644
--- a/libbb/bb_asprintf.c
+++ b/libbb/bb_asprintf.c
@@ -5,17 +5,18 @@
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
-
-
#include "libbb.h"
-
-void bb_asprintf(char **string_ptr, const char *format, ...)
+void bb_xasprintf(char **string_ptr, const char *format, ...)
{
- va_list p;
+ va_list p;
+ int r;
+
+ va_start(p, format);
+ r = vasprintf(string_ptr, format, p);
+ va_end(p);
- va_start(p, format);
- if(vasprintf(string_ptr, format, p)<0)
- error_msg_and_die(memory_exhausted);
- va_end(p);
+ if (r < 0) {
+ bb_perror_msg_and_die("bb_xasprintf");
+ }
}
diff --git a/libbb/change_identity.c b/libbb/change_identity.c
index 819b216e0..c2b73eeb8 100644
--- a/libbb/change_identity.c
+++ b/libbb/change_identity.c
@@ -43,12 +43,12 @@
void change_identity ( const struct passwd *pw )
{
if ( initgroups ( pw-> pw_name, pw-> pw_gid ) == -1 )
- perror_msg_and_die ( "cannot set groups" );
+ bb_perror_msg_and_die ( "cannot set groups" );
endgrent ( );
if ( setgid ( pw-> pw_gid ))
- perror_msg_and_die ( "cannot set group id" );
+ bb_perror_msg_and_die ( "cannot set group id" );
if ( setuid ( pw->pw_uid ))
- perror_msg_and_die ( "cannot set user id" );
+ bb_perror_msg_and_die ( "cannot set user id" );
}
diff --git a/libbb/compare_string_array.c b/libbb/compare_string_array.c
index b158ae447..993b46266 100644
--- a/libbb/compare_string_array.c
+++ b/libbb/compare_string_array.c
@@ -27,4 +27,5 @@ extern unsigned short compare_string_array(const char *string_array[], const cha
}
}
return(i);
-} \ No newline at end of file
+}
+
diff --git a/libbb/concat_path_file.c b/libbb/concat_path_file.c
index 0146606a1..b972ba6a3 100644
--- a/libbb/concat_path_file.c
+++ b/libbb/concat_path_file.c
@@ -38,7 +38,7 @@ extern char *concat_path_file(const char *path, const char *filename)
lc = last_char_is(path, '/');
while (*filename == '/')
filename++;
- bb_asprintf(&outbuf, "%s%s%s", path, (lc==NULL)? "/" : "", filename);
+ bb_xasprintf(&outbuf, "%s%s%s", path, (lc==NULL)? "/" : "", filename);
return outbuf;
}
diff --git a/libbb/copy_file.c b/libbb/copy_file.c
index 23a2d75a3..81c547479 100644
--- a/libbb/copy_file.c
+++ b/libbb/copy_file.c
@@ -43,19 +43,19 @@ int copy_file(const char *source, const char *dest, int flags)
lstat(source, &source_stat) < 0) ||
((flags & FILEUTILS_DEREFERENCE) &&
stat(source, &source_stat) < 0)) {
- perror_msg("%s", source);
+ bb_perror_msg("%s", source);
return -1;
}
if (lstat(dest, &dest_stat) < 0) {
if (errno != ENOENT) {
- perror_msg("unable to stat `%s'", dest);
+ bb_perror_msg("unable to stat `%s'", dest);
return -1;
}
} else {
if (source_stat.st_dev == dest_stat.st_dev &&
source_stat.st_ino == dest_stat.st_ino) {
- error_msg("`%s' and `%s' are the same file", source, dest);
+ bb_error_msg("`%s' and `%s' are the same file", source, dest);
return -1;
}
dest_exists = 1;
@@ -67,14 +67,14 @@ int copy_file(const char *source, const char *dest, int flags)
mode_t saved_umask = 0;
if (!(flags & FILEUTILS_RECUR)) {
- error_msg("%s: omitting directory", source);
+ bb_error_msg("%s: omitting directory", source);
return -1;
}
/* Create DEST. */
if (dest_exists) {
if (!S_ISDIR(dest_stat.st_mode)) {
- error_msg("`%s' is not a directory", dest);
+ bb_error_msg("`%s' is not a directory", dest);
return -1;
}
} else {
@@ -88,7 +88,7 @@ int copy_file(const char *source, const char *dest, int flags)
if (mkdir(dest, mode) < 0) {
umask(saved_umask);
- perror_msg("cannot create directory `%s'", dest);
+ bb_perror_msg("cannot create directory `%s'", dest);
return -1;
}
@@ -97,7 +97,7 @@ int copy_file(const char *source, const char *dest, int flags)
/* Recursively copy files in SOURCE. */
if ((dp = opendir(source)) == NULL) {
- perror_msg("unable to open directory `%s'", source);
+ bb_perror_msg("unable to open directory `%s'", source);
status = -1;
goto end;
}
@@ -121,7 +121,7 @@ int copy_file(const char *source, const char *dest, int flags)
if (!dest_exists &&
chmod(dest, source_stat.st_mode & ~saved_umask) < 0) {
- perror_msg("unable to change permissions of `%s'", dest);
+ bb_perror_msg("unable to change permissions of `%s'", dest);
status = -1;
}
} else if (S_ISREG(source_stat.st_mode)) {
@@ -132,7 +132,7 @@ int copy_file(const char *source, const char *dest, int flags)
if (!(flags & FILEUTILS_DEREFERENCE) &&
is_in_ino_dev_hashtable(&source_stat, &link_name)) {
if (link(link_name, dest) < 0) {
- perror_msg("unable to link `%s'", dest);
+ bb_perror_msg("unable to link `%s'", dest);
return -1;
}
@@ -140,14 +140,14 @@ int copy_file(const char *source, const char *dest, int flags)
}
#endif
- if ((sfp = wfopen(source, "r")) == NULL) {
+ if ((sfp = bb_wfopen(source, "r")) == NULL) {
return -1;
}
if (dest_exists) {
if (flags & FILEUTILS_INTERACTIVE) {
- fprintf(stderr, "%s: overwrite `%s'? ", applet_name, dest);
- if (!ask_confirmation()) {
+ fprintf(stderr, "%s: overwrite `%s'? ", bb_applet_name, dest);
+ if (!bb_ask_confirmation()) {
fclose (sfp);
return 0;
}
@@ -155,13 +155,13 @@ int copy_file(const char *source, const char *dest, int flags)
if ((dfp = fopen(dest, "w")) == NULL) {
if (!(flags & FILEUTILS_FORCE)) {
- perror_msg("unable to open `%s'", dest);
+ bb_perror_msg("unable to open `%s'", dest);
fclose (sfp);
return -1;
}
if (unlink(dest) < 0) {
- perror_msg("unable to remove `%s'", dest);
+ bb_perror_msg("unable to remove `%s'", dest);
fclose (sfp);
return -1;
}
@@ -177,22 +177,22 @@ int copy_file(const char *source, const char *dest, int flags)
(dfp = fdopen(fd, "w")) == NULL) {
if (fd >= 0)
close(fd);
- perror_msg("unable to open `%s'", dest);
+ bb_perror_msg("unable to open `%s'", dest);
fclose (sfp);
return -1;
}
}
- if (copyfd(fileno(sfp), fileno(dfp), 0) == -1)
+ if (bb_copyfd(fileno(sfp), fileno(dfp), 0) == -1)
status = -1;
if (fclose(dfp) < 0) {
- perror_msg("unable to close `%s'", dest);
+ bb_perror_msg("unable to close `%s'", dest);
status = -1;
}
if (fclose(sfp) < 0) {
- perror_msg("unable to close `%s'", source);
+ bb_perror_msg("unable to close `%s'", source);
status = -1;
}
}
@@ -202,23 +202,23 @@ int copy_file(const char *source, const char *dest, int flags)
if (dest_exists &&
((flags & FILEUTILS_FORCE) == 0 || unlink(dest) < 0)) {
- perror_msg("unable to remove `%s'", dest);
+ bb_perror_msg("unable to remove `%s'", dest);
return -1;
}
} else {
- error_msg("internal error: unrecognized file type");
+ bb_error_msg("internal error: unrecognized file type");
return -1;
}
if (S_ISBLK(source_stat.st_mode) || S_ISCHR(source_stat.st_mode) ||
S_ISSOCK(source_stat.st_mode)) {
if (mknod(dest, source_stat.st_mode, source_stat.st_rdev) < 0) {
- perror_msg("unable to create `%s'", dest);
+ bb_perror_msg("unable to create `%s'", dest);
return -1;
}
} else if (S_ISFIFO(source_stat.st_mode)) {
if (mkfifo(dest, source_stat.st_mode) < 0) {
- perror_msg("cannot create fifo `%s'", dest);
+ bb_perror_msg("cannot create fifo `%s'", dest);
return -1;
}
} else if (S_ISLNK(source_stat.st_mode)) {
@@ -226,7 +226,7 @@ int copy_file(const char *source, const char *dest, int flags)
lpath = xreadlink(source);
if (symlink(lpath, dest) < 0) {
- perror_msg("cannot create symlink `%s'", dest);
+ bb_perror_msg("cannot create symlink `%s'", dest);
return -1;
}
free(lpath);
@@ -234,7 +234,7 @@ int copy_file(const char *source, const char *dest, int flags)
#if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
if (flags & FILEUTILS_PRESERVE_STATUS)
if (lchown(dest, source_stat.st_uid, source_stat.st_gid) < 0)
- perror_msg("unable to preserve ownership of `%s'", dest);
+ bb_perror_msg("unable to preserve ownership of `%s'", dest);
#endif
#ifdef CONFIG_FEATURE_PRESERVE_HARDLINKS
@@ -256,13 +256,13 @@ end:
times.actime = source_stat.st_atime;
times.modtime = source_stat.st_mtime;
if (utime(dest, &times) < 0)
- perror_msg("unable to preserve times of `%s'", dest);
+ bb_perror_msg("unable to preserve times of `%s'", dest);
if (chown(dest, source_stat.st_uid, source_stat.st_gid) < 0) {
source_stat.st_mode &= ~(S_ISUID | S_ISGID);
- perror_msg("unable to preserve ownership of `%s'", dest);
+ bb_perror_msg("unable to preserve ownership of `%s'", dest);
}
if (chmod(dest, source_stat.st_mode) < 0)
- perror_msg("unable to preserve permissions of `%s'", dest);
+ bb_perror_msg("unable to preserve permissions of `%s'", dest);
}
return status;
diff --git a/libbb/copy_file_chunk.c b/libbb/copy_file_chunk.c
deleted file mode 100644
index 63d2ab173..000000000
--- a/libbb/copy_file_chunk.c
+++ /dev/null
@@ -1,70 +0,0 @@
-/* vi: set sw=4 ts=4: */
-/*
- * Utility routines.
- *
- * Copyright (C) many different people. If you wrote this, please
- * acknowledge your work.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
- */
-
-#include <stdio.h>
-#include <sys/stat.h>
-#include "libbb.h"
-
-/* Copy CHUNKSIZE bytes (or until EOF if CHUNKSIZE equals -1) from SRC_FILE
- * to DST_FILE. */
-extern int copy_file_chunk(FILE *src_file, FILE *dst_file, unsigned long long chunksize)
-{
- size_t nread, nwritten, size;
- char buffer[BUFSIZ];
-
- while (chunksize != 0) {
- if (chunksize > BUFSIZ)
- size = BUFSIZ;
- else
- size = chunksize;
-
- nread = fread (buffer, 1, size, src_file);
-
- if (nread != size && ferror (src_file)) {
- perror_msg ("read");
- return -1;
- } else if (nread == 0) {
- if (chunksize != -1) {
- error_msg ("Unable to read all data");
- return -1;
- }
-
- return 0;
- }
-
- nwritten = fwrite (buffer, 1, nread, dst_file);
-
- if (nwritten != nread) {
- if (ferror (dst_file))
- perror_msg ("write");
- else
- error_msg ("Unable to write all data");
- return -1;
- }
-
- if (chunksize != -1)
- chunksize -= nwritten;
- }
-
- return 0;
-}
diff --git a/libbb/copyfd.c b/libbb/copyfd.c
index 4df1fd084..41b78c7d6 100644
--- a/libbb/copyfd.c
+++ b/libbb/copyfd.c
@@ -22,65 +22,51 @@
#include <unistd.h>
#include <string.h>
#include <errno.h>
-#include "libbb.h"
+#include "busybox.h"
-/* If chunksize is 0 copy untill EOF */
-extern int copyfd(int fd1, int fd2, const off_t chunksize)
+#if BUFSIZ < 4096
+#undef BUFSIZ
+#define BUFSIZ 4096
+#endif
+
+/* If chunksize is 0 copy until EOF */
+extern int bb_copyfd(int fd1, int fd2, const off_t chunksize)
{
- size_t nread;
- size_t nwritten;
+ ssize_t nread;
size_t size;
- size_t remaining;
- char buffer[BUFSIZ];
+ off_t remaining;
+ RESERVE_CONFIG_BUFFER(buffer,BUFSIZ);
+ remaining = size = BUFSIZ;
if (chunksize) {
remaining = chunksize;
- } else {
- remaining = -1;
}
do {
- if ((chunksize > BUFSIZ) || (chunksize == 0)) {
- size = BUFSIZ;
- } else {
- size = chunksize;
+ if (size > remaining) {
+ size = remaining;
}
- nread = safe_read(fd1, buffer, size);
-
- if (nread == -1) {
- perror_msg("read failure");
- return(-1);
- }
- else if (nread == 0) {
+ if ((nread = safe_read(fd1, buffer, size)) > 0) {
+ if (bb_full_write(fd2, buffer, nread) < 0) {
+ bb_perror_msg(bb_msg_write_error); /* match Read error below */
+ break;
+ }
+ if (chunksize && ((remaining -= nread) == 0)) {
+ return 0;
+ }
+ } else if (!nread) {
if (chunksize) {
- error_msg("Unable to read all data");
- return(-1);
- } else {
- return(0);
+ bb_error_msg("Unable to read all data");
+ break;
}
+ return 0;
+ } else { /* nread < 0 */
+ bb_perror_msg("Read error"); /* match bb_msg_write_error above */
+ break;
}
- nwritten = full_write(fd2, buffer, nread);
+ } while (1);
- if (nwritten != nread) {
- error_msg("Unable to write all data");
- return(-1);
- }
-
- if (chunksize) {
- remaining -= nwritten;
- }
- } while (remaining != 0);
-
- return 0;
+ return -1;
}
-
-/* END CODE */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
diff --git a/libbb/correct_password.c b/libbb/correct_password.c
index 758b89eed..396253614 100644
--- a/libbb/correct_password.c
+++ b/libbb/correct_password.c
@@ -55,7 +55,7 @@ int correct_password ( const struct passwd *pw )
struct spwd *sp = getspnam ( pw-> pw_name );
if ( !sp )
- error_msg_and_die ( "no valid shadow password" );
+ bb_error_msg_and_die ( "no valid shadow password" );
correct = sp-> sp_pwdp;
}
@@ -73,6 +73,6 @@ int correct_password ( const struct passwd *pw )
return 0;
}
encrypted = crypt ( unencrypted, correct );
- memset ( unencrypted, 0, xstrlen ( unencrypted ));
+ memset ( unencrypted, 0, bb_strlen ( unencrypted ));
return ( strcmp ( encrypted, correct ) == 0 ) ? 1 : 0;
}
diff --git a/libbb/create_icmp6_socket.c b/libbb/create_icmp6_socket.c
index 1d0b6b6bf..596610449 100644
--- a/libbb/create_icmp6_socket.c
+++ b/libbb/create_icmp6_socket.c
@@ -26,9 +26,9 @@ int create_icmp6_socket(void)
if ((sock = socket(AF_INET6, SOCK_RAW,
(proto ? proto->p_proto : IPPROTO_ICMPV6))) < 0) {
if (errno == EPERM)
- error_msg_and_die("permission denied. (are you root?)");
+ bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
else
- perror_msg_and_die(can_not_create_raw_socket);
+ bb_perror_msg_and_die(bb_msg_can_not_create_raw_socket);
}
/* drop root privs if running setuid */
diff --git a/libbb/create_icmp_socket.c b/libbb/create_icmp_socket.c
index d804b3987..58d792b1b 100644
--- a/libbb/create_icmp_socket.c
+++ b/libbb/create_icmp_socket.c
@@ -25,9 +25,9 @@ int create_icmp_socket(void)
if ((sock = socket(AF_INET, SOCK_RAW,
(proto ? proto->p_proto : 1))) < 0) { /* 1 == ICMP */
if (errno == EPERM)
- error_msg_and_die("permission denied. (are you root?)");
+ bb_error_msg_and_die(bb_msg_perm_denied_are_you_root);
else
- perror_msg_and_die(can_not_create_raw_socket);
+ bb_perror_msg_and_die(bb_msg_can_not_create_raw_socket);
}
/* drop root privs if running setuid */
diff --git a/libbb/default_error_retval.c b/libbb/default_error_retval.c
new file mode 100644
index 000000000..7d2d89bb5
--- /dev/null
+++ b/libbb/default_error_retval.c
@@ -0,0 +1,32 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/* Seems silly to copyright a global variable. ;-) Oh well.
+ *
+ * At least one applet (cmp) returns a value different from the typical
+ * EXIT_FAILURE values (1) when an error occurs. So, make it configureable
+ * by the applet. I suppose we could use a wrapper function to set it, but
+ * that too seems silly.
+ */
+
+#include <stdlib.h>
+#include "libbb.h"
+
+int bb_default_error_retval = EXIT_FAILURE;
diff --git a/libbb/dirname.c b/libbb/dirname.c
index df9a49daa..81298730b 100644
--- a/libbb/dirname.c
+++ b/libbb/dirname.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini dirname function.
+ * dirname implementation for busybox (for libc's missing one)
*
- * Copyright (C) 2001 Matt Kraai.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,39 +17,53 @@
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/* Note: The previous busybox implementation did not handle NULL path
+ * and also moved a pointer before path, which is not portable in C.
+ * So I replaced it with my uClibc version.
*/
#include <string.h>
#include "libbb.h"
-#if defined __UCLIBC__ || __GNU_LIBRARY___ < 5
-
-/* Return a string containing the path name of the parent
- * directory of PATH. */
+#if __GNU_LIBRARY__ < 5
+extern
char *dirname(char *path)
{
- char *s;
-
- /* Go to the end of the string. */
- s = path + strlen(path) - 1;
-
- /* Strip off trailing /s (unless it is also the leading /). */
- while (path < s && s[0] == '/')
- s--;
+ static const char null_or_empty_or_noslash[] = ".";
+ register char *s;
+ register char *last;
+ char *first;
- /* Strip the last component. */
- while (path <= s && s[0] != '/')
- s--;
+ last = s = path;
- while (path < s && s[0] == '/')
- s--;
+ if (s != NULL) {
- if (s < path)
- return ".";
+ LOOP:
+ while (*s && (*s != '/')) ++s;
+ first = s;
+ while (*s == '/') ++s;
+ if (*s) {
+ last = first;
+ goto LOOP;
+ }
- s[1] = '\0';
- return path;
+ if (last == path) {
+ if (*last != '/') {
+ goto DOT;
+ }
+ if ((*++last == '/') && (last[1] == 0)) {
+ ++last;
+ }
+ }
+ *last = 0;
+ return path;
+ }
+ DOT:
+ return (char *) null_or_empty_or_noslash;
}
#endif
diff --git a/libbb/dump.c b/libbb/dump.c
index 1afad83fd..26dabe57f 100644
--- a/libbb/dump.c
+++ b/libbb/dump.c
@@ -25,94 +25,80 @@
#include <stdlib.h>
#include <string.h>
#include <ctype.h> /* for isdigit() */
-#include "dump.h"
#include "libbb.h"
+#include "dump.h"
-enum _vflag vflag = FIRST;
-FS *fshead; /* head of format strings */
-extern FS *fshead; /* head of format strings */
-extern int blocksize;
+enum _vflag bb_dump_vflag = FIRST;
+FS *bb_dump_fshead; /* head of format strings */
static FU *endfu;
static char **_argv;
static off_t savaddress; /* saved address/offset in stream */
static off_t eaddress; /* end address */
static off_t address; /* address/offset in stream */
-off_t skip; /* bytes to skip */
-off_t saveaddress;
-int exitval; /* final exit value */
-int blocksize; /* data block size */
-int length = -1; /* max bytes to read */
+off_t bb_dump_skip; /* bytes to skip */
+static int exitval; /* final exit value */
+int bb_dump_blocksize; /* data block size */
+int bb_dump_length = -1; /* max bytes to read */
+
+static const char index_str[] = ".#-+ 0123456789";
+static const char size_conv_str[] =
+"\x1\x4\x4\x4\x4\x4\x4\x8\x8\x8\x8\010cdiouxXeEfgG";
-int size(FS * fs)
+static const char lcc[] = "diouxX";
+
+int bb_dump_size(FS * fs)
{
register FU *fu;
- register int bcnt, cursize;
+ register int bcnt, cur_size;
register char *fmt;
+ const char *p;
int prec;
- /* figure out the data block size needed for each format unit */
- for (cursize = 0, fu = fs->nextfu; fu; fu = fu->nextfu) {
+ /* figure out the data block bb_dump_size needed for each format unit */
+ for (cur_size = 0, fu = fs->nextfu; fu; fu = fu->nextfu) {
if (fu->bcnt) {
- cursize += fu->bcnt * fu->reps;
+ cur_size += fu->bcnt * fu->reps;
continue;
}
for (bcnt = prec = 0, fmt = fu->fmt; *fmt; ++fmt) {
if (*fmt != '%')
continue;
/*
- * skip any special chars -- save precision in
+ * bb_dump_skip any special chars -- save precision in
* case it's a %s format.
*/
- while (index(".#-+ 0123456789" + 1, *++fmt));
+ while (strchr(index_str + 1, *++fmt));
if (*fmt == '.' && isdigit(*++fmt)) {
prec = atoi(fmt);
while (isdigit(*++fmt));
}
- switch (*fmt) {
- case 'c':
- bcnt += 1;
- break;
- case 'd':
- case 'i':
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- bcnt += 4;
- break;
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- case 'G':
- bcnt += 8;
- break;
- case 's':
- bcnt += prec;
- break;
- case '_':
- switch (*++fmt) {
- case 'c':
- case 'p':
- case 'u':
- bcnt += 1;
- break;
+ if (!(p = strchr(size_conv_str + 12, *fmt))) {
+ if (*fmt == 's') {
+ bcnt += prec;
+ } else if (*fmt == '_') {
+ ++fmt;
+ if ((*fmt == 'c') || (*fmt == 'p') || (*fmt == 'u')) {
+ bcnt += 1;
+ }
}
+ } else {
+ bcnt += size_conv_str[p - (size_conv_str + 12)];
}
}
- cursize += bcnt * fu->reps;
+ cur_size += bcnt * fu->reps;
}
- return (cursize);
+ return (cur_size);
}
-void rewrite(FS * fs)
+static void rewrite(FS * fs)
{
enum { NOTOKAY, USEBCNT, USEPREC } sokay;
register PR *pr, **nextpr = NULL;
register FU *fu;
register char *p1, *p2;
char savech, *fmtp;
+ const char *byte_count_str;
int nconv, prec = 0;
for (fu = fs->nextfu; fu; fu = fu->nextfu) {
@@ -128,7 +114,7 @@ void rewrite(FS * fs)
else
*nextpr = pr;
- /* skip preceding text and up to the next % sign */
+ /* bb_dump_skip preceding text and up to the next % sign */
for (p1 = fmtp; *p1 && *p1 != '%'; ++p1);
/* only text in the string */
@@ -144,11 +130,11 @@ void rewrite(FS * fs)
*/
if (fu->bcnt) {
sokay = USEBCNT;
- /* skip to conversion character */
- for (++p1; index(".#-+ 0123456789", *p1); ++p1);
+ /* bb_dump_skip to conversion character */
+ for (++p1; strchr(index_str, *p1); ++p1);
} else {
- /* skip any special chars, field width */
- while (index(".#-+ 0123456789" + 1, *++p1));
+ /* bb_dump_skip any special chars, field width */
+ while (strchr(index_str + 1, *++p1));
if (*p1 == '.' && isdigit(*++p1)) {
sokay = USEPREC;
prec = atoi(p1);
@@ -162,104 +148,59 @@ void rewrite(FS * fs)
/*
* figure out the byte count for each conversion;
* rewrite the format as necessary, set up blank-
- * padding for end of data.
+ * pbb_dump_adding for end of data.
*/
- switch (*p1) {
- case 'c':
+
+ if (*p1 == 'c') {
pr->flags = F_CHAR;
- switch (fu->bcnt) {
- case 0:
- case 1:
- pr->bcnt = 1;
- break;
- default:
- p1[1] = '\0';
- error_msg_and_die
- ("bad byte count for conversion character %s.", p1);
+ DO_BYTE_COUNT_1:
+ byte_count_str = "\001";
+ DO_BYTE_COUNT:
+ if (fu->bcnt) {
+ do {
+ if (fu->bcnt == *byte_count_str) {
+ break;
+ }
+ } while (*++byte_count_str);
}
- break;
- case 'd':
- case 'i':
- pr->flags = F_INT;
- goto sw1;
- case 'l':
+ /* Unlike the original, output the remainder of the format string. */
+ if (!*byte_count_str) {
+ bb_error_msg_and_die("bad byte count for conversion character %s.", p1);
+ }
+ pr->bcnt = *byte_count_str;
+ } else if (*p1 == 'l') {
++p2;
- switch (p1[1]) {
- case 'd':
- case 'i':
- ++p1;
+ ++p1;
+ DO_INT_CONV:
+ {
+ const char *e;
+ if (!(e = strchr(lcc, *p1))) {
+ goto DO_BAD_CONV_CHAR;
+ }
pr->flags = F_INT;
- goto sw1;
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- ++p1;
- pr->flags = F_UINT;
- goto sw1;
- default:
- p1[2] = '\0';
- error_msg_and_die
- ("hexdump: bad conversion character %%%s.\n", p1);
+ if (e > lcc + 1) {
+ pr->flags = F_UINT;
+ }
+ byte_count_str = "\004\002\001";
+ goto DO_BYTE_COUNT;
}
/* NOTREACHED */
- case 'o':
- case 'u':
- case 'x':
- case 'X':
- pr->flags = F_UINT;
- sw1:switch (fu->bcnt) {
- case 0:
- case 4:
- pr->bcnt = 4;
- break;
- case 1:
- pr->bcnt = 1;
- break;
- case 2:
- pr->bcnt = 2;
- break;
- default:
- p1[1] = '\0';
- error_msg_and_die
- ("bad byte count for conversion character %s.", p1);
- }
- break;
- case 'e':
- case 'E':
- case 'f':
- case 'g':
- case 'G':
+ } else if (strchr(lcc, *p1)) {
+ goto DO_INT_CONV;
+ } else if (strchr("eEfgG", *p1)) {
pr->flags = F_DBL;
- switch (fu->bcnt) {
- case 0:
- case 8:
- pr->bcnt = 8;
- break;
- case 4:
- pr->bcnt = 4;
- break;
- default:
- p1[1] = '\0';
- error_msg_and_die
- ("bad byte count for conversion character %s.", p1);
- }
- break;
- case 's':
+ byte_count_str = "\010\004";
+ goto DO_BYTE_COUNT;
+ } else if (*p1 == 's') {
pr->flags = F_STR;
- switch (sokay) {
- case NOTOKAY:
- error_msg_and_die
- ("%%s requires a precision or a byte count.");
- case USEBCNT:
+ if (sokay == USEBCNT) {
pr->bcnt = fu->bcnt;
- break;
- case USEPREC:
+ } else if (sokay == USEPREC) {
pr->bcnt = prec;
- break;
+ } else { /* NOTOKAY */
+ bb_error_msg_and_die("%%s requires a precision or a byte count.");
}
- break;
- case '_':
+ } else if (*p1 == '_') {
++p2;
switch (p1[1]) {
case 'A':
@@ -269,51 +210,29 @@ void rewrite(FS * fs)
case 'a':
pr->flags = F_ADDRESS;
++p2;
- switch (p1[2]) {
- case 'd':
- case 'o':
- case 'x':
- *p1 = p1[2];
- break;
- default:
- p1[3] = '\0';
- error_msg_and_die
- ("hexdump: bad conversion character %%%s.\n", p1);
+ if ((p1[2] != 'd') && (p1[2] != 'o') && (p1[2] != 'x')) {
+ goto DO_BAD_CONV_CHAR;
}
+ *p1 = p1[2];
break;
case 'c':
pr->flags = F_C;
/* *p1 = 'c'; set in conv_c */
- goto sw2;
+ goto DO_BYTE_COUNT_1;
case 'p':
pr->flags = F_P;
*p1 = 'c';
- goto sw2;
+ goto DO_BYTE_COUNT_1;
case 'u':
pr->flags = F_U;
/* *p1 = 'c'; set in conv_u */
- sw2:switch (fu->bcnt) {
- case 0:
- case 1:
- pr->bcnt = 1;
- break;
- default:
- p1[2] = '\0';
- error_msg_and_die
- ("bad byte count for conversion character %s.",
- p1);
- }
- break;
+ goto DO_BYTE_COUNT_1;
default:
- p1[2] = '\0';
- error_msg_and_die
- ("hexdump: bad conversion character %%%s.\n", p1);
+ goto DO_BAD_CONV_CHAR;
}
- break;
- default:
- p1[1] = '\0';
- error_msg_and_die("hexdump: bad conversion character %%%s.\n",
- p1);
+ } else {
+ DO_BAD_CONV_CHAR:
+ bb_error_msg_and_die("bad conversion character %%%s.\n", p1);
}
/*
@@ -322,16 +241,14 @@ void rewrite(FS * fs)
*/
savech = *p2;
p1[1] = '\0';
- if (!(pr->fmt = strdup(fmtp)))
- perror_msg_and_die("hexdump");
+ pr->fmt = bb_xstrdup(fmtp);
*p2 = savech;
pr->cchar = pr->fmt + (p1 - fmtp);
fmtp = p2;
/* only one conversion character if byte count */
if (!(pr->flags & F_ADDRESS) && fu->bcnt && nconv++) {
- error_msg_and_die
- ("hexdump: byte count with multiple conversion characters.\n");
+ bb_error_msg_and_die("byte count with multiple conversion characters.\n");
}
}
/*
@@ -344,7 +261,7 @@ void rewrite(FS * fs)
}
/*
* if the format string interprets any data at all, and it's
- * not the same as the blocksize, and its last format unit
+ * not the same as the bb_dump_blocksize, and its last format unit
* interprets any data at all, and has no iteration count,
* repeat it as necessary.
*
@@ -352,9 +269,9 @@ void rewrite(FS * fs)
* gets output from the last iteration of the format unit.
*/
for (fu = fs->nextfu;; fu = fu->nextfu) {
- if (!fu->nextfu && fs->bcnt < blocksize &&
+ if (!fu->nextfu && fs->bcnt < bb_dump_blocksize &&
!(fu->flags & F_SETREP) && fu->bcnt)
- fu->reps += (blocksize - fs->bcnt) / fu->bcnt;
+ fu->reps += (bb_dump_blocksize - fs->bcnt) / fu->bcnt;
if (fu->reps > 1) {
for (pr = fu->nextpr;; pr = pr->nextpr)
if (!pr->nextpr)
@@ -369,31 +286,31 @@ void rewrite(FS * fs)
}
}
-static void doskip(char *fname, int statok)
+static void do_skip(char *fname, int statok)
{
struct stat sbuf;
if (statok) {
if (fstat(fileno(stdin), &sbuf)) {
- perror_msg_and_die("hexdump: %s", fname);
+ bb_perror_msg_and_die("%s", fname);
}
if ((!(S_ISCHR(sbuf.st_mode) ||
S_ISBLK(sbuf.st_mode) ||
- S_ISFIFO(sbuf.st_mode))) && skip >= sbuf.st_size) {
- /* If size valid and skip >= size */
- skip -= sbuf.st_size;
+ S_ISFIFO(sbuf.st_mode))) && bb_dump_skip >= sbuf.st_size) {
+ /* If bb_dump_size valid and bb_dump_skip >= size */
+ bb_dump_skip -= sbuf.st_size;
address += sbuf.st_size;
return;
}
}
- if (fseek(stdin, skip, SEEK_SET)) {
- perror_msg_and_die("hexdump: %s", fname);
+ if (fseek(stdin, bb_dump_skip, SEEK_SET)) {
+ bb_perror_msg_and_die("%s", fname);
}
- savaddress = address += skip;
- skip = 0;
+ savaddress = address += bb_dump_skip;
+ bb_dump_skip = 0;
}
-int next(char **argv)
+static int next(char **argv)
{
static int done;
int statok;
@@ -405,7 +322,7 @@ int next(char **argv)
for (;;) {
if (*_argv) {
if (!(freopen(*_argv, "r", stdin))) {
- perror_msg("%s", *_argv);
+ bb_perror_msg("%s", *_argv);
exitval = 1;
++_argv;
continue;
@@ -416,11 +333,11 @@ int next(char **argv)
return (0);
statok = 0;
}
- if (skip)
- doskip(statok ? *_argv : "stdin", statok);
+ if (bb_dump_skip)
+ do_skip(statok ? *_argv : "stdin", statok);
if (*_argv)
++_argv;
- if (!skip)
+ if (!bb_dump_skip)
return (1);
}
/* NOTREACHED */
@@ -435,26 +352,26 @@ static u_char *get(void)
u_char *tmpp;
if (!curp) {
- curp = (u_char *) xmalloc(blocksize);
- savp = (u_char *) xmalloc(blocksize);
+ curp = (u_char *) xmalloc(bb_dump_blocksize);
+ savp = (u_char *) xmalloc(bb_dump_blocksize);
} else {
tmpp = curp;
curp = savp;
savp = tmpp;
- address = savaddress += blocksize;
+ address = savaddress += bb_dump_blocksize;
}
- for (need = blocksize, nread = 0;;) {
+ for (need = bb_dump_blocksize, nread = 0;;) {
/*
* if read the right number of bytes, or at EOF for one file,
* and no other files are available, zero-pad the rest of the
* block and set the end flag.
*/
- if (!length || (ateof && !next((char **) NULL))) {
- if (need == blocksize) {
+ if (!bb_dump_length || (ateof && !next((char **) NULL))) {
+ if (need == bb_dump_blocksize) {
return ((u_char *) NULL);
}
- if (vflag != ALL && !bcmp(curp, savp, nread)) {
- if (vflag != DUP) {
+ if (bb_dump_vflag != ALL && !bcmp(curp, savp, nread)) {
+ if (bb_dump_vflag != DUP) {
printf("*\n");
}
return ((u_char *) NULL);
@@ -464,31 +381,32 @@ static u_char *get(void)
return (curp);
}
n = fread((char *) curp + nread, sizeof(u_char),
- length == -1 ? need : MIN(length, need), stdin);
+ bb_dump_length == -1 ? need : MIN(bb_dump_length, need), stdin);
if (!n) {
if (ferror(stdin)) {
- perror_msg("%s", _argv[-1]);
+ bb_perror_msg("%s", _argv[-1]);
}
ateof = 1;
continue;
}
ateof = 0;
- if (length != -1) {
- length -= n;
+ if (bb_dump_length != -1) {
+ bb_dump_length -= n;
}
if (!(need -= n)) {
- if (vflag == ALL || vflag == FIRST || bcmp(curp, savp, blocksize)) {
- if (vflag == DUP || vflag == FIRST) {
- vflag = WAIT;
+ if (bb_dump_vflag == ALL || bb_dump_vflag == FIRST
+ || bcmp(curp, savp, bb_dump_blocksize)) {
+ if (bb_dump_vflag == DUP || bb_dump_vflag == FIRST) {
+ bb_dump_vflag = WAIT;
}
return (curp);
}
- if (vflag == WAIT) {
+ if (bb_dump_vflag == WAIT) {
printf("*\n");
}
- vflag = DUP;
- address = savaddress += blocksize;
- need = blocksize;
+ bb_dump_vflag = DUP;
+ address = savaddress += bb_dump_blocksize;
+ need = bb_dump_blocksize;
nread = 0;
} else {
nread += n;
@@ -507,67 +425,59 @@ static void bpad(PR * pr)
pr->flags = F_BPAD;
*pr->cchar = 's';
for (p1 = pr->fmt; *p1 != '%'; ++p1);
- for (p2 = ++p1; *p1 && index(" -0+#", *p1); ++p1);
+ for (p2 = ++p1; *p1 && strchr(" -0+#", *p1); ++p1);
while ((*p2++ = *p1++) != 0);
}
-void conv_c(PR * pr, u_char * p)
+static const char conv_str[] =
+ "\0\\0\0"
+ "\007\\a\0" /* \a */
+ "\b\\b\0"
+ "\f\\b\0"
+ "\n\\n\0"
+ "\r\\r\0"
+ "\t\\t\0"
+ "\v\\v\0"
+ "\0";
+
+
+static void conv_c(PR * pr, u_char * p)
{
- char buf[10], *str;
-
- switch (*p) {
- case '\0':
- str = "\\0";
- goto strpr;
- /* case '\a': */
- case '\007':
- str = "\\a";
- goto strpr;
- case '\b':
- str = "\\b";
- goto strpr;
- case '\f':
- str = "\\f";
- goto strpr;
- case '\n':
- str = "\\n";
- goto strpr;
- case '\r':
- str = "\\r";
- goto strpr;
- case '\t':
- str = "\\t";
- goto strpr;
- case '\v':
- str = "\\v";
- goto strpr;
- default:
- break;
- }
+ const char *str = conv_str;
+ char buf[10];
+
+ do {
+ if (*p == *str) {
+ ++str;
+ goto strpr;
+ }
+ str += 4;
+ } while (*str);
+
if (isprint(*p)) {
*pr->cchar = 'c';
(void) printf(pr->fmt, *p);
} else {
- sprintf(str = buf, "%03o", (int) *p);
+ sprintf(buf, "%03o", (int) *p);
+ str = buf;
strpr:
*pr->cchar = 's';
printf(pr->fmt, str);
}
}
-void conv_u(PR * pr, u_char * p)
+static void conv_u(PR * pr, u_char * p)
{
- static char *list[] = {
- "nul", "soh", "stx", "etx", "eot", "enq", "ack", "bel",
- "bs", "ht", "lf", "vt", "ff", "cr", "so", "si",
- "dle", "dcl", "dc2", "dc3", "dc4", "nak", "syn", "etb",
- "can", "em", "sub", "esc", "fs", "gs", "rs", "us",
- };
+ static const char list[] =
+ "nul\0soh\0stx\0etx\0eot\0enq\0ack\0bel\0"
+ "bs\0_ht\0_lf\0_vt\0_ff\0_cr\0_so\0_si\0_"
+ "dle\0dcl\0dc2\0dc3\0dc4\0nak\0syn\0etb\0"
+ "can\0em\0_sub\0esc\0fs\0_gs\0_rs\0_us";
/* od used nl, not lf */
if (*p <= 0x1f) {
*pr->cchar = 's';
- printf(pr->fmt, list[*p]);
+ printf(pr->fmt, list[4 * (int)(*p)]);
} else if (*p == 0x7f) {
*pr->cchar = 's';
printf(pr->fmt, "del");
@@ -580,7 +490,7 @@ void conv_u(PR * pr, u_char * p)
}
}
-void display(void)
+static void display(void)
{
/* extern FU *endfu; */
register FS *fs;
@@ -589,11 +499,11 @@ void display(void)
register int cnt;
register u_char *bp;
-/* off_t saveaddress; */
+ off_t saveaddress;
u_char savech = 0, *savebp;
while ((bp = get()) != NULL) {
- for (fs = fshead, savebp = bp, saveaddress = address; fs;
+ for (fs = bb_dump_fshead, savebp = bp, saveaddress = address; fs;
fs = fs->nextfs, bp = savebp, address = saveaddress) {
for (fu = fs->nextfu; fu; fu = fu->nextfu) {
if (fu->flags & F_IGNORE) {
@@ -707,8 +617,8 @@ void display(void)
}
if (endfu) {
/*
- * if eaddress not set, error or file size was multiple of
- * blocksize, and no partial block ever found.
+ * if eaddress not set, error or file bb_dump_size was multiple of
+ * bb_dump_blocksize, and no partial block ever found.
*/
if (!eaddress) {
if (!address) {
@@ -729,19 +639,19 @@ void display(void)
}
}
-int dump(char **argv)
+int bb_dump_dump(char **argv)
{
register FS *tfs;
- /* figure out the data block size */
- for (blocksize = 0, tfs = fshead; tfs; tfs = tfs->nextfs) {
- tfs->bcnt = size(tfs);
- if (blocksize < tfs->bcnt) {
- blocksize = tfs->bcnt;
+ /* figure out the data block bb_dump_size */
+ for (bb_dump_blocksize = 0, tfs = bb_dump_fshead; tfs; tfs = tfs->nextfs) {
+ tfs->bcnt = bb_dump_size(tfs);
+ if (bb_dump_blocksize < tfs->bcnt) {
+ bb_dump_blocksize = tfs->bcnt;
}
}
/* rewrite the rules, do syntax checking */
- for (tfs = fshead; tfs; tfs = tfs->nextfs) {
+ for (tfs = bb_dump_fshead; tfs; tfs = tfs->nextfs) {
rewrite(tfs);
}
@@ -751,21 +661,21 @@ int dump(char **argv)
return (exitval);
}
-void add(char *fmt)
+void bb_dump_add(const char *fmt)
{
- register char *p;
+ register const char *p;
register char *p1;
register char *p2;
static FS **nextfs;
FS *tfs;
FU *tfu, **nextfu;
- char *savep;
+ const char *savep;
/* start new linked list of format units */
/* NOSTRICT */
tfs = (FS *) xmalloc(sizeof(FS));
- if (!fshead) {
- fshead = tfs;
+ if (!bb_dump_fshead) {
+ bb_dump_fshead = tfs;
} else {
*nextfs = tfs;
}
@@ -774,8 +684,8 @@ void add(char *fmt)
/* take the format string and break it up into format units */
for (p = fmt;;) {
- /* skip leading white space */
- for (; isspace(*p); ++p);
+ /* bb_dump_skip leading white space */
+ p = bb_skip_whitespace(p);
if (!*p) {
break;
}
@@ -791,43 +701,41 @@ void add(char *fmt)
if (isdigit(*p)) {
for (savep = p; isdigit(*p); ++p);
if (!isspace(*p) && *p != '/') {
- error_msg_and_die("hexdump: bad format {%s}", fmt);
+ bb_error_msg_and_die("bad format {%s}", fmt);
}
/* may overwrite either white space or slash */
tfu->reps = atoi(savep);
tfu->flags = F_SETREP;
- /* skip trailing white space */
- for (++p; isspace(*p); ++p);
+ /* bb_dump_skip trailing white space */
+ p = bb_skip_whitespace(++p);
}
- /* skip slash and trailing white space */
+ /* bb_dump_skip slash and trailing white space */
if (*p == '/') {
- while (isspace(*++p));
+ p = bb_skip_whitespace(++p);
}
/* byte count */
if (isdigit(*p)) {
for (savep = p; isdigit(*p); ++p);
if (!isspace(*p)) {
- error_msg_and_die("hexdump: bad format {%s}", fmt);
+ bb_error_msg_and_die("bad format {%s}", fmt);
}
tfu->bcnt = atoi(savep);
- /* skip trailing white space */
- for (++p; isspace(*p); ++p);
+ /* bb_dump_skip trailing white space */
+ p = bb_skip_whitespace(++p);
}
/* format */
if (*p != '"') {
- error_msg_and_die("hexdump: bad format {%s}", fmt);
+ bb_error_msg_and_die("bad format {%s}", fmt);
}
for (savep = ++p; *p != '"';) {
if (*p++ == 0) {
- error_msg_and_die("hexdump: bad format {%s}", fmt);
+ bb_error_msg_and_die("bad format {%s}", fmt);
}
}
- if (!(tfu->fmt = malloc(p - savep + 1))) {
- perror_msg_and_die("hexdump");
- }
+ tfu->fmt = xmalloc(p - savep + 1);
strncpy(tfu->fmt, savep, p - savep);
tfu->fmt[p - savep] = '\0';
/* escape(tfu->fmt); */
@@ -841,33 +749,16 @@ void add(char *fmt)
break;
}
if (*p1 == '\\') {
- switch (*++p1) {
- case 'a':
- /* *p2 = '\a'; */
- *p2 = '\007';
- break;
- case 'b':
- *p2 = '\b';
- break;
- case 'f':
- *p2 = '\f';
- break;
- case 'n':
- *p2 = '\n';
- break;
- case 'r':
- *p2 = '\r';
- break;
- case 't':
- *p2 = '\t';
- break;
- case 'v':
- *p2 = '\v';
- break;
- default:
- *p2 = *p1;
- break;
- }
+ const char *cs = conv_str + 4;
+ ++p1;
+ *p2 = *p1;
+ do {
+ if (*p1 == cs[2]) {
+ *p2 = cs[0];
+ break;
+ }
+ cs += 4;
+ } while (*cs);
}
}
diff --git a/libbb/error_msg.c b/libbb/error_msg.c
index 58308b6be..5456dd361 100644
--- a/libbb/error_msg.c
+++ b/libbb/error_msg.c
@@ -25,12 +25,12 @@
#include <stdlib.h>
#include "libbb.h"
-extern void error_msg(const char *s, ...)
+extern void bb_error_msg(const char *s, ...)
{
va_list p;
va_start(p, s);
- verror_msg(s, p);
+ bb_verror_msg(s, p);
va_end(p);
putc('\n', stderr);
}
diff --git a/libbb/error_msg_and_die.c b/libbb/error_msg_and_die.c
index 67a79c375..7e7393773 100644
--- a/libbb/error_msg_and_die.c
+++ b/libbb/error_msg_and_die.c
@@ -25,15 +25,15 @@
#include <stdlib.h>
#include "libbb.h"
-extern void error_msg_and_die(const char *s, ...)
+extern void bb_error_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
- verror_msg(s, p);
+ bb_verror_msg(s, p);
va_end(p);
putc('\n', stderr);
- exit(EXIT_FAILURE);
+ exit(bb_default_error_retval);
}
diff --git a/libbb/fclose_nonstdin.c b/libbb/fclose_nonstdin.c
new file mode 100644
index 000000000..97e303e9c
--- /dev/null
+++ b/libbb/fclose_nonstdin.c
@@ -0,0 +1,37 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * fclose_nonstdin implementation for busybox
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/* A number of standard utilites can accept multiple command line args
+ * of '-' for stdin, according to SUSv3. So we encapsulate the check
+ * here to save a little space.
+ */
+
+#include <stdio.h>
+#include <libbb.h>
+
+int bb_fclose_nonstdin(FILE *f)
+{
+ if (f != stdin) {
+ return fclose(f);
+ }
+ return 0;
+}
diff --git a/libbb/fflush_stdout_and_exit.c b/libbb/fflush_stdout_and_exit.c
new file mode 100644
index 000000000..cbba04207
--- /dev/null
+++ b/libbb/fflush_stdout_and_exit.c
@@ -0,0 +1,37 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * fflush_stdout_and_exit implementation for busybox
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/* Attempt to fflush(stdout), and exit with an error code if stdout is
+ * in an error state.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <libbb.h>
+
+void bb_fflush_stdout_and_exit(int retval)
+{
+ if (fflush(stdout)) {
+ retval = bb_default_error_retval;
+ }
+ exit(retval);
+}
diff --git a/libbb/find_root_device.c b/libbb/find_root_device.c
index 0a3f1bc77..763ac7519 100644
--- a/libbb/find_root_device.c
+++ b/libbb/find_root_device.c
@@ -38,14 +38,14 @@ extern char *find_real_root_device_name(const char* name)
dev_t dev;
if (stat("/", &rootStat) != 0)
- perror_msg("could not stat '/'");
+ bb_perror_msg("could not stat '/'");
else {
if ((dev = rootStat.st_rdev)==0)
dev=rootStat.st_dev;
dir = opendir("/dev");
if (!dir)
- perror_msg("could not open '/dev'");
+ bb_perror_msg("could not open '/dev'");
else {
while((entry = readdir(dir)) != NULL) {
@@ -69,7 +69,7 @@ extern char *find_real_root_device_name(const char* name)
}
}
if(fileName==NULL)
- fileName=xstrdup("/dev/root");
+ fileName=bb_xstrdup("/dev/root");
return fileName;
}
diff --git a/libbb/full_read.c b/libbb/full_read.c
index ccf26fc3d..e75f967db 100644
--- a/libbb/full_read.c
+++ b/libbb/full_read.c
@@ -23,17 +23,16 @@
#include <unistd.h>
#include "libbb.h"
-
/*
* Read all of the supplied buffer from a file.
* This does multiple reads as necessary.
* Returns the amount read, or -1 on an error.
* A short read is returned on an end of file.
*/
-int full_read(int fd, char *buf, int len)
+ssize_t bb_full_read(int fd, void *buf, size_t len)
{
- int cc;
- int total;
+ ssize_t cc;
+ ssize_t total;
total = 0;
@@ -41,12 +40,12 @@ int full_read(int fd, char *buf, int len)
cc = read(fd, buf, len);
if (cc < 0)
- return -1;
+ return cc; /* read() returns -1 on failure. */
if (cc == 0)
break;
- buf += cc;
+ buf = ((char *)buf) + cc;
total += cc;
len -= cc;
}
diff --git a/libbb/full_write.c b/libbb/full_write.c
index a2c07fbc9..1106a53b4 100644
--- a/libbb/full_write.c
+++ b/libbb/full_write.c
@@ -28,10 +28,10 @@
* This does multiple writes as necessary.
* Returns the amount written, or -1 on an error.
*/
-int full_write(int fd, const char *buf, int len)
+ssize_t bb_full_write(int fd, const void *buf, size_t len)
{
- int cc;
- int total;
+ ssize_t cc;
+ ssize_t total;
total = 0;
@@ -39,10 +39,10 @@ int full_write(int fd, const char *buf, int len)
cc = write(fd, buf, len);
if (cc < 0)
- return -1;
+ return cc; /* write() returns -1 on failure. */
- buf += cc;
total += cc;
+ buf = ((const char *)buf) + cc;
len -= cc;
}
diff --git a/libbb/get_console.c b/libbb/get_console.c
index 794888fa7..562b57703 100644
--- a/libbb/get_console.c
+++ b/libbb/get_console.c
@@ -106,7 +106,7 @@ int get_console_fd(void)
if (is_a_console(fd))
return fd;
- error_msg("Couldn't get a file descriptor referring to the console");
+ bb_error_msg("Couldn't get a file descriptor referring to the console");
return -1; /* total failure */
}
diff --git a/libbb/get_last_path_component.c b/libbb/get_last_path_component.c
index 6af726c83..497d6ae4e 100644
--- a/libbb/get_last_path_component.c
+++ b/libbb/get_last_path_component.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * get_last_path_component implementation for busybox
+ * bb_get_last_path_component implementation for busybox
*
- * Copyright (C) 2001 Manuel Novoa III <mjn3@opensource.lineo.com>
+ * Copyright (C) 2001 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -24,7 +24,7 @@
/* WARNING!!! Doing so will break basename applet at least! */
#define EMULATE_BASENAME 0
-char *get_last_path_component(char *path)
+char *bb_get_last_path_component(char *path)
{
#if EMULATE_BASENAME
static const char null_or_empty[] = ".";
diff --git a/libbb/get_line_from_file.c b/libbb/get_line_from_file.c
index 5e7062127..5af898934 100644
--- a/libbb/get_line_from_file.c
+++ b/libbb/get_line_from_file.c
@@ -21,41 +21,57 @@
*/
#include <stdio.h>
+#include <stdlib.h>
#include "libbb.h"
-
-
-/* get_line_from_file() - This function reads an entire line from a text file
+/* get_line_from_file() - This function reads an entire line from a text file,
* up to a newline. It returns a malloc'ed char * which must be stored and
- * free'ed by the caller. */
-extern char *get_line_from_file(FILE *file)
+ * free'ed by the caller. If 'c' is nonzero, the trailing '\n' (if any)
+ * is removed. In event of a read error or EOF, NULL is returned. */
+
+static char *private_get_line_from_file(FILE *file, int c)
{
- static const int GROWBY = 80; /* how large we will grow strings by */
+#define GROWBY (80) /* how large we will grow strings by */
int ch;
int idx = 0;
char *linebuf = NULL;
int linebufsz = 0;
- while (1) {
- ch = fgetc(file);
- if (ch == EOF)
- break;
+ while ((ch = getc(file)) != EOF) {
/* grow the line buffer as necessary */
- while (idx > linebufsz-2)
+ if (idx > linebufsz-2) {
linebuf = xrealloc(linebuf, linebufsz += GROWBY);
+ }
linebuf[idx++] = (char)ch;
- if (ch == '\n' || ch == '\0')
+ if (ch == '\n' || ch == '\0') {
+ if (c) {
+ --idx;
+ }
break;
+ }
}
- if (idx == 0)
- return NULL;
-
- linebuf[idx] = 0;
+ if (linebuf) {
+ if (ferror(file)) {
+ free(linebuf);
+ return NULL;
+ }
+ linebuf[idx] = 0;
+ }
return linebuf;
}
+extern char *bb_get_line_from_file(FILE *file)
+{
+ return private_get_line_from_file(file, 0);
+}
+
+extern char *bb_get_chomped_line_from_file(FILE *file)
+{
+ return private_get_line_from_file(file, 1);
+}
+
/* END CODE */
/*
diff --git a/libbb/time_string.c b/libbb/getopt_ulflags.c
index d103a02f8..91de392b6 100644
--- a/libbb/time_string.c
+++ b/libbb/getopt_ulflags.c
@@ -1,8 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Utility routines.
+ * getopt_ulflags implementation for busybox
*
- * Copyright (C) 1999,2000,2001 by Erik Andersen <andersee@debian.org>
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -17,46 +17,25 @@
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
*/
-#include <stdio.h>
+#include <getopt.h>
#include <string.h>
-#include <time.h>
-#include <utime.h>
#include "libbb.h"
-
-/*
- * Return the standard ls-like time string from a time_t
- * This is static and so is overwritten on each call.
- */
-const char *time_string(time_t timeVal)
+unsigned long bb_getopt_ulflags(int argc, char **argv, const char *applet_opts)
{
- time_t now;
- char *str;
- static char buf[26];
-
- time(&now);
-
- str = ctime(&timeVal);
-
- strcpy(buf, &str[4]);
- buf[12] = '\0';
-
- if ((timeVal > now) || (timeVal < now - 365 * 24 * 60 * 60L)) {
- strcpy(&buf[7], &str[20]);
- buf[11] = '\0';
+ unsigned long flags = 0;
+ const char *s;
+ int c;
+
+ while ((c = getopt(argc, argv, applet_opts)) > 0) {
+ if (!(s = strchr(applet_opts, c))) {
+ bb_show_usage();
+ }
+ flags |= (1 << (s-applet_opts));
}
- return buf;
+ return flags;
}
-
-
-/* END CODE */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
diff --git a/libbb/herror_msg.c b/libbb/herror_msg.c
index 1081a56b1..4fe921b29 100644
--- a/libbb/herror_msg.c
+++ b/libbb/herror_msg.c
@@ -24,12 +24,12 @@
#include "libbb.h"
-extern void herror_msg(const char *s, ...)
+extern void bb_herror_msg(const char *s, ...)
{
va_list p;
va_start(p, s);
- vherror_msg(s, p);
+ bb_vherror_msg(s, p);
va_end(p);
}
diff --git a/libbb/herror_msg_and_die.c b/libbb/herror_msg_and_die.c
index a47c7ff95..33a8c3e28 100644
--- a/libbb/herror_msg_and_die.c
+++ b/libbb/herror_msg_and_die.c
@@ -24,14 +24,14 @@
#include "libbb.h"
-extern void herror_msg_and_die(const char *s, ...)
+extern void bb_herror_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
- vherror_msg(s, p);
+ bb_vherror_msg(s, p);
va_end(p);
- exit(EXIT_FAILURE);
+ exit(bb_default_error_retval);
}
diff --git a/libbb/inet_common.c b/libbb/inet_common.c
index 16dd1db7c..5e2343bdd 100644
--- a/libbb/inet_common.c
+++ b/libbb/inet_common.c
@@ -4,7 +4,7 @@
*
* Heavily modified by Manuel Novoa III Mar 12, 2001
*
- * Version: $Id: inet_common.c,v 1.5 2002/11/28 09:52:23 bug1 Exp $
+ * Version: $Id: inet_common.c,v 1.6 2003/03/19 09:12:07 mjn3 Exp $
*
*/
@@ -44,7 +44,7 @@ int INET_resolve(const char *name, struct sockaddr_in *s_in, int hostfirst)
/* If we expect this to be a hostname, try hostname database first */
#ifdef DEBUG
if (hostfirst) {
- error_msg("gethostbyname (%s)", name);
+ bb_error_msg("gethostbyname (%s)", name);
}
#endif
if (hostfirst && (hp = gethostbyname(name)) != (struct hostent *) NULL) {
@@ -54,7 +54,7 @@ int INET_resolve(const char *name, struct sockaddr_in *s_in, int hostfirst)
}
/* Try the NETWORKS database to see if this is a known network. */
#ifdef DEBUG
- error_msg("getnetbyname (%s)", name);
+ bb_error_msg("getnetbyname (%s)", name);
#endif
if ((np = getnetbyname(name)) != (struct netent *) NULL) {
s_in->sin_addr.s_addr = htonl(np->n_net);
@@ -71,7 +71,7 @@ int INET_resolve(const char *name, struct sockaddr_in *s_in, int hostfirst)
#endif
#ifdef DEBUG
- error_msg("gethostbyname (%s)", name);
+ bb_error_msg("gethostbyname (%s)", name);
#endif
if ((hp = gethostbyname(name)) == (struct hostent *) NULL) {
errno = h_errno;
@@ -109,7 +109,7 @@ int INET_rresolve(char *name, size_t len, struct sockaddr_in *s_in,
/* Grmpf. -FvK */
if (s_in->sin_family != AF_INET) {
#ifdef DEBUG
- error_msg("rresolve: unsupport address family %d !",
+ bb_error_msg("rresolve: unsupport address family %d !",
s_in->sin_family);
#endif
errno = EAFNOSUPPORT;
@@ -117,7 +117,7 @@ int INET_rresolve(char *name, size_t len, struct sockaddr_in *s_in,
}
ad = (unsigned long) s_in->sin_addr.s_addr;
#ifdef DEBUG
- error_msg("rresolve: %08lx, mask %08x, num %08x", ad, netmask, numeric);
+ bb_error_msg("rresolve: %08lx, mask %08x, num %08x", ad, netmask, numeric);
#endif
if (ad == INADDR_ANY) {
if ((numeric & 0x0FFF) == 0) {
@@ -143,7 +143,7 @@ int INET_rresolve(char *name, size_t len, struct sockaddr_in *s_in,
if (pn->addr.sin_addr.s_addr == ad && pn->host == host) {
safe_strncpy(name, pn->name, len);
#ifdef DEBUG
- error_msg("rresolve: found %s %08lx in cache",
+ bb_error_msg("rresolve: found %s %08lx in cache",
(host ? "host" : "net"), ad);
#endif
return (0);
@@ -156,7 +156,7 @@ int INET_rresolve(char *name, size_t len, struct sockaddr_in *s_in,
ent = NULL;
if (host) {
#ifdef DEBUG
- error_msg("gethostbyaddr (%08lx)", ad);
+ bb_error_msg("gethostbyaddr (%08lx)", ad);
#endif
ent = gethostbyaddr((char *) &ad, 4, AF_INET);
if (ent != NULL) {
@@ -164,7 +164,7 @@ int INET_rresolve(char *name, size_t len, struct sockaddr_in *s_in,
}
} else {
#ifdef DEBUG
- error_msg("getnetbyaddr (%08lx)", host_ad);
+ bb_error_msg("getnetbyaddr (%08lx)", host_ad);
#endif
np = getnetbyaddr(host_ad, AF_INET);
if (np != NULL) {
@@ -178,7 +178,7 @@ int INET_rresolve(char *name, size_t len, struct sockaddr_in *s_in,
pn->addr = *s_in;
pn->next = INET_nn;
pn->host = host;
- pn->name = xstrdup(name);
+ pn->name = bb_xstrdup(name);
INET_nn = pn;
return (0);
@@ -194,7 +194,7 @@ int INET6_resolve(char *name, struct sockaddr_in6 *sin6)
memset(&req, '\0', sizeof req);
req.ai_family = AF_INET6;
if ((s = getaddrinfo(name, NULL, &req, &ai))) {
- error_msg("getaddrinfo: %s: %d", name, s);
+ bb_error_msg("getaddrinfo: %s: %d", name, s);
return -1;
}
memcpy(sin6, ai->ai_addr, sizeof(struct sockaddr_in6));
@@ -219,7 +219,7 @@ int INET6_rresolve(char *name, size_t len, struct sockaddr_in6 *sin6,
/* Grmpf. -FvK */
if (sin6->sin6_family != AF_INET6) {
#ifdef DEBUG
- error_msg(_("rresolve: unsupport address family %d !\n"),
+ bb_error_msg(_("rresolve: unsupport address family %d !\n"),
sin6->sin6_family);
#endif
errno = EAFNOSUPPORT;
@@ -240,7 +240,7 @@ int INET6_rresolve(char *name, size_t len, struct sockaddr_in6 *sin6,
s = getnameinfo((struct sockaddr *) sin6, sizeof(struct sockaddr_in6), name, len, NULL, 0, 0);
if (s) {
- error_msg("getnameinfo failed");
+ bb_error_msg("getnameinfo failed");
return -1;
}
return (0);
diff --git a/libbb/interface.c b/libbb/interface.c
index fb794169d..531700f45 100644
--- a/libbb/interface.c
+++ b/libbb/interface.c
@@ -15,7 +15,7 @@
* that either displays or sets the characteristics of
* one or more of the system's networking interfaces.
*
- * Version: $Id: interface.c,v 1.14 2003/02/09 22:40:33 bug1 Exp $
+ * Version: $Id: interface.c,v 1.15 2003/03/19 09:12:07 mjn3 Exp $
*
* Author: Fred N. van Kempen, <waltje@uwalt.nl.mugnet.org>
* and others. Copyright 1993 MicroWalt Corporation
@@ -619,7 +619,7 @@ static int aftrans_opt(const char *arg)
if (strcmp(tmp1, paft->alias))
continue;
if (strlen(paft->name) + strlen(afname) + 1 >= sizeof(afname)) {
- error_msg(_("Too many address family arguments."));
+ bb_error_msg(_("Too many address family arguments."));
return (0);
}
if (paft->flag)
@@ -630,7 +630,7 @@ static int aftrans_opt(const char *arg)
break;
}
if (!paft->alias) {
- error_msg(_("Unknown address family `%s'."), tmp1);
+ bb_error_msg(_("Unknown address family `%s'."), tmp1);
return (1);
}
tmp1 = tmp2;
@@ -693,7 +693,7 @@ static struct aftype *get_aftype(const char *name)
afp++;
}
if (strchr(name, ','))
- error_msg(_("Please don't supply more than one address family."));
+ bb_error_msg(_("Please don't supply more than one address family."));
return (NULL);
}
#endif /* KEEP_UNUSED */
@@ -888,7 +888,7 @@ static int sockets_open(int family)
sfd = af->fd;
}
if (sfd < 0) {
- error_msg(_("No usable address families found."));
+ bb_error_msg(_("No usable address families found."));
}
return sfd;
}
@@ -960,7 +960,7 @@ static int if_readconf(void)
(as of 2.1.128) */
skfd2 = get_socket_for_af(AF_INET);
if (skfd2 < 0) {
- perror_msg(("warning: no inet socket available"));
+ bb_perror_msg(("warning: no inet socket available"));
/* Try to soldier on with whatever socket we can get hold of. */
skfd2 = sockets_open(0);
if (skfd2 < 0)
@@ -1106,7 +1106,7 @@ static int if_readlist_proc(char *target)
fh = fopen(_PATH_PROCNET_DEV, "r");
if (!fh) {
- perror_msg(_("Warning: cannot open %s. Limited output."), _PATH_PROCNET_DEV);
+ bb_perror_msg(_("Warning: cannot open %s. Limited output."), _PATH_PROCNET_DEV);
return if_readconf();
}
fgets(buf, sizeof buf, fh); /* eat line */
@@ -1366,7 +1366,7 @@ static int do_if_fetch(struct interface *ife)
} else {
errmsg = strerror(errno);
}
- error_msg(_("%s: error fetching interface information: %s\n"),
+ bb_error_msg(_("%s: error fetching interface information: %s\n"),
ife->name, errmsg);
return -1;
}
@@ -1441,7 +1441,7 @@ static int in_ether(char *bufp, struct sockaddr *sap)
val = c - 'A' + 10;
else {
#ifdef DEBUG
- error_msg(_("in_ether(%s): invalid ether address!\n"), orig);
+ bb_error_msg(_("in_ether(%s): invalid ether address!\n"), orig);
#endif
errno = EINVAL;
return (-1);
@@ -1458,7 +1458,7 @@ static int in_ether(char *bufp, struct sockaddr *sap)
val >>= 4;
else {
#ifdef DEBUG
- error_msg(_("in_ether(%s): invalid ether address!"), orig);
+ bb_error_msg(_("in_ether(%s): invalid ether address!"), orig);
#endif
errno = EINVAL;
return (-1);
@@ -1472,7 +1472,7 @@ static int in_ether(char *bufp, struct sockaddr *sap)
if (*bufp == ':') {
#ifdef DEBUG
if (i == ETH_ALEN) {
- error_msg(_("in_ether(%s): trailing : ignored!"), orig);
+ bb_error_msg(_("in_ether(%s): trailing : ignored!"), orig);
}
#endif
bufp++;
@@ -1482,11 +1482,11 @@ static int in_ether(char *bufp, struct sockaddr *sap)
#ifdef DEBUG
/* That's it. Any trailing junk? */
if ((i == ETH_ALEN) && (*bufp != '\0')) {
- error_msg(_("in_ether(%s): trailing junk!"), orig);
+ bb_error_msg(_("in_ether(%s): trailing junk!"), orig);
errno = EINVAL;
return (-1);
}
- error_msg("in_ether(%s): %s", orig, pr_ether(sap->sa_data));
+ bb_error_msg("in_ether(%s): %s", orig, pr_ether(sap->sa_data));
#endif
return (0);
@@ -1511,7 +1511,7 @@ static struct hwtype ether_hwtype = {
/* Start the PPP encapsulation on the file descriptor. */
static int do_ppp(int fd)
{
- error_msg(_("You cannot start PPP with this program."));
+ bb_error_msg(_("You cannot start PPP with this program."));
return -1;
}
#endif /* KEEP_UNUSED */
@@ -2052,7 +2052,7 @@ int display_interfaces(char *ifname)
/* Create a channel to the NET kernel. */
if ((skfd = sockets_open(0)) < 0) {
- perror_msg_and_die("socket");
+ bb_perror_msg_and_die("socket");
}
/* Do we have to show the current setup? */
diff --git a/libbb/kernel_version.c b/libbb/kernel_version.c
index 694af8e2c..14b163654 100644
--- a/libbb/kernel_version.c
+++ b/libbb/kernel_version.c
@@ -37,7 +37,7 @@ extern int get_kernel_revision(void)
int i, r;
if (uname(&name) == -1) {
- perror_msg("cannot get system information");
+ bb_perror_msg("cannot get system information");
return (0);
}
diff --git a/libbb/loop.c b/libbb/loop.c
index 7e58b2f85..29128abe4 100644
--- a/libbb/loop.c
+++ b/libbb/loop.c
@@ -33,11 +33,11 @@ extern int del_loop(const char *device)
int fd;
if ((fd = open(device, O_RDONLY)) < 0) {
- perror_msg("%s", device);
+ bb_perror_msg("%s", device);
return (FALSE);
}
if (ioctl(fd, LOOP_CLR_FD, 0) < 0) {
- perror_msg("ioctl: LOOP_CLR_FD");
+ bb_perror_msg("ioctl: LOOP_CLR_FD");
return (FALSE);
}
close(fd);
@@ -53,12 +53,12 @@ extern int set_loop(const char *device, const char *file, int offset,
mode = *loopro ? O_RDONLY : O_RDWR;
if ((ffd = open(file, mode)) < 0 && !*loopro
&& (errno != EROFS || (ffd = open(file, mode = O_RDONLY)) < 0)) {
- perror_msg("%s", file);
+ bb_perror_msg("%s", file);
return 1;
}
if ((fd = open(device, mode)) < 0) {
close(ffd);
- perror_msg("%s", device);
+ bb_perror_msg("%s", device);
return 1;
}
*loopro = (mode == O_RDONLY);
@@ -70,14 +70,14 @@ extern int set_loop(const char *device, const char *file, int offset,
loopinfo.lo_encrypt_key_size = 0;
if (ioctl(fd, LOOP_SET_FD, ffd) < 0) {
- perror_msg("ioctl: LOOP_SET_FD");
+ bb_perror_msg("ioctl: LOOP_SET_FD");
close(fd);
close(ffd);
return 1;
}
if (ioctl(fd, LOOP_SET_STATUS, &loopinfo) < 0) {
(void) ioctl(fd, LOOP_CLR_FD, 0);
- perror_msg("ioctl: LOOP_SET_STATUS");
+ bb_perror_msg("ioctl: LOOP_SET_STATUS");
close(fd);
close(ffd);
return 1;
diff --git a/libbb/make_directory.c b/libbb/make_directory.c
index 65be397bf..e3d2c52b1 100644
--- a/libbb/make_directory.c
+++ b/libbb/make_directory.c
@@ -1,12 +1,8 @@
/* vi: set sw=4 ts=4: */
/*
- * Mini make_directory implementation for busybox
+ * parse_mode implementation for busybox
*
- * Copyright (C) 2001 Matt Kraai.
- *
- * Rewriten in 2002
- * Copyright (C) 2002 Glenn McGrath
- * Copyright (C) 2002 Vladimir N. Oleynik
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -24,57 +20,87 @@
*
*/
+/* Mar 5, 2003 Manuel Novoa III
+ *
+ * This is the main work function for the 'mkdir' applet. As such, it
+ * strives to be SUSv3 compliant in it's behaviour when recursively
+ * making missing parent dirs, and in it's mode setting of the final
+ * directory 'path'.
+ *
+ * To recursively build all missing intermediate directories, make
+ * sure that (flags & FILEUTILS_RECUR) is non-zero. Newly created
+ * intermediate directories will have at least u+wx perms.
+ *
+ * To set specific permisions on 'path', pass the appropriate 'mode'
+ * val. Otherwise, pass -1 to get default permisions.
+ */
+
#include <errno.h>
-#include <fcntl.h>
-#include <string.h>
-#include <sys/stat.h>
-#include <sys/types.h>
#include <unistd.h>
-#include <stdlib.h>
-
#include "libbb.h"
-/* Create the directory PATH with mode MODE, or the default if MODE is -1.
- * Also create parent directories as necessary if flags contains
- * FILEUTILS_RECUR. */
-
-int make_directory (char *path, long mode, int flags)
+int bb_make_directory (char *path, long mode, int flags)
{
- int ret;
-
- if (flags == FILEUTILS_RECUR) {
- char *pp = strrchr(path, '/');
- if ((pp) && (pp != path)) {
- *pp = '\0';
- make_directory(path, -1, flags);
- *pp = '/';
- }
- }
+ mode_t mask;
+ const char *fail_msg;
+ char *s = path;
+ char c;
- if (mode == -1) {
- struct stat statbuf;
- char *pp = strrchr(path, '/');
+ mask = umask(0);
+ umask(mask & ~0300);
- statbuf.st_mode = 0777;
+ do {
+ c = 0;
- /* stat the directory */
- if ((pp) && (pp != path)) {
- *pp = '\0';
- stat(path, &statbuf);
- *pp = '/';
+ if (flags & FILEUTILS_RECUR) { /* Get the parent. */
+ /* Bypass leading non-'/'s and then subsequent '/'s. */
+ while (*s) {
+ if (*s == '/') {
+ do {
+ ++s;
+ } while (*s == '/');
+ c = *s; /* Save the current char */
+ *s = 0; /* and replace it with nul. */
+ break;
+ }
+ ++s;
+ }
}
- mode = statbuf.st_mode;
- }
+ if (mkdir(path, 0777) < 0) {
+ /* If we failed for any other reason than the directory
+ * already exists, output a diagnostic and return -1.*/
+ if (errno != EEXIST) {
+ fail_msg = "create";
+ umask(mask);
+ break;
+ }
+ /* Since the directory exists, don't attempt to change
+ * permissions if it was the full target. Note that
+ * this is not an error conditon. */
+ if (!c) {
+ umask(mask);
+ return 0;
+ }
+ }
- ret = mkdir(path, mode);
- if (ret == -1) {
- if ((flags == FILEUTILS_RECUR) && (errno == EEXIST)) {
- ret = 0;
- } else {
- perror_msg_and_die("Cannot create directory '%s'", path);
+ if (!c) {
+ /* Done. If necessary, updated perms on the newly
+ * created directory. Failure to update here _is_
+ * an error.*/
+ umask(mask);
+ if ((mode != -1) && (chmod(path, mode) < 0)){
+ fail_msg = "set permissions of";
+ break;
+ }
+ return 0;
}
- }
- return(ret);
+ /* Remove any inserted nul from the path (recursive mode). */
+ *s = c;
+
+ } while (1);
+
+ bb_perror_msg ("Cannot %s directory `%s'", fail_msg, path);
+ return -1;
}
diff --git a/libbb/messages.c b/libbb/messages.c
index cc7e2146c..e5ffbf7f7 100644
--- a/libbb/messages.c
+++ b/libbb/messages.c
@@ -23,82 +23,71 @@
#include "libbb.h"
#ifdef L_full_version
- const char * const full_version = BB_BANNER " multi-call binary";
-#endif
-#ifdef L_name_too_long
- const char * const name_too_long = "file name too long";
-#endif
-
-#ifdef L_omitting_directory
- const char * const omitting_directory = "%s: omitting directory";
-#endif
-#ifdef L_not_a_directory
- const char * const not_a_directory = "%s: not a directory";
+ const char * const bb_msg_full_version = BB_BANNER " multi-call binary";
#endif
#ifdef L_memory_exhausted
- const char * const memory_exhausted = "memory exhausted";
+ const char * const bb_msg_memory_exhausted = "memory exhausted";
#endif
#ifdef L_invalid_date
- const char * const invalid_date = "invalid date `%s'";
-#endif
-#ifdef L_invalid_option
- const char * const invalid_option = "invalid option -- %c";
+ const char * const bb_msg_invalid_date = "invalid date `%s'";
#endif
#ifdef L_io_error
- const char * const io_error = "%s: input/output error -- %m";
-#endif
-#ifdef L_dash_dash_help
- const char * const dash_dash_help = "--help";
+ const char * const bb_msg_io_error = "%s: input/output error -- %m";
#endif
#ifdef L_write_error
- const char * const write_error = "Write Error";
-#endif
-#ifdef L_too_few_args
- const char * const too_few_args = "too few arguments";
+ const char * const bb_msg_write_error = "Write Error";
#endif
#ifdef L_name_longer_than_foo
- const char * const name_longer_than_foo = "Names longer than %d chars not supported.";
+ const char * const bb_msg_name_longer_than_foo = "Names longer than %d chars not supported.";
#endif
#ifdef L_unknown
- const char * const unknown = "(unknown)";
+ const char * const bb_msg_unknown = "(unknown)";
#endif
-
#ifdef L_can_not_create_raw_socket
- const char * const can_not_create_raw_socket = "can`t create raw socket";
+ const char * const bb_msg_can_not_create_raw_socket = "can`t create raw socket";
+#endif
+#ifdef L_perm_denied_are_you_root
+ const char * const bb_msg_perm_denied_are_you_root = "permission denied. (are you root?)";
+#endif
+#ifdef L_msg_standard_input
+ const char * const bb_msg_standard_input = "standard input";
+#endif
+#ifdef L_msg_standard_output
+ const char * const bb_msg_standard_output = "standard output";
#endif
#ifdef L_passwd_file
#define PASSWD_FILE "/etc/passwd"
-const char * const passwd_file = PASSWD_FILE;
+const char * const bb_path_passwd_file = PASSWD_FILE;
#endif
#ifdef L_shadow_file
#define SHADOW_FILE "/etc/shadow"
-const char * const shadow_file = SHADOW_FILE;
+const char * const bb_path_shadow_file = SHADOW_FILE;
#endif
#ifdef L_group_file
#define GROUP_FILE "/etc/group"
-const char * const group_file = GROUP_FILE;
+const char * const bb_path_group_file = GROUP_FILE;
#endif
#ifdef L_gshadow_file
#define GSHADOW_FILE "/etc/gshadow"
-const char * const gshadow_file = GSHADOW_FILE;
+const char * const bb_path_gshadow_file = GSHADOW_FILE;
#endif
#ifdef L_nologin_file
#define NOLOGIN_FILE "/etc/nologin"
-const char * const nologin_file = NOLOGIN_FILE;
+const char * const bb_path_nologin_file = NOLOGIN_FILE;
#endif
#ifdef L_securetty_file
#define SECURETTY_FILE "/etc/securetty"
-const char * const securetty_file = SECURETTY_FILE;
+const char * const bb_path_securetty_file = SECURETTY_FILE;
#endif
#ifdef L_motd_file
#define MOTD_FILE "/etc/motd"
-const char * const motd_file = MOTD_FILE;
+const char * const bb_path_motd_file = MOTD_FILE;
#endif
diff --git a/libbb/mode_string.c b/libbb/mode_string.c
index 12dc17966..8d4d736ef 100644
--- a/libbb/mode_string.c
+++ b/libbb/mode_string.c
@@ -1,78 +1,134 @@
/* vi: set sw=4 ts=4: */
/*
- * Utility routines.
+ * mode_string implementation for busybox
*
- * Copyright (C) many different people. If you wrote this, please
- * acknowledge your work.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
*/
-#include <stdio.h>
-#include "libbb.h"
+#include <assert.h>
+#include <sys/stat.h>
+#if ( S_ISUID != 04000 ) || ( S_ISGID != 02000 ) || ( S_ISVTX != 01000 ) \
+ || ( S_IRUSR != 00400 ) || ( S_IWUSR != 00200 ) || ( S_IXUSR != 00100 ) \
+ || ( S_IRGRP != 00040 ) || ( S_IWGRP != 00020 ) || ( S_IXGRP != 00010 ) \
+ || ( S_IROTH != 00004 ) || ( S_IWOTH != 00002 ) || ( S_IXOTH != 00001 )
+#error permission bitflag value assumption(s) violated!
+#endif
+#if ( S_IFSOCK!= 0140000 ) || ( S_IFLNK != 0120000 ) \
+ || ( S_IFREG != 0100000 ) || ( S_IFBLK != 0060000 ) \
+ || ( S_IFDIR != 0040000 ) || ( S_IFCHR != 0020000 ) \
+ || ( S_IFIFO != 0010000 )
+#warning mode type bitflag value assumption(s) violated! falling back to larger version
-#define TYPEINDEX(mode) (((mode) >> 12) & 0x0f)
-#define TYPECHAR(mode) ("0pcCd?bB-?l?s???" [TYPEINDEX(mode)])
+#if (S_IRWXU | S_IRWXG | S_IRWXO | S_ISUID | S_ISGID | S_ISVTX) == 07777
+#undef mode_t
+#define mode_t unsigned short
+#endif
-/* The special bits. If set, display SMODE0/1 instead of MODE0/1 */
-static const mode_t SBIT[] = {
- 0, 0, S_ISUID,
- 0, 0, S_ISGID,
- 0, 0, S_ISVTX
+static const mode_t mode_flags[] = {
+ S_IRUSR, S_IWUSR, S_IXUSR, S_ISUID,
+ S_IRGRP, S_IWGRP, S_IXGRP, S_ISGID,
+ S_IROTH, S_IWOTH, S_IXOTH, S_ISVTX
};
-/* The 9 mode bits to test */
-static const mode_t MBIT[] = {
- S_IRUSR, S_IWUSR, S_IXUSR,
- S_IRGRP, S_IWGRP, S_IXGRP,
- S_IROTH, S_IWOTH, S_IXOTH
-};
+/* The static const char arrays below are duplicated for the two cases
+ * because moving them ahead of the mode_flags declaration cause a text
+ * size increase with the gcc version I'm using. */
-static const char MODE1[] = "rwxrwxrwx";
-static const char MODE0[] = "---------";
-static const char SMODE1[] = "..s..s..t";
-static const char SMODE0[] = "..S..S..T";
+/* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C',
+ * and 'B' types don't appear to be available on linux. So I removed them. */
+static const char type_chars[16] = "?pc?d?b?-?l?s???";
+/* 0123456789abcdef */
+static const char mode_chars[7] = "rwxSTst";
-/*
- * Return the standard ls-like mode string from a file mode.
- * This is static and so is overwritten on each call.
- */
-const char *mode_string(int mode)
+const char *bb_mode_string(int mode)
{
static char buf[12];
+ char *p = buf;
+
+ int i, j, k;
- int i;
+ *p = type_chars[ (mode >> 12) & 0xf ];
+ i = 0;
+ do {
+ j = k = 0;
+ do {
+ *++p = '-';
+ if (mode & mode_flags[i+j]) {
+ *p = mode_chars[j];
+ k = j;
+ }
+ } while (++j < 3);
+ if (mode & mode_flags[i+j]) {
+ *p = mode_chars[3 + (k & 2) + ((i&8) >> 3)];
+ }
+ i += 4;
+ } while (i < 12);
+
+ /* Note: We don't bother with nul termination because bss initialization
+ * should have taken care of that for us. If the user scribbled in buf
+ * memory, they deserve whatever happens. But we'll at least assert. */
+ assert(buf[10] == 0);
- buf[0] = TYPECHAR(mode);
- for (i = 0; i < 9; i++) {
- if (mode & SBIT[i])
- buf[i + 1] = (mode & MBIT[i]) ? SMODE1[i] : SMODE0[i];
- else
- buf[i + 1] = (mode & MBIT[i]) ? MODE1[i] : MODE0[i];
- }
return buf;
}
-/* END CODE */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
+#else
+
+/* The previous version used "0pcCd?bB-?l?s???". However, the '0', 'C',
+ * and 'B' types don't appear to be available on linux. So I removed them. */
+static const char type_chars[16] = "?pc?d?b?-?l?s???";
+/* 0123456789abcdef */
+static const char mode_chars[7] = "rwxSTst";
+
+const char *bb_mode_string(int mode)
+{
+ static char buf[12];
+ char *p = buf;
+
+ int i, j, k, m;
+
+ *p = type_chars[ (mode >> 12) & 0xf ];
+ i = 0;
+ m = 0400;
+ do {
+ j = k = 0;
+ do {
+ *++p = '-';
+ if (mode & m) {
+ *p = mode_chars[j];
+ k = j;
+ }
+ m >>= 1;
+ } while (++j < 3);
+ ++i;
+ if (mode & (010000 >> i)) {
+ *p = mode_chars[3 + k + (i >> 1)];
+ }
+ } while (i < 3);
+
+ /* Note: We don't bother with nul termination because bss initialization
+ * should have taken care of that for us. If the user scribbled in buf
+ * memory, they deserve whatever happens. But we'll at least assert. */
+ assert(buf[10] == 0);
+
+ return buf;
+}
+
+#endif
diff --git a/libbb/module_syscalls.c b/libbb/module_syscalls.c
index 6bfff207f..8fe9e525c 100644
--- a/libbb/module_syscalls.c
+++ b/libbb/module_syscalls.c
@@ -51,7 +51,7 @@ _syscall5(int, init_module, void *, first, void *, second, void *, third,
#warning -> The query_module system call is being stubbed out...
int query_module(const char *name, int which, void *buf, size_t bufsize, size_t *ret)
{
- error_msg("\n\nTo make this application work, you will need to recompile\n"
+ bb_error_msg("\n\nTo make this application work, you will need to recompile\n"
"with a kernel supporting the query_module system call. -Erik\n");
errno=ENOSYS;
return -1;
diff --git a/libbb/mtab.c b/libbb/mtab.c
index c521b1e05..54905c724 100644
--- a/libbb/mtab.c
+++ b/libbb/mtab.c
@@ -27,21 +27,20 @@
#include <mntent.h>
#include "libbb.h"
-extern const char mtab_file[]; /* Defined in utility.c */
static const int MS_RDONLY = 1; /* Mount read-only. */
void erase_mtab(const char *name)
{
struct mntent entries[20];
int count = 0;
- FILE *mountTable = setmntent(mtab_file, "r");
+ FILE *mountTable = setmntent(bb_path_mtab_file, "r");
struct mntent *m;
/* Check if reading the mtab file failed */
if (mountTable == 0
/* Bummer. fall back on trying the /proc filesystem */
&& (mountTable = setmntent("/proc/mounts", "r")) == 0) {
- perror_msg("%s", mtab_file);
+ bb_perror_msg(bb_path_mtab_file);
return;
}
@@ -55,7 +54,7 @@ void erase_mtab(const char *name)
count++;
}
endmntent(mountTable);
- if ((mountTable = setmntent(mtab_file, "w"))) {
+ if ((mountTable = setmntent(bb_path_mtab_file, "w"))) {
int i;
for (i = 0; i < count; i++) {
@@ -69,17 +68,17 @@ void erase_mtab(const char *name)
}
endmntent(mountTable);
} else if (errno != EROFS)
- perror_msg("%s", mtab_file);
+ bb_perror_msg(bb_path_mtab_file);
}
void write_mtab(char *blockDevice, char *directory,
char *filesystemType, long flags, char *string_flags)
{
- FILE *mountTable = setmntent(mtab_file, "a+");
+ FILE *mountTable = setmntent(bb_path_mtab_file, "a+");
struct mntent m;
if (mountTable == 0) {
- perror_msg("%s", mtab_file);
+ bb_perror_msg(bb_path_mtab_file);
return;
}
if (mountTable) {
diff --git a/libbb/mtab_file.c b/libbb/mtab_file.c
index 2124e0144..898e2fa89 100644
--- a/libbb/mtab_file.c
+++ b/libbb/mtab_file.c
@@ -26,9 +26,9 @@
/* Busybox mount uses either /proc/mounts or /etc/mtab to
* get the list of currently mounted filesystems */
#if defined CONFIG_FEATURE_MTAB_SUPPORT
-const char mtab_file[] = CONFIG_FEATURE_MTAB_FILENAME;
+const char bb_path_mtab_file[] = CONFIG_FEATURE_MTAB_FILENAME;
#else
-const char mtab_file[] = "/proc/mounts";
+const char bb_path_mtab_file[] = "/proc/mounts";
#endif
diff --git a/libbb/my_getgrnam.c b/libbb/my_getgrnam.c
index f80d3f824..eb5b58174 100644
--- a/libbb/my_getgrnam.c
+++ b/libbb/my_getgrnam.c
@@ -33,7 +33,7 @@ long my_getgrnam(const char *name)
mygroup = getgrnam(name);
if (mygroup==NULL)
- error_msg_and_die("unknown group name: %s", name);
+ bb_error_msg_and_die("unknown group name: %s", name);
return (mygroup->gr_gid);
}
diff --git a/libbb/my_getpwnam.c b/libbb/my_getpwnam.c
index 04951a4d0..ada2ffb56 100644
--- a/libbb/my_getpwnam.c
+++ b/libbb/my_getpwnam.c
@@ -33,7 +33,7 @@ long my_getpwnam(const char *name)
myuser = getpwnam(name);
if (myuser==NULL)
- error_msg_and_die("unknown user name: %s", name);
+ bb_error_msg_and_die("unknown user name: %s", name);
return myuser->pw_uid;
}
diff --git a/libbb/my_getpwnamegid.c b/libbb/my_getpwnamegid.c
index 07e02c1cf..06071c9f2 100644
--- a/libbb/my_getpwnamegid.c
+++ b/libbb/my_getpwnamegid.c
@@ -35,11 +35,11 @@ long my_getpwnamegid(const char *name)
myuser=getpwnam(name);
if (myuser==NULL)
- error_msg_and_die("unknown user name: %s", name);
+ bb_error_msg_and_die("unknown user name: %s", name);
mygroup = getgrgid(myuser->pw_gid);
if (mygroup==NULL)
- error_msg_and_die("unknown gid %ld", (long)myuser->pw_gid);
+ bb_error_msg_and_die("unknown gid %ld", (long)myuser->pw_gid);
return mygroup->gr_gid;
}
diff --git a/libbb/obscure.c b/libbb/obscure.c
index 588ef5af6..1a99b7cf9 100644
--- a/libbb/obscure.c
+++ b/libbb/obscure.c
@@ -143,7 +143,7 @@ password_check(const char *old, const char *newval, const struct passwd *pwdp)
return "too simple";
msg = NULL;
- newmono = str_lower(xstrdup(newval));
+ newmono = str_lower(bb_xstrdup(newval));
lenwrap = strlen(old) * 2 + 1;
wrapped = (char *) xmalloc(lenwrap);
str_lower(strcpy(wrapped, old));
@@ -208,8 +208,8 @@ obscure_msg(const char *old, const char *newval, const struct passwd *pwdp)
if (oldlen <= maxlen && newlen <= maxlen)
return NULL;
- new1 = (char *) xstrdup(newval);
- old1 = (char *) xstrdup(old);
+ new1 = (char *) bb_xstrdup(newval);
+ old1 = (char *) bb_xstrdup(old);
if (newlen > maxlen)
new1[maxlen] = '\0';
if (oldlen > maxlen)
diff --git a/libbb/parse_mode.c b/libbb/parse_mode.c
index ba34ea929..49573dfbb 100644
--- a/libbb/parse_mode.c
+++ b/libbb/parse_mode.c
@@ -1,134 +1,177 @@
/* vi: set sw=4 ts=4: */
/*
- * Utility routines.
+ * parse_mode implementation for busybox
*
- * Copyright (C) many different people. If you wrote this, please
- * acknowledge your work.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
*/
-#include <stdio.h>
+/* http://www.opengroup.org/onlinepubs/007904975/utilities/chmod.html */
+
#include <stdlib.h>
+#include <assert.h>
+#include <sys/stat.h>
#include "libbb.h"
+#define FILEMODEBITS (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)
-/* This function parses the sort of string you might pass
- * to chmod (i.e., [ugoa]{+|-|=}[rwxst] ) and returns the
- * correct mode described by the string. */
-extern int parse_mode(const char *s, mode_t * theMode)
+extern int bb_parse_mode(const char *s, mode_t *current_mode)
{
- static const mode_t group_set[] = {
+ static const mode_t who_mask[] = {
+ S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO, /* a */
S_ISUID | S_IRWXU, /* u */
S_ISGID | S_IRWXG, /* g */
- S_IRWXO, /* o */
- S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO /* a */
+ S_IRWXO /* o */
};
- static const mode_t mode_set[] = {
+ static const mode_t perm_mask[] = {
S_IRUSR | S_IRGRP | S_IROTH, /* r */
S_IWUSR | S_IWGRP | S_IWOTH, /* w */
S_IXUSR | S_IXGRP | S_IXOTH, /* x */
+ S_IXUSR | S_IXGRP | S_IXOTH, /* X -- special -- see below */
S_ISUID | S_ISGID, /* s */
S_ISVTX /* t */
};
- static const char group_chars[] = "ugoa";
- static const char mode_chars[] = "rwxst";
+ static const char who_chars[] = "augo";
+ static const char perm_chars[] = "rwxXst";
const char *p;
- mode_t andMode =
- S_ISVTX | S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
- mode_t orMode = 0;
- mode_t mode;
- mode_t groups;
- char type;
- char c;
+ mode_t wholist;
+ mode_t permlist;
+ mode_t mask;
+ mode_t new_mode;
+ char op;
+
+ assert(s);
+
+ if (((unsigned int)(*s - '0')) < 8) {
+ unsigned long tmp;
+ char *e;
- if (s==NULL) {
- return (FALSE);
+ tmp = strtol(s, &e, 8);
+ if (*e || (tmp > 0xffffU)) { /* Check range and trailing chars. */
+ return 0;
+ }
+ *current_mode = tmp;
+ return 1;
}
- do {
- mode = 0;
- groups = 0;
- NEXT_GROUP:
- if ((c = *s++) == '\0') {
- return -1;
+ mask = umask(0);
+ umask(mask);
+
+ new_mode = *current_mode;
+
+ /* Note: We allow empty clauses, and hence empty modes.
+ * We treat an empty mode as no change to perms. */
+
+ while (*s) { /* Process clauses. */
+
+ if (*s == ',') { /* We allow empty clauses. */
+ ++s;
+ continue;
}
- for (p=group_chars ; *p ; p++) {
- if (*p == c) {
- groups |= group_set[(int)(p-group_chars)];
- goto NEXT_GROUP;
+
+ /* Get a wholist. */
+ wholist = 0;
+
+ WHO_LIST:
+ p = who_chars;
+ do {
+ if (*p == *s) {
+ wholist |= who_mask[(int)(p-who_chars)];
+ if (!*++s) {
+ return 0;
+ }
+ goto WHO_LIST;
}
- }
- switch (c) {
- case '=':
- case '+':
- case '-':
- type = c;
- if (groups == 0) { /* The default is "all" */
- groups |= S_ISUID | S_ISGID | S_ISVTX
- | S_IRWXU | S_IRWXG | S_IRWXO;
+ } while (*++p);
+
+ do { /* Process action list. */
+ if ((*s != '+') && (*s != '-')) {
+ if (*s != '=') {
+ return 0;
}
- break;
- default:
- if ((c < '0') || (c > '7') || (mode | groups)) {
- return (FALSE);
- } else {
- *theMode = strtol(--s, NULL, 8);
- return (TRUE);
+ /* Since op is '=', clear all bits corresponding to the
+ * wholist, of all file bits if wholist is empty. */
+ permlist = ~FILEMODEBITS;
+ if (wholist) {
+ permlist = ~wholist;
}
- }
+ new_mode &= permlist;
+ }
+ op = *s++;
+
+ /* Check for permcopy. */
+ p = who_chars + 1; /* Skip 'a' entry. */
+ do {
+ if (*p == *s) {
+ int i = 0;
+ permlist = who_mask[(int)(p-who_chars)]
+ & (S_IRWXU | S_IRWXG | S_IRWXO)
+ & new_mode;
+ do {
+ if (permlist & perm_mask[i]) {
+ permlist |= perm_mask[i];
+ }
+ } while (++i < 3);
+ ++s;
+ goto GOT_ACTION;
+ }
+ } while (*++p);
- NEXT_MODE:
- if (((c = *s++) != '\0') && (c != ',')) {
- for (p=mode_chars ; *p ; p++) {
- if (*p == c) {
- mode |= mode_set[(int)(p-mode_chars)];
- goto NEXT_MODE;
+ /* It was not a permcopy, so get a permlist. */
+ permlist = 0;
+
+ PERM_LIST:
+ p = perm_chars;
+ do {
+ if (*p == *s) {
+ if ((*p != 'X')
+ || (new_mode & (S_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH))
+ ) {
+ permlist |= perm_mask[(int)(p-perm_chars)];
+ }
+ if (!*++s) {
+ break;
+ }
+ goto PERM_LIST;
+ }
+ } while (*++p);
+
+ GOT_ACTION:
+ if (permlist) { /* The permlist was nonempty. */
+ mode_t tmp = ~mask;
+ if (wholist) {
+ tmp = wholist;
+ }
+ permlist &= tmp;
+
+ if (op == '-') {
+ new_mode &= ~permlist;
+ } else {
+ new_mode |= permlist;
}
}
- break; /* We're done so break out of loop.*/
- }
- switch (type) {
- case '=':
- andMode &= ~(groups); /* Now fall through. */
- case '+':
- orMode |= mode & groups;
- break;
- case '-':
- andMode &= ~(mode & groups);
- orMode &= ~(mode & groups);
- break;
- }
- } while (c == ',');
+ } while (*s && (*s != ','));
+ }
- *theMode &= andMode;
- *theMode |= orMode;
+ *current_mode = new_mode;
- return TRUE;
+ return 1;
}
-
-/* END CODE */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
diff --git a/libbb/parse_number.c b/libbb/parse_number.c
index 755a357ad..92ad6a216 100644
--- a/libbb/parse_number.c
+++ b/libbb/parse_number.c
@@ -1,70 +1,64 @@
/* vi: set sw=4 ts=4: */
/*
- * Utility routines.
+ * bb_xparse_number implementation for busybox
*
- * Copyright (C) many different people. If you wrote this, please
- * acknowledge your work.
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
- * This program is distributed in the hope that it will be useful, but
- * WITHOUT ANY WARRANTY; without even the implied warranty of
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
- * USA
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
*/
-#include <stdio.h>
-#include <string.h>
#include <stdlib.h>
+#include <string.h>
+#include <limits.h>
+#include <errno.h>
+#include <assert.h>
#include "libbb.h"
-
-unsigned long parse_number(const char *numstr,
- const struct suffix_mult *suffixes)
+extern
+unsigned long bb_xparse_number(const char *numstr,
+ const struct suffix_mult *suffixes)
{
- const struct suffix_mult *sm;
- unsigned long int ret;
- int len;
- char *end;
+ unsigned long int r;
+ char *e;
+ int old_errno;
- ret = strtoul(numstr, &end, 10);
- if (numstr == end)
- error_msg_and_die("invalid number `%s'", numstr);
- while (end[0] != '\0') {
- sm = suffixes;
- while ( sm != 0 ) {
- if(sm->suffix) {
- len = strlen(sm->suffix);
- if (strncmp(sm->suffix, end, len) == 0) {
- ret *= sm->mult;
- end += len;
- break;
+ /* Since this is a lib function, we're not allowed to reset errno to 0.
+ * Doing so could break an app that is deferring checking of errno.
+ * So, save the old value so that we can restore it if successful. */
+ old_errno = errno;
+ errno = 0;
+ r = strtoul(numstr, &e, 10);
+
+ if ((numstr != e) && !errno) {
+ errno = old_errno; /* Ok. So restore errno. */
+ if (!*e) {
+ return r;
+ }
+ if (suffixes) {
+ assert(suffixes->suffix); /* No nul suffixes. */
+ do {
+ if (strcmp(suffixes->suffix, e) == 0) {
+ if (ULONG_MAX / suffixes->mult < r) { /* Overflow! */
+ break;
+ }
+ return r * suffixes->mult;
}
- sm++;
-
- } else
- sm = 0;
+ ++suffixes;
+ } while (suffixes->suffix);
}
- if (sm == 0)
- error_msg_and_die("invalid number `%s'", numstr);
}
- return ret;
+ bb_error_msg_and_die("invalid number `%s'", numstr);
}
-
-
-/* END CODE */
-/*
-Local Variables:
-c-file-style: "linux"
-c-basic-offset: 4
-tab-width: 4
-End:
-*/
diff --git a/libbb/perror_msg.c b/libbb/perror_msg.c
index 8c57b0d16..f32c1c8fe 100644
--- a/libbb/perror_msg.c
+++ b/libbb/perror_msg.c
@@ -25,12 +25,12 @@
#include <stdlib.h>
#include "libbb.h"
-extern void perror_msg(const char *s, ...)
+extern void bb_perror_msg(const char *s, ...)
{
va_list p;
va_start(p, s);
- vperror_msg(s, p);
+ bb_vperror_msg(s, p);
va_end(p);
}
diff --git a/libbb/perror_msg_and_die.c b/libbb/perror_msg_and_die.c
index 9004925cc..57a21136d 100644
--- a/libbb/perror_msg_and_die.c
+++ b/libbb/perror_msg_and_die.c
@@ -25,14 +25,14 @@
#include <stdlib.h>
#include "libbb.h"
-extern void perror_msg_and_die(const char *s, ...)
+extern void bb_perror_msg_and_die(const char *s, ...)
{
va_list p;
va_start(p, s);
- vperror_msg(s, p);
+ bb_vperror_msg(s, p);
va_end(p);
- exit(EXIT_FAILURE);
+ exit(bb_default_error_retval);
}
diff --git a/libbb/perror_nomsg.c b/libbb/perror_nomsg.c
new file mode 100644
index 000000000..464cb86c4
--- /dev/null
+++ b/libbb/perror_nomsg.c
@@ -0,0 +1,30 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * bb_perror_nomsg implementation for busybox
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+#include <stddef.h>
+#include <libbb.h>
+
+extern void bb_perror_nomsg(void)
+{
+ /* Ignore the gcc warning about a null format string. */
+ bb_perror_msg(NULL);
+}
diff --git a/libbb/perror_nomsg_and_die.c b/libbb/perror_nomsg_and_die.c
new file mode 100644
index 000000000..bab228455
--- /dev/null
+++ b/libbb/perror_nomsg_and_die.c
@@ -0,0 +1,30 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * bb_perror_nomsg_and_die implementation for busybox
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+#include <stddef.h>
+#include "libbb.h"
+
+extern void bb_perror_nomsg_and_die(void)
+{
+ /* Ignore the gcc warning about a null format string. */
+ bb_perror_msg_and_die(NULL);
+}
diff --git a/libbb/print_file.c b/libbb/print_file.c
index cdd60e7a0..8417c10d3 100644
--- a/libbb/print_file.c
+++ b/libbb/print_file.c
@@ -21,39 +21,50 @@
#include <stdio.h>
#include <stdlib.h>
-#include <sys/stat.h>
#include "libbb.h"
-
-extern void print_file(FILE *file)
+extern void bb_xprint_and_close_file(FILE *file)
{
- fflush(stdout);
- if (copyfd(fileno(file), fileno(stdout), 0) == -1) {
- exit(EXIT_FAILURE);
+ bb_xfflush_stdout();
+ /* Note: Do not use STDOUT_FILENO here, as this is a lib routine
+ * and the calling code may have reassigned stdout. */
+ if (bb_copyfd(fileno(file), fileno(stdout), 0) == -1) {
+ /* bb_copyfd outputs any needed messages, so just die. */
+ exit(bb_default_error_retval);
}
+ /* Note: Since we're reading, don't bother checking the return value
+ * of fclose(). The only possible failure is EINTR which
+ * should already have been taken care of. */
fclose(file);
}
-extern int print_file_by_name(char *filename)
+/* Returns:
+ * 0 if successful
+ * -1 if 'filename' does not exist or is a directory
+ * exits with default error code if an error occurs
+ */
+
+extern int bb_xprint_file_by_name(const char *filename)
{
+ FILE *f;
+
+#if 0
+ /* This check shouldn't be necessary for linux, but is left
+ * here disabled just in case. */
struct stat statBuf;
- int status = TRUE;
- if(is_directory(filename, TRUE, &statBuf)==TRUE) {
- error_msg("%s: Is directory", filename);
- status = FALSE;
- } else {
- FILE *f = wfopen(filename, "r");
- if(f!=NULL)
- print_file(f);
- else
- status = FALSE;
+ if(is_directory(filename, TRUE, &statBuf)) {
+ bb_error_msg("%s: Is directory", filename);
+ } else
+#endif
+ if ((f = bb_wfopen(filename, "r")) != NULL) {
+ bb_xprint_and_close_file(f);
+ return 0;
}
- return status;
+ return -1;
}
-
/* END CODE */
/*
Local Variables:
diff --git a/libbb/printf.c b/libbb/printf.c
new file mode 100644
index 000000000..686257699
--- /dev/null
+++ b/libbb/printf.c
@@ -0,0 +1,177 @@
+/* vi: set sw=4 ts=4: */
+/*
+ * *printf implementations for busybox
+ *
+ * Copyright (C) 2003 Manuel Novoa III <mjn3@codepoet.org>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ */
+
+/* Mar 12, 2003 Manuel Novoa III
+ *
+ * While fwrite(), fputc(), fputs(), etc. all set the stream error flag
+ * on failure, the *printf functions are unique in that they can fail
+ * for reasons not related to the actual output itself. Among the possible
+ * reasons for failure which don't set the streams error indicator,
+ * SUSv3 lists EILSEQ, EINVAL, and ENOMEM.
+ *
+ * In some cases, it would be desireable to have a group of *printf()
+ * functions available that _always_ set the stream error indicator on
+ * failure. That would allow us to defer error checking until applet
+ * exit. Unfortunately, there is no standard way of setting a streams
+ * error indicator... even though we can clear it with clearerr().
+ *
+ * Therefore, we have to resort to implementation dependent code. Feel
+ * free to send patches for stdio implementations where the following
+ * fails.
+ *
+ * NOTE: None of this is threadsafe. As busybox is a nonthreaded app,
+ * that isn't currently an issue.
+ */
+
+#include <stdio.h>
+#include <stdarg.h>
+#include "libbb.h"
+
+#if defined(__UCLIBC__)
+
+# if defined(__FLAG_ERROR)
+/* Using my newer stdio implementation. Unlocked macros are:
+ * #define __CLEARERR(stream) \
+ ((stream)->modeflags &= ~(__FLAG_EOF|__FLAG_ERROR), (void)0)
+ * #define __FEOF(stream) ((stream)->modeflags & __FLAG_EOF)
+ * #define __FERROR(stream) ((stream)->modeflags & __FLAG_ERROR)
+ */
+#define SET_FERROR_UNLOCKED(S) ((S)->modeflags |= __FLAG_ERROR)
+
+#elif defined(__MODE_ERR)
+/* Using either the original stdio implementation (from dev86) or
+ * my original stdio rewrite. Macros were:
+ * #define ferror(fp) (((fp)->mode&__MODE_ERR) != 0)
+ * #define feof(fp) (((fp)->mode&__MODE_EOF) != 0)
+ * #define clearerr(fp) ((fp)->mode &= ~(__MODE_EOF|__MODE_ERR),0)
+ */
+#define SET_FERROR_UNLOCKED(S) ((S)->mode |= __MODE_ERR)
+
+#else
+#error unknown uClibc stdio implemenation!
+#endif
+
+#elif defined(__GLIBC__)
+
+# if defined(_STDIO_USES_IOSTREAM)
+/* Apparently using the newer libio implementation, with associated defines:
+ * #define _IO_feof_unlocked(__fp) (((__fp)->_flags & _IO_EOF_SEEN) != 0)
+ * #define _IO_ferror_unlocked(__fp) (((__fp)->_flags & _IO_ERR_SEEN) != 0)
+ */
+#define SET_FERROR_UNLOCKED(S) ((S)->_flags |= _IO_ERR_SEEN)
+
+# else
+/* Assume the older version of glibc which used a bitfield entry
+ * as a stream error flag. The associated defines were:
+ * #define __clearerr(stream) ((stream)->__error = (stream)->__eof = 0)
+ * #define feof_unlocked(stream) ((stream)->__eof != 0)
+ * #define ferror_unlocked(stream) ((stream)->__error != 0)
+ */
+#define SET_FERROR_UNLOCKED(S) ((S)->__error = 1)
+
+# endif
+
+#elif defined(__NEWLIB_H__)
+/* I honestly don't know if there are different versions of stdio in
+ * newlibs history. Anyway, here's what's current.
+ * #define __sfeof(p) (((p)->_flags & __SEOF) != 0)
+ * #define __sferror(p) (((p)->_flags & __SERR) != 0)
+ * #define __sclearerr(p) ((void)((p)->_flags &= ~(__SERR|__SEOF)))
+ */
+#define SET_FERROR_UNLOCKED(S) ((S)->_flags |= __SERR)
+
+#elif defined(__dietlibc__)
+/*
+ * WARNING!!! dietlibc is quite buggy. WARNING!!!
+ *
+ * Some example bugs as of March 12, 2003...
+ * 1) fputc() doesn't set the error indicator on failure.
+ * 2) freopen() doesn't maintain the same stream object, contary to
+ * standards. This makes it useless in its primary role of
+ * reassociating stdin/stdout/stderr.
+ * 3) printf() often fails to correctly format output when conversions
+ * involve padding. It is also practically useless for floating
+ * point output.
+ *
+ * But, if you're determined to use it anyway, (as of the current version)
+ * you can extract the information you need from dietstdio.h. See the
+ * other library implementations for examples.
+ */
+#error dietlibc is currently not supported. Please see the commented source.
+
+#else /* some other lib */
+/* Please see the comments for the above supported libaries for examples
+ * of what is required to support your stdio implementation.
+ */
+#error Your stdio library is currently not supported. Please see the commented source.
+#endif
+
+#ifdef L_vfprintf
+extern int bb_vfprintf(FILE * __restrict stream,
+ const char * __restrict format,
+ va_list arg)
+{
+ int rv;
+
+ if ((rv = vfprintf(stream, format, arg)) < 0) {
+ SET_FERROR_UNLOCKED(stream);
+ }
+
+ return rv;
+}
+#endif
+
+#ifdef L_vprintf
+extern int bb_vprintf(const char * __restrict format, va_list arg)
+{
+ return bb_vfprintf(stdout, format, arg);
+}
+#endif
+
+#ifdef L_fprintf
+extern int bb_fprintf(FILE * __restrict stream,
+ const char * __restrict format, ...)
+{
+ va_list arg;
+ int rv;
+
+ va_start(arg, format);
+ rv = bb_vfprintf(stream, format, arg);
+ va_end(arg);
+
+ return rv;
+}
+#endif
+
+#ifdef L_printf
+extern int bb_printf(const char * __restrict format, ...)
+{
+ va_list arg;
+ int rv;
+
+ va_start(arg, format);
+ rv = bb_vfprintf(stdout, format, arg);
+ va_end(arg);
+
+ return rv;
+}
+#endif
diff --git a/libbb/process_escape_sequence.c b/libbb/process_escape_sequence.c
index 9a16f80ab..ef2717bdd 100644
--- a/libbb/process_escape_sequence.c
+++ b/libbb/process_escape_sequence.c
@@ -2,7 +2,7 @@
/*
* Utility routines.
*
- * Copyright (C) Manuel Nova III <mnovoa3@bellsouth.net>
+ * Copyright (C) Manuel Novoa III <mjn3@codepoet.org>
* and Vladimir Oleynik <dzo@simtreas.ru>
*
* This program is free software; you can redistribute it and/or modify
@@ -26,9 +26,7 @@
#include <limits.h>
#include "libbb.h"
-
-
-char process_escape_sequence(const char **ptr)
+char bb_process_escape_sequence(const char **ptr)
{
static const char charmap[] = {
'a', 'b', 'f', 'n', 'r', 't', 'v', '\\', 0,
@@ -36,40 +34,43 @@ char process_escape_sequence(const char **ptr)
const char *p;
const char *q;
- int num_digits;
+ unsigned int num_digits;
+ unsigned int r;
unsigned int n;
n = 0;
q = *ptr;
- for ( num_digits = 0 ; num_digits < 3 ; ++num_digits) {
- if ((*q < '0') || (*q > '7')) { /* not a digit? */
- break;
+ num_digits = 0;
+ do {
+ if (((unsigned int)(*q - '0')) <= 7) {
+ r = n * 8 + (*q - '0');
+ if (r <= UCHAR_MAX) {
+ n = r;
+ ++q;
+ if (++num_digits < 3) {
+ continue;
+ }
+ }
}
- n = n * 8 + (*q++ - '0');
- }
+ break;
+ } while (1);
if (num_digits == 0) { /* mnemonic escape sequence? */
- for (p=charmap ; *p ; p++) {
+ p = charmap;
+ do {
if (*p == *q) {
q++;
break;
}
- }
+ } while (*++p);
n = *(p+(sizeof(charmap)/2));
}
- /* doesn't hurt to fall through to here from mnemonic case */
- if (n > UCHAR_MAX) { /* is octal code too big for a char? */
- n /= 8; /* adjust value and */
- --q; /* back up one char */
- }
-
*ptr = q;
return (char) n;
}
-
/* END CODE */
/*
Local Variables:
diff --git a/libbb/procps.c b/libbb/procps.c
index fcc9c2d3a..a513f3f7f 100644
--- a/libbb/procps.c
+++ b/libbb/procps.c
@@ -34,7 +34,7 @@ extern procps_status_t * procps_scan(int save_user_arg0)
if (!dir) {
dir = opendir("/proc");
if(!dir)
- error_msg_and_die("Can't open /proc");
+ bb_error_msg_and_die("Can't open /proc");
}
for(;;) {
if((entry = readdir(dir)) == NULL) {
diff --git a/libbb/read_package_field.c b/libbb/read_package_field.c
index 867b198ba..42628f35c 100644
--- a/libbb/read_package_field.c
+++ b/libbb/read_package_field.c
@@ -102,10 +102,10 @@ int read_package_field(const char *package_buffer, char **field_name, char **fie
if (name_length == 0) {
*field_name = NULL;
} else {
- *field_name = xstrndup(&package_buffer[offset_name_start], name_length);
+ *field_name = bb_xstrndup(&package_buffer[offset_name_start], name_length);
}
if (value_length > 0) {
- *field_value = xstrndup(&package_buffer[offset_value_start], value_length);
+ *field_value = bb_xstrndup(&package_buffer[offset_value_start], value_length);
} else {
*field_value = NULL;
}
diff --git a/libbb/recursive_action.c b/libbb/recursive_action.c
index 8f9cc2f91..a4a4a7be3 100644
--- a/libbb/recursive_action.c
+++ b/libbb/recursive_action.c
@@ -60,10 +60,10 @@ int recursive_action(const char *fileName,
if (status < 0) {
#ifdef DEBUG_RECURS_ACTION
- error_msg("status=%d followLinks=%d TRUE=%d",
+ bb_error_msg("status=%d followLinks=%d TRUE=%d",
status, followLinks, TRUE);
#endif
- perror_msg("%s", fileName);
+ bb_perror_msg("%s", fileName);
return FALSE;
}
@@ -89,14 +89,14 @@ int recursive_action(const char *fileName,
if (dirAction != NULL && ! depthFirst) {
status = dirAction(fileName, &statbuf, userData);
if (! status) {
- perror_msg("%s", fileName);
+ bb_perror_msg("%s", fileName);
return FALSE;
} else if (status == SKIP)
return TRUE;
}
dir = opendir(fileName);
if (!dir) {
- perror_msg("%s", fileName);
+ bb_perror_msg("%s", fileName);
return FALSE;
}
status = TRUE;
@@ -117,7 +117,7 @@ int recursive_action(const char *fileName,
closedir(dir);
if (dirAction != NULL && depthFirst) {
if (! dirAction(fileName, &statbuf, userData)) {
- perror_msg("%s", fileName);
+ bb_perror_msg("%s", fileName);
return FALSE;
}
}
diff --git a/libbb/remove_file.c b/libbb/remove_file.c
index 988b09124..65708a252 100644
--- a/libbb/remove_file.c
+++ b/libbb/remove_file.c
@@ -37,7 +37,7 @@ extern int remove_file(const char *path, int flags)
if (lstat(path, &path_stat) < 0) {
if (errno != ENOENT) {
- perror_msg("unable to stat `%s'", path);
+ bb_perror_msg("unable to stat `%s'", path);
return -1;
}
@@ -46,7 +46,7 @@ extern int remove_file(const char *path, int flags)
if (!path_exists) {
if (!(flags & FILEUTILS_FORCE)) {
- perror_msg("cannot remove `%s'", path);
+ bb_perror_msg("cannot remove `%s'", path);
return -1;
}
return 0;
@@ -58,21 +58,21 @@ extern int remove_file(const char *path, int flags)
int status = 0;
if (!(flags & FILEUTILS_RECUR)) {
- error_msg("%s: is a directory", path);
+ bb_error_msg("%s: is a directory", path);
return -1;
}
if ((!(flags & FILEUTILS_FORCE) && access(path, W_OK) < 0 &&
isatty(0)) ||
(flags & FILEUTILS_INTERACTIVE)) {
- fprintf(stderr, "%s: descend into directory `%s'? ", applet_name,
+ fprintf(stderr, "%s: descend into directory `%s'? ", bb_applet_name,
path);
- if (!ask_confirmation())
+ if (!bb_ask_confirmation())
return 0;
}
if ((dp = opendir(path)) == NULL) {
- perror_msg("unable to open `%s'", path);
+ bb_perror_msg("unable to open `%s'", path);
return -1;
}
@@ -90,18 +90,18 @@ extern int remove_file(const char *path, int flags)
}
if (closedir(dp) < 0) {
- perror_msg("unable to close `%s'", path);
+ bb_perror_msg("unable to close `%s'", path);
return -1;
}
if (flags & FILEUTILS_INTERACTIVE) {
- fprintf(stderr, "%s: remove directory `%s'? ", applet_name, path);
- if (!ask_confirmation())
+ fprintf(stderr, "%s: remove directory `%s'? ", bb_applet_name, path);
+ if (!bb_ask_confirmation())
return status;
}
if (rmdir(path) < 0) {
- perror_msg("unable to remove `%s'", path);
+ bb_perror_msg("unable to remove `%s'", path);
return -1;
}
@@ -111,13 +111,13 @@ extern int remove_file(const char *path, int flags)
!S_ISLNK(path_stat.st_mode) &&
isatty(0)) ||
(flags & FILEUTILS_INTERACTIVE)) {
- fprintf(stderr, "%s: remove `%s'? ", applet_name, path);
- if (!ask_confirmation())
+ fprintf(stderr, "%s: remove `%s'? ", bb_applet_name, path);
+ if (!bb_ask_confirmation())
return 0;
}
if (unlink(path) < 0) {
- perror_msg("unable to remove `%s'", path);
+ bb_perror_msg("unable to remove `%s'", path);
return -1;
}
diff --git a/libbb/run_parts.c b/libbb/run_parts.c
index 7829a84ba..58645660b 100644
--- a/libbb/run_parts.c
+++ b/libbb/run_parts.c
@@ -69,7 +69,7 @@ extern int run_parts(char **args, const unsigned char test_mode)
if (test_mode & 2) {
return(2);
}
- perror_msg_and_die("failed to open directory %s", arg0);
+ bb_perror_msg_and_die("failed to open directory %s", arg0);
}
for (i = 0; i < entries; i++) {
@@ -77,7 +77,7 @@ extern int run_parts(char **args, const unsigned char test_mode)