diff options
176 files changed, 19864 insertions, 19864 deletions
diff --git a/.gitmodules b/.gitmodules index acb26693d..bb9e1baf5 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,3 @@ [submodule "gnulib"] - path = gnulib - url = git://git.sv.gnu.org/gnulib.git + path = gnulib + url = git://git.sv.gnu.org/gnulib.git @@ -437,8 +437,8 @@ Miscellaneous useful git commands its SHA1 and then tag it or cherry-pick it onto an existing branch. For example, run this: git fsck --lost-found HEAD && cd .git/lost-found/commit \ - && for i in *; do git show $i|grep SOME_IDENTIFYING_STRING \ - && echo $i; done + && for i in *; do git show $i|grep SOME_IDENTIFYING_STRING \ + && echo $i; done The "git fsck ..." command creates the .git/lost-found/... hierarchy listing all unreachable objects. Then the for loop print SHA1s for commits that match via log or patch. diff --git a/build-aux/cvsu b/build-aux/cvsu index 49be49650..741f6b238 100755 --- a/build-aux/cvsu +++ b/build-aux/cvsu @@ -27,20 +27,20 @@ use Time::Local; use strict; use vars qw($list_types %messages %options @batch_list $batch_cmd - $no_recurse $explain_type $find_mode $short_print - $no_cvsignore $nolinks $file $single_filename $curr_dir - @common_ignores $ignore_rx %entries %subdirs %removed); + $no_recurse $explain_type $find_mode $short_print + $no_cvsignore $nolinks $file $single_filename $curr_dir + @common_ignores $ignore_rx %entries %subdirs %removed); use constant SUBDIR_FOUND => 1; use constant SUBDIR_CVS => 2; # This list comes from the CVS manual. use constant STANDARD_IGNORES => - ('RCS', 'SCCS', 'CVS', 'CVS.adm', 'RCSLOG', 'cvslog.*', 'tags', - 'TAGS', '.make.state', '.nse_depinfo', '*~', '#*', '.#*', ',*', - "_\$*", "*\$", '*.old', '*.bak', '*.BAK', '*.orig', '*.rej', - '.del-*', '*.a', '*.olb', '*.o', '*.obj', '*.so', '*.exe', - '*.Z', '*.elc', '*.ln', 'core'); + ('RCS', 'SCCS', 'CVS', 'CVS.adm', 'RCSLOG', 'cvslog.*', 'tags', + 'TAGS', '.make.state', '.nse_depinfo', '*~', '#*', '.#*', ',*', + "_\$*", "*\$", '*.old', '*.bak', '*.BAK', '*.orig', '*.rej', + '.del-*', '*.a', '*.olb', '*.o', '*.obj', '*.so', '*.exe', + '*.Z', '*.elc', '*.ln', 'core'); # 3-letter month names in POSIX locale, for fast date decoding my %months = ( @@ -62,20 +62,20 @@ my %months = ( sub usage () { print "Usage:\n" . - " cvsu [OPTIONS] [FILE] ...\n" . - "Options:\n" . - " --local Disable recursion\n" . - " --explain Verbosely print status of files\n" . - " --find Emulate find - filenames only\n" . - " --short Don't print paths\n" . - " --ignore Don't read .cvsignore\n" . - " --messages List known file types and long messages\n" . - " --nolinks Disable recognizing hard and soft links\n" . - " --types=[^]LIST Print only file types [not] from LIST\n" . - " --batch=COMMAND Execute this command on files\n" . - " --help Print this usage information\n" . - " --version Print version number\n" . - "Abbreviations and short options are supported\n"; + " cvsu [OPTIONS] [FILE] ...\n" . + "Options:\n" . + " --local Disable recursion\n" . + " --explain Verbosely print status of files\n" . + " --find Emulate find - filenames only\n" . + " --short Don't print paths\n" . + " --ignore Don't read .cvsignore\n" . + " --messages List known file types and long messages\n" . + " --nolinks Disable recognizing hard and soft links\n" . + " --types=[^]LIST Print only file types [not] from LIST\n" . + " --batch=COMMAND Execute this command on files\n" . + " --help Print this usage information\n" . + " --version Print version number\n" . + "Abbreviations and short options are supported\n"; exit 0; } @@ -90,11 +90,11 @@ sub version () sub adjust_types () { if ($list_types =~ m{^\^(.*)$}) { - $list_types = ""; - foreach (keys %messages) { - $list_types .= $_ - if (index ($1, $_) < 0); - } + $list_types = ""; + foreach (keys %messages) { + $list_types .= $_ + if (index ($1, $_) < 0); + } } } @@ -104,12 +104,12 @@ sub list_messages () my $default_mark; print "Recognizable file types are:\n"; foreach (sort keys %messages) { - if (index($list_types, $_) >= 0) { - $default_mark = "*"; - } else { - $default_mark = " "; - } - print " $default_mark $_ $messages{$_}\n"; + if (index($list_types, $_) >= 0) { + $default_mark = "*"; + } else { + $default_mark = " "; + } + print " $default_mark $_ $messages{$_}\n"; } print "* indicates file types listed by default\n"; exit 0; @@ -124,28 +124,28 @@ sub init_ignores () push @common_ignores, STANDARD_IGNORES; unless (defined($HOME)) { - return; + return; } my $home_cvsignore = "${HOME}/.cvsignore"; if (-f "$home_cvsignore") { - unless (open (CVSIGNORE, "< $home_cvsignore")) { - error ("couldn't open $home_cvsignore: $!"); - } + unless (open (CVSIGNORE, "< $home_cvsignore")) { + error ("couldn't open $home_cvsignore: $!"); + } - while (<CVSIGNORE>) { - push (@common_ignores, split); - } + while (<CVSIGNORE>) { + push (@common_ignores, split); + } - close (CVSIGNORE); + close (CVSIGNORE); } my $CVSIGNOREENV = $ENV{"CVSIGNORE"}; unless (defined($CVSIGNOREENV)) { - return; + return; } my @ignores_var = split (/ /, $CVSIGNOREENV); @@ -157,15 +157,15 @@ sub init_ignores () # Newline is added at the end. sub error ($) { - print STDERR "cvsu: ERROR: " . shift(@_) . "\n"; - exit 1; + print STDERR "cvsu: ERROR: " . shift(@_) . "\n"; + exit 1; } # execute commands from @exec_list with $exec_cmd sub do_batch () { - my @cmd_list = split (' ', $batch_cmd); - system (@cmd_list, @batch_list); + my @cmd_list = split (' ', $batch_cmd); + system (@cmd_list, @batch_list); } # print files status @@ -177,34 +177,34 @@ sub file_status ($) my $pathfile; return - if $ignore_rx ne '' && $type =~ /[?SLD]/ && $file =~ /$ignore_rx/; + if $ignore_rx ne '' && $type =~ /[?SLD]/ && $file =~ /$ignore_rx/; return - if (index($list_types, $type) < 0); + if (index($list_types, $type) < 0); $pathfile = $curr_dir . $file; if (defined($batch_cmd)) { - push (@batch_list, $pathfile); - # 1000 items in the command line might be too much for HP-UX - if ($#batch_list > 1000) { - do_batch(); - undef @batch_list; - } + push (@batch_list, $pathfile); + # 1000 items in the command line might be too much for HP-UX + if ($#batch_list > 1000) { + do_batch(); + undef @batch_list; + } } if ($short_print) { - $item = $file; + $item = $file; } else { - $item = $pathfile; + $item = $pathfile; } if ($find_mode) { - print "$item\n"; + print "$item\n"; } else { - $type = $messages{$type} - if ($explain_type); - print "$type $item\n"; + $type = $messages{$type} + if ($explain_type); + print "$type $item\n"; } } @@ -219,28 +219,28 @@ sub load_entries ($) my %ent = (); unless (open (ENTRIES, "< $entries_file")) { - error ("couldn't open $entries_file: $!"); + error ("couldn't open $entries_file: $!"); } while (<ENTRIES>) { - chomp; - $ent{$_} = 1; + chomp; + $ent{$_} = 1; } close (ENTRIES); if (open (ENTRIES, "< $entries_log_file")) { - while (<ENTRIES>) { - chomp; - if ( m{^A (.+)} ) { - $ent{$1} = 1; - } elsif ( m{^R (.+)} ) { - delete $ent{$1}; - } else { - # Note: "cvs commit" helps even when you are offline - error ("$entries_log_file:$.: unrecognizable line, " . - "try \"cvs commit\""); - } - } - close (ENTRIES); + while (<ENTRIES>) { + chomp; + if ( m{^A (.+)} ) { + $ent{$1} = 1; + } elsif ( m{^R (.+)} ) { + delete $ent{$1}; + } else { + # Note: "cvs commit" helps even when you are offline + error ("$entries_log_file:$.: unrecognizable line, " . + "try \"cvs commit\""); + } + } + close (ENTRIES); } return keys %ent; @@ -260,28 +260,28 @@ sub process_arg ($) local $single_filename = 0; if ( $arg eq "" or -d $arg ) { - $curr_dir = $arg; - my $real_curr_dir = $curr_dir eq "" ? "." : $curr_dir; - - error ("$real_curr_dir is not a directory") - unless ( -d $real_curr_dir ); - - # Scan present files. - file_status ("."); - opendir (DIR, $real_curr_dir) || - error ("couldn't open directory $real_curr_dir: $!"); - foreach (readdir (DIR)) { - $found_files {$_} = 1; - } - closedir (DIR); + $curr_dir = $arg; + my $real_curr_dir = $curr_dir eq "" ? "." : $curr_dir; + + error ("$real_curr_dir is not a directory") + unless ( -d $real_curr_dir ); + + # Scan present files. + file_status ("."); + opendir (DIR, $real_curr_dir) || + error ("couldn't open directory $real_curr_dir: $!"); + foreach (readdir (DIR)) { + $found_files {$_} = 1; + } + closedir (DIR); } else { - $single_filename = basename $arg; - $curr_dir = dirname $arg; - $found_files{$single_filename} = 1 if lstat $arg; + $single_filename = basename $arg; + $curr_dir = dirname $arg; + $found_files{$single_filename} = 1 if lstat $arg; } $curr_dir .= "/" - unless ( $curr_dir eq "" || $curr_dir =~ m{/$} ); + unless ( $curr_dir eq "" || $curr_dir =~ m{/$} ); # Scan CVS/Entries. my %entries = (); @@ -289,118 +289,118 @@ sub process_arg ($) my %removed = (); foreach ( load_entries ("${curr_dir}CVS/Entries") ) { - if ( m{^D/([^/]+)/} ) { - $subdirs{$1} = SUBDIR_FOUND if !$single_filename; - } elsif ( m{^/([^/]+)/([^/])[^/]*/([^/]*)/} ) { - if ( !$single_filename or $single_filename eq $1 ) { - $entries{$1} = $3; - $removed{$1} = 1 - if $2 eq '-'; - } - } elsif ( m{^D$} ) { - next; - } else { - error ("${curr_dir}CVS/Entries: unrecognizable line"); - } + if ( m{^D/([^/]+)/} ) { + $subdirs{$1} = SUBDIR_FOUND if !$single_filename; + } elsif ( m{^/([^/]+)/([^/])[^/]*/([^/]*)/} ) { + if ( !$single_filename or $single_filename eq $1 ) { + $entries{$1} = $3; + $removed{$1} = 1 + if $2 eq '-'; + } + } elsif ( m{^D$} ) { + next; + } else { + error ("${curr_dir}CVS/Entries: unrecognizable line"); + } } if ( $single_filename && !$entries{$single_filename} && - !$found_files{$single_filename} ) { - error ("nothing known about $arg"); + !$found_files{$single_filename} ) { + error ("nothing known about $arg"); } # Scan .cvsignore if any unless ($no_cvsignore) { - my (@ignore_list) = (); - - if (-f "${curr_dir}.cvsignore") { - open (CVSIGNORE, "< ${curr_dir}.cvsignore") - || error ("couldn't open ${curr_dir}.cvsignore: $!"); - while (<CVSIGNORE>) { - push (@ignore_list, split); - } - close (CVSIGNORE); - } - - my ($iter); - foreach $iter (@ignore_list, @common_ignores) { - if ($iter eq '!') { - $ignore_rx = '' - } else { - if ($ignore_rx eq '') { - $ignore_rx = '^('; - } else { - $ignore_rx .= '|'; - } - $ignore_rx .= glob_to_rx ($iter); - } - } - $ignore_rx .= ')$' - if $ignore_rx ne ''; + my (@ignore_list) = (); + + if (-f "${curr_dir}.cvsignore") { + open (CVSIGNORE, "< ${curr_dir}.cvsignore") + || error ("couldn't open ${curr_dir}.cvsignore: $!"); + while (<CVSIGNORE>) { + push (@ignore_list, split); + } + close (CVSIGNORE); + } + + my ($iter); + foreach $iter (@ignore_list, @common_ignores) { + if ($iter eq '!') { + $ignore_rx = '' + } else { + if ($ignore_rx eq '') { + $ignore_rx = '^('; + } else { + $ignore_rx .= '|'; + } + $ignore_rx .= glob_to_rx ($iter); + } + } + $ignore_rx .= ')$' + if $ignore_rx ne ''; } # File is missing foreach $file (sort keys %entries) { - unless ($found_files{$file}) { - if ($removed{$file}) { - file_status("R"); - } else { - file_status("U"); - } - } + unless ($found_files{$file}) { + if ($removed{$file}) { + file_status("R"); + } else { + file_status("U"); + } + } } foreach $file (sort keys %found_files) { - next if ($file eq '.' || $file eq '..'); - lstat ($curr_dir . $file) || - error ("lstat() failed on $curr_dir . $file"); - if (! $nolinks && -l _) { - file_status ("L"); - } elsif (-d _) { - if ($file eq 'CVS') { - file_status ("C"); - } elsif ($subdirs{$file}) { - $subdirs{$file} = SUBDIR_CVS; - } else { - file_status ("D"); # Unknown directory - } - } elsif (! (-f _) && ! (-l _)) { - file_status ("S"); # This must be something very special - } elsif (! $nolinks && (stat _) [3] > 1 ) { - file_status ("H"); # Hard link - } elsif (! $entries{$file}) { - file_status ("?"); - } elsif ($entries{$file} =~ /^Initial |^dummy /) { - file_status ("A"); - } elsif ($entries{$file} =~ /^Result of merge/) { - file_status ("G"); - } elsif ($entries{$file} !~ - /^(...) (...) (..) (..):(..):(..) (....)$/) { - error ("Invalid timestamp for $curr_dir$file: $entries{$file}"); - } else { - my $cvtime = timegm($6, $5, $4, $3, $months{$2}, $7 - 1900); - my $mtime = (stat _) [9]; - if ($cvtime == $mtime) { - file_status ("F"); - } elsif ($cvtime < $mtime) { - file_status ("M"); - } else { - file_status ("O"); - } - } + next if ($file eq '.' || $file eq '..'); + lstat ($curr_dir . $file) || + error ("lstat() failed on $curr_dir . $file"); + if (! $nolinks && -l _) { + file_status ("L"); + } elsif (-d _) { + if ($file eq 'CVS') { + file_status ("C"); + } elsif ($subdirs{$file}) { + $subdirs{$file} = SUBDIR_CVS; + } else { + file_status ("D"); # Unknown directory + } + } elsif (! (-f _) && ! (-l _)) { + file_status ("S"); # This must be something very special + } elsif (! $nolinks && (stat _) [3] > 1 ) { + file_status ("H"); # Hard link + } elsif (! $entries{$file}) { + file_status ("?"); + } elsif ($entries{$file} =~ /^Initial |^dummy /) { + file_status ("A"); + } elsif ($entries{$file} =~ /^Result of merge/) { + file_status ("G"); + } elsif ($entries{$file} !~ + /^(...) (...) (..) (..):(..):(..) (....)$/) { + error ("Invalid timestamp for $curr_dir$file: $entries{$file}"); + } else { + my $cvtime = timegm($6, $5, $4, $3, $months{$2}, $7 - 1900); + my $mtime = (stat _) [9]; + if ($cvtime == $mtime) { + file_status ("F"); + } elsif ($cvtime < $mtime) { + file_status ("M"); + } else { + file_status ("O"); + } + } } # Now do directories. unless ($no_recurse) { - my $save_curr_dir = $curr_dir; - foreach $file (sort keys %subdirs) { - if ($subdirs{$file} == SUBDIR_FOUND) { - $curr_dir = $save_curr_dir; - file_status ("X"); - } elsif ($subdirs{$file} == SUBDIR_CVS) { - process_arg ($save_curr_dir . $file) - } - } + my $save_curr_dir = $curr_dir; + foreach $file (sort keys %subdirs) { + if ($subdirs{$file} == SUBDIR_FOUND) { + $curr_dir = $save_curr_dir; + file_status ("X"); + } elsif ($subdirs{$file} == SUBDIR_CVS) { + process_arg ($save_curr_dir . $file) + } + } } } @@ -423,13 +423,13 @@ sub glob_to_rx ($) # Find parts in square brackets and copy them literally # Text outside brackets is processed by glob_to_rx_simple() while ($expr ne '') { - if ($expr =~ /^(.*?)(\[.*?\])(.*)/) { - $expr = $3; - $result .= glob_to_rx_simple ($1) . $2; - } else { - $result .= glob_to_rx_simple ($expr); - last; - } + if ($expr =~ /^(.*?)(\[.*?\])(.*)/) { + $expr = $3; + $result .= glob_to_rx_simple ($1) . $2; + } else { + $result .= glob_to_rx_simple ($expr); + last; + } } return $result; } @@ -441,21 +441,21 @@ sub Main () # long status messages %messages = ( - "?" => "Unlisted file", - "." => "Known directory", - "F" => "Up-to-date file", - "C" => "CVS admin directory", - "M" => "Modified file", - "S" => "Special file", - "D" => "Unlisted directory", - "L" => "Symbolic link", - "H" => "Hard link", - "U" => "Lost file", - "X" => "Lost directory", - "A" => "Newly added", - "O" => "Older copy", - "G" => "Result of merge", - "R" => "Removed file" + "?" => "Unlisted file", + "." => "Known directory", + "F" => "Up-to-date file", + "C" => "CVS admin directory", + "M" => "Modified file", + "S" => "Special file", + "D" => "Unlisted directory", + "L" => "Symbolic link", + "H" => "Hard link", + "U" => "Lost file", + "X" => "Lost directory", + "A" => "Newly added", + "O" => "Older copy", + "G" => "Result of merge", + "R" => "Removed file" ); undef @batch_list; # List of files for batch processing @@ -471,17 +471,17 @@ sub Main () my $want_ver = 0; # Print version and exit my %options = ( - "types=s" => \$list_types, - "batch=s" => \$batch_cmd, - "local" => \$no_recurse, - "explain" => \$explain_type, - "find" => \$find_mode, - "short" => \$short_print, - "ignore" => \$no_cvsignore, - "messages" => \$want_msg, - "nolinks" => \$nolinks, - "help" => \$want_help, - "version" => \$want_ver + "types=s" => \$list_types, + "batch=s" => \$batch_cmd, + "local" => \$no_recurse, + "explain" => \$explain_type, + "find" => \$find_mode, + "short" => \$short_print, + "ignore" => \$no_cvsignore, + "messages" => \$want_msg, + "nolinks" => \$nolinks, + "help" => \$want_help, + "version" => \$want_ver ); GetOptions(%options); @@ -493,19 +493,19 @@ sub Main () version() if $want_ver; unless ($no_cvsignore) { - init_ignores(); + init_ignores(); } if ($#ARGV < 0) { - @ARGV = (""); + @ARGV = (""); } foreach (@ARGV) { - process_arg ($_); + process_arg ($_); } if ($#batch_list >= 0) { - do_batch(); + do_batch(); } } diff --git a/configure.ac b/configure.ac index 2793060da..e718b36b3 100644 --- a/configure.ac +++ b/configure.ac @@ -24,8 +24,8 @@ AC_PREREQ([2.61]) # indicates that it is built from the 219th delta (in _some_ repository) # following the v6.9 tag, and that 58ddd is a prefix of the commit SHA1. AC_INIT([GNU coreutils], - m4_esyscmd([build-aux/git-version-gen .tarball-version]), - [bug-coreutils@gnu.org]) + m4_esyscmd([build-aux/git-version-gen .tarball-version]), + [bug-coreutils@gnu.org]) AC_CONFIG_SRCDIR([src/ls.c]) @@ -47,7 +47,7 @@ coreutils_MACROS AC_ARG_ENABLE([gcc-warnings], [AS_HELP_STRING([--enable-gcc-warnings], - [turn on lots of GCC warnings (for developers)])], + [turn on lots of GCC warnings (for developers)])], [case $enableval in yes|no) ;; *) AC_MSG_ERROR([bad value $enableval for gcc-warnings option]) ;; @@ -122,11 +122,11 @@ AC_FUNC_FORK optional_bin_progs= AC_CHECK_FUNCS([uname], - gl_ADD_PROG([optional_bin_progs], [uname])) + gl_ADD_PROG([optional_bin_progs], [uname])) AC_CHECK_FUNCS([chroot], - gl_ADD_PROG([optional_bin_progs], [chroot])) + gl_ADD_PROG([optional_bin_progs], [chroot])) AC_CHECK_FUNCS([gethostid], - gl_ADD_PROG([optional_bin_progs], [hostid])) + gl_ADD_PROG([optional_bin_progs], [hostid])) gl_WINSIZE_IN_PTEM @@ -168,9 +168,9 @@ int main() [# If we have tzset, assume the worst when cross-compiling. utils_cv_localtime_cache=yes]) else - # If we lack tzset, report that localtime does not cache TZ, - # since we can't invalidate the cache if we don't have tzset. - utils_cv_localtime_cache=no + # If we lack tzset, report that localtime does not cache TZ, + # since we can't invalidate the cache if we don't have tzset. + utils_cv_localtime_cache=no fi])dnl AC_MSG_RESULT([$utils_cv_localtime_cache]) if test $utils_cv_localtime_cache = yes; then @@ -197,7 +197,7 @@ AC_CACHE_CHECK([for 3-argument setpriority function], [AC_LINK_IFELSE( [AC_LANG_PROGRAM( [[#include <sys/time.h> - #include <sys/resource.h> + #include <sys/resource.h> ]], [[setpriority (0, 0, 0);]])], [utils_cv_func_setpriority=yes], @@ -374,8 +374,8 @@ case $t in $no_install_progs_default) ;; *) AC_MSG_ERROR([[internal error: g'l_INCLUDE_EXCLUDE_PROG's 2nd arg, $t, does not match the list of default-not-installed programs - ($no_install_progs_default) also recorded in $mk]], - 1) ;; + ($no_install_progs_default) also recorded in $mk]], + 1) ;; esac # Given the name of a variable containing a space-separated list of diff --git a/gl/lib/mgetgroups.c b/gl/lib/mgetgroups.c index 736dd87f3..0ebc2be15 100644 --- a/gl/lib/mgetgroups.c +++ b/gl/lib/mgetgroups.c @@ -76,45 +76,45 @@ mgetgroups (char const *username, gid_t gid, GETGROUPS_T **groups) g = realloc_groupbuf (NULL, max_n_groups); if (g == NULL) - return -1; + return -1; while (1) - { - GETGROUPS_T *h; - int last_n_groups = max_n_groups; - - /* getgrouplist updates max_n_groups to num required. */ - ng = getgrouplist (username, gid, g, &max_n_groups); - - /* Some systems (like Darwin) have a bug where they - never increase max_n_groups. */ - if (ng < 0 && last_n_groups == max_n_groups) - max_n_groups *= 2; - - if ((h = realloc_groupbuf (g, max_n_groups)) == NULL) - { - int saved_errno = errno; - free (g); - errno = saved_errno; - return -1; - } - g = h; - - if (0 <= ng) - { - *groups = g; - /* On success some systems just return 0 from getgrouplist, - so return max_n_groups rather than ng. */ - return max_n_groups; - } - } + { + GETGROUPS_T *h; + int last_n_groups = max_n_groups; + + /* getgrouplist updates max_n_groups to num required. */ + ng = getgrouplist (username, gid, g, &max_n_groups); + + /* Some systems (like Darwin) have a bug where they + never increase max_n_groups. */ + if (ng < 0 && last_n_groups == max_n_groups) + max_n_groups *= 2; + + if ((h = realloc_groupbuf (g, max_n_groups)) == NULL) + { + int saved_errno = errno; + free (g); + errno = saved_errno; + return -1; + } + g = h; + + if (0 <= ng) + { + *groups = g; + /* On success some systems just return 0 from getgrouplist, + so return max_n_groups rather than ng. */ + return max_n_groups; + } + } } /* else no username, so fall through and use getgroups. */ #endif max_n_groups = (username - ? getugroups (0, NULL, username, gid) - : getgroups (0, NULL)); + ? getugroups (0, NULL, username, gid) + : getgroups (0, NULL)); /* If we failed to count groups with NULL for a buffer, try again with a non-NULL one, just in case. */ @@ -126,8 +126,8 @@ mgetgroups (char const *username, gid_t gid, GETGROUPS_T **groups) return -1; ng = (username - ? getugroups (max_n_groups, g, username, gid) - : getgroups (max_n_groups, g)); + ? getugroups (max_n_groups, g, username, gid) + : getgroups (max_n_groups, g)); if (ng < 0) { diff --git a/gl/lib/rand-isaac.c b/gl/lib/rand-isaac.c index 5b6171478..a1edf4785 100644 --- a/gl/lib/rand-isaac.c +++ b/gl/lib/rand-isaac.c @@ -43,7 +43,7 @@ /* This index operation is more efficient on many processors */ #define ind(mm, x) \ (* (uint32_t *) ((char *) (mm) \ - + ((x) & (ISAAC_WORDS - 1) * sizeof (uint32_t)))) + + ((x) & (ISAAC_WORDS - 1) * sizeof (uint32_t)))) /* * The central step. This uses two temporaries, x and y. mm is the @@ -191,18 +191,18 @@ isaac_init (struct isaac_state *s, uint32_t const *seed, size_t seedsize) isaac_mix (s, seed); /* Second and subsequent passes (extension to ISAAC) */ while (seedsize -= ISAAC_BYTES) - { - seed += ISAAC_WORDS; - for (i = 0; i < ISAAC_WORDS; i++) - s->mm[i] += seed[i]; - isaac_mix (s, s->mm); - } + { + seed += ISAAC_WORDS; + for (i = 0; i < ISAAC_WORDS; i++) + s->mm[i] += seed[i]; + isaac_mix (s, s->mm); + } } else { /* The no seed case (as in reference ISAAC code) */ for (i = 0; i < ISAAC_WORDS; i++) - s->mm[i] = 0; + s->mm[i] = 0; } /* Final pass */ @@ -252,7 +252,7 @@ isaac_seed_data (struct isaac_state *s, void const *buffer, size_t size) { p = (unsigned char *) s->mm + s->c; for (i = 0; i < avail; i++) - p[i] ^= buf[i]; + p[i] ^= buf[i]; buf += avail; size -= avail; isaac_mix (s, s->mm); diff --git a/gl/lib/randint.c b/gl/lib/randint.c index 0edda0aa0..cfa6e232b 100644 --- a/gl/lib/randint.c +++ b/gl/lib/randint.c @@ -128,75 +128,75 @@ randint_genmax (struct randint_source *s, randint genmax) for (;;) { if (randmax < genmax) - { - /* Calculate how many input bytes will be needed, and read - the bytes. */ - - size_t i = 0; - randint rmax = randmax; - unsigned char buf[sizeof randnum]; - - do - { - rmax = shift_left (rmax) + UCHAR_MAX; - i++; - } - while (rmax < genmax); - - randread (source, buf, i); - - /* Increase RANDMAX by appending random bytes to RANDNUM and - UCHAR_MAX to RANDMAX until RANDMAX is no less than - GENMAX. This may lose up to CHAR_BIT bits of information - if shift_right (RANDINT_MAX) < GENMAX, but it is not - worth the programming hassle of saving these bits since - GENMAX is rarely that large in practice. */ - - i = 0; - - do - { - randnum = shift_left (randnum) + buf[i]; - randmax = shift_left (randmax) + UCHAR_MAX; - i++; - } - while (randmax < genmax); - } + { + /* Calculate how many input bytes will be needed, and read + the bytes. */ + + size_t i = 0; + randint rmax = randmax; + unsigned char buf[sizeof randnum]; + + do + { + rmax = shift_left (rmax) + UCHAR_MAX; + i++; + } + while (rmax < genmax); + + randread (source, buf, i); + + /* Increase RANDMAX by appending random bytes to RANDNUM and + UCHAR_MAX to RANDMAX until RANDMAX is no less than + GENMAX. This may lose up to CHAR_BIT bits of information + if shift_right (RANDINT_MAX) < GENMAX, but it is not + worth the programming hassle of saving these bits since + GENMAX is rarely that large in practice. */ + + i = 0; + + do + { + randnum = shift_left (randnum) + buf[i]; + randmax = shift_left (randmax) + UCHAR_MAX; + i++; + } + while (randmax < genmax); + } if (randmax == genmax) - { - s->randnum = s->randmax = 0; - return randnum; - } + { + s->randnum = s->randmax = 0; + return randnum; + } else - { - /* GENMAX < RANDMAX, so attempt to generate a random number - by taking RANDNUM modulo GENMAX+1. This will choose - fairly so long as RANDNUM falls within an integral - multiple of GENMAX+1; otherwise, LAST_USABLE_CHOICE < RANDNUM, - so discard this attempt and try again. - - Since GENMAX cannot be RANDINT_MAX, CHOICES cannot be - zero and there is no need to worry about dividing by - zero. */ - - randint excess_choices = randmax - genmax; - randint unusable_choices = excess_choices % choices; - randint last_usable_choice = randmax - unusable_choices; - randint reduced_randnum = randnum % choices; - - if (randnum <= last_usable_choice) - { - s->randnum = randnum / choices; - s->randmax = excess_choices / choices; - return reduced_randnum; - } - - /* Retry, but retain the randomness from the fact that RANDNUM fell - into the range LAST_USABLE_CHOICE+1 .. RANDMAX. */ - randnum = reduced_randnum; - randmax = unusable_choices - 1; - } + { + /* GENMAX < RANDMAX, so attempt to generate a random number + by taking RANDNUM modulo GENMAX+1. This will choose + fairly so long as RANDNUM falls within an integral + multiple of GENMAX+1; otherwise, LAST_USABLE_CHOICE < RANDNUM, + so discard this attempt and try again. + + Since GENMAX cannot be RANDINT_MAX, CHOICES cannot be + zero and there is no need to worry about dividing by + zero. */ + + randint excess_choices = randmax - genmax; + randint unusable_choices = excess_choices % choices; + randint last_usable_choice = randmax - unusable_choices; + randint reduced_randnum = randnum % choices; + + if (randnum <= last_usable_choice) + { + s->randnum = randnum / choices; + s->randmax = excess_choices / choices; + return reduced_randnum; + } + + /* Retry, but retain the randomness from the fact that RANDNUM fell + into the range LAST_USABLE_CHOICE+1 .. RANDMAX. */ + randnum = reduced_randnum; + randmax = unusable_choices - 1; + } } } diff --git a/gl/lib/randperm.c b/gl/lib/randperm.c index 507e21460..a03c5b87f 100644 --- a/gl/lib/randperm.c +++ b/gl/lib/randperm.c @@ -79,21 +79,21 @@ randperm_new (struct randint_source *r, size_t h, size_t n) default: { - size_t i; + size_t i; - v = xnmalloc (n, sizeof *v); - for (i = 0; i < n; i++) - v[i] = i; + v = xnmalloc (n, sizeof *v); + for (i = 0; i < n; i++) + v[i] = i; - for (i = 0; i < h; i++) - { - size_t j = i + randint_choose (r, n - i); - size_t t = v[i]; - v[i] = v[j]; - v[j] = t; - } + for (i = 0; i < h; i++) + { + size_t j = i + randint_choose (r, n - i); + size_t t = v[i]; + v[i] = v[j]; + v[j] = t; + } - v = xnrealloc (v, h, sizeof *v); + v = xnrealloc (v, h, sizeof *v); } break; } diff --git a/gl/lib/randread.c b/gl/lib/randread.c index 48ce92e9a..72475017e 100644 --- a/gl/lib/randread.c +++ b/gl/lib/randread.c @@ -100,8 +100,8 @@ struct randread_source /* Up to a buffer's worth of pseudorandom data. */ union { - uint32_t w[ISAAC_WORDS]; - unsigned char b[ISAAC_BYTES]; + uint32_t w[ISAAC_WORDS]; + unsigned char b[ISAAC_BYTES]; } data; } isaac; } buf; @@ -115,8 +115,8 @@ randread_error (void const *file_name) { if (file_name) error (exit_failure, errno, - _(errno == 0 ? "%s: end of file" : "%s: read error"), - quotearg_colon (file_name)); + _(errno == 0 ? "%s: end of file" : "%s: read error"), + quotearg_colon (file_name)); abort (); } @@ -155,18 +155,18 @@ randread_new (char const *name, size_t bytes_bound) struct randread_source *s; if (name) - if (! (source = fopen_safer (name, "rb"))) - return NULL; + if (! (source = fopen_safer (name, "rb"))) + return NULL; s = simple_new (source, name); if (source) - setvbuf (source, s->buf.c, _IOFBF, MIN (sizeof s->buf.c, bytes_bound)); + setvbuf (source, s->buf.c, _IOFBF, MIN (sizeof s->buf.c, bytes_bound)); else - { - s->buf.isaac.buffered = 0; - isaac_seed (&s->buf.isaac.state); - } + { + s->buf.isaac.buffered = 0; + isaac_seed (&s->buf.isaac.state); + } return s; } @@ -206,7 +206,7 @@ readsource (struct randread_source *s, unsigned char *p, size_t size) p += inbytes; size -= inbytes; if (size == 0) - break; + break; errno = (ferror (s->source) ? fread_errno : 0); s->handler (s->handler_arg); } @@ -224,34 +224,34 @@ readisaac (struct isaac *isaac, unsigned char *p, size_t size) for (;;) { if (size <= inbytes) - { - memcpy (p, isaac->data.b + ISAAC_BYTES - inbytes, size); - isaac->buffered = inbytes - size; - return; - } + { + memcpy (p, isaac->data.b + ISAAC_BYTES - inbytes, size); + isaac->buffered = inbytes - size; + return; + } memcpy (p, isaac->data.b + ISAAC_BYTES - inbytes, inbytes); p += inbytes; size -= inbytes; /* If P is aligned, write to *P directly to avoid the overhead - of copying from the buffer. */ + of copying from the buffer. */ if (ALIGNED_POINTER (p, uint32_t)) - { - uint32_t *wp = (uint32_t *) p; - while (ISAAC_BYTES <= size) - { - isaac_refill (&isaac->state, wp); - wp += ISAAC_WORDS; - size -= ISAAC_BYTES; - if (size == 0) - { - isaac->buffered = 0; - return; - } - } - p = (unsigned char *) wp; - } + { + uint32_t *wp = (uint32_t *) p; + while (ISAAC_BYTES <= size) + { + isaac_refill (&isaac->state, wp); + wp += ISAAC_WORDS; + size -= ISAAC_BYTES; + if (size == 0) + { + isaac->buffered = 0; + return; + } + } + p = (unsigned char *) wp; + } isaac_refill (&isaac->state, isaac->data.w); inbytes = ISAAC_BYTES; diff --git a/gl/lib/root-dev-ino.h b/gl/lib/root-dev-ino.h index 2832096c1..bec27f0ae 100644 --- a/gl/lib/root-dev-ino.h +++ b/gl/lib/root-dev-ino.h @@ -34,12 +34,12 @@ get_root_dev_ino (struct dev_ino *root_d_i); do \ { \ if (STREQ (Dirname, "/")) \ - error (0, 0, _("it is dangerous to operate recursively on %s"), \ - quote (Dirname)); \ + error (0, 0, _("it is dangerous to operate recursively on %s"), \ + quote (Dirname)); \ else \ - error (0, 0, \ - _("it is dangerous to operate recursively on %s (same as %s)"), \ - quote_n (0, Dirname), quote_n (1, "/")); \ + error (0, 0, \ + _("it is dangerous to operate recursively on %s (same as %s)"), \ + quote_n (0, Dirname), quote_n (1, "/")); \ error (0, 0, _("use --no-preserve-root to override this failsafe")); \ } \ while (0) diff --git a/gl/lib/tempname.c b/gl/lib/tempname.c index e9fb60670..01715168d 100644 --- a/gl/lib/tempname.c +++ b/gl/lib/tempname.c @@ -96,7 +96,7 @@ direxists (const char *dir) enough space in TMPL. */ int __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx, - int try_tmpdir) + int try_tmpdir) { const char *d; size_t dlen, plen; @@ -110,30 +110,30 @@ __path_search (char *tmpl, size_t tmpl_len, const char *dir, const char *pfx, { plen = strlen (pfx); if (plen > 5) - plen = 5; + plen = 5; } if (try_tmpdir) { d = __secure_getenv ("TMPDIR"); if (d != NULL && direxists (d)) - dir = d; + dir = d; else if (dir != NULL && direxists (dir)) - /* nothing */ ; + /* nothing */ ; else - dir = NULL; + dir = NULL; } if (dir == NULL) { if (direxists (P_tmpdir)) - dir = P_tmpdir; + dir = P_tmpdir; else if (strcmp (P_tmpdir, "/tmp") != 0 && direxists ("/tmp")) - dir = "/tmp"; + dir = "/tmp"; else - { - __set_errno (ENOENT); - return -1; - } + { + __set_errno (ENOENT); + return -1; + } } dlen = strlen (dir); @@ -169,9 +169,9 @@ static const char letters[] = KIND may be one of: __GT_NOCREATE: simply verify that the name does not exist - at the time of the call. + at the time of the call. __GT_FILE: create the file using open(O_CREAT|O_EXCL) - and return a read-write fd. The file is mode 0600. + and return a read-write fd. The file is mode 0600. __GT_BIGFILE: same as __GT_FILE but use open64(). __GT_DIR: create a directory, which will be mode 0700. @@ -205,7 +205,7 @@ gen_tempname_len (char *tmpl, int kind, size_t x_suffix_len) len = strlen (tmpl); if (len < x_suffix_len || ! check_x_suffix (&tmpl[len - x_suffix_len], - x_suffix_len)) + x_suffix_len)) { __set_errno (EINVAL); return -1; @@ -223,60 +223,60 @@ gen_tempname_len (char *tmpl, int kind, size_t x_suffix_len) size_t i; for (i = 0; i < x_suffix_len; i++) - { - XXXXXX[i] = letters[randint_genmax (rand_src, sizeof letters - 2)]; - } + { + XXXXXX[i] = letters[randint_genmax (rand_src, sizeof letters - 2)]; + } switch (kind) - { - case __GT_FILE: - fd = small_open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); - break; - - case __GT_BIGFILE: - fd = large_open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); - break; - - case __GT_DIR: - fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR); - break; - - case __GT_NOCREATE: - /* This case is backward from the other three. This function - succeeds if __xstat fails because the name does not exist. - Note the continue to bypass the common logic at the bottom - of the loop. */ - if (__lxstat64 (_STAT_VER, tmpl, &st) < 0) - { - if (errno == ENOENT) - { - __set_errno (save_errno); - fd = 0; - goto done; - } - else - { - /* Give up now. */ - fd = -1; - goto done; - } - } - continue; - - default: - assert (! "invalid KIND in __gen_tempname"); - } + { + case __GT_FILE: + fd = small_open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); + break; + + case __GT_BIGFILE: + fd = large_open (tmpl, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR); + break; + + case __GT_DIR: + fd = __mkdir (tmpl, S_IRUSR | S_IWUSR | S_IXUSR); + break; + + case __GT_NOCREATE: + /* This case is backward from the other three. This function + succeeds if __xstat fails because the name does not exist. + Note the continue to bypass the common logic at the bottom + of the loop. */ + if (__lxstat64 (_STAT_VER, tmpl, &st) < 0) + { + if (errno == ENOENT) + { + __set_errno (save_errno); + fd = 0; + goto done; + } + else + { + /* Give up now. */ + fd = -1; + goto done; + } + } + continue; + + default: + assert (! "invalid KIND in __gen_tempname"); + } if (fd >= 0) - { - __set_errno (save_errno); - goto done; - } + { + __set_errno (save_errno); + goto done; + } else if (errno != EEXIST) - { - fd = -1; - goto done; - } + { + fd = -1; + goto done; + } } randint_all_free (rand_src); diff --git a/gl/lib/tempname.h b/gl/lib/tempname.h index b7dd3a101..ee34aca21 100644 --- a/gl/lib/tempname.h +++ b/gl/lib/tempname.h @@ -30,9 +30,9 @@ KIND may be one of: GT_NOCREATE: simply verify that the name does not exist - at the time of the call. + at the time of the call. GT_FILE: create a large file using open(O_CREAT|O_EXCL) - and return a read-write fd. The file is mode 0600. + and return a read-write fd. The file is mode 0600. GT_DIR: create a directory, which will be mode 0700. We use a clever algorithm to get hard-to-predict names. */ diff --git a/gl/lib/xfreopen.c b/gl/lib/xfreopen.c index a20965f25..61091694b 100644 --- a/gl/lib/xfreopen.c +++ b/gl/lib/xfreopen.c @@ -31,11 +31,11 @@ xfreopen (char const *filename, char const *mode, FILE *fp) if (!freopen (filename, mode, fp)) { char const *f = (filename ? filename - : (fp == stdin ? _("stdin") - : (fp == stdout ? _("stdout") - : (fp == stderr ? _("stderr") - : _("unknown stream"))))); + : (fp == stdin ? _("stdin") + : (fp == stdout ? _("stdout") + : (fp == stderr ? _("stderr") + : _("unknown stream"))))); error (exit_failure, errno, _("failed to reopen %s with mode %s"), - quote_n (0, f), quote_n (1, mode)); + quote_n (0, f), quote_n (1, mode)); } } diff --git a/lib/buffer-lcm.c b/lib/buffer-lcm.c index b8d87d31d..ee901741d 100644 --- a/lib/buffer-lcm.c +++ b/lib/buffer-lcm.c @@ -34,22 +34,22 @@ buffer_lcm (size_t a, size_t b, size_t lcm_max) else { if (b) - { - /* Return lcm (A, B) if it is in range; otherwise, fall back - on A. */ - - size_t lcm, m, n, q, r; - - /* N = gcd (A, B). */ - for (m = a, n = b; (r = m % n) != 0; m = n, n = r) - continue; - - /* LCM = lcm (A, B), if in range. */ - q = a / n; - lcm = q * b; - if (lcm <= lcm_max && lcm / b == q) - return lcm; - } + { + /* Return lcm (A, B) if it is in range; otherwise, fall back + on A. */ + + size_t lcm, m, n, q, r; + + /* N = gcd (A, B). */ + for (m = a, n = b; (r = m % n) != 0; m = n, n = r) + continue; + + /* LCM = lcm (A, B), if in range. */ + q = a / n; + lcm = q * b; + if (lcm <= lcm_max && lcm / b == q) + return lcm; + } size = a; } diff --git a/lib/euidaccess-stat.c b/lib/euidaccess-stat.c index 0213c93fc..98ce28157 100644 --- a/lib/euidaccess-stat.c +++ b/lib/euidaccess-stat.c @@ -57,8 +57,8 @@ euidaccess_stat (struct stat const *st, int mode) mode &= 7; else mode = ((mode & R_OK ? 4 : 0) - + (mode & W_OK ? 2 : 0) - + (mode & X_OK ? 1 : 0)); + + (mode & W_OK ? 2 : 0) + + (mode & X_OK ? 1 : 0)); if (mode == 0) return true; /* The file exists. */ @@ -68,7 +68,7 @@ euidaccess_stat (struct stat const *st, int mode) /* The super-user can read and write any file, and execute any file that anyone can execute. */ if (euid == 0 && ((mode & X_OK) == 0 - || (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))) + || (st->st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))) return true; /* Convert the file's permission bits to traditional form. */ @@ -84,14 +84,14 @@ euidaccess_stat (struct stat const *st, int mode) granted = st->st_mode; else granted = ( (st->st_mode & S_IRUSR ? 4 << 6 : 0) - + (st->st_mode & S_IWUSR ? 2 << 6 : 0) - + (st->st_mode & S_IXUSR ? 1 << 6 : 0) - + (st->st_mode & S_IRGRP ? 4 << 3 : 0) - + (st->st_mode & S_IWGRP ? 2 << 3 : 0) - + (st->st_mode & S_IXGRP ? 1 << 3 : 0) - + (st->st_mode & S_IROTH ? 4 << 0 : 0) - + (st->st_mode & S_IWOTH ? 2 << 0 : 0) - + (st->st_mode & S_IXOTH ? 1 << 0 : 0)); + + (st->st_mode & S_IWUSR ? 2 << 6 : 0) + + (st->st_mode & S_IXUSR ? 1 << 6 : 0) + + (st->st_mode & S_IRGRP ? 4 << 3 : 0) + + (st->st_mode & S_IWGRP ? 2 << 3 : 0) + + (st->st_mode & S_IXGRP ? 1 << 3 : 0) + + (st->st_mode & S_IROTH ? 4 << 0 : 0) + + (st->st_mode & S_IWOTH ? 2 << 0 : 0) + + (st->st_mode & S_IXOTH ? 1 << 0 : 0)); if (euid == st->st_uid) granted >>= 6; @@ -99,7 +99,7 @@ euidaccess_stat (struct stat const *st, int mode) { gid_t egid = getegid (); if (egid == st->st_gid || group_member (st->st_gid)) - granted >>= 3; + granted >>= 3; } if ((mode & ~granted) == 0) diff --git a/lib/fdopendir-glibc.c b/lib/fdopendir-glibc.c index a35917113..1e6a460e9 100644 --- a/lib/fdopendir-glibc.c +++ b/lib/fdopendir-glibc.c @@ -77,12 +77,12 @@ __alloc_dir (int fd, bool close_fd) size_t allocation; #ifdef _STATBUF_ST_BLKSIZE if (__builtin_expect ((size_t) statp->st_blksize >= sizeof (struct dirent64), - 1)) + 1)) allocation = statp->st_blksize; else #endif allocation = (BUFSIZ < sizeof (struct dirent64) - ? sizeof (struct dirent64) : BUFSIZ); + ? sizeof (struct dirent64) : BUFSIZ); const int pad = -sizeof (DIR) % __alignof__ (struct dirent64); @@ -91,11 +91,11 @@ __alloc_dir (int fd, bool close_fd) lose: { if (close_fd) - { - int save_errno = errno; - close_not_cancel_no_status (fd); - __set_errno (save_errno); - } + { + int save_errno = errno; + close_not_cancel_no_status (fd); + __set_errno (save_errno); + } return NULL; } memset (dirp, '\0', sizeof (DIR)); diff --git a/lib/memxfrm.c b/lib/memxfrm.c index 7376b3e97..a186ed87a 100644 --- a/lib/memxfrm.c +++ b/lib/memxfrm.c @@ -40,7 +40,7 @@ size_t memxfrm (char *restrict dest, size_t destsize, - char *restrict src, size_t srcsize) + char *restrict src, size_t srcsize) { #if HAVE_STRXFRM @@ -59,33 +59,33 @@ memxfrm (char *restrict dest, size_t destsize, errno = 0; result += strxfrm (dest + di, src + si, destsize - di) + 1; if (errno != 0) - break; + break; if (result <= result0) - { - errno = ERANGE; - break; - } + { + errno = ERANGE; + break; + } if (result == destsize + 1 && si + slen == srcsize) - { - /* The destination is exactly the right size, but strxfrm wants - room for a trailing null. Work around the problem with a - temporary buffer. */ - size_t bufsize = destsize - di + 1; - char stackbuf[4000]; - char *buf = stackbuf; - if (sizeof stackbuf < bufsize) - { - buf = malloc (bufsize); - if (! buf) - break; - } - strxfrm (buf, src + si, bufsize); - memcpy (dest + di, buf, destsize - di); - if (sizeof stackbuf < bufsize) - free (buf); - errno = 0; - } + { + /* The destination is exactly the right size, but strxfrm wants + room for a trailing null. Work around the problem with a + temporary buffer. */ + size_t bufsize = destsize - di + 1; + char stackbuf[4000]; + char *buf = stackbuf; + if (sizeof stackbuf < bufsize) + { + buf = malloc (bufsize); + if (! buf) + break; + } + strxfrm (buf, src + si, bufsize); + memcpy (dest + di, buf, destsize - di); + if (sizeof stackbuf < bufsize) + free (buf); + errno = 0; + } di = (result < destsize ? result : destsize); si += slen + 1; diff --git a/lib/strnumcmp-in.h b/lib/strnumcmp-in.h index db2d15875..886427490 100644 --- a/lib/strnumcmp-in.h +++ b/lib/strnumcmp-in.h @@ -77,28 +77,28 @@ fraccompare (char const *a, char const *b, char decimal_point) if (*a == decimal_point && *b == decimal_point) { while (*++a == *++b) - if (! ISDIGIT (*a)) - return 0; + if (! ISDIGIT (*a)) + return 0; if (ISDIGIT (*a) && ISDIGIT (*b)) - return *a - *b; + return *a - *b; if (ISDIGIT (*a)) - goto a_trailing_nonzero; + goto a_trailing_nonzero; if (ISDIGIT (*b)) - goto b_trailing_nonzero; + goto b_trailing_nonzero; return 0; } else if (*a++ == decimal_point) { a_trailing_nonzero: while (*a == NUMERIC_ZERO) - a++; + a++; return ISDIGIT (*a); } else if (*b++ == decimal_point) { b_trailing_nonzero: while (*b == NUMERIC_ZERO) - b++; + b++; return - ISDIGIT (*b); } return 0; @@ -113,7 +113,7 @@ fraccompare (char const *a, char const *b, char decimal_point) static inline int numcompare (char const *a, char const *b, - int decimal_point, int thousands_sep) + int decimal_point, int thousands_sep) { unsigned char tmpa = *a; unsigned char tmpb = *b; @@ -124,119 +124,119 @@ numcompare (char const *a, char const *b, if (tmpa == NEGATION_SIGN) { do - tmpa = *++a; + tmpa = *++a; while (tmpa == NUMERIC_ZERO || tmpa == thousands_sep); if (tmpb != NEGATION_SIGN) - { - if (tmpa == decimal_point) - do - tmpa = *++a; - while (tmpa == NUMERIC_ZERO); - if (ISDIGIT (tmpa)) - return -1; - while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep) - tmpb = *++b; - if (tmpb == decimal_point) - do - tmpb = *++b; - while (tmpb == NUMERIC_ZERO); - return - ISDIGIT (tmpb); - } + { + if (tmpa == decimal_point) + do + tmpa = *++a; + while (tmpa == NUMERIC_ZERO); + if (ISDIGIT (tmpa)) + return -1; + while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep) + tmpb = *++b; + if (tmpb == decimal_point) + do + tmpb = *++b; + while (tmpb == NUMERIC_ZERO); + return - ISDIGIT (tmpb); + } do - tmpb = *++b; + tmpb = *++b; while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep); while (tmpa == tmpb && ISDIGIT (tmpa)) - { - do - tmpa = *++a; - while (tmpa == thousands_sep); - do - tmpb = *++b; - while (tmpb == thousands_sep); - } + { + do + tmpa = *++a; + while (tmpa == thousands_sep); + do + tmpb = *++b; + while (tmpb == thousands_sep); + } if ((tmpa == decimal_point && !ISDIGIT (tmpb)) - || (tmpb == decimal_point && !ISDIGIT (tmpa))) - return fraccompare (b, a, decimal_point); + || (tmpb == decimal_point && !ISDIGIT (tmpa))) + return fraccompare (b, a, decimal_point); tmp = tmpb - tmpa; for (log_a = 0; ISDIGIT (tmpa); ++log_a) - do - tmpa = *++a; - while (tmpa == thousands_sep); + do + tmpa = *++a; + while (tmpa == thousands_sep); for (log_b = 0; ISDIGIT (tmpb); ++log_b) - do - tmpb = *++b; - while (tmpb == thousands_sep); + do + tmpb = *++b; + while (tmpb == thousands_sep); if (log_a != log_b) - return log_a < log_b ? 1 : -1; + return log_a < log_b ? 1 : -1; if (!log_a) - return 0; + return 0; return tmp; } else if (tmpb == NEGATION_SIGN) { do - tmpb = *++b; + tmpb = *++b; while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep); if (tmpb == decimal_point) - do - tmpb = *++b; - while (tmpb == NUMERIC_ZERO); + do + tmpb = *++b; + while (tmpb == NUMERIC_ZERO); if (ISDIGIT (tmpb)) - return 1; + return 1; while (tmpa == NUMERIC_ZERO || tmpa == thousands_sep) - tmpa = *++a; + tmpa = *++a; if (tmpa == decimal_point) - do - tmpa = *++a; - while (tmpa == NUMERIC_ZERO); + do + tmpa = *++a; + while (tmpa == NUMERIC_ZERO); return ISDIGIT (tmpa); } else { while (tmpa == NUMERIC_ZERO || tmpa == thousands_sep) - tmpa = *++a; + tmpa = *++a; while (tmpb == NUMERIC_ZERO || tmpb == thousands_sep) - tmpb = *++b; + tmpb = *++b; while (tmpa == tmpb && ISDIGIT (tmpa)) - { - do - tmpa = *++a; - while (tmpa == thousands_sep); - do - tmpb = *++b; - while (tmpb == thousands_sep); - } + { + do + tmpa = *++a; + while (tmpa == thousands_sep); + do + tmpb = *++b; + while (tmpb == thousands_sep); + } if ((tmpa == decimal_point && !ISDIGIT (tmpb)) - || (tmpb == decimal_point && !ISDIGIT (tmpa))) - return fraccompare (a, b, decimal_point); + || (tmpb == decimal_point && !ISDIGIT (tmpa))) + return fraccompare (a, b, decimal_point); tmp = tmpa - tmpb; for (log_a = 0; ISDIGIT (tmpa); ++log_a) - do - tmpa = *++a; - while (tmpa == thousands_sep); + do + tmpa = *++a; + while (tmpa == thousands_sep); for (log_b = 0; ISDIGIT (tmpb); ++log_b) - do - tmpb = *++b; - while (tmpb == thousands_sep); + do + tmpb = *++b; + while (tmpb == thousands_sep); if (log_a != log_b) - return log_a < log_b ? -1 : 1; + return log_a < log_b ? -1 : 1; if (!log_a) - return 0; + return 0; return tmp; } diff --git a/lib/strnumcmp.c b/lib/strnumcmp.c index 2a2f2f729..aae09e156 100644 --- a/lib/strnumcmp.c +++ b/lib/strnumcmp.c @@ -25,7 +25,7 @@ int strnumcmp (char const *a, char const *b, - int decimal_point, int thousands_sep) + int decimal_point, int thousands_sep) { return numcompare (a, b, decimal_point, thousands_sep); } diff --git a/lib/t-chdir-long b/lib/t-chdir-long index e92d445ae..489c6b50a 100755 --- a/lib/t-chdir-long +++ b/lib/t-chdir-long @@ -38,10 +38,10 @@ function mkdir_len ( cd $root && perl -e 'my $len='$n'-length "'$root'";$i=100;$d="z"x$i; while ($i+2 < $len) { - $len -= $i + 1; - mkdir $d,0700 or die "$!\n"; - chdir $d} $d="z"x($len-1); - mkdir $d or die "mkdir_len: $d: $!\n"' ) + $len -= $i + 1; + mkdir $d,0700 or die "$!\n"; + chdir $d} $d="z"x($len-1); + mkdir $d or die "mkdir_len: $d: $!\n"' ) } size_list= diff --git a/lib/xfts.c b/lib/xfts.c index e91ab079e..5994a5fef 100644 --- a/lib/xfts.c +++ b/lib/xfts.c @@ -35,28 +35,28 @@ FTS * xfts_open (char * const *argv, int options, - int (*compar) (const FTSENT **, const FTSENT **)) + int (*compar) (const FTSENT **, const FTSENT **)) { FTS *fts = fts_open (argv, options | FTS_CWDFD, compar); if (fts == NULL) { /* This can fail in three ways: out of memory, invalid bit_flags, - and one or more of the FILES is an empty string. We could try - to decipher that errno==EINVAL means invalid bit_flags and - errno==ENOENT means there's an empty string, but that seems wrong. - Ideally, fts_open would return a proper error indicator. For now, - we'll presume that the bit_flags are valid and just check for - empty strings. */ + and one or more of the FILES is an empty string. We could try + to decipher that errno==EINVAL means invalid bit_flags and + errno==ENOENT means there's an empty string, but that seems wrong. + Ideally, fts_open would return a proper error indicator. For now, + we'll presume that the bit_flags are valid and just check for + empty strings. */ bool invalid_arg = false; for (; *argv; ++argv) - { - if (**argv == '\0') - invalid_arg = true; - } + { + if (**argv == '\0') + invalid_arg = true; + } if (invalid_arg) - error (EXIT_FAILURE, 0, _("invalid argument: %s"), quote ("")); + error (EXIT_FAILURE, 0, _("invalid argument: %s"), quote ("")); else - xalloc_die (); + xalloc_die (); } return fts; diff --git a/lib/xfts.h b/lib/xfts.h index 47906132a..27ddb5d48 100644 --- a/lib/xfts.h +++ b/lib/xfts.h @@ -2,4 +2,4 @@ FTS * xfts_open (char * const *, int options, - int (*) (const FTSENT **, const FTSENT **)); + int (*) (const FTSENT **, const FTSENT **)); diff --git a/lib/xmemxfrm.c b/lib/xmemxfrm.c index 2e9979ddb..bfbf658ab 100644 --- a/lib/xmemxfrm.c +++ b/lib/xmemxfrm.c @@ -45,7 +45,7 @@ size_t xmemxfrm (char *restrict dest, size_t destsize, - char *restrict src, size_t srcsize) + char *restrict src, size_t srcsize) { size_t translated_size = memxfrm (dest, destsize, src, srcsize); @@ -54,8 +54,8 @@ xmemxfrm (char *restrict dest, size_t destsize, error (0, errno, _("string transformation failed")); error (0, 0, _("set LC_ALL='C' to work around the problem")); error (exit_failure, 0, - _("the untransformed string was %s"), - quotearg_n_style_mem (0, locale_quoting_style, src, srcsize)); + _("the untransformed string was %s"), + quotearg_n_style_mem (0, locale_quoting_style, src, srcsize)); } return translated_size; diff --git a/m4/include-exclude-prog.m4 b/m4/include-exclude-prog.m4 index ea4c169a2..51bd1d036 100644 --- a/m4/include-exclude-prog.m4 +++ b/m4/include-exclude-prog.m4 @@ -36,8 +36,8 @@ AC_DEFUN([gl_INCLUDE_EXCLUDE_PROG], gl_no_install_progs_default=`echo '$2'|sed 's/,/ /g'` AC_ARG_ENABLE([install-program], [AS_HELP_STRING([--enable-install-program=PROG_LIST], - [install the programs in PROG_LIST (comma-separated, - default: none)])], + [install the programs in PROG_LIST (comma-separated, + default: none)])], [gl_do_install_prog=$enableval], [gl_do_install_prog=] ) @@ -46,8 +46,8 @@ AC_DEFUN([gl_INCLUDE_EXCLUDE_PROG], # use --enable-no-install-program=A,B AC_ARG_ENABLE([no-install-program], [AS_HELP_STRING([--enable-no-install-program=PROG_LIST], - [do NOT install the programs in PROG_LIST - (comma-separated, default: $2)])], + [do NOT install the programs in PROG_LIST + (comma-separated, default: $2)])], [gl_no_install_prog=$enableval], [gl_no_install_prog=] ) @@ -78,7 +78,7 @@ AC_DEFUN([gl_INCLUDE_EXCLUDE_PROG], # Warn about a request not to install a program that is # already on the default-no-install list. case " $gl_no_install_progs_default " in - *" $gl_i "*) gl_msg="by default, '$gl_i' is not installed" ;; + *" $gl_i "*) gl_msg="by default, '$gl_i' is not installed" ;; esac fi diff --git a/m4/jm-macros.m4 b/m4/jm-macros.m4 index 32a0954a7..416a0af25 100644 --- a/m4/jm-macros.m4 +++ b/m4/jm-macros.m4 @@ -37,9 +37,9 @@ AC_DEFUN([coreutils_MACROS], # By default, argmatch should fail calling usage (1). AC_DEFINE([ARGMATCH_DIE], [usage (1)], - [Define to the function xargmatch calls on failures.]) + [Define to the function xargmatch calls on failures.]) AC_DEFINE([ARGMATCH_DIE_DECL], [void usage (int _e)], - [Define to the declaration of the xargmatch failure function.]) + [Define to the declaration of the xargmatch failure function.]) # used by ls AC_REQUIRE([gl_CLOCK_TIME]) @@ -52,13 +52,13 @@ AC_DEFUN([coreutils_MACROS], AC_CHECK_FUNCS([matchpathcon_init_prefix], [], [ case "$ac_cv_search_setfilecon:$ac_cv_header_selinux_selinux_h" in - no:*) # SELinux disabled - ;; - *:no) # SELinux disabled - ;; - *) - AC_MSG_WARN([SELinux enabled, but matchpathcon_init_prefix not found]) - AC_MSG_WARN([The install utility may run slowly]) + no:*) # SELinux disabled + ;; + *:no) # SELinux disabled + ;; + *) + AC_MSG_WARN([SELinux enabled, but matchpathcon_init_prefix not found]) + AC_MSG_WARN([The install utility may run slowly]) esac ]) LIBS=$coreutils_saved_libs @@ -98,8 +98,8 @@ AC_DEFUN([coreutils_MACROS], # for dd.c and shred.c coreutils_saved_libs=$LIBS AC_SEARCH_LIBS([fdatasync], [rt posix4], - [test "$ac_cv_search_fdatasync" = "none required" || - LIB_FDATASYNC=$ac_cv_search_fdatasync]) + [test "$ac_cv_search_fdatasync" = "none required" || + LIB_FDATASYNC=$ac_cv_search_fdatasync]) AC_SUBST([LIB_FDATASYNC]) AC_CHECK_FUNCS([fdatasync]) LIBS=$coreutils_saved_libs @@ -110,9 +110,9 @@ AC_DEFUN([coreutils_MACROS], AC_MSG_WARN([libcap support disabled by user]), [AC_CHECK_LIB([cap], [cap_get_file], [AC_CHECK_HEADER([sys/capability.h], - [LIB_CAP=-lcap - AC_DEFINE([HAVE_CAP], [1], [libcap usability])], - [AC_MSG_WARN([header sys/capability.h was not found, support for libcap will not be built])] + [LIB_CAP=-lcap + AC_DEFINE([HAVE_CAP], [1], [libcap usability])], + [AC_MSG_WARN([header sys/capability.h was not found, support for libcap will not be built])] )], [AC_MSG_WARN([libcap library was not found or not usable, support for libcap will not be built])]) ]) diff --git a/m4/lib-check.m4 b/m4/lib-check.m4 index 952101bda..e169fa16a 100644 --- a/m4/lib-check.m4 +++ b/m4/lib-check.m4 @@ -53,8 +53,8 @@ $ac_includes_default # NetBSD needs -lcrypt for crypt. cu_saved_libs="$LIBS" AC_SEARCH_LIBS([crypt], [ufc crypt], - [test "$ac_cv_search_crypt" = "none required" || - LIB_CRYPT="$ac_cv_search_crypt"]) + [test "$ac_cv_search_crypt" = "none required" || + LIB_CRYPT="$ac_cv_search_crypt"]) LIBS="$cu_saved_libs" AC_SUBST([LIB_CRYPT]) ]) diff --git a/m4/stat-prog.m4 b/m4/stat-prog.m4 index 0db9c7d41..c80499c83 100644 --- a/m4/stat-prog.m4 +++ b/m4/stat-prog.m4 @@ -57,30 +57,30 @@ AC_INCLUDES_DEFAULT { AC_CHECK_MEMBERS([struct statvfs.f_basetype],,, [$statvfs_includes]) test $ac_cv_member_struct_statvfs_f_basetype = yes || { AC_CHECK_MEMBERS([struct statvfs.f_fstypename],,, [$statvfs_includes]) - test $ac_cv_member_struct_statvfs_f_fstypename = yes || - { test $ac_cv_member_struct_statfs_f_fstypename != yes && - { AC_CHECK_MEMBERS([struct statvfs.f_type],,, [$statvfs_includes]) - test $ac_cv_member_struct_statvfs_f_type = yes; }; }; }; } + test $ac_cv_member_struct_statvfs_f_fstypename = yes || + { test $ac_cv_member_struct_statfs_f_fstypename != yes && + { AC_CHECK_MEMBERS([struct statvfs.f_type],,, [$statvfs_includes]) + test $ac_cv_member_struct_statvfs_f_type = yes; }; }; }; } then AC_CHECK_MEMBERS([struct statvfs.f_namemax],,, [$statvfs_includes]) AC_COMPILE_IFELSE( [AC_LANG_PROGRAM( - [$statvfs_includes], - [static statvfs s; - return (s.s_fsid ^ 0) == 0;])], + [$statvfs_includes], + [static statvfs s; + return (s.s_fsid ^ 0) == 0;])], [AC_DEFINE([STRUCT_STATVFS_F_FSID_IS_INTEGER], [1], - [Define to 1 if the f_fsid member of struct statvfs is an integer.])]) + [Define to 1 if the f_fsid member of struct statvfs is an integer.])]) else AC_CHECK_MEMBERS([struct statfs.f_namelen, struct statfs.f_type],,, [$statfs_includes]) if test $ac_cv_header_OS_h != yes; then AC_COMPILE_IFELSE( - [AC_LANG_PROGRAM( - [$statfs_includes], - [static statfs s; - return (s.s_fsid ^ 0) == 0;])], - [AC_DEFINE([STRUCT_STATFS_F_FSID_IS_INTEGER], [1], - [Define to 1 if the f_fsid member of struct statfs is an integer.])]) + [AC_LANG_PROGRAM( + [$statfs_includes], + [static statfs s; + return (s.s_fsid ^ 0) == 0;])], + [AC_DEFINE([STRUCT_STATFS_F_FSID_IS_INTEGER], [1], + [Define to 1 if the f_fsid member of struct statfs is an integer.])]) fi fi ]) diff --git a/m4/xattr.m4 b/m4/xattr.m4 index 6aa612bc3..878e86bc0 100644 --- a/m4/xattr.m4 +++ b/m4/xattr.m4 @@ -11,9 +11,9 @@ AC_DEFUN([gl_FUNC_XATTR], [ AC_ARG_ENABLE([xattr], - AC_HELP_STRING([--disable-xattr], - [do not support extended attributes]), - [use_xattr=$enableval], [use_xattr=yes]) + AC_HELP_STRING([--disable-xattr], + [do not support extended attributes]), + [use_xattr=$enableval], [use_xattr=yes]) if test "$use_xattr" = "yes"; then AC_CHECK_HEADERS([attr/error_context.h attr/libattr.h]) @@ -24,11 +24,11 @@ AC_DEFUN([gl_FUNC_XATTR], use_xattr=0 fi AC_DEFINE_UNQUOTED([USE_XATTR], [$use_xattr], - [Define if you want extended attribute support.]) + [Define if you want extended attribute support.]) xattr_saved_LIBS=$LIBS AC_SEARCH_LIBS([attr_copy_file], [attr], - [test "$ac_cv_search_attr_copy_file" = "none required" || - LIB_XATTR=$ac_cv_search_attr_copy_file]) + [test "$ac_cv_search_attr_copy_file" = "none required" || + LIB_XATTR=$ac_cv_search_attr_copy_file]) AC_CHECK_FUNCS([attr_copy_file]) LIBS=$xattr_saved_LIBS AC_SUBST([LIB_XATTR]) diff --git a/old/fileutils/NEWS b/old/fileutils/NEWS index d4ac2dffc..7daf48087 100644 --- a/old/fileutils/NEWS +++ b/old/fileutils/NEWS @@ -504,17 +504,17 @@ Changes in release 4.0: * ls accepts new options: --indicator-style=none (no indicators, the default) --indicator-style=classify (all indicators) - (equivalent to -F or --classify) + (equivalent to -F or --classify) --indicator-style=file-type (file type indicators) - (equivalent to -p or --file-type) + (equivalent to -p or --file-type) --quoting-style=literal (do not quote output) --quoting-style=shell (minimally quote output for the shell) --quoting-style=shell-always (always quote output with '' for the shell) --quoting-style=c (quote output as for a C-language string) - (equivalent to -Q or --quote-name) + (equivalent to -Q or --quote-name) --quoting-style=escape (like c but omit enclosing "") - (equivalent to -b or --escape) + (equivalent to -b or --escape) --show-control-chars is the opposite of --hide-control-chars This option can be useful if output is to a terminal, diff --git a/src/base64.c b/src/base64.c index e24b11125..c7cf034da 100644 --- a/src/base64.c +++ b/src/base64.c @@ -53,7 +53,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -80,7 +80,7 @@ The data are encoded as described for the base64 alphabet in RFC 3548.\n\ When decoding, the input may contain newlines in addition to the bytes of\n\ the formal base64 alphabet. Use --ignore-garbage to attempt to recover\n\ from any other non-alphabet bytes in the encoded stream.\n"), - stdout); + stdout); emit_bug_reporting_address (); } @@ -99,7 +99,7 @@ from any other non-alphabet bytes in the encoded stream.\n"), static void wrap_write (const char *buffer, size_t len, - uintmax_t wrap_column, size_t *current_column, FILE *out) + uintmax_t wrap_column, size_t *current_column, FILE *out) { size_t written; @@ -107,28 +107,28 @@ wrap_write (const char *buffer, size_t len, { /* Simple write. */ if (fwrite (buffer, 1, len, stdout) < len) - error (EXIT_FAILURE, errno, _("write error")); + error (EXIT_FAILURE, errno, _("write error")); } else for (written = 0; written < len;) { - uintmax_t cols_remaining = wrap_column - *current_column; - size_t to_write = MIN (cols_remaining, SIZE_MAX); - to_write = MIN (to_write, len - written); - - if (to_write == 0) - { - if (fputs ("\n", out) < 0) - error (EXIT_FAILURE, errno, _("write error")); - *current_column = 0; - } - else - { - if (fwrite (buffer + written, 1, to_write, stdout) < to_write) - error (EXIT_FAILURE, errno, _("write error")); - *current_column += to_write; - written += to_write; - } + uintmax_t cols_remaining = wrap_column - *current_column; + size_t to_write = MIN (cols_remaining, SIZE_MAX); + to_write = MIN (to_write, len - written); + + if (to_write == 0) + { + if (fputs ("\n", out) < 0) + error (EXIT_FAILURE, errno, _("write error")); + *current_column = 0; + } + else + { + if (fwrite (buffer + written, 1, to_write, stdout) < to_write) + error (EXIT_FAILURE, errno, _("write error")); + *current_column += to_write; + written += to_write; + } } } @@ -146,21 +146,21 @@ do_encode (FILE *in, FILE *out, uintmax_t wrap_column) sum = 0; do - { - n = fread (inbuf + sum, 1, BLOCKSIZE - sum, in); - sum += n; - } + { + n = fread (inbuf + sum, 1, BLOCKSIZE - sum, in); + sum += n; + } while (!feof (in) && !ferror (in) && sum < BLOCKSIZE); if (sum > 0) - { - /* Process input one block at a time. Note that BLOCKSIZE % - 3 == 0, so that no base64 pads will appear in output. */ - base64_encode (inbuf, sum, outbuf, BASE64_LENGTH (sum)); - - wrap_write (outbuf, BASE64_LENGTH (sum), wrap_column, - ¤t_column, out); - } + { + /* Process input one block at a time. Note that BLOCKSIZE % + 3 == 0, so that no base64 pads will appear in output. */ + base64_encode (inbuf, sum, outbuf, BASE64_LENGTH (sum)); + + wrap_write (outbuf, BASE64_LENGTH (sum), wrap_column, + ¤t_column, out); + } } while (!feof (in) && !ferror (in) && sum == BLOCKSIZE); @@ -190,43 +190,43 @@ do_decode (FILE *in, FILE *out, bool ignore_garbage) sum = 0; do - { - n = fread (inbuf + sum, 1, B64BLOCKSIZE - sum, in); - - if (ignore_garbage) - { - size_t i; - for (i = 0; n > 0 && i < n;) - if (isbase64 (inbuf[sum + i]) || inbuf[sum + i] == '=') - i++; - else - memmove (inbuf + sum + i, inbuf + sum + i + 1, --n - i); - } - - sum += n; - - if (ferror (in)) - error (EXIT_FAILURE, errno, _("read error")); - } + { + n = fread (inbuf + sum, 1, B64BLOCKSIZE - sum, in); + + if (ignore_garbage) + { + size_t i; + for (i = 0; n > 0 && i < n;) + if (isbase64 (inbuf[sum + i]) || inbuf[sum + i] == '=') + i++; + else + memmove (inbuf + sum + i, inbuf + sum + i + 1, --n - i); + } + + sum += n; + + if (ferror (in)) + error (EXIT_FAILURE, errno, _("read error")); + } while (sum < B64BLOCKSIZE && !feof (in)); /* The following "loop" is usually iterated just once. - However, when it processes the final input buffer, we want - to iterate it one additional time, but with an indicator - telling it to flush what is in CTX. */ + However, when it processes the final input buffer, we want + to iterate it one additional time, but with an indicator + telling it to flush what is in CTX. */ for (k = 0; k < 1 + !!feof (in); k++) - { - if (k == 1 && ctx.i == 0) - break; - n = BLOCKSIZE; - ok = base64_decode_ctx (&ctx, inbuf, (k == 0 ? sum : 0), outbuf, &n); - - if (fwrite (outbuf, 1, n, out) < n) - error (EXIT_FAILURE, errno, _("write error")); - - if (!ok) - error (EXIT_FAILURE, 0, _("invalid input")); - } + { + if (k == 1 && ctx.i == 0) + break; + n = BLOCKSIZE; + ok = base64_decode_ctx (&ctx, inbuf, (k == 0 ? sum : 0), outbuf, &n); + + if (fwrite (outbuf, 1, n, out) < n) + error (EXIT_FAILURE, errno, _("write error")); + + if (!ok) + error (EXIT_FAILURE, 0, _("invalid input")); + } } while (!feof (in)); } @@ -257,26 +257,26 @@ main (int argc, char **argv) switch (opt) { case 'd': - decode = true; - break; + decode = true; + break; case 'w': - if (xstrtoumax (optarg, NULL, 0, &wrap_column, NULL) != LONGINT_OK) - error (EXIT_FAILURE, 0, _("invalid wrap size: %s"), - quotearg (optarg)); - break; + if (xstrtoumax (optarg, NULL, 0, &wrap_column, NULL) != LONGINT_OK) + error (EXIT_FAILURE, 0, _("invalid wrap size: %s"), + quotearg (optarg)); + break; case 'i': - ignore_garbage = true; - break; + ignore_garbage = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); - break; + usage (EXIT_FAILURE); + break; } if (argc - optind > 1) @@ -296,7 +296,7 @@ main (int argc, char **argv) { input_fh = fopen (infile, "r"); if (input_fh == NULL) - error (EXIT_FAILURE, errno, "%s", infile); + error (EXIT_FAILURE, errno, "%s", infile); } if (decode) @@ -307,9 +307,9 @@ main (int argc, char **argv) if (fclose (input_fh) == EOF) { if (STREQ (infile, "-")) - error (EXIT_FAILURE, errno, _("closing standard input")); + error (EXIT_FAILURE, errno, _("closing standard input")); else - error (EXIT_FAILURE, errno, "%s", infile); + error (EXIT_FAILURE, errno, "%s", infile); } exit (EXIT_SUCCESS); diff --git a/src/basename.c b/src/basename.c index d79ad209c..4300d4983 100644 --- a/src/basename.c +++ b/src/basename.c @@ -44,14 +44,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s NAME [SUFFIX]\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Print NAME with any leading directory components removed.\n\ If specified, also remove a trailing SUFFIX.\n\ @@ -65,7 +65,7 @@ Examples:\n\ %s /usr/bin/sort Output \"sort\".\n\ %s include/stdio.h .h Output \"stdio\".\n\ "), - program_name, program_name); + program_name, program_name); emit_bug_reporting_address (); } exit (status); @@ -104,7 +104,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "+", NULL, NULL) != -1) usage (EXIT_FAILURE); diff --git a/src/c99-to-c89.diff b/src/c99-to-c89.diff index 51b0a42ca..a5dd6c9b8 100644 --- a/src/c99-to-c89.diff +++ b/src/c99-to-c89.diff @@ -43,21 +43,21 @@ diff -upr src/remove.c src/remove.c && ((x->interactive == RMI_ALWAYS) || x->stdin_tty) && dirent_type != DT_LNK) @@ -889,6 +890,7 @@ prompt (int fd_cwd, Dirstack_state const - break; - } + break; + } + { char const *quoted_name = quote (full_filename (filename)); if (write_protected < 0) @@ -928,6 +930,7 @@ prompt (int fd_cwd, Dirstack_state const - : _("%s: remove %s %s? ")), - program_name, file_type (sbuf), quoted_name); - } + : _("%s: remove %s %s? ")), + program_name, file_type (sbuf), quoted_name); + } + } if (!yesno ()) - return RM_USER_DECLINED; + return RM_USER_DECLINED; @@ -1547,6 +1550,7 @@ rm_1 (Dirstack_state *ds, char const *fi return RM_ERROR; } @@ -72,7 +72,7 @@ diff -upr src/remove.c src/remove.c + { enum RM_status status = remove_entry (AT_FDCWD, ds, filename, - DT_UNKNOWN, &st, x); + DT_UNKNOWN, &st, x); if (status == RM_NONEMPTY_DIR) @@ -1587,6 +1592,8 @@ rm_1 (Dirstack_state *ds, char const *fi ds_clear (ds); @@ -87,7 +87,7 @@ diff -upr src/rm.c src/rm.c --- src/rm.c 1970-01-01 00:00:00.000000000 +0000 +++ src/rm.c 1970-01-01 00:00:00.000000000 +0000 @@ -354,6 +354,7 @@ main (int argc, char **argv) - quote ("/")); + quote ("/")); } + { @@ -96,7 +96,7 @@ diff -upr src/rm.c src/rm.c @@ -367,7 +368,10 @@ main (int argc, char **argv) if (!yesno ()) - exit (EXIT_SUCCESS); + exit (EXIT_SUCCESS); } + { enum RM_status status = rm (n_files, file, &x); @@ -109,37 +109,37 @@ diff -upr src/seq.c src/seq.c --- src/seq.c 1970-01-01 00:00:00.000000000 +0000 +++ src/seq.c 1970-01-01 00:00:00.000000000 +0000 @@ -163,6 +163,7 @@ scan_arg (const char *arg) - : (decimal_point == arg /* .# -> 0.# */ - || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */ - } + : (decimal_point == arg /* .# -> 0.# */ + || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */ + } + { char const *e = strchr (arg, 'e'); if (! e) - e = strchr (arg, 'E'); + e = strchr (arg, 'E'); @@ -171,6 +172,7 @@ scan_arg (const char *arg) - long exponent = strtol (e + 1, NULL, 10); - ret.precision += exponent < 0 ? -exponent : 0; - } + long exponent = strtol (e + 1, NULL, 10); + ret.precision += exponent < 0 ? -exponent : 0; + } + } } return ret; @@ -346,6 +348,7 @@ get_default_format (operand first, opera - size_t last_width = last.width + (prec - last.precision); - if (last.precision && prec == 0) - last_width--; /* don't include space for '.' */ + size_t last_width = last.width + (prec - last.precision); + if (last.precision && prec == 0) + last_width--; /* don't include space for '.' */ + { - size_t width = MAX (first_width, last_width); - if (width <= INT_MAX) - { + size_t width = MAX (first_width, last_width); + if (width <= INT_MAX) + { @@ -353,6 +356,7 @@ get_default_format (operand first, opera - sprintf (format_buf, "%%0%d.%dLf", w, prec); - return format_buf; - } + sprintf (format_buf, "%%0%d.%dLf", w, prec); + return format_buf; + } + } - } + } else - { + { @@ -441,6 +445,7 @@ main (int argc, char **argv) if (format_str) { @@ -147,10 +147,10 @@ diff -upr src/seq.c src/seq.c + { char const *f = long_double_format (format_str, &layout); if (! f) - { + { @@ -448,6 +453,7 @@ main (int argc, char **argv) - usage (EXIT_FAILURE); - } + usage (EXIT_FAILURE); + } format_str = f; + } } @@ -160,11 +160,11 @@ diff -upr src/shred.c src/shred.c --- src/shred.c 1970-01-01 00:00:00.000000000 +0000 +++ src/shred.c 1970-01-01 00:00:00.000000000 +0000 @@ -468,7 +468,7 @@ dopass (int fd, char const *qname, off_t - out. Thus, it shouldn't give up on bad blocks. This - code works because lim is always a multiple of - SECTOR_SIZE, except at the end. */ + out. Thus, it shouldn't give up on bad blocks. This + code works because lim is always a multiple of + SECTOR_SIZE, except at the end. */ - verify (sizeof r % SECTOR_SIZE == 0); + { verify (sizeof r % SECTOR_SIZE == 0); } - if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim) - { - size_t soff1 = (soff | SECTOR_MASK) + 1; + if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim) + { + size_t soff1 = (soff | SECTOR_MASK) + 1; @@ -83,13 +83,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Concatenate FILE(s), or standard input, to standard output.\n\ \n\ @@ -118,7 +118,7 @@ Examples:\n\ %s f - g Output f's contents, then standard input, then g's contents.\n\ %s Copy standard input to standard output.\n\ "), - program_name, program_name); + program_name, program_name); emit_bug_reporting_address (); } exit (status); @@ -133,7 +133,7 @@ next_line_num (void) do { if ((*endp)++ < '9') - return; + return; *endp-- = '0'; } while (endp >= line_num_start); @@ -168,23 +168,23 @@ simple_cat ( n_read = safe_read (input_desc, buf, bufsize); if (n_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", infile); - return false; - } + { + error (0, errno, "%s", infile); + return false; + } /* End of this file? */ if (n_read == 0) - return true; + return true; /* Write this block out. */ { - /* The following is ok, since we know that 0 < n_read. */ - size_t n = n_read; - if (full_write (STDOUT_FILENO, buf, n) != n) - error (EXIT_FAILURE, errno, _("write error")); + /* The following is ok, since we know that 0 < n_read. */ + size_t n = n_read; + if (full_write (STDOUT_FILENO, buf, n) != n) + error (EXIT_FAILURE, errno, _("write error")); } } } @@ -274,227 +274,227 @@ cat ( for (;;) { do - { - /* Write if there are at least OUTSIZE bytes in OUTBUF. */ - - if (outbuf + outsize <= bpout) - { - char *wp = outbuf; - size_t remaining_bytes; - do - { - if (full_write (STDOUT_FILENO, wp, outsize) != outsize) - error (EXIT_FAILURE, errno, _("write error")); - wp += outsize; - remaining_bytes = bpout - wp; - } - while (outsize <= remaining_bytes); - - /* Move the remaining bytes to the beginning of the - buffer. */ - - memmove (outbuf, wp, remaining_bytes); - bpout = outbuf + remaining_bytes; - } - - /* Is INBUF empty? */ - - if (bpin > eob) - { - bool input_pending = false; + { + /* Write if there are at least OUTSIZE bytes in OUTBUF. */ + + if (outbuf + outsize <= bpout) + { + char *wp = outbuf; + size_t remaining_bytes; + do + { + if (full_write (STDOUT_FILENO, wp, outsize) != outsize) + error (EXIT_FAILURE, errno, _("write error")); + wp += outsize; + remaining_bytes = bpout - wp; + } + while (outsize <= remaining_bytes); + + /* Move the remaining bytes to the beginning of the + buffer. */ + + memmove (outbuf, wp, remaining_bytes); + bpout = outbuf + remaining_bytes; + } + + /* Is INBUF empty? */ + + if (bpin > eob) + { + bool input_pending = false; #ifdef FIONREAD - int n_to_read = 0; - - /* Is there any input to read immediately? - If not, we are about to wait, - so write all buffered output before waiting. */ - - if (use_fionread - && ioctl (input_desc, FIONREAD, &n_to_read) < 0) - { - /* Ultrix returns EOPNOTSUPP on NFS; - HP-UX returns ENOTTY on pipes. - SunOS returns EINVAL and - More/BSD returns ENODEV on special files - like /dev/null. - Irix-5 returns ENOSYS on pipes. */ - if (errno == EOPNOTSUPP || errno == ENOTTY - || errno == EINVAL || errno == ENODEV - || errno == ENOSYS) - use_fionread = false; - else - { - error (0, errno, _("cannot do ioctl on %s"), quote (infile)); - newlines2 = newlines; - return false; - } - } - if (n_to_read != 0) - input_pending = true; + int n_to_read = 0; + + /* Is there any input to read immediately? + If not, we are about to wait, + so write all buffered output before waiting. */ + + if (use_fionread + && ioctl (input_desc, FIONREAD, &n_to_read) < 0) + { + /* Ultrix returns EOPNOTSUPP on NFS; + HP-UX returns ENOTTY on pipes. + SunOS returns EINVAL and + More/BSD returns ENODEV on special files + like /dev/null. + Irix-5 returns ENOSYS on pipes. */ + if (errno == EOPNOTSUPP || errno == ENOTTY + || errno == EINVAL || errno == ENODEV + || errno == ENOSYS) + use_fionread = false; + else + { + error (0, errno, _("cannot do ioctl on %s"), quote (infile)); + newlines2 = newlines; + return false; + } + } + if (n_to_read != 0) + input_pending = true; #endif - if (!input_pending) - write_pending (outbuf, &bpout); - - /* Read more input into INBUF. */ - - n_read = safe_read (input_desc, inbuf, insize); - if (n_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", infile); - write_pending (outbuf, &bpout); - newlines2 = newlines; - return false; - } - if (n_read == 0) - { - write_pending (outbuf, &bpout); - newlines2 = newlines; - return true; - } - - /* Update the pointers and insert a sentinel at the buffer - end. */ - - bpin = inbuf; - eob = bpin + n_read; - *eob = '\n'; - } - else - { - /* It was a real (not a sentinel) newline. */ - - /* Was the last line empty? - (i.e. have two or more consecutive newlines been read?) */ - - if (++newlines > 0) - { - if (newlines >= 2) - { - /* Limit this to 2 here. Otherwise, with lots of - consecutive newlines, the counter could wrap - around at INT_MAX. */ - newlines = 2; - - /* Are multiple adjacent empty lines to be substituted - by single ditto (-s), and this was the second empty - line? */ - if (squeeze_blank) - { - ch = *bpin++; - continue; - } - } - - /* Are line numbers to be written at empty lines (-n)? */ - - if (number & !number_nonblank) - { - next_line_num (); - bpout = stpcpy (bpout, line_num_print); - } - } - - /* Output a currency symbol if requested (-e). */ - - if (show_ends) - *bpout++ = '$'; - - /* Output the newline. */ - - *bpout++ = '\n'; - } - ch = *bpin++; - } + if (!input_pending) + write_pending (outbuf, &bpout); + + /* Read more input into INBUF. */ + + n_read = safe_read (input_desc, inbuf, insize); + if (n_read == SAFE_READ_ERROR) + { + error (0, errno, "%s", infile); + write_pending (outbuf, &bpout); + newlines2 = newlines; + return false; + } + if (n_read == 0) + { + write_pending (outbuf, &bpout); + newlines2 = newlines; + return true; + } + + /* Update the pointers and insert a sentinel at the buffer + end. */ + + bpin = inbuf; + eob = bpin + n_read; + *eob = '\n'; + } + else + { + /* It was a real (not a sentinel) newline. */ + + /* Was the last line empty? + (i.e. have two or more consecutive newlines been read?) */ + + if (++newlines > 0) + { + if (newlines >= 2) + { + /* Limit this to 2 here. Otherwise, with lots of + consecutive newlines, the counter could wrap + around at INT_MAX. */ + newlines = 2; + + /* Are multiple adjacent empty lines to be substituted + by single ditto (-s), and this was the second empty + line? */ + if (squeeze_blank) + { + ch = *bpin++; + continue; + } + } + + /* Are line numbers to be written at empty lines (-n)? */ + + if (number & !number_nonblank) + { + next_line_num (); + bpout = stpcpy (bpout, line_num_print); + } + } + + /* Output a currency symbol if requested (-e). */ + + if (show_ends) + *bpout++ = '$'; + + /* Output the newline. */ + + *bpout++ = '\n'; + } + ch = *bpin++; + } while (ch == '\n'); /* Are we at the beginning of a line, and line numbers are requested? */ if (newlines >= 0 && number) - { - next_line_num (); - bpout = stpcpy (bpout, line_num_print); - } + { + next_line_num (); + bpout = stpcpy (bpout, line_num_print); + } /* Here CH cannot contain a newline character. */ /* The loops below continue until a newline character is found, - which means that the buffer is empty or that a proper newline - has been found. */ + which means that the buffer is empty or that a proper newline + has been found. */ /* If quoting, i.e. at least one of -v, -e, or -t specified, - scan for chars that need conversion. */ + scan for chars that need conversion. */ if (show_nonprinting) - { - for (;;) - { - 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 == '\t' && !show_tabs) - *bpout++ = '\t'; - else if (ch == '\n') - { - newlines = -1; - break; - } - else - { - *bpout++ = '^'; - *bpout++ = ch + 64; - } - - ch = *bpin++; - } - } + { + for (;;) + { + 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 == '\t' && !show_tabs) + *bpout++ = '\t'; + else if (ch == '\n') + { + newlines = -1; + break; + } + else + { + *bpout++ = '^'; + *bpout++ = ch + 64; + } + + ch = *bpin++; + } + } else - { - /* Not quoting, neither of -v, -e, or -t specified. */ - for (;;) - { - if (ch == '\t' && show_tabs) - { - *bpout++ = '^'; - *bpout++ = ch + 64; - } - else if (ch != '\n') - *bpout++ = ch; - else - { - newlines = -1; - break; - } - - ch = *bpin++; - } - } + { + /* Not quoting, neither of -v, -e, or -t specified. */ + for (;;) + { + if (ch == '\t' && show_tabs) + { + *bpout++ = '^'; + *bpout++ = ch + 64; + } + else if (ch != '\n') + *bpout++ = ch; + else + { + newlines = -1; + break; + } + + ch = *bpin++; + } + } } } @@ -573,62 +573,62 @@ main (int argc, char **argv) /* Parse command line options. */ while ((c = getopt_long (argc, argv, "benstuvAET", long_options, NULL)) - != -1) + != -1) { switch (c) - { - case 'b': - number = true; - number_nonblank = true; - break; - - case 'e': - show_ends = true; - show_nonprinting = true; - break; - - case 'n': - number = true; - break; - - case 's': - squeeze_blank = true; - break; - - case 't': - show_tabs = true; - show_nonprinting = true; - break; - - case 'u': - /* We provide the -u feature unconditionally. */ - break; - - case 'v': - show_nonprinting = true; - break; - - case 'A': - show_nonprinting = true; - show_ends = true; - show_tabs = true; - break; - - case 'E': - show_ends = true; - break; - - case 'T': - show_tabs = true; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'b': + number = true; + number_nonblank = true; + break; + + case 'e': + show_ends = true; + show_nonprinting = true; + break; + + case 'n': + number = true; + break; + + case 's': + squeeze_blank = true; + break; + + case 't': + show_tabs = true; + show_nonprinting = true; + break; + + case 'u': + /* We provide the -u feature unconditionally. */ + break; + + case 'v': + show_nonprinting = true; + break; + + case 'A': + show_nonprinting = true; + show_ends = true; + show_tabs = true; + break; + + case 'E': + show_ends = true; + break; + + case 'T': + show_tabs = true; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } /* Get device, i-node number, and optimal blocksize of output. */ @@ -661,7 +661,7 @@ main (int argc, char **argv) { file_open_mode |= O_BINARY; if (O_BINARY && ! isatty (STDOUT_FILENO)) - xfreopen (NULL, "wb", stdout); + xfreopen (NULL, "wb", stdout); } /* Check if any of the input files are the same as the output file. */ @@ -674,104 +674,104 @@ main (int argc, char **argv) do { if (argind < argc) - infile = argv[argind]; + infile = argv[argind]; if (STREQ (infile, "-")) - { - have_read_stdin = true; - input_desc = STDIN_FILENO; - if ((file_open_mode & O_BINARY) && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); - } + { + have_read_stdin = true; + input_desc = STDIN_FILENO; + if ((file_open_mode & O_BINARY) && ! isatty (STDIN_FILENO)) + xfreopen (NULL, "rb", stdin); + } else - { - input_desc = open (infile, file_open_mode); - if (input_desc < 0) - { - error (0, errno, "%s", infile); - ok = false; - continue; - } - } + { + input_desc = open (infile, file_open_mode); + if (input_desc < 0) + { + error (0, errno, "%s", infile); + ok = false; + continue; + } + } if (fstat (input_desc, &stat_buf) < 0) - { - error (0, errno, "%s", infile); - ok = false; - goto contin; - } + { + error (0, errno, "%s", infile); + ok = false; + goto contin; + } insize = io_blksize (stat_buf); /* Compare the device and i-node numbers of this input file with - the corresponding values of the (output file associated with) - stdout, and skip this input file if they coincide. Input - files cannot be redirected to themselves. */ + the corresponding values of the (output file associated with) + stdout, and skip this input file if they coincide. Input + files cannot be redirected to themselves. */ if (check_redirection - && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino - && (input_desc != STDIN_FILENO)) - { - error (0, 0, _("%s: input file is output file"), infile); - ok = false; - goto contin; - } + && stat_buf.st_dev == out_dev && stat_buf.st_ino == out_ino + && (input_desc != STDIN_FILENO)) + { + error (0, 0, _("%s: input file is output file"), infile); + ok = false; + goto contin; + } /* Select which version of `cat' to use. If any format-oriented - options were given use `cat'; otherwise use `simple_cat'. */ + options were given use `cat'; otherwise use `simple_cat'. */ if (! (number | show_ends | show_nonprinting - | show_tabs | squeeze_blank)) - { - insize = MAX (insize, outsize); - inbuf = xmalloc (insize + page_size - 1); + | show_tabs | squeeze_blank)) + { + insize = MAX (insize, outsize); + inbuf = xmalloc (insize + page_size - 1); - ok &= simple_cat (ptr_align (inbuf, page_size), insize); - } + ok &= simple_cat (ptr_align (inbuf, page_size), insize); + } else - { - inbuf = xmalloc (insize + 1 + page_size - 1); - - /* Why are - (OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN + PAGE_SIZE - 1) - bytes allocated for the output buffer? - - A test whether output needs to be written is done when the input - buffer empties or when a newline appears in the input. After - output is written, at most (OUTSIZE - 1) bytes will remain in the - buffer. Now INSIZE bytes of input is read. Each input character - may grow by a factor of 4 (by the prepending of M-^). If all - characters do, and no newlines appear in this block of input, we - will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer. - If the last character in the preceding block of input was a - newline, a line number may be written (according to the given - options) as the first thing in the output buffer. (Done after the - new input is read, but before processing of the input begins.) - A line number requires seldom more than LINE_COUNTER_BUF_LEN - positions. - - Align the output buffer to a page size boundary, for efficency on - some paging implementations, so add PAGE_SIZE - 1 bytes to the - request to make room for the alignment. */ - - outbuf = xmalloc (outsize - 1 + insize * 4 + LINE_COUNTER_BUF_LEN - + page_size - 1); - - ok &= cat (ptr_align (inbuf, page_size), insize, - ptr_align (outbuf, page_size), outsize, show_nonprinting, - show_tabs, number, number_nonblank, show_ends, - squeeze_blank); - - free (outbuf); - } + { + inbuf = xmalloc (insize + 1 + page_size - 1); + + /* Why are + (OUTSIZE - 1 + INSIZE * 4 + LINE_COUNTER_BUF_LEN + PAGE_SIZE - 1) + bytes allocated for the output buffer? + + A test whether output needs to be written is done when the input + buffer empties or when a newline appears in the input. After + output is written, at most (OUTSIZE - 1) bytes will remain in the + buffer. Now INSIZE bytes of input is read. Each input character + may grow by a factor of 4 (by the prepending of M-^). If all + characters do, and no newlines appear in this block of input, we + will have at most (OUTSIZE - 1 + INSIZE * 4) bytes in the buffer. + If the last character in the preceding block of input was a + newline, a line number may be written (according to the given + options) as the first thing in the output buffer. (Done after the + new input is read, but before processing of the input begins.) + A line number requires seldom more than LINE_COUNTER_BUF_LEN + positions. + + Align the output buffer to a page size boundary, for efficency on + some paging implementations, so add PAGE_SIZE - 1 bytes to the + request to make room for the alignment. */ + + outbuf = xmalloc (outsize - 1 + insize * 4 + LINE_COUNTER_BUF_LEN + + page_size - 1); + + ok &= cat (ptr_align (inbuf, page_size), insize, + ptr_align (outbuf, page_size), outsize, show_nonprinting, + show_tabs, number, number_nonblank, show_ends, + squeeze_blank); + + free (outbuf); + } free (inbuf); contin: if (!STREQ (infile, "-") && close (input_desc) < 0) - { - error (0, errno, "%s", infile); - ok = false; - } + { + error (0, errno, "%s", infile); + ok = false; + } } while (++argind < argc); diff --git a/src/chcon.c b/src/chcon.c index f5b5f22df..266260066 100644 --- a/src/chcon.c +++ b/src/chcon.c @@ -97,7 +97,7 @@ compute_context_from_mask (security_context_t context, context_t *ret) if (!new_context) { error (0, errno, _("failed to create security context: %s"), - quotearg_colon (context)); + quotearg_colon (context)); return 1; } @@ -105,13 +105,13 @@ compute_context_from_mask (security_context_t context, context_t *ret) do \ { \ if (specified_ ## comp \ - && context_ ## comp ## _set ((C), specified_ ## comp)) \ + && context_ ## comp ## _set ((C), specified_ ## comp)) \ { \ - error (0, errno, \ - _("failed to set %s security context component to %s"), \ - #comp, quote (specified_ ## comp)); \ + error (0, errno, \ + _("failed to set %s security context component to %s"), \ + #comp, quote (specified_ ## comp)); \ ok = false; \ - } \ + } \ } \ while (0) @@ -147,35 +147,35 @@ change_file_context (int fd, char const *file) if (specified_context == NULL) { int status = (affect_symlink_referent - ? getfileconat (fd, file, &file_context) - : lgetfileconat (fd, file, &file_context)); + ? getfileconat (fd, file, &file_context) + : lgetfileconat (fd, file, &file_context)); if (status < 0 && errno != ENODATA) - { - error (0, errno, _("failed to get security context of %s"), - quote (file)); - return 1; - } + { + error (0, errno, _("failed to get security context of %s"), + quote (file)); + return 1; + } /* If the file doesn't have a context, and we're not setting all of - the context components, there isn't really an obvious default. - Thus, we just give up. */ + the context components, there isn't really an obvious default. + Thus, we just give up. */ if (file_context == NULL) - { - error (0, 0, _("can't apply partial context to unlabeled file %s"), - quote (file)); - return 1; - } + { + error (0, 0, _("can't apply partial context to unlabeled file %s"), + quote (file)); + return 1; + } if (compute_context_from_mask (file_context, &context)) - return 1; + return 1; } else { /* FIXME: this should be done exactly once, in main. */ context = context_new (specified_context); if (!context) - abort (); + abort (); } context_string = context_str (context); @@ -183,15 +183,15 @@ change_file_context (int fd, char const *file) if (file_context == NULL || ! STREQ (context_string, file_context)) { int fail = (affect_symlink_referent - ? setfileconat (fd, file, context_string) - : lsetfileconat (fd, file, context_string)); + ? setfileconat (fd, file, context_string) + : lsetfileconat (fd, file, context_string)); if (fail) - { - errors = 1; - error (0, errno, _("failed to change context of %s to %s"), - quote_n (0, file), quote_n (1, context_string)); - } + { + errors = 1; + error (0, errno, _("failed to change context of %s to %s"), + quote_n (0, file), quote_n (1, context_string)); + } } context_free (context); @@ -216,41 +216,41 @@ process_file (FTS *fts, FTSENT *ent) { case FTS_D: if (recurse) - { - if (ROOT_DEV_INO_CHECK (root_dev_ino, ent->fts_statp)) - { - /* This happens e.g., with "chcon -R --preserve-root ... /" - and with "chcon -RH --preserve-root ... symlink-to-root". */ - ROOT_DEV_INO_WARN (file_full_name); - /* Tell fts not to traverse into this hierarchy. */ - fts_set (fts, ent, FTS_SKIP); - /* Ensure that we do not process "/" on the second visit. */ - ent = fts_read (fts); - return false; - } - return true; - } + { + if (ROOT_DEV_INO_CHECK (root_dev_ino, ent->fts_statp)) + { + /* This happens e.g., with "chcon -R --preserve-root ... /" + and with "chcon -RH --preserve-root ... symlink-to-root". */ + ROOT_DEV_INO_WARN (file_full_name); + /* Tell fts not to traverse into this hierarchy. */ + fts_set (fts, ent, FTS_SKIP); + /* Ensure that we do not process "/" on the second visit. */ + ent = fts_read (fts); + return false; + } + return true; + } break; case FTS_DP: if (! recurse) - return true; + return true; break; case FTS_NS: /* For a top-level file or directory, this FTS_NS (stat failed) - indicator is determined at the time of the initial fts_open call. - With programs like chmod, chown, and chgrp, that modify - permissions, it is possible that the file in question is - accessible when control reaches this point. So, if this is - the first time we've seen the FTS_NS for this file, tell - fts_read to stat it "again". */ + indicator is determined at the time of the initial fts_open call. + With programs like chmod, chown, and chgrp, that modify + permissions, it is possible that the file in question is + accessible when control reaches this point. So, if this is + the first time we've seen the FTS_NS for this file, tell + fts_read to stat it "again". */ if (ent->fts_level == 0 && ent->fts_number == 0) - { - ent->fts_number = 1; - fts_set (fts, ent, FTS_AGAIN); - return true; - } + { + ent->fts_number = 1; + fts_set (fts, ent, FTS_AGAIN); + return true; + } error (0, ent->fts_errno, _("cannot access %s"), quote (file_full_name)); ok = false; break; @@ -262,7 +262,7 @@ process_file (FTS *fts, FTSENT *ent) case FTS_DNR: error (0, ent->fts_errno, _("cannot read directory %s"), - quote (file_full_name)); + quote (file_full_name)); ok = false; break; @@ -280,11 +280,11 @@ process_file (FTS *fts, FTSENT *ent) if (ok) { if (verbose) - printf (_("changing security context of %s\n"), - quote (file_full_name)); + printf (_("changing security context of %s\n"), + quote (file_full_name)); if (change_file_context (fts->fts_cwd_fd, file) != 0) - ok = false; + ok = false; } if ( ! recurse) @@ -310,15 +310,15 @@ process_files (char **files, int bit_flags) ent = fts_read (fts); if (ent == NULL) - { - if (errno != 0) - { - /* FIXME: try to give a better message */ - error (0, errno, _("fts_read failed")); - ok = false; - } - break; - } + { + if (errno != 0) + { + /* FIXME: try to give a better message */ + error (0, errno, _("fts_read failed")); + ok = false; + } + break; + } ok &= process_file (fts, ent); } @@ -336,7 +336,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -344,7 +344,7 @@ Usage: %s [OPTION]... CONTEXT FILE...\n\ or: %s [OPTION]... [-u USER] [-r ROLE] [-l RANGE] [-t TYPE] FILE...\n\ or: %s [OPTION]... --reference=RFILE FILE...\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Change the security context of each FILE to CONTEXT.\n\ With --reference, change the security context of each FILE to that of RFILE.\n\ @@ -410,97 +410,97 @@ main (int argc, char **argv) atexit (close_stdout); while ((optc = getopt_long (argc, argv, "HLPRhvu:r:t:l:", long_options, NULL)) - != -1) + != -1) { switch (optc) - { - case 'H': /* Traverse command-line symlinks-to-directories. */ - bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL; - break; - - case 'L': /* Traverse all symlinks-to-directories. */ - bit_flags = FTS_LOGICAL; - break; - - case 'P': /* Traverse no symlinks-to-directories. */ - bit_flags = FTS_PHYSICAL; - break; - - case 'h': /* --no-dereference: affect symlinks */ - dereference = 0; - break; - - case DEREFERENCE_OPTION: /* --dereference: affect the referent - of each symlink */ - dereference = 1; - break; - - case NO_PRESERVE_ROOT: - preserve_root = false; - break; - - case PRESERVE_ROOT: - preserve_root = true; - break; - - case REFERENCE_FILE_OPTION: - reference_file = optarg; - break; - - case 'R': - recurse = true; - break; - - case 'f': - /* ignore */ - break; - - case 'v': - verbose = true; - break; - - case 'u': - specified_user = optarg; - component_specified = true; - break; - - case 'r': - specified_role = optarg; - component_specified = true; - break; - - case 't': - specified_type = optarg; - component_specified = true; - break; - - case 'l': - specified_range = optarg; - component_specified = true; - break; - - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'H': /* Traverse command-line symlinks-to-directories. */ + bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL; + break; + + case 'L': /* Traverse all symlinks-to-directories. */ + bit_flags = FTS_LOGICAL; + break; + + case 'P': /* Traverse no symlinks-to-directories. */ + bit_flags = FTS_PHYSICAL; + break; + + case 'h': /* --no-dereference: affect symlinks */ + dereference = 0; + break; + + case DEREFERENCE_OPTION: /* --dereference: affect the referent + of each symlink */ + dereference = 1; + break; + + case NO_PRESERVE_ROOT: + preserve_root = false; + break; + + case PRESERVE_ROOT: + preserve_root = true; + break; + + case REFERENCE_FILE_OPTION: + reference_file = optarg; + break; + + case 'R': + recurse = true; + break; + + case 'f': + /* ignore */ + break; + + case 'v': + verbose = true; + break; + + case 'u': + specified_user = optarg; + component_specified = true; + break; + + case 'r': + specified_role = optarg; + component_specified = true; + break; + + case 't': + specified_type = optarg; + component_specified = true; + break; + + case 'l': + specified_range = optarg; + component_specified = true; + break; + + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (recurse) { if (bit_flags == FTS_PHYSICAL) - { - if (dereference == 1) - error (EXIT_FAILURE, 0, - _("-R --dereference requires either -H or -L")); - affect_symlink_referent = false; - } + { + if (dereference == 1) + error (EXIT_FAILURE, 0, + _("-R --dereference requires either -H or -L")); + affect_symlink_referent = false; + } else - { - if (dereference == 0) - error (EXIT_FAILURE, 0, _("-R -h requires -P")); - affect_symlink_referent = true; - } + { + if (dereference == 0) + error (EXIT_FAILURE, 0, _("-R -h requires -P")); + affect_symlink_referent = true; + } } else { @@ -511,17 +511,17 @@ main (int argc, char **argv) if (argc - optind < (reference_file || component_specified ? 1 : 2)) { if (argc <= optind) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } if (reference_file) { if (getfilecon (reference_file, &ref_context) < 0) - error (EXIT_FAILURE, errno, _("failed to get security context of %s"), - quote (reference_file)); + error (EXIT_FAILURE, errno, _("failed to get security context of %s"), + quote (reference_file)); specified_context = ref_context; } @@ -536,8 +536,8 @@ main (int argc, char **argv) specified_context = argv[optind++]; context = context_new (specified_context); if (!context) - error (EXIT_FAILURE, 0, _("invalid context: %s"), - quotearg_colon (specified_context)); + error (EXIT_FAILURE, 0, _("invalid context: %s"), + quotearg_colon (specified_context)); context_free (context); } @@ -552,8 +552,8 @@ main (int argc, char **argv) static struct dev_ino dev_ino_buf; root_dev_ino = get_root_dev_ino (&dev_ino_buf); if (root_dev_ino == NULL) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote ("/")); } else { diff --git a/src/chgrp.c b/src/chgrp.c index 0653a9033..0102ef098 100644 --- a/src/chgrp.c +++ b/src/chgrp.c @@ -84,15 +84,15 @@ parse_group (const char *name) { struct group *grp = getgrnam (name); if (grp) - gid = grp->gr_gid; + gid = grp->gr_gid; else - { - unsigned long int tmp; - if (! (xstrtoul (name, NULL, 10, &tmp, "") == LONGINT_OK - && tmp <= GID_T_MAX)) - error (EXIT_FAILURE, 0, _("invalid group: %s"), quote (name)); - gid = tmp; - } + { + unsigned long int tmp; + if (! (xstrtoul (name, NULL, 10, &tmp, "") == LONGINT_OK + && tmp <= GID_T_MAX)) + error (EXIT_FAILURE, 0, _("invalid group: %s"), quote (name)); + gid = tmp; + } endgrent (); /* Save a file descriptor. */ } @@ -104,14 +104,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... GROUP FILE...\n\ or: %s [OPTION]... --reference=RFILE FILE...\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Change the group of each FILE to GROUP.\n\ With --reference, change the group of each FILE to that of RFILE.\n\ @@ -157,7 +157,7 @@ Examples:\n\ %s staff /u Change the group of /u to \"staff\".\n\ %s -hR staff /u Change the group of /u and subfiles to \"staff\".\n\ "), - program_name, program_name); + program_name, program_name); emit_bug_reporting_address (); } exit (status); @@ -191,75 +191,75 @@ main (int argc, char **argv) chopt_init (&chopt); while ((optc = getopt_long (argc, argv, "HLPRcfhv", long_options, NULL)) - != -1) + != -1) { switch (optc) - { - case 'H': /* Traverse command-line symlinks-to-directories. */ - bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL; - break; - - case 'L': /* Traverse all symlinks-to-directories. */ - bit_flags = FTS_LOGICAL; - break; - - case 'P': /* Traverse no symlinks-to-directories. */ - bit_flags = FTS_PHYSICAL; - break; - - case 'h': /* --no-dereference: affect symlinks */ - dereference = 0; - break; - - case DEREFERENCE_OPTION: /* --dereference: affect the referent - of each symlink */ - dereference = 1; - break; - - case NO_PRESERVE_ROOT: - preserve_root = false; - break; - - case PRESERVE_ROOT: - preserve_root = true; - break; - - case REFERENCE_FILE_OPTION: - reference_file = optarg; - break; - - case 'R': - chopt.recurse = true; - break; - - case 'c': - chopt.verbosity = V_changes_only; - break; - - case 'f': - chopt.force_silent = true; - break; - - case 'v': - chopt.verbosity = V_high; - break; - - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'H': /* Traverse command-line symlinks-to-directories. */ + bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL; + break; + + case 'L': /* Traverse all symlinks-to-directories. */ + bit_flags = FTS_LOGICAL; + break; + + case 'P': /* Traverse no symlinks-to-directories. */ + bit_flags = FTS_PHYSICAL; + break; + + case 'h': /* --no-dereference: affect symlinks */ + dereference = 0; + break; + + case DEREFERENCE_OPTION: /* --dereference: affect the referent + of each symlink */ + dereference = 1; + break; + + case NO_PRESERVE_ROOT: + preserve_root = false; + break; + + case PRESERVE_ROOT: + preserve_root = true; + break; + + case REFERENCE_FILE_OPTION: + reference_file = optarg; + break; + + case 'R': + chopt.recurse = true; + break; + + case 'c': + chopt.verbosity = V_changes_only; + break; + + case 'f': + chopt.force_silent = true; + break; + + case 'v': + chopt.verbosity = V_high; + break; + + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (chopt.recurse) { if (bit_flags == FTS_PHYSICAL) - { - if (dereference == 1) - error (EXIT_FAILURE, 0, - _("-R --dereference requires either -H or -L")); - dereference = 0; - } + { + if (dereference == 1) + error (EXIT_FAILURE, 0, + _("-R --dereference requires either -H or -L")); + dereference = 0; + } } else { @@ -270,9 +270,9 @@ main (int argc, char **argv) if (argc - optind < (reference_file ? 1 : 2)) { if (argc <= optind) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } @@ -280,8 +280,8 @@ main (int argc, char **argv) { struct stat ref_stats; if (stat (reference_file, &ref_stats)) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote (reference_file)); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote (reference_file)); gid = ref_stats.st_gid; chopt.group_name = gid_to_name (ref_stats.st_gid); @@ -298,14 +298,14 @@ main (int argc, char **argv) static struct dev_ino dev_ino_buf; chopt.root_dev_ino = get_root_dev_ino (&dev_ino_buf); if (chopt.root_dev_ino == NULL) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote ("/")); } bit_flags |= FTS_DEFER_STAT; ok = chown_files (argv + optind, bit_flags, - (uid_t) -1, gid, - (uid_t) -1, (gid_t) -1, &chopt); + (uid_t) -1, gid, + (uid_t) -1, (gid_t) -1, &chopt); chopt_free (&chopt); diff --git a/src/chmod.c b/src/chmod.c index 91dfbc3aa..0e39c8b01 100644 --- a/src/chmod.c +++ b/src/chmod.c @@ -115,16 +115,16 @@ mode_changed (char const *file, mode_t old_mode, mode_t new_mode) if (new_mode & (S_ISUID | S_ISGID | S_ISVTX)) { /* The new mode contains unusual bits that the call to chmod may - have silently cleared. Check whether they actually changed. */ + have silently cleared. Check whether they actually changed. */ struct stat new_stats; if (stat (file, &new_stats) != 0) - { - if (! force_silent) - error (0, errno, _("getting new attributes of %s"), quote (file)); - return false; - } + { + if (! force_silent) + error (0, errno, _("getting new attributes of %s"), quote (file)); + return false; + } new_mode = new_stats.st_mode; } @@ -137,7 +137,7 @@ mode_changed (char const *file, mode_t old_mode, mode_t new_mode) static void describe_change (const char *file, mode_t mode, - enum Change_status changed) + enum Change_status changed) { char perms[12]; /* "-rwxrwxrwx" ls-style modes. */ const char *fmt; @@ -145,7 +145,7 @@ describe_change (const char *file, mode_t mode, if (changed == CH_NOT_APPLIED) { printf (_("neither symbolic link %s nor referent has been changed\n"), - quote (file)); + quote (file)); return; } @@ -166,7 +166,7 @@ describe_change (const char *file, mode_t mode, abort (); } printf (fmt, quote (file), - (unsigned long int) (mode & CHMOD_MODE_BITS), &perms[1]); + (unsigned long int) (mode & CHMOD_MODE_BITS), &perms[1]); } /* Change the mode of FILE. @@ -191,21 +191,21 @@ process_file (FTS *fts, FTSENT *ent) case FTS_NS: /* For a top-level file or directory, this FTS_NS (stat failed) - indicator is determined at the time of the initial fts_open call. - With programs like chmod, chown, and chgrp, that modify - permissions, it is possible that the file in question is - accessible when control reaches this point. So, if this is - the first time we've seen the FTS_NS for this file, tell - fts_read to stat it "again". */ + indicator is determined at the time of the initial fts_open call. + With programs like chmod, chown, and chgrp, that modify + permissions, it is possible that the file in question is + accessible when control reaches this point. So, if this is + the first time we've seen the FTS_NS for this file, tell + fts_read to stat it "again". */ if (ent->fts_level == 0 && ent->fts_number == 0) - { - ent->fts_number = 1; - fts_set (fts, ent, FTS_AGAIN); - return true; - } + { + ent->fts_number = 1; + fts_set (fts, ent, FTS_AGAIN); + return true; + } if (! force_silent) error (0, ent->fts_errno, _("cannot access %s"), - quote (file_full_name)); + quote (file_full_name)); ok = false; break; @@ -218,14 +218,14 @@ process_file (FTS *fts, FTSENT *ent) case FTS_DNR: if (! force_silent) error (0, ent->fts_errno, _("cannot read directory %s"), - quote (file_full_name)); + quote (file_full_name)); ok = false; break; case FTS_SLNONE: if (! force_silent) error (0, 0, _("cannot operate on dangling symlink %s"), - quote (file_full_name)); + quote (file_full_name)); ok = false; default: @@ -246,55 +246,55 @@ process_file (FTS *fts, FTSENT *ent) { old_mode = file_stats->st_mode; new_mode = mode_adjust (old_mode, S_ISDIR (old_mode) != 0, umask_value, - change, NULL); + change, NULL); if (! S_ISLNK (old_mode)) - { - if (chmodat (fts->fts_cwd_fd, file, new_mode) == 0) - chmod_succeeded = true; - else - { - if (! force_silent) - error (0, errno, _("changing permissions of %s"), - quote (file_full_name)); - ok = false; - } - } + { + if (chmodat (fts->fts_cwd_fd, file, new_mode) == 0) + chmod_succeeded = true; + else + { + if (! force_silent) + error (0, errno, _("changing permissions of %s"), + quote (file_full_name)); + ok = false; + } + } } if (verbosity != V_off) { bool changed = (chmod_succeeded - && mode_changed (file, old_mode, new_mode)); + && mode_changed (file, old_mode, new_mode)); if (changed || verbosity == V_high) - { - enum Change_status ch_status = - (!ok ? CH_FAILED - : !chmod_succeeded ? CH_NOT_APPLIED - : !changed ? CH_NO_CHANGE_REQUESTED - : CH_SUCCEEDED); - describe_change (file_full_name, new_mode, ch_status); - } + { + enum Change_status ch_status = + (!ok ? CH_FAILED + : !chmod_succeeded ? CH_NOT_APPLIED + : !changed ? CH_NO_CHANGE_REQUESTED + : CH_SUCCEEDED); + describe_change (file_full_name, new_mode, ch_status); + } } if (chmod_succeeded & diagnose_surprises) { mode_t naively_expected_mode = - mode_adjust (old_mode, S_ISDIR (old_mode) != 0, 0, change, NULL); + mode_adjust (old_mode, S_ISDIR (old_mode) != 0, 0, change, NULL); if (new_mode & ~naively_expected_mode) - { - char new_perms[12]; - char naively_expected_perms[12]; - strmode (new_mode, new_perms); - strmode (naively_expected_mode, naively_expected_perms); - new_perms[10] = naively_expected_perms[10] = '\0'; - error (0, 0, - _("%s: new permissions are %s, not %s"), - quotearg_colon (file_full_name), - new_perms + 1, naively_expected_perms + 1); - ok = false; - } + { + char new_perms[12]; + char naively_expected_perms[12]; + strmode (new_mode, new_perms); + strmode (naively_expected_mode, naively_expected_perms); + new_perms[10] = naively_expected_perms[10] = '\0'; + error (0, 0, + _("%s: new permissions are %s, not %s"), + quotearg_colon (file_full_name), + new_perms + 1, naively_expected_perms + 1); + ok = false; + } } if ( ! recurse) @@ -320,16 +320,16 @@ process_files (char **files, int bit_flags) ent = fts_read (fts); if (ent == NULL) - { - if (errno != 0) - { - /* FIXME: try to give a better message */ - if (! force_silent) - error (0, errno, _("fts_read failed")); - ok = false; - } - break; - } + { + if (errno != 0) + { + /* FIXME: try to give a better message */ + if (! force_silent) + error (0, errno, _("fts_read failed")); + ok = false; + } + break; + } ok &= process_file (fts, ent); } @@ -347,7 +347,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -355,7 +355,7 @@ Usage: %s [OPTION]... MODE[,MODE]... FILE...\n\ or: %s [OPTION]... OCTAL-MODE FILE...\n\ or: %s [OPTION]... --reference=RFILE FILE...\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Change the mode of each FILE to MODE.\n\ \n\ @@ -407,99 +407,99 @@ main (int argc, char **argv) recurse = force_silent = diagnose_surprises = false; while ((c = getopt_long (argc, argv, - "Rcfvr::w::x::X::s::t::u::g::o::a::,::+::=::", - long_options, NULL)) - != -1) + "Rcfvr::w::x::X::s::t::u::g::o::a::,::+::=::", + long_options, NULL)) + != -1) { switch (c) - { - case 'r': - case 'w': - case 'x': - case 'X': - case 's': - case 't': - case 'u': - case 'g': - case 'o': - case 'a': - case ',': - case '+': - case '=': - /* Support nonportable uses like "chmod -w", but diagnose - surprises due to umask confusion. Even though "--", "--r", - etc., are valid modes, there is no "case '-'" here since - getopt_long reserves leading "--" for long options. */ - { - /* Allocate a mode string (e.g., "-rwx") by concatenating - the argument containing this option. If a previous mode - string was given, concatenate the previous string, a - comma, and the new string (e.g., "-s,-rwx"). */ - - char const *arg = argv[optind - 1]; - size_t arg_len = strlen (arg); - size_t mode_comma_len = mode_len + !!mode_len; - size_t new_mode_len = mode_comma_len + arg_len; - if (mode_alloc <= new_mode_len) - { - mode_alloc = new_mode_len + 1; - mode = X2REALLOC (mode, &mode_alloc); - } - mode[mode_len] = ','; - strcpy (mode + mode_comma_len, arg); - mode_len = new_mode_len; - - diagnose_surprises = true; - } - break; - case NO_PRESERVE_ROOT: - preserve_root = false; - break; - case PRESERVE_ROOT: - preserve_root = true; - break; - case REFERENCE_FILE_OPTION: - reference_file = optarg; - break; - case 'R': - recurse = true; - break; - case 'c': - verbosity = V_changes_only; - break; - case 'f': - force_silent = true; - break; - case 'v': - verbosity = V_high; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'r': + case 'w': + case 'x': + case 'X': + case 's': + case 't': + case 'u': + case 'g': + case 'o': + case 'a': + case ',': + case '+': + case '=': + /* Support nonportable uses like "chmod -w", but diagnose + surprises due to umask confusion. Even though "--", "--r", + etc., are valid modes, there is no "case '-'" here since + getopt_long reserves leading "--" for long options. */ + { + /* Allocate a mode string (e.g., "-rwx") by concatenating + the argument containing this option. If a previous mode + string was given, concatenate the previous string, a + comma, and the new string (e.g., "-s,-rwx"). */ + + char const *arg = argv[optind - 1]; + size_t arg_len = strlen (arg); + size_t mode_comma_len = mode_len + !!mode_len; + size_t new_mode_len = mode_comma_len + arg_len; + if (mode_alloc <= new_mode_len) + { + mode_alloc = new_mode_len + 1; + mode = X2REALLOC (mode, &mode_alloc); + } + mode[mode_len] = ','; + strcpy (mode + mode_comma_len, arg); + mode_len = new_mode_len; + + diagnose_surprises = true; + } + break; + case NO_PRESERVE_ROOT: + preserve_root = false; + break; + case PRESERVE_ROOT: + preserve_root = true; + break; + case REFERENCE_FILE_OPTION: + reference_file = optarg; + break; + case 'R': + recurse = true; + break; + case 'c': + verbosity = V_changes_only; + break; + case 'f': + force_silent = true; + break; + case 'v': + verbosity = V_high; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (reference_file) { if (mode) - { - error (0, 0, _("cannot combine mode and --reference options")); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("cannot combine mode and --reference options")); + usage (EXIT_FAILURE); + } } else { if (!mode) - mode = argv[optind++]; + mode = argv[optind++]; } if (optind >= argc) { if (!mode || mode != argv[optind - 1]) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } @@ -507,17 +507,17 @@ main (int argc, char **argv) { change = mode_create_from_ref (reference_file); if (!change) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote (reference_file)); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote (reference_file)); } else { change = mode_compile (mode); if (!change) - { - error (0, 0, _("invalid mode: %s"), quote (mode)); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("invalid mode: %s"), quote (mode)); + usage (EXIT_FAILURE); + } umask_value = umask (0); } @@ -526,8 +526,8 @@ main (int argc, char **argv) static struct dev_ino dev_ino_buf; root_dev_ino = get_root_dev_ino (&dev_ino_buf); if (root_dev_ino == NULL) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote ("/")); } else { @@ -535,7 +535,7 @@ main (int argc, char **argv) } ok = process_files (argv + optind, - FTS_COMFOLLOW | FTS_PHYSICAL | FTS_DEFER_STAT); + FTS_COMFOLLOW | FTS_PHYSICAL | FTS_DEFER_STAT); exit (ok ? EXIT_SUCCESS : EXIT_FAILURE); } diff --git a/src/chown-core.c b/src/chown-core.c index 3d6bb0e62..7e5774ee1 100644 --- a/src/chown-core.c +++ b/src/chown-core.c @@ -83,8 +83,8 @@ gid_to_name (gid_t gid) char buf[INT_BUFSIZE_BOUND (intmax_t)]; struct group *grp = getgrgid (gid); return xstrdup (grp ? grp->gr_name - : TYPE_SIGNED (gid_t) ? imaxtostr (gid, buf) - : umaxtostr (gid, buf)); + : TYPE_SIGNED (gid_t) ? imaxtostr (gid, buf) + : umaxtostr (gid, buf)); } /* Convert the numeric user-id, UID, to a string stored in xmalloc'd memory, @@ -97,8 +97,8 @@ uid_to_name (uid_t uid) char buf[INT_BUFSIZE_BOUND (intmax_t)]; struct passwd *pwd = getpwuid (uid); return xstrdup (pwd ? pwd->pw_name - : TYPE_SIGNED (uid_t) ? imaxtostr (uid, buf) - : umaxtostr (uid, buf)); + : TYPE_SIGNED (uid_t) ? imaxtostr (uid, buf) + : umaxtostr (uid, buf)); } /* Tell the user how/if the user and group of FILE have been changed. @@ -107,7 +107,7 @@ uid_to_name (uid_t uid) static void describe_change (const char *file, enum Change_status changed, - char const *user, char const *group) + char const *user, char const *group) { const char *fmt; char const *spec; @@ -116,22 +116,22 @@ describe_change (const char *file, enum Change_status changed, if (changed == CH_NOT_APPLIED) { printf (_("neither symbolic link %s nor referent has been changed\n"), - quote (file)); + quote (file)); return; } if (user) { if (group) - { - spec_allocated = xmalloc (strlen (user) + 1 + strlen (group) + 1); - stpcpy (stpcpy (stpcpy (spec_allocated, user), ":"), group); - spec = spec_allocated; - } + { + spec_allocated = xmalloc (strlen (user) + 1 + strlen (group) + 1); + stpcpy (stpcpy (stpcpy (spec_allocated, user), ":"), group); + spec = spec_allocated; + } else - { - spec = user; - } + { + spec = user; + } } else { @@ -142,18 +142,18 @@ describe_change (const char *file, enum Change_status changed, { case CH_SUCCEEDED: fmt = (user ? _("changed ownership of %s to %s\n") - : group ? _("changed group of %s to %s\n") - : _("no change to ownership of %s\n")); + : group ? _("changed group of %s to %s\n") + : _("no change to ownership of %s\n")); break; case CH_FAILED: fmt = (user ? _("failed to change ownership of %s to %s\n") - : group ? _("failed to change group of %s to %s\n") - : _("failed to change ownership of %s\n")); + : group ? _("failed to change group of %s to %s\n") + : _("failed to change ownership of %s\n")); break; case CH_NO_CHANGE_REQUESTED: fmt = (user ? _("ownership of %s retained as %s\n") - : group ? _("group of %s retained as %s\n") - : _("ownership of %s retained\n")); + : group ? _("group of %s retained as %s\n") + : _("ownership of %s retained\n")); break; default: abort (); @@ -184,9 +184,9 @@ describe_change (const char *file, enum Change_status changed, static enum RCH_status restricted_chown (int cwd_fd, char const *file, - struct stat const *orig_st, - uid_t uid, gid_t gid, - uid_t required_uid, gid_t required_gid) + struct stat const *orig_st, + uid_t uid, gid_t gid, + uid_t required_uid, gid_t required_gid) { enum RCH_status status = RC_ok; struct stat st; @@ -199,15 +199,15 @@ restricted_chown (int cwd_fd, char const *file, if (! S_ISREG (orig_st->st_mode)) { if (S_ISDIR (orig_st->st_mode)) - open_flags |= O_DIRECTORY; + open_flags |= O_DIRECTORY; else - return RC_do_ordinary_chown; + return RC_do_ordinary_chown; } fd = openat (cwd_fd, file, O_RDONLY | open_flags); if (! (0 <= fd - || (errno == EACCES && S_ISREG (orig_st->st_mode) - && 0 <= (fd = openat (cwd_fd, file, O_WRONLY | open_flags))))) + || (errno == EACCES && S_ISREG (orig_st->st_mode) + && 0 <= (fd = openat (cwd_fd, file, O_WRONLY | open_flags))))) return (errno == EACCES ? RC_do_ordinary_chown : RC_error); if (fstat (fd, &st) != 0) @@ -215,18 +215,18 @@ restricted_chown (int cwd_fd, char const *file, else if (! SAME_INODE (*orig_st, st)) status = RC_inode_changed; else if ((required_uid == (uid_t) -1 || required_uid == st.st_uid) - && (required_gid == (gid_t) -1 || required_gid == st.st_gid)) + && (required_gid == (gid_t) -1 || required_gid == st.st_gid)) { if (fchown (fd, uid, gid) == 0) - { - status = (close (fd) == 0 - ? RC_ok : RC_error); - return status; - } + { + status = (close (fd) == 0 + ? RC_ok : RC_error); + return status; + } else - { - status = RC_error; - } + { + status = RC_error; + } } { /* FIXME: remove these curly braces when we assume C99. */ @@ -245,9 +245,9 @@ restricted_chown (int cwd_fd, char const *file, Return true if successful. */ static bool change_file_owner (FTS *fts, FTSENT *ent, - uid_t uid, gid_t gid, - uid_t required_uid, gid_t required_gid, - struct Chown_option const *chopt) + uid_t uid, gid_t gid, + uid_t required_uid, gid_t required_gid, + struct Chown_option const *chopt) { char const *file_full_name = ent->fts_path; char const *file = ent->fts_accpath; @@ -261,44 +261,44 @@ change_file_owner (FTS *fts, FTSENT *ent, { case FTS_D: if (chopt->recurse) - { - if (ROOT_DEV_INO_CHECK (chopt->root_dev_ino, ent->fts_statp)) - { - /* This happens e.g., with "chown -R --preserve-root 0 /" - and with "chown -RH --preserve-root 0 symlink-to-root". */ - ROOT_DEV_INO_WARN (file_full_name); - /* Tell fts not to traverse into this hierarchy. */ - fts_set (fts, ent, FTS_SKIP); - /* Ensure that we do not process "/" on the second visit. */ - ent = fts_read (fts); - return false; - } - return true; - } + { + if (ROOT_DEV_INO_CHECK (chopt->root_dev_ino, ent->fts_statp)) + { + /* This happens e.g., with "chown -R --preserve-root 0 /" + and with "chown -RH --preserve-root 0 symlink-to-root". */ + ROOT_DEV_INO_WARN (file_full_name); + /* Tell fts not to traverse into this hierarchy. */ + fts_set (fts, ent, FTS_SKIP); + /* Ensure that we do not process "/" on the second visit. */ + ent = fts_read (fts); + return false; + } + return true; + } break; case FTS_DP: if (! chopt->recurse) - return true; + return true; break; case FTS_NS: /* For a top-level file or directory, this FTS_NS (stat failed) - indicator is determined at the time of the initial fts_open call. - With programs like chmod, chown, and chgrp, that modify - permissions, it is possible that the file in question is - accessible when control reaches this point. So, if this is - the first time we've seen the FTS_NS for this file, tell - fts_read to stat it "again". */ + indicator is determined at the time of the initial fts_open call. + With programs like chmod, chown, and chgrp, that modify + permissions, it is possible that the file in question is + accessible when control reaches this point. So, if this is + the first time we've seen the FTS_NS for this file, tell + fts_read to stat it "again". */ if (ent->fts_level == 0 && ent->fts_number == 0) - { - ent->fts_number = 1; - fts_set (fts, ent, FTS_AGAIN); - return true; - } + { + ent->fts_number = 1; + fts_set (fts, ent, FTS_AGAIN); + return true; + } if (! chopt->force_silent) error (0, ent->fts_errno, _("cannot access %s"), - quote (file_full_name)); + quote (file_full_name)); ok = false; break; @@ -311,7 +311,7 @@ change_file_owner (FTS *fts, FTSENT *ent, case FTS_DNR: if (! chopt->force_silent) error (0, ent->fts_errno, _("cannot read directory %s"), - quote (file_full_name)); + quote (file_full_name)); ok = false; break; @@ -325,9 +325,9 @@ change_file_owner (FTS *fts, FTSENT *ent, file_stats = NULL; } else if (required_uid == (uid_t) -1 && required_gid == (gid_t) -1 - && chopt->verbosity == V_off - && ! chopt->root_dev_ino - && ! chopt->affect_symlink_referent) + && chopt->verbosity == V_off + && ! chopt->root_dev_ino + && ! chopt->affect_symlink_referent) { do_chown = true; file_stats = ent->fts_statp; @@ -337,25 +337,25 @@ change_file_owner (FTS *fts, FTSENT *ent, file_stats = ent->fts_statp; /* If this is a symlink and we're dereferencing them, - stat it to get info on the referent. */ + stat it to get info on the referent. */ if (chopt->affect_symlink_referent && S_ISLNK (file_stats->st_mode)) - { - if (fstatat (fts->fts_cwd_fd, file, &stat_buf, 0) != 0) - { - if (! chopt->force_silent) - error (0, errno, _("cannot dereference %s"), - quote (file_full_name)); - ok = false; - } - - file_stats = &stat_buf; - } + { + if (fstatat (fts->fts_cwd_fd, file, &stat_buf, 0) != 0) + { + if (! chopt->force_silent) + error (0, errno, _("cannot dereference %s"), + quote (file_full_name)); + ok = false; + } + + file_stats = &stat_buf; + } do_chown = (ok - && (required_uid == (uid_t) -1 - || required_uid == file_stats->st_uid) - && (required_gid == (gid_t) -1 - || required_gid == file_stats->st_gid)); + && (required_uid == (uid_t) -1 + || required_uid == file_stats->st_uid) + && (required_gid == (gid_t) -1 + || required_gid == file_stats->st_gid)); } /* This happens when chown -LR --preserve-root encounters a symlink-to-/. */ @@ -370,89 +370,89 @@ change_file_owner (FTS *fts, FTSENT *ent, if (do_chown) { if ( ! chopt->affect_symlink_referent) - { - ok = (lchownat (fts->fts_cwd_fd, file, uid, gid) == 0); - - /* Ignore any error due to lack of support; POSIX requires - this behavior for top-level symbolic links with -h, and - implies that it's required for all symbolic links. */ - if (!ok && errno == EOPNOTSUPP) - { - ok = true; - symlink_changed = false; - } - } + { + ok = (lchownat (fts->fts_cwd_fd, file, uid, gid) == 0); + + /* Ignore any error due to lack of support; POSIX requires + this behavior for top-level symbolic links with -h, and + implies that it's required for all symbolic links. */ + if (!ok && errno == EOPNOTSUPP) + { + ok = true; + symlink_changed = false; + } + } else - { - /* If possible, avoid a race condition with --from=O:G and without the - (-h) --no-dereference option. If fts's stat call determined - that the uid/gid of FILE matched the --from=O:G-selected - owner and group IDs, blindly using chown(2) here could lead - chown(1) or chgrp(1) mistakenly to dereference a *symlink* - to an arbitrary file that an attacker had moved into the - place of FILE during the window between the stat and - chown(2) calls. If FILE is a regular file or a directory - that can be opened, this race condition can be avoided safely. */ - - enum RCH_status err - = restricted_chown (fts->fts_cwd_fd, file, file_stats, uid, gid, - required_uid, required_gid); - switch (err) - { - case RC_ok: - break; - - case RC_do_ordinary_chown: - ok = (chownat (fts->fts_cwd_fd, file, uid, gid) == 0); - break; - - case RC_error: - ok = false; - break; - - case RC_inode_changed: - /* FIXME: give a diagnostic in this case? */ - case RC_excluded: - do_chown = false; - ok = false; - break; - - default: - abort (); - } - } + { + /* If possible, avoid a race condition with --from=O:G and without the + (-h) --no-dereference option. If fts's stat call determined + that the uid/gid of FILE matched the --from=O:G-selected + owner and group IDs, blindly using chown(2) here could lead + chown(1) or chgrp(1) mistakenly to dereference a *symlink* + to an arbitrary file that an attacker had moved into the + place of FILE during the window between the stat and + chown(2) calls. If FILE is a regular file or a directory + that can be opened, this race condition can be avoided safely. */ + + enum RCH_status err + = restricted_chown (fts->fts_cwd_fd, file, file_stats, uid, gid, + required_uid, required_gid); + switch (err) + { + case RC_ok: + break; + + case RC_do_ordinary_chown: + ok = (chownat (fts->fts_cwd_fd, file, uid, gid) == 0); + break; + + case RC_error: + ok = false; + break; + + case RC_inode_changed: + /* FIXME: give a diagnostic in this case? */ + case RC_excluded: + do_chown = false; + ok = false; + break; + + default: + abort (); + } + } /* On some systems (e.g., GNU/Linux 2.4.x), - the chown function resets the `special' permission bits. - Do *not* restore those bits; doing so would open a window in - which a malicious user, M, could subvert a chown command run - by some other user and operating on files in a directory - where M has write access. */ + the chown function resets the `special' permission bits. + Do *not* restore those bits; doing so would open a window in + which a malicious user, M, could subvert a chown command run + by some other user and operating on files in a directory + where M has write access. */ if (do_chown && !ok && ! chopt->force_silent) - error (0, errno, (uid != (uid_t) -1 - ? _("changing ownership of %s") - : _("changing group of %s")), - quote (file_full_name)); + error (0, errno, (uid != (uid_t) -1 + ? _("changing ownership of %s") + : _("changing group of %s")), + quote (file_full_name)); } if (chopt->verbosity != V_off) { bool changed = - ((do_chown & ok & symlink_changed) - && ! ((uid == (uid_t) -1 || uid == file_stats->st_uid) - && (gid == (gid_t) -1 || gid == file_stats->st_gid))); + ((do_chown & ok & symlink_changed) + && ! ((uid == (uid_t) -1 || uid == file_stats->st_uid) + && (gid == (gid_t) -1 || gid == file_stats->st_gid))); if (changed || chopt->verbosity == V_high) - { - enum Change_status ch_status = - (!ok ? CH_FAILED - : !symlink_changed ? CH_NOT_APPLIED - : !changed ? CH_NO_CHANGE_REQUESTED - : CH_SUCCEEDED); - describe_change (file_full_name, ch_status, - chopt->user_name, chopt->group_name); - } + { + enum Change_status ch_status = + (!ok ? CH_FAILED + : !symlink_changed ? CH_NOT_APPLIED + : !changed ? CH_NO_CHANGE_REQUESTED + : CH_SUCCEEDED); + describe_change (file_full_name, ch_status, + chopt->user_name, chopt->group_name); + } } if ( ! chopt->recurse) @@ -472,18 +472,18 @@ change_file_owner (FTS *fts, FTSENT *ent, Return true if successful. */ extern bool chown_files (char **files, int bit_flags, - uid_t uid, gid_t gid, - uid_t required_uid, gid_t required_gid, - struct Chown_option const *chopt) + uid_t uid, gid_t gid, + uid_t required_uid, gid_t required_gid, + struct Chown_option const *chopt) { bool ok = true; /* Use lstat and stat only if they're needed. */ int stat_flags = ((required_uid != (uid_t) -1 || required_gid != (gid_t) -1 - || chopt->affect_symlink_referent - || chopt->verbosity != V_off) - ? 0 - : FTS_NOSTAT); + || chopt->affect_symlink_referent + || chopt->verbosity != V_off) + ? 0 + : FTS_NOSTAT); FTS *fts = xfts_open (files, bit_flags | stat_flags, NULL); @@ -493,19 +493,19 @@ chown_files (char **files, int bit_flags, ent = fts_read (fts); if (ent == NULL) - { - if (errno != 0) - { - /* FIXME: try to give a better message */ - if (! chopt->force_silent) - error (0, errno, _("fts_read failed")); - ok = false; - } - break; - } + { + if (errno != 0) + { + /* FIXME: try to give a better message */ + if (! chopt->force_silent) + error (0, errno, _("fts_read failed")); + ok = false; + } + break; + } ok &= change_file_owner (fts, ent, uid, gid, - required_uid, required_gid, chopt); + required_uid, required_gid, chopt); } /* Ignore failure, since the only way it can do so is in failing to diff --git a/src/chown-core.h b/src/chown-core.h index 2c6998e35..4947cad29 100644 --- a/src/chown-core.h +++ b/src/chown-core.h @@ -79,8 +79,8 @@ uid_to_name (uid_t); bool chown_files (char **files, int bit_flags, - uid_t uid, gid_t gid, - uid_t required_uid, gid_t required_gid, - struct Chown_option const *chopt); + uid_t uid, gid_t gid, + uid_t required_uid, gid_t required_gid, + struct Chown_option const *chopt); #endif /* CHOWN_CORE_H */ diff --git a/src/chown.c b/src/chown.c index 00cdb242b..35488d90e 100644 --- a/src/chown.c +++ b/src/chown.c @@ -85,14 +85,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [OWNER][:[GROUP]] FILE...\n\ or: %s [OPTION]... --reference=RFILE FILE...\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Change the owner and/or group of each FILE to OWNER and/or GROUP.\n\ With --reference, change the owner and group of each FILE to those of RFILE.\n\ @@ -152,7 +152,7 @@ Examples:\n\ %s root:staff /u Likewise, but also change its group to \"staff\".\n\ %s -hR root /u Change the owner of /u and subfiles to \"root\".\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); emit_bug_reporting_address (); } exit (status); @@ -193,86 +193,86 @@ main (int argc, char **argv) chopt_init (&chopt); while ((optc = getopt_long (argc, argv, "HLPRcfhv", long_options, NULL)) - != -1) + != -1) { switch (optc) - { - case 'H': /* Traverse command-line symlinks-to-directories. */ - bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL; - break; - - case 'L': /* Traverse all symlinks-to-directories. */ - bit_flags = FTS_LOGICAL; - break; - - case 'P': /* Traverse no symlinks-to-directories. */ - bit_flags = FTS_PHYSICAL; - break; - - case 'h': /* --no-dereference: affect symlinks */ - dereference = 0; - break; - - case DEREFERENCE_OPTION: /* --dereference: affect the referent - of each symlink */ - dereference = 1; - break; - - case NO_PRESERVE_ROOT: - preserve_root = false; - break; - - case PRESERVE_ROOT: - preserve_root = true; - break; - - case REFERENCE_FILE_OPTION: - reference_file = optarg; - break; - - case FROM_OPTION: - { - char *u_dummy, *g_dummy; - const char *e = parse_user_spec (optarg, - &required_uid, &required_gid, - &u_dummy, &g_dummy); - if (e) - error (EXIT_FAILURE, 0, "%s: %s", e, quote (optarg)); - break; - } - - case 'R': - chopt.recurse = true; - break; - - case 'c': - chopt.verbosity = V_changes_only; - break; - - case 'f': - chopt.force_silent = true; - break; - - case 'v': - chopt.verbosity = V_high; - break; - - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'H': /* Traverse command-line symlinks-to-directories. */ + bit_flags = FTS_COMFOLLOW | FTS_PHYSICAL; + break; + + case 'L': /* Traverse all symlinks-to-directories. */ + bit_flags = FTS_LOGICAL; + break; + + case 'P': /* Traverse no symlinks-to-directories. */ + bit_flags = FTS_PHYSICAL; + break; + + case 'h': /* --no-dereference: affect symlinks */ + dereference = 0; + break; + + case DEREFERENCE_OPTION: /* --dereference: affect the referent + of each symlink */ + dereference = 1; + break; + + case NO_PRESERVE_ROOT: + preserve_root = false; + break; + + case PRESERVE_ROOT: + preserve_root = true; + break; + + case REFERENCE_FILE_OPTION: + reference_file = optarg; + break; + + case FROM_OPTION: + { + char *u_dummy, *g_dummy; + const char *e = parse_user_spec (optarg, + &required_uid, &required_gid, + &u_dummy, &g_dummy); + if (e) + error (EXIT_FAILURE, 0, "%s: %s", e, quote (optarg)); + break; + } + + case 'R': + chopt.recurse = true; + break; + + case 'c': + chopt.verbosity = V_changes_only; + break; + + case 'f': + chopt.force_silent = true; + break; + + case 'v': + chopt.verbosity = V_high; + break; + + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (chopt.recurse) { if (bit_flags == FTS_PHYSICAL) - { - if (dereference == 1) - error (EXIT_FAILURE, 0, - _("-R --dereference requires either -H or -L")); - dereference = 0; - } + { + if (dereference == 1) + error (EXIT_FAILURE, 0, + _("-R --dereference requires either -H or -L")); + dereference = 0; + } } else { @@ -283,9 +283,9 @@ main (int argc, char **argv) if (argc - optind < (reference_file ? 1 : 2)) { if (argc <= optind) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } @@ -293,8 +293,8 @@ main (int argc, char **argv) { struct stat ref_stats; if (stat (reference_file, &ref_stats)) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote (reference_file)); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote (reference_file)); uid = ref_stats.st_uid; gid = ref_stats.st_gid; @@ -304,13 +304,13 @@ main (int argc, char **argv) else { const char *e = parse_user_spec (argv[optind], &uid, &gid, - &chopt.user_name, &chopt.group_name); + &chopt.user_name, &chopt.group_name); if (e) error (EXIT_FAILURE, 0, "%s: %s", e, quote (argv[optind])); /* If a group is specified but no user, set the user name to the - empty string so that diagnostics say "ownership :GROUP" - rather than "group GROUP". */ + empty string so that diagnostics say "ownership :GROUP" + rather than "group GROUP". */ if (!chopt.user_name && chopt.group_name) chopt.user_name = bad_cast (""); @@ -322,14 +322,14 @@ main (int argc, char **argv) static struct dev_ino dev_ino_buf; chopt.root_dev_ino = get_root_dev_ino (&dev_ino_buf); if (chopt.root_dev_ino == NULL) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote ("/")); } bit_flags |= FTS_DEFER_STAT; ok = chown_files (argv + optind, bit_flags, - uid, gid, - required_uid, required_gid, &chopt); + uid, gid, + required_uid, required_gid, &chopt); chopt_free (&chopt); diff --git a/src/chroot.c b/src/chroot.c index b773f0db6..3fa26f8da 100644 --- a/src/chroot.c +++ b/src/chroot.c @@ -118,7 +118,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -164,7 +164,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); while ((c = getopt_long (argc, argv, "+", long_opts, NULL)) != -1) { @@ -189,7 +189,7 @@ main (int argc, char **argv) if (chroot (argv[optind]) != 0) error (EXIT_FAILURE, errno, _("cannot change root directory to %s"), - argv[optind]); + argv[optind]); if (chdir ("/")) error (EXIT_FAILURE, errno, _("cannot chdir to root directory")); @@ -199,7 +199,7 @@ main (int argc, char **argv) /* No command. Run an interactive shell. */ char *shell = getenv ("SHELL"); if (shell == NULL) - shell = bad_cast ("/bin/sh"); + shell = bad_cast ("/bin/sh"); argv[0] = shell; argv[1] = bad_cast ("-i"); argv[2] = NULL; diff --git a/src/cksum.c b/src/cksum.c index da1faedf8..25cdb4789 100644 --- a/src/cksum.c +++ b/src/cksum.c @@ -58,8 +58,8 @@ The i bit in GEN is set if X^i is a summand of G(X) except X^32. */ # define GEN (BIT (26) | BIT (23) | BIT (22) | BIT (16) | BIT (12) \ - | BIT (11) | BIT (10) | BIT (8) | BIT (7) | BIT (5) \ - | BIT (4) | BIT (2) | BIT (1) | BIT (0)) + | BIT (11) | BIT (10) | BIT (8) | BIT (7) | BIT (5) \ + | BIT (4) | BIT (2) | BIT (1) | BIT (0)) static uint_fast32_t r[8]; @@ -96,9 +96,9 @@ main (void) for (i = 0; i < 51; i++) { printf (",\n 0x%08x, 0x%08x, 0x%08x, 0x%08x, 0x%08x", - crc_remainder (i * 5 + 1), crc_remainder (i * 5 + 2), - crc_remainder (i * 5 + 3), crc_remainder (i * 5 + 4), - crc_remainder (i * 5 + 5)); + crc_remainder (i * 5 + 1), crc_remainder (i * 5 + 2), + crc_remainder (i * 5 + 3), crc_remainder (i * 5 + 4), + crc_remainder (i * 5 + 5)); } printf ("\n};\n"); exit (EXIT_SUCCESS); @@ -193,16 +193,16 @@ cksum (const char *file, bool print_name) fp = stdin; have_read_stdin = true; if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); } else { fp = fopen (file, (O_BINARY ? "rb" : "r")); if (fp == NULL) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } } while ((bytes_read = fread (buf, 1, BUFLEN, fp)) > 0) @@ -210,19 +210,19 @@ cksum (const char *file, bool print_name) unsigned char *cp = buf; if (length + bytes_read < length) - error (EXIT_FAILURE, 0, _("%s: file too long"), file); + error (EXIT_FAILURE, 0, _("%s: file too long"), file); length += bytes_read; while (bytes_read--) - crc = (crc << 8) ^ crctab[((crc >> 24) ^ *cp++) & 0xFF]; + crc = (crc << 8) ^ crctab[((crc >> 24) ^ *cp++) & 0xFF]; if (feof (fp)) - break; + break; } if (ferror (fp)) { error (0, errno, "%s", file); if (!STREQ (file, "-")) - fclose (fp); + fclose (fp); return false; } @@ -255,14 +255,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [FILE]...\n\ or: %s [OPTION]\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Print CRC checksum and byte counts of each FILE.\n\ \n\ @@ -289,7 +289,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -301,7 +301,7 @@ main (int argc, char **argv) { ok = true; for (i = optind; i < argc; i++) - ok &= cksum (argv[i], true); + ok &= cksum (argv[i], true); } if (have_read_stdin && fclose (stdin) == EOF) diff --git a/src/comm.c b/src/comm.c index e37cf8875..63b6b0c26 100644 --- a/src/comm.c +++ b/src/comm.c @@ -96,13 +96,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... FILE1 FILE2\n\ "), - program_name); + program_name); fputs (_("\ Compare sorted files FILE1 and FILE2 line by line.\n\ "), stdout); @@ -139,7 +139,7 @@ Examples:\n\ %s -12 file1 file2 Print only lines present in both file1 and file2.\n\ %s -3 file1 file2 Print lines in file1 not in file2, and vice versa.\n\ "), - program_name, program_name); + program_name, program_name); emit_bug_reporting_address (); } exit (status); @@ -157,26 +157,26 @@ writeline (struct linebuffer const *line, FILE *stream, int class) { case 1: if (!only_file_1) - return; + return; break; case 2: if (!only_file_2) - return; + return; /* Print a delimiter if we are printing lines from file 1. */ if (only_file_1) - fputs (delimiter, stream); + fputs (delimiter, stream); break; case 3: if (!both) - return; + return; /* Print a delimiter if we are printing lines from file 1. */ if (only_file_1) - fputs (delimiter, stream); + fputs (delimiter, stream); /* Print a delimiter if we are printing lines from file 2. */ if (only_file_2) - fputs (delimiter, stream); + fputs (delimiter, stream); break; } @@ -196,35 +196,35 @@ writeline (struct linebuffer const *line, FILE *stream, int class) static void check_order (struct linebuffer const *prev, - struct linebuffer const *current, - int whatfile) + struct linebuffer const *current, + int whatfile) { if (check_input_order != CHECK_ORDER_DISABLED && ((check_input_order == CHECK_ORDER_ENABLED) || seen_unpairable)) { if (!issued_disorder_warning[whatfile - 1]) - { - int order; - - if (hard_LC_COLLATE) - order = xmemcoll (prev->buffer, prev->length - 1, - current->buffer, current->length - 1); - else - order = memcmp2 (prev->buffer, prev->length - 1, - current->buffer, current->length - 1); - - if (0 < order) - { - error ((check_input_order == CHECK_ORDER_ENABLED - ? EXIT_FAILURE : 0), - 0, _("file %d is not in sorted order"), whatfile); - - /* If we get to here, the message was just a warning, but we - want only to issue it once. */ - issued_disorder_warning[whatfile - 1] = true; - } - } + { + int order; + + if (hard_LC_COLLATE) + order = xmemcoll (prev->buffer, prev->length - 1, + current->buffer, current->length - 1); + else + order = memcmp2 (prev->buffer, prev->length - 1, + current->buffer, current->length - 1); + + if (0 < order) + { + error ((check_input_order == CHECK_ORDER_ENABLED + ? EXIT_FAILURE : 0), + 0, _("file %d is not in sorted order"), whatfile); + + /* If we get to here, the message was just a warning, but we + want only to issue it once. */ + issued_disorder_warning[whatfile - 1] = true; + } + } } } @@ -260,20 +260,20 @@ compare_files (char **infiles) for (i = 0; i < 2; i++) { for (j = 0; j < 4; j++) - { - initbuffer (&lba[i][j]); - all_line[i][j] = &lba[i][j]; - } + { + initbuffer (&lba[i][j]); + all_line[i][j] = &lba[i][j]; + } alt[i][0] = 0; alt[i][1] = 0; alt[i][2] = 0; streams[i] = (STREQ (infiles[i], "-") ? stdin : fopen (infiles[i], "r")); if (!streams[i]) - error (EXIT_FAILURE, errno, "%s", infiles[i]); + error (EXIT_FAILURE, errno, "%s", infiles[i]); thisline[i] = readlinebuffer (all_line[i][alt[i][0]], streams[i]); if (ferror (streams[i])) - error (EXIT_FAILURE, errno, "%s", infiles[i]); + error (EXIT_FAILURE, errno, "%s", infiles[i]); } while (thisline[0] || thisline[1]) @@ -284,69 +284,69 @@ compare_files (char **infiles) /* Compare the next available lines of the two files. */ if (!thisline[0]) - order = 1; + order = 1; else if (!thisline[1]) - order = -1; + order = -1; else - { - if (hard_LC_COLLATE) - order = xmemcoll (thisline[0]->buffer, thisline[0]->length - 1, - thisline[1]->buffer, thisline[1]->length - 1); - else - { - size_t len = min (thisline[0]->length, thisline[1]->length) - 1; - order = memcmp (thisline[0]->buffer, thisline[1]->buffer, len); - if (order == 0) - order = (thisline[0]->length < thisline[1]->length - ? -1 - : thisline[0]->length != thisline[1]->length); - } - } + { + if (hard_LC_COLLATE) + order = xmemcoll (thisline[0]->buffer, thisline[0]->length - 1, + thisline[1]->buffer, thisline[1]->length - 1); + else + { + size_t len = min (thisline[0]->length, thisline[1]->length) - 1; + order = memcmp (thisline[0]->buffer, thisline[1]->buffer, len); + if (order == 0) + order = (thisline[0]->length < thisline[1]->length + ? -1 + : thisline[0]->length != thisline[1]->length); + } + } /* Output the line that is lesser. */ if (order == 0) - writeline (thisline[1], stdout, 3); + writeline (thisline[1], stdout, 3); else - { - seen_unpairable = true; - if (order <= 0) - writeline (thisline[0], stdout, 1); - else - writeline (thisline[1], stdout, 2); - } + { + seen_unpairable = true; + if (order <= 0) + writeline (thisline[0], stdout, 1); + else + writeline (thisline[1], stdout, 2); + } /* Step the file the line came from. - If the files match, step both files. */ + If the files match, step both files. */ if (0 <= order) - fill_up[1] = true; + fill_up[1] = true; if (order <= 0) - fill_up[0] = true; + fill_up[0] = true; for (i = 0; i < 2; i++) - if (fill_up[i]) - { - /* Rotate the buffers for this file. */ - alt[i][2] = alt[i][1]; - alt[i][1] = alt[i][0]; - alt[i][0] = (alt[i][0] + 1) & 0x03; - - thisline[i] = readlinebuffer (all_line[i][alt[i][0]], streams[i]); - - if (thisline[i]) - check_order (all_line[i][alt[i][1]], thisline[i], i + 1); - - /* If this is the end of the file we may need to re-check - the order of the previous two lines, since we might have - discovered an unpairable match since we checked before. */ - else if (all_line[i][alt[i][2]]->buffer) - check_order (all_line[i][alt[i][2]], - all_line[i][alt[i][1]], i + 1); - - if (ferror (streams[i])) - error (EXIT_FAILURE, errno, "%s", infiles[i]); - - fill_up[i] = false; - } + if (fill_up[i]) + { + /* Rotate the buffers for this file. */ + alt[i][2] = alt[i][1]; + alt[i][1] = alt[i][0]; + alt[i][0] = (alt[i][0] + 1) & 0x03; + + thisline[i] = readlinebuffer (all_line[i][alt[i][0]], streams[i]); + + if (thisline[i]) + check_order (all_line[i][alt[i][1]], thisline[i], i + 1); + + /* If this is the end of the file we may need to re-check + the order of the previous two lines, since we might have + discovered an unpairable match since we checked before. */ + else if (all_line[i][alt[i][2]]->buffer) + check_order (all_line[i][alt[i][2]], + all_line[i][alt[i][1]], i + 1); + + if (ferror (streams[i])) + error (EXIT_FAILURE, errno, "%s", infiles[i]); + + fill_up[i] = false; + } } for (i = 0; i < 2; i++) @@ -380,50 +380,50 @@ main (int argc, char **argv) switch (c) { case '1': - only_file_1 = false; - break; + only_file_1 = false; + break; case '2': - only_file_2 = false; - break; + only_file_2 = false; + break; case '3': - both = false; - break; + both = false; + break; case NOCHECK_ORDER_OPTION: - check_input_order = CHECK_ORDER_DISABLED; - break; + check_input_order = CHECK_ORDER_DISABLED; + break; case CHECK_ORDER_OPTION: - check_input_order = CHECK_ORDER_ENABLED; - break; + check_input_order = CHECK_ORDER_ENABLED; + break; case OUTPUT_DELIMITER_OPTION: - if (delimiter && !STREQ (delimiter, optarg)) - error (EXIT_FAILURE, 0, _("multiple delimiters specified")); - delimiter = optarg; - if (!*delimiter) - { - error (EXIT_FAILURE, 0, _("empty %s not allowed"), - quote ("--output-delimiter")); - } - break; + if (delimiter && !STREQ (delimiter, optarg)) + error (EXIT_FAILURE, 0, _("multiple delimiters specified")); + delimiter = optarg; + if (!*delimiter) + { + error (EXIT_FAILURE, 0, _("empty %s not allowed"), + quote ("--output-delimiter")); + } + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } if (argc - optind < 2) { if (argc <= optind) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } diff --git a/src/copy.c b/src/copy.c index b5cf64c6a..238764a39 100644 --- a/src/copy.c +++ b/src/copy.c @@ -104,13 +104,13 @@ struct dir_list #define DEST_INFO_INITIAL_CAPACITY 61 static bool copy_internal (char const *src_name, char const *dst_name, - bool new_dst, dev_t device, - struct dir_list *ancestors, - const struct cp_options *x, - bool command_line_arg, - bool *first_dir_created_per_command_line_arg, - bool *copy_into_self, - bool *rename_succeeded); + bool new_dst, dev_t device, + struct dir_list *ancestors, + const struct cp_options *x, + bool command_line_arg, + bool *first_dir_created_per_command_line_arg, + bool *copy_into_self, + bool *rename_succeeded); static bool owner_failure_ok (struct cp_options const *x); /* Pointers to the file names: they're used in the diagnostic that is issued @@ -165,7 +165,7 @@ is_ancestor (const struct stat *sb, const struct dir_list *ancestors) while (ancestors != 0) { if (ancestors->ino == sb->st_ino && ancestors->dev == sb->st_dev) - return true; + return true; ancestors = ancestors->parent; } return false; @@ -180,7 +180,7 @@ errno_unsupported (int err) #if USE_XATTR static void copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED, - char const *fmt, ...) + char const *fmt, ...) { int err = errno; va_list ap; @@ -196,7 +196,7 @@ copy_attr_error (struct error_context *ctx ATTRIBUTE_UNUSED, static void copy_attr_allerror (struct error_context *ctx ATTRIBUTE_UNUSED, - char const *fmt, ...) + char const *fmt, ...) { int err = errno; va_list ap; @@ -215,7 +215,7 @@ copy_attr_quote (struct error_context *ctx ATTRIBUTE_UNUSED, char const *str) static void copy_attr_free (struct error_context *ctx ATTRIBUTE_UNUSED, - char const *str ATTRIBUTE_UNUSED) + char const *str ATTRIBUTE_UNUSED) { } @@ -276,10 +276,10 @@ copy_attr_by_name (char const *src_path, char const *dst_path, static bool copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst, - const struct stat *src_sb, struct dir_list *ancestors, - const struct cp_options *x, - bool *first_dir_created_per_command_line_arg, - bool *copy_into_self) + const struct stat *src_sb, struct dir_list *ancestors, + const struct cp_options *x, + bool *first_dir_created_per_command_line_arg, + bool *copy_into_self) { char *name_space; char *namep; @@ -308,19 +308,19 @@ copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst, char *dst_name = file_name_concat (dst_name_in, namep, NULL); ok &= copy_internal (src_name, dst_name, new_dst, src_sb->st_dev, - ancestors, &non_command_line_options, false, - first_dir_created_per_command_line_arg, - &local_copy_into_self, NULL); + ancestors, &non_command_line_options, false, + first_dir_created_per_command_line_arg, + &local_copy_into_self, NULL); *copy_into_self |= local_copy_into_self; free (dst_name); free (src_name); /* If we're copying into self, there's no point in continuing, - and in fact, that would even infloop, now that we record only - the first created directory per command line argument. */ + and in fact, that would even infloop, now that we record only + the first created directory per command line argument. */ if (local_copy_into_self) - break; + break; namep += strlen (namep) + 1; } @@ -342,8 +342,8 @@ copy_dir (char const *src_name_in, char const *dst_name_in, bool new_dst, static int set_owner (const struct cp_options *x, char const *dst_name, int dest_desc, - struct stat const *src_sb, bool new_dst, - struct stat const *dst_sb) + struct stat const *src_sb, bool new_dst, + struct stat const *dst_sb) { uid_t uid = src_sb->st_uid; gid_t gid = src_sb->st_gid; @@ -358,28 +358,28 @@ set_owner (const struct cp_options *x, char const *dst_name, int dest_desc, { mode_t old_mode = dst_sb->st_mode; mode_t new_mode = - (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode); + (x->preserve_mode | x->move_mode ? src_sb->st_mode : x->mode); mode_t restrictive_temp_mode = old_mode & new_mode & S_IRWXU; if ((USE_ACL - || (old_mode & CHMOD_MODE_BITS - & (~new_mode | S_ISUID | S_ISGID | S_ISVTX))) - && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0) - { - if (! owner_failure_ok (x)) - error (0, errno, _("clearing permissions for %s"), quote (dst_name)); - return -x->require_preserve; - } + || (old_mode & CHMOD_MODE_BITS + & (~new_mode | S_ISUID | S_ISGID | S_ISVTX))) + && qset_acl (dst_name, dest_desc, restrictive_temp_mode) != 0) + { + if (! owner_failure_ok (x)) + error (0, errno, _("clearing permissions for %s"), quote (dst_name)); + return -x->require_preserve; + } } if (HAVE_FCHOWN && dest_desc != -1) { if (fchown (dest_desc, uid, gid) == 0) - return 1; + return 1; if (errno == EPERM || errno == EINVAL) { - /* We've failed to set *both*. Now, try to set just the group - ID, but ignore any failure here, and don't change errno. */ + /* We've failed to set *both*. Now, try to set just the group + ID, but ignore any failure here, and don't change errno. */ int saved_errno = errno; ignore_value (fchown (dest_desc, -1, gid)); errno = saved_errno; @@ -388,11 +388,11 @@ set_owner (const struct cp_options *x, char const *dst_name, int dest_desc, else { if (lchown (dst_name, uid, gid) == 0) - return 1; + return 1; if (errno == EPERM || errno == EINVAL) { - /* We've failed to set *both*. Now, try to set just the group - ID, but ignore any failure here, and don't change errno. */ + /* We've failed to set *both*. Now, try to set just the group + ID, but ignore any failure here, and don't change errno. */ int saved_errno = errno; ignore_value (lchown (dst_name, -1, gid)); errno = saved_errno; @@ -402,9 +402,9 @@ set_owner (const struct cp_options *x, char const *dst_name, int dest_desc, if (! chown_failure_ok (x)) { error (0, errno, _("failed to preserve ownership for %s"), - quote (dst_name)); + quote (dst_name)); if (x->require_preserve) - return -1; + return -1; } return 0; @@ -424,16 +424,16 @@ set_author (const char *dst_name, int dest_desc, const struct stat *src_sb) /* Preserve the st_author field. */ file_t file = (dest_desc < 0 - ? file_name_lookup (dst_name, 0, 0) - : getdport (dest_desc)); + ? file_name_lookup (dst_name, 0, 0) + : getdport (dest_desc)); if (file == MACH_PORT_NULL) error (0, errno, _("failed to lookup file %s"), quote (dst_name)); else { error_t err = file_chauthor (file, src_sb->st_author); if (err) - error (0, err, _("failed to preserve authorship for %s"), - quote (dst_name)); + error (0, err, _("failed to preserve authorship for %s"), + quote (dst_name)); mach_port_deallocate (mach_task_self (), file); } #else @@ -470,9 +470,9 @@ fchmod_or_lchmod (int desc, char const *name, mode_t mode) static bool copy_reg (char const *src_name, char const *dst_name, - const struct cp_options *x, - mode_t dst_mode, mode_t omitted_permissions, bool *new_dst, - struct stat const *src_sb) + const struct cp_options *x, + mode_t dst_mode, mode_t omitted_permissions, bool *new_dst, + struct stat const *src_sb) { char *buf; char *buf_alloc = NULL; @@ -486,8 +486,8 @@ copy_reg (char const *src_name, char const *dst_name, bool return_val = true; source_desc = open (src_name, - (O_RDONLY | O_BINARY - | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0))); + (O_RDONLY | O_BINARY + | (x->dereference == DEREF_NEVER ? O_NOFOLLOW : 0))); if (source_desc < 0) { error (0, errno, _("cannot open %s for reading"), quote (src_name)); @@ -506,8 +506,8 @@ copy_reg (char const *src_name, char const *dst_name, if (! SAME_INODE (*src_sb, src_open_sb)) { error (0, 0, - _("skipping file %s, as it was replaced while being copied"), - quote (src_name)); + _("skipping file %s, as it was replaced while being copied"), + quote (src_name)); return_val = false; goto close_src_desc; } @@ -520,96 +520,96 @@ copy_reg (char const *src_name, char const *dst_name, dest_errno = errno; /* When using cp --preserve=context to copy to an existing destination, - use the default context rather than that of the source. Why? - 1) the src context may prohibit writing, and - 2) because it's more consistent to use the same context - that is used when the destination file doesn't already exist. */ + use the default context rather than that of the source. Why? + 1) the src context may prohibit writing, and + 2) because it's more consistent to use the same context + that is used when the destination file doesn't already exist. */ if (x->preserve_security_context && 0 <= dest_desc) - { - security_context_t con = NULL; - if (getfscreatecon (&con) < 0) - { - if (!x->reduce_diagnostics || x->require_preserve_context) - error (0, errno, _("failed to get file system create context")); - if (x->require_preserve_context) - { - return_val = false; - goto close_src_and_dst_desc; - } - } - - if (con) - { - if (fsetfilecon (dest_desc, con) < 0) - { - if (!x->reduce_diagnostics || x->require_preserve_context) - error (0, errno, - _("failed to set the security context of %s to %s"), - quote_n (0, dst_name), quote_n (1, con)); - if (x->require_preserve_context) - { - return_val = false; - freecon (con); - goto close_src_and_dst_desc; - } - } - freecon (con); - } - } + { + security_context_t con = NULL; + if (getfscreatecon (&con) < 0) + { + if (!x->reduce_diagnostics || x->require_preserve_context) + error (0, errno, _("failed to get file system create context")); + if (x->require_preserve_context) + { + return_val = false; + goto close_src_and_dst_desc; + } + } + + if (con) + { + if (fsetfilecon (dest_desc, con) < 0) + { + if (!x->reduce_diagnostics || x->require_preserve_context) + error (0, errno, + _("failed to set the security context of %s to %s"), + quote_n (0, dst_name), quote_n (1, con)); + if (x->require_preserve_context) + { + return_val = false; + freecon (con); + goto close_src_and_dst_desc; + } + } + freecon (con); + } + } if (dest_desc < 0 && x->unlink_dest_after_failed_open) - { - if (unlink (dst_name) != 0) - { - error (0, errno, _("cannot remove %s"), quote (dst_name)); - return_val = false; - goto close_src_desc; - } - if (x->verbose) - printf (_("removed %s\n"), quote (dst_name)); - - /* Tell caller that the destination file was unlinked. */ - *new_dst = true; - } + { + if (unlink (dst_name) != 0) + { + error (0, errno, _("cannot remove %s"), quote (dst_name)); + return_val = false; + goto close_src_desc; + } + if (x->verbose) + printf (_("removed %s\n"), quote (dst_name)); + + /* Tell caller that the destination file was unlinked. */ + *new_dst = true; + } } if (*new_dst) { int open_flags = O_WRONLY | O_CREAT | O_BINARY; dest_desc = open (dst_name, open_flags | O_EXCL, - dst_mode & ~omitted_permissions); + dst_mode & ~omitted_permissions); dest_errno = errno; /* When trying to copy through a dangling destination symlink, - the above open fails with EEXIST. If that happens, and - lstat'ing the DST_NAME shows that it is a symlink, then we - have a problem: trying to resolve this dangling symlink to - a directory/destination-entry pair is fundamentally racy, - so punt. If POSIXLY_CORRECT is set, simply call open again, - but without O_EXCL (potentially dangerous). If not, fail - with a diagnostic. These shenanigans are necessary only - when copying, i.e., not in move_mode. */ + the above open fails with EEXIST. If that happens, and + lstat'ing the DST_NAME shows that it is a symlink, then we + have a problem: trying to resolve this dangling symlink to + a directory/destination-entry pair is fundamentally racy, + so punt. If POSIXLY_CORRECT is set, simply call open again, + but without O_EXCL (potentially dangerous). If not, fail + with a diagnostic. These shenanigans are necessary only + when copying, i.e., not in move_mode. */ if (dest_desc < 0 && dest_errno == EEXIST && ! x->move_mode) - { - struct stat dangling_link_sb; - if (lstat (dst_name, &dangling_link_sb) == 0 - && S_ISLNK (dangling_link_sb.st_mode)) - { - if (x->open_dangling_dest_symlink) - { - dest_desc = open (dst_name, open_flags, - dst_mode & ~omitted_permissions); - dest_errno = errno; - } - else - { - error (0, 0, _("not writing through dangling symlink %s"), - quote (dst_name)); - return_val = false; - goto close_src_desc; - } - } - } + { + struct stat dangling_link_sb; + if (lstat (dst_name, &dangling_link_sb) == 0 + && S_ISLNK (dangling_link_sb.st_mode)) + { + if (x->open_dangling_dest_symlink) + { + dest_desc = open (dst_name, open_flags, + dst_mode & ~omitted_permissions); + dest_errno = errno; + } + else + { + error (0, 0, _("not writing through dangling symlink %s"), + quote (dst_name)); + return_val = false; + goto close_src_desc; + } + } + } } else omitted_permissions = 0; @@ -617,7 +617,7 @@ copy_reg (char const *src_name, char const *dst_name, if (dest_desc < 0) { error (0, dest_errno, _("cannot create regular file %s"), - quote (dst_name)); + quote (dst_name)); return_val = false; goto close_src_desc; } @@ -654,19 +654,19 @@ copy_reg (char const *src_name, char const *dst_name, if (S_ISREG (sb.st_mode)) { - /* Even with --sparse=always, try to create holes only - if the destination is a regular file. */ - if (x->sparse_mode == SPARSE_ALWAYS) - make_holes = true; + /* Even with --sparse=always, try to create holes only + if the destination is a regular file. */ + if (x->sparse_mode == SPARSE_ALWAYS) + make_holes = true; #if HAVE_STRUCT_STAT_ST_BLOCKS - /* Use a heuristic to determine whether SRC_NAME contains any sparse - blocks. If the file has fewer blocks than would normally be - needed for a file of its size, then at least one of the blocks in - the file is a hole. */ - if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode) - && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE) - make_holes = true; + /* Use a heuristic to determine whether SRC_NAME contains any sparse + blocks. If the file has fewer blocks than would normally be + needed for a file of its size, then at least one of the blocks in + the file is a hole. */ + if (x->sparse_mode == SPARSE_AUTO && S_ISREG (src_open_sb.st_mode) + && ST_NBLOCKS (src_open_sb) < src_open_sb.st_size / ST_NBLOCKSIZE) + make_holes = true; #endif } @@ -674,24 +674,24 @@ copy_reg (char const *src_name, char const *dst_name, buffer size. */ if (! make_holes) { - /* Compute the least common multiple of the input and output - buffer sizes, adjusting for outlandish values. */ - size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop; - size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size, - blcm_max); - - /* Do not bother with a buffer larger than the input file, plus one - byte to make sure the file has not grown while reading it. */ - if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size) - buf_size = src_open_sb.st_size + 1; - - /* However, stick with a block size that is a positive multiple of - blcm, overriding the above adjustments. Watch out for - overflow. */ - buf_size += blcm - 1; - buf_size -= buf_size % blcm; - if (buf_size == 0 || blcm_max < buf_size) - buf_size = blcm; + /* Compute the least common multiple of the input and output + buffer sizes, adjusting for outlandish values. */ + size_t blcm_max = MIN (SIZE_MAX, SSIZE_MAX) - buf_alignment_slop; + size_t blcm = buffer_lcm (io_blksize (src_open_sb), buf_size, + blcm_max); + + /* Do not bother with a buffer larger than the input file, plus one + byte to make sure the file has not grown while reading it. */ + if (S_ISREG (src_open_sb.st_mode) && src_open_sb.st_size < buf_size) + buf_size = src_open_sb.st_size + 1; + + /* However, stick with a block size that is a positive multiple of + blcm, overriding the above adjustments. Watch out for + overflow. */ + buf_size += blcm - 1; + buf_size -= buf_size % blcm; + if (buf_size == 0 || blcm_max < buf_size) + buf_size = blcm; } /* Make a buffer with space for a sentinel at the end. */ @@ -700,85 +700,85 @@ copy_reg (char const *src_name, char const *dst_name, for (;;) { - word *wp = NULL; + word *wp = NULL; - ssize_t n_read = read (source_desc, buf, buf_size); - if (n_read < 0) - { + ssize_t n_read = read (source_desc, buf, buf_size); + if (n_read < 0) + { #ifdef EINTR - if (errno == EINTR) - continue; + if (errno == EINTR) + continue; #endif - error (0, errno, _("reading %s"), quote (src_name)); - return_val = false; - goto close_src_and_dst_desc; - } - if (n_read == 0) - break; + error (0, errno, _("reading %s"), quote (src_name)); + return_val = false; + goto close_src_and_dst_desc; + } + if (n_read == 0) + break; - n_read_total += n_read; + n_read_total += n_read; - if (make_holes) - { - char *cp; + if (make_holes) + { + char *cp; - /* Sentinel to stop loop. */ - buf[n_read] = '\1'; + /* Sentinel to stop loop. */ + buf[n_read] = '\1'; #ifdef lint - /* Usually, buf[n_read] is not the byte just before a "word" - (aka uintptr_t) boundary. In that case, the word-oriented - test below (*wp++ == 0) would read some uninitialized bytes - after the sentinel. To avoid false-positive reports about - this condition (e.g., from a tool like valgrind), set the - remaining bytes -- to any value. */ - memset (buf + n_read + 1, 0, sizeof (word) - 1); + /* Usually, buf[n_read] is not the byte just before a "word" + (aka uintptr_t) boundary. In that case, the word-oriented + test below (*wp++ == 0) would read some uninitialized bytes + after the sentinel. To avoid false-positive reports about + this condition (e.g., from a tool like valgrind), set the + remaining bytes -- to any value. */ + memset (buf + n_read + 1, 0, sizeof (word) - 1); #endif - /* Find first nonzero *word*, or the word with the sentinel. */ - - wp = (word *) buf; - while (*wp++ == 0) - continue; - - /* Find the first nonzero *byte*, or the sentinel. */ - - cp = (char *) (wp - 1); - while (*cp++ == 0) - continue; - - if (cp <= buf + n_read) - /* Clear to indicate that a normal write is needed. */ - wp = NULL; - else - { - /* We found the sentinel, so the whole input block was zero. - Make a hole. */ - if (lseek (dest_desc, n_read, SEEK_CUR) < 0) - { - error (0, errno, _("cannot lseek %s"), quote (dst_name)); - return_val = false; - goto close_src_and_dst_desc; - } - last_write_made_hole = true; - } - } - - if (!wp) - { - size_t n = n_read; - if (full_write (dest_desc, buf, n) != n) - { - error (0, errno, _("writing %s"), quote (dst_name)); - return_val = false; - goto close_src_and_dst_desc; - } - last_write_made_hole = false; + /* Find first nonzero *word*, or the word with the sentinel. */ + + wp = (word *) buf; + while (*wp++ == 0) + continue; + + /* Find the first nonzero *byte*, or the sentinel. */ + + cp = (char *) (wp - 1); + while (*cp++ == 0) + continue; + + if (cp <= buf + n_read) + /* Clear to indicate that a normal write is needed. */ + wp = NULL; + else + { + /* We found the sentinel, so the whole input block was zero. + Make a hole. */ + if (lseek (dest_desc, n_read, SEEK_CUR) < 0) + { + error (0, errno, _("cannot lseek %s"), quote (dst_name)); + return_val = false; + goto close_src_and_dst_desc; + } + last_write_made_hole = true; + } + } + + if (!wp) + { + size_t n = n_read; + if (full_write (dest_desc, buf, n) != n) + { + error (0, errno, _("writing %s"), quote (dst_name)); + return_val = false; + goto close_src_and_dst_desc; + } + last_write_made_hole = false; /* It is tempting to return early here upon a short read from a regular file. That would save the final read syscall for each file. Unfortunately that doesn't work for certain files in /proc with linux kernels from at least 2.6.9 .. 2.6.29. */ - } + } } /* If the file ends with a `hole', we need to do something to record @@ -789,18 +789,18 @@ copy_reg (char const *src_name, char const *dst_name, if (last_write_made_hole) { - if (HAVE_FTRUNCATE - ? /* ftruncate sets the file size, - so there is no need for a write. */ - ftruncate (dest_desc, n_read_total) < 0 - : /* Seek backwards one character and write a null. */ - (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L - || full_write (dest_desc, "", 1) != 1)) - { - error (0, errno, _("writing %s"), quote (dst_name)); - return_val = false; - goto close_src_and_dst_desc; - } + if (HAVE_FTRUNCATE + ? /* ftruncate sets the file size, + so there is no need for a write. */ + ftruncate (dest_desc, n_read_total) < 0 + : /* Seek backwards one character and write a null. */ + (lseek (dest_desc, (off_t) -1, SEEK_CUR) < 0L + || full_write (dest_desc, "", 1) != 1)) + { + error (0, errno, _("writing %s"), quote (dst_name)); + return_val = false; + goto close_src_and_dst_desc; + } } } @@ -811,59 +811,59 @@ copy_reg (char const *src_name, char const *dst_name, timespec[1] = get_stat_mtime (src_sb); if (gl_futimens (dest_desc, dst_name, timespec) != 0) - { - error (0, errno, _("preserving times for %s"), quote (dst_name)); - if (x->require_preserve) - { - return_val = false; - goto close_src_and_dst_desc; - } - } + { + error (0, errno, _("preserving times for %s"), quote (dst_name)); + if (x->require_preserve) + { + return_val = false; + goto close_src_and_dst_desc; + } + } } if (x->preserve_ownership && ! SAME_OWNER_AND_GROUP (*src_sb, sb)) { switch (set_owner (x, dst_name, dest_desc, src_sb, *new_dst, &sb)) - { - case -1: - return_val = false; - goto close_src_and_dst_desc; - - case 0: - src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX); - break; - } + { + case -1: + return_val = false; + goto close_src_and_dst_desc; + + case 0: + src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX); + break; + } } set_author (dst_name, dest_desc, src_sb); if (x->preserve_xattr && ! copy_attr_by_fd (src_name, source_desc, - dst_name, dest_desc, x) + dst_name, dest_desc, x) && x->require_preserve_xattr) return false; if (x->preserve_mode || x->move_mode) { if (copy_acl (src_name, source_desc, dst_name, dest_desc, src_mode) != 0 - && x->require_preserve) - return_val = false; + && x->require_preserve) + return_val = false; } else if (x->set_mode) { if (set_acl (dst_name, dest_desc, x->mode) != 0) - return_val = false; + return_val = false; } else if (omitted_permissions) { omitted_permissions &= ~ cached_umask (); if (omitted_permissions - && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0) - { - error (0, errno, _("preserving permissions for %s"), - quote (dst_name)); - if (x->require_preserve) - return_val = false; - } + && fchmod_or_lchmod (dest_desc, dst_name, dst_mode) != 0) + { + error (0, errno, _("preserving permissions for %s"), + quote (dst_name)); + if (x->require_preserve) + return_val = false; + } } close_src_and_dst_desc: @@ -903,8 +903,8 @@ close_src_desc: static bool same_file_ok (char const *src_name, struct stat const *src_sb, - char const *dst_name, struct stat const *dst_sb, - const struct cp_options *x, bool *return_now, bool *unlink_src) + char const *dst_name, struct stat const *dst_sb, + const struct cp_options *x, bool *return_now, bool *unlink_src) { const struct stat *src_sb_link; const struct stat *dst_sb_link; @@ -933,10 +933,10 @@ same_file_ok (char const *src_name, struct stat const *src_sb, same_link = same; /* If both the source and destination files are symlinks (and we'll - know this here IFF preserving symlinks), then it's ok -- as long - as they are distinct. */ + know this here IFF preserving symlinks), then it's ok -- as long + as they are distinct. */ if (S_ISLNK (src_sb->st_mode) && S_ISLNK (dst_sb->st_mode)) - return ! same_name (src_name, dst_name); + return ! same_name (src_name, dst_name); src_sb_link = src_sb; dst_sb_link = dst_sb; @@ -944,11 +944,11 @@ same_file_ok (char const *src_name, struct stat const *src_sb, else { if (!same) - return true; + return true; if (lstat (dst_name, &tmp_dst_sb) != 0 - || lstat (src_name, &tmp_src_sb) != 0) - return true; + || lstat (src_name, &tmp_src_sb) != 0) + return true; src_sb_link = &tmp_src_sb; dst_sb_link = &tmp_dst_sb; @@ -956,13 +956,13 @@ same_file_ok (char const *src_name, struct stat const *src_sb, same_link = SAME_INODE (*src_sb_link, *dst_sb_link); /* If both are symlinks, then it's ok, but only if the destination - will be unlinked before being opened. This is like the test - above, but with the addition of the unlink_dest_before_opening - conjunct because otherwise, with two symlinks to the same target, - we'd end up truncating the source file. */ + will be unlinked before being opened. This is like the test + above, but with the addition of the unlink_dest_before_opening + conjunct because otherwise, with two symlinks to the same target, + we'd end up truncating the source file. */ if (S_ISLNK (src_sb_link->st_mode) && S_ISLNK (dst_sb_link->st_mode) - && x->unlink_dest_before_opening) - return true; + && x->unlink_dest_before_opening) + return true; } /* The backup code ensures there's a copy, so it's usually ok to @@ -973,31 +973,31 @@ same_file_ok (char const *src_name, struct stat const *src_sb, if (x->backup_type != no_backups) { if (!same_link) - { - /* In copy mode when dereferencing symlinks, if the source is a - symlink and the dest is not, then backing up the destination - (moving it aside) would make it a dangling symlink, and the - subsequent attempt to open it in copy_reg would fail with - a misleading diagnostic. Avoid that by returning zero in - that case so the caller can make cp (or mv when it has to - resort to reading the source file) fail now. */ - - /* FIXME-note: even with the following kludge, we can still provoke - the offending diagnostic. It's just a little harder to do :-) - $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b - cp: cannot open `a' for reading: No such file or directory - That's misleading, since a subsequent `ls' shows that `a' - is still there. - One solution would be to open the source file *before* moving - aside the destination, but that'd involve a big rewrite. */ - if ( ! x->move_mode - && x->dereference != DEREF_NEVER - && S_ISLNK (src_sb_link->st_mode) - && ! S_ISLNK (dst_sb_link->st_mode)) - return false; - - return true; - } + { + /* In copy mode when dereferencing symlinks, if the source is a + symlink and the dest is not, then backing up the destination + (moving it aside) would make it a dangling symlink, and the + subsequent attempt to open it in copy_reg would fail with + a misleading diagnostic. Avoid that by returning zero in + that case so the caller can make cp (or mv when it has to + resort to reading the source file) fail now. */ + + /* FIXME-note: even with the following kludge, we can still provoke + the offending diagnostic. It's just a little harder to do :-) + $ rm -f a b c; touch c; ln -s c b; ln -s b a; cp -b a b + cp: cannot open `a' for reading: No such file or directory + That's misleading, since a subsequent `ls' shows that `a' + is still there. + One solution would be to open the source file *before* moving + aside the destination, but that'd involve a big rewrite. */ + if ( ! x->move_mode + && x->dereference != DEREF_NEVER + && S_ISLNK (src_sb_link->st_mode) + && ! S_ISLNK (dst_sb_link->st_mode)) + return false; + + return true; + } return ! same_name (src_name, dst_name); } @@ -1027,19 +1027,19 @@ same_file_ok (char const *src_name, struct stat const *src_sb, if (x->move_mode || x->unlink_dest_before_opening) { if (S_ISLNK (dst_sb_link->st_mode)) - return true; + return true; if (same_link - && 1 < dst_sb_link->st_nlink - && ! same_name (src_name, dst_name)) - { - if (x->move_mode) - { - *unlink_src = true; - *return_now = true; - } - return true; - } + && 1 < dst_sb_link->st_nlink + && ! same_name (src_name, dst_name)) + { + if (x->move_mode) + { + *unlink_src = true; + *return_now = true; + } + return true; + } } /* If neither is a symlink, then it's ok as long as they aren't @@ -1047,14 +1047,14 @@ same_file_ok (char const *src_name, struct stat const *src_sb, if (!S_ISLNK (src_sb_link->st_mode) && !S_ISLNK (dst_sb_link->st_mode)) { if (!SAME_INODE (*src_sb_link, *dst_sb_link)) - return true; + return true; /* If they are the same file, it's ok if we're making hard links. */ if (x->hard_link) - { - *return_now = true; - return true; - } + { + *return_now = true; + return true; + } } /* It's ok to remove a destination symlink. But that works only when we @@ -1067,24 +1067,24 @@ same_file_ok (char const *src_name, struct stat const *src_sb, if (x->dereference == DEREF_NEVER) { if ( ! S_ISLNK (src_sb_link->st_mode)) - tmp_src_sb = *src_sb_link; + tmp_src_sb = *src_sb_link; else if (stat (src_name, &tmp_src_sb) != 0) - return true; + return true; if ( ! S_ISLNK (dst_sb_link->st_mode)) - tmp_dst_sb = *dst_sb_link; + tmp_dst_sb = *dst_sb_link; else if (stat (dst_name, &tmp_dst_sb) != 0) - return true; + return true; if ( ! SAME_INODE (tmp_src_sb, tmp_dst_sb)) - return true; + return true; /* FIXME: shouldn't this be testing whether we're making symlinks? */ if (x->hard_link) - { - *return_now = true; - return true; - } + { + *return_now = true; + return true; + } } return false; @@ -1096,8 +1096,8 @@ static bool writable_destination (char const *file, mode_t mode) { return (S_ISLNK (mode) - || can_write_any_file () - || euidaccess (file, W_OK) == 0); + || can_write_any_file () + || euidaccess (file, W_OK) == 0); } static void @@ -1109,15 +1109,15 @@ overwrite_prompt (char const *dst_name, struct stat const *dst_sb) strmode (dst_sb->st_mode, perms); perms[10] = '\0'; fprintf (stderr, - _("%s: try to overwrite %s, overriding mode %04lo (%s)? "), - program_name, quote (dst_name), - (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS), - &perms[1]); + _("%s: try to overwrite %s, overriding mode %04lo (%s)? "), + program_name, quote (dst_name), + (unsigned long int) (dst_sb->st_mode & CHMOD_MODE_BITS), + &perms[1]); } else { fprintf (stderr, _("%s: overwrite %s? "), - program_name, quote (dst_name)); + program_name, quote (dst_name)); } } @@ -1128,10 +1128,10 @@ dest_info_init (struct cp_options *x) { x->dest_info = hash_initialize (DEST_INFO_INITIAL_CAPACITY, - NULL, - triple_hash, - triple_compare, - triple_free); + NULL, + triple_hash, + triple_compare, + triple_free); } /* Initialize the hash table implementing a set of F_triple entries @@ -1150,10 +1150,10 @@ src_info_init (struct cp_options *x) */ x->src_info = hash_initialize (DEST_INFO_INITIAL_CAPACITY, - NULL, - triple_hash_no_name, - triple_compare, - triple_free); + NULL, + triple_hash_no_name, + triple_compare, + triple_free); } /* When effecting a move (e.g., for mv(1)), and given the name DST_NAME @@ -1195,7 +1195,7 @@ restore_default_fscreatecon_or_die (void) { if (setfscreatecon (NULL) != 0) error (EXIT_FAILURE, errno, - _("failed to restore the default file creation context")); + _("failed to restore the default file creation context")); } /* Copy the file SRC_NAME to the file DST_NAME. The files may be of @@ -1212,14 +1212,14 @@ restore_default_fscreatecon_or_die (void) Return true if successful. */ static bool copy_internal (char const *src_name, char const *dst_name, - bool new_dst, - dev_t device, - struct dir_list *ancestors, - const struct cp_options *x, - bool command_line_arg, - bool *first_dir_created_per_command_line_arg, - bool *copy_into_self, - bool *rename_succeeded) + bool new_dst, + dev_t device, + struct dir_list *ancestors, + const struct cp_options *x, + bool command_line_arg, + bool *first_dir_created_per_command_line_arg, + bool *copy_into_self, + bool *rename_succeeded) { struct stat src_sb; struct stat dst_sb; @@ -1262,13 +1262,13 @@ copy_internal (char const *src_name, char const *dst_name, if (command_line_arg) { if ( ! S_ISDIR (src_sb.st_mode) - && x->backup_type == no_backups - && seen_file (x->src_info, src_name, &src_sb)) - { - error (0, 0, _("warning: source file %s specified more than once"), - quote (src_name)); - return true; - } + && x->backup_type == no_backups + && seen_file (x->src_info, src_name, &src_sb)) + { + error (0, 0, _("warning: source file %s specified more than once"), + quote (src_name)); + return true; + } record_file (x->src_info, src_name, &src_sb); } @@ -1276,256 +1276,256 @@ copy_internal (char const *src_name, char const *dst_name, if (!new_dst) { /* Regular files can be created by writing through symbolic - links, but other files cannot. So use stat on the - destination when copying a regular file, and lstat otherwise. - However, if we intend to unlink or remove the destination - first, use lstat, since a copy won't actually be made to the - destination in that case. */ + links, but other files cannot. So use stat on the + destination when copying a regular file, and lstat otherwise. + However, if we intend to unlink or remove the destination + first, use lstat, since a copy won't actually be made to the + destination in that case. */ bool use_stat = - ((S_ISREG (src_mode) - || (x->copy_as_regular - && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode)))) - && ! (x->move_mode || x->symbolic_link || x->hard_link - || x->backup_type != no_backups - || x->unlink_dest_before_opening)); + ((S_ISREG (src_mode) + || (x->copy_as_regular + && ! (S_ISDIR (src_mode) || S_ISLNK (src_mode)))) + && ! (x->move_mode || x->symbolic_link || x->hard_link + || x->backup_type != no_backups + || x->unlink_dest_before_opening)); if ((use_stat - ? stat (dst_name, &dst_sb) - : lstat (dst_name, &dst_sb)) - != 0) - { - if (errno != ENOENT) - { - error (0, errno, _("cannot stat %s"), quote (dst_name)); - return false; - } - else - { - new_dst = true; - } - } + ? stat (dst_name, &dst_sb) + : lstat (dst_name, &dst_sb)) + != 0) + { + if (errno != ENOENT) + { + error (0, errno, _("cannot stat %s"), quote (dst_name)); + return false; + } + else + { + new_dst = true; + } + } else - { /* Here, we know that dst_name exists, at least to the point - that it is stat'able or lstat'able. */ - bool return_now; - bool unlink_src; - - have_dst_lstat = !use_stat; - if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb, - x, &return_now, &unlink_src)) - { - error (0, 0, _("%s and %s are the same file"), - quote_n (0, src_name), quote_n (1, dst_name)); - return false; - } - - if (!S_ISDIR (src_mode) && x->update) - { - /* When preserving time stamps (but not moving within a file - system), don't worry if the destination time stamp is - less than the source merely because of time stamp - truncation. */ - int options = ((x->preserve_timestamps - && ! (x->move_mode - && dst_sb.st_dev == src_sb.st_dev)) - ? UTIMECMP_TRUNCATE_SOURCE - : 0); - - if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options)) - { - /* We're using --update and the destination is not older - than the source, so do not copy or move. Pretend the - rename succeeded, so the caller (if it's mv) doesn't - end up removing the source file. */ - if (rename_succeeded) - *rename_succeeded = true; - return true; - } - } - - /* When there is an existing destination file, we may end up - returning early, and hence not copying/moving the file. - This may be due to an interactive `negative' reply to the - prompt about the existing file. It may also be due to the - use of the --reply=no option. - - cp and mv treat -i and -f differently. */ - if (x->move_mode) - { - if (abandon_move (x, dst_name, &dst_sb) - || (unlink_src && unlink (src_name) == 0)) - { - /* Pretend the rename succeeded, so the caller (mv) - doesn't end up removing the source file. */ - if (rename_succeeded) - *rename_succeeded = true; - if (unlink_src && x->verbose) - printf (_("removed %s\n"), quote (src_name)); - return true; - } - if (unlink_src) - { - error (0, errno, _("cannot remove %s"), quote (src_name)); - return false; - } - } - else - { - if (! S_ISDIR (src_mode) - && (x->interactive == I_ALWAYS_NO - || (x->interactive == I_ASK_USER - && (overwrite_prompt (dst_name, &dst_sb), 1) - && ! yesno ()))) - return true; - } - - if (return_now) - return true; - - if (!S_ISDIR (dst_sb.st_mode)) - { - if (S_ISDIR (src_mode)) - { - if (x->move_mode && x->backup_type != no_backups) - { - /* Moving a directory onto an existing - non-directory is ok only with --backup. */ - } - else - { - error (0, 0, - _("cannot overwrite non-directory %s with directory %s"), - quote_n (0, dst_name), quote_n (1, src_name)); - return false; - } - } - - /* Don't let the user destroy their data, even if they try hard: - This mv command must fail (likewise for cp): - rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c - Otherwise, the contents of b/f would be lost. - In the case of `cp', b/f would be lost if the user simulated - a move using cp and rm. - Note that it works fine if you use --backup=numbered. */ - if (command_line_arg - && x->backup_type != numbered_backups - && seen_file (x->dest_info, dst_name, &dst_sb)) - { - error (0, 0, - _("will not overwrite just-created %s with %s"), - quote_n (0, dst_name), quote_n (1, src_name)); - return false; - } - } - - if (!S_ISDIR (src_mode)) - { - if (S_ISDIR (dst_sb.st_mode)) - { - if (x->move_mode && x->backup_type != no_backups) - { - /* Moving a non-directory onto an existing - directory is ok only with --backup. */ - } - else - { - error (0, 0, - _("cannot overwrite directory %s with non-directory"), - quote (dst_name)); - return false; - } - } - } - - if (x->move_mode) - { - /* Don't allow user to move a directory onto a non-directory. */ - if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode) - && x->backup_type == no_backups) - { - error (0, 0, - _("cannot move directory onto non-directory: %s -> %s"), - quote_n (0, src_name), quote_n (0, dst_name)); - return false; - } - } - - if (x->backup_type != no_backups - /* Don't try to back up a destination if the last - component of src_name is "." or "..". */ - && ! dot_or_dotdot (last_component (src_name)) - /* Create a backup of each destination directory in move mode, - but not in copy mode. FIXME: it might make sense to add an - option to suppress backup creation also for move mode. - That would let one use mv to merge new content into an - existing hierarchy. */ - && (x->move_mode || ! S_ISDIR (dst_sb.st_mode))) - { - char *tmp_backup = find_backup_file_name (dst_name, - x->backup_type); - - /* Detect (and fail) when creating the backup file would - destroy the source file. Before, running the commands - cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a - would leave two zero-length files: a and a~. */ - /* FIXME: but simply change e.g., the final a~ to `./a~' - and the source will still be destroyed. */ - if (STREQ (tmp_backup, src_name)) - { - const char *fmt; - fmt = (x->move_mode - ? _("backing up %s would destroy source; %s not moved") - : _("backing up %s would destroy source; %s not copied")); - error (0, 0, fmt, - quote_n (0, dst_name), - quote_n (1, src_name)); - free (tmp_backup); - return false; - } - - /* FIXME: use fts: - Using alloca for a file name that may be arbitrarily - long is not recommended. In fact, even forming such a name - should be discouraged. Eventually, this code will be rewritten - to use fts, so using alloca here will be less of a problem. */ - ASSIGN_STRDUPA (dst_backup, tmp_backup); - free (tmp_backup); - if (rename (dst_name, dst_backup) != 0) - { - if (errno != ENOENT) - { - error (0, errno, _("cannot backup %s"), quote (dst_name)); - return false; - } - else - { - dst_backup = NULL; - } - } - else - { - backup_succeeded = true; - } - new_dst = true; - } - else if (! S_ISDIR (dst_sb.st_mode) - /* Never unlink dst_name when in move mode. */ - && ! x->move_mode - && (x->unlink_dest_before_opening - || (x->preserve_links && 1 < dst_sb.st_nlink) - || (x->dereference == DEREF_NEVER - && ! S_ISREG (src_sb.st_mode)) - )) - { - if (unlink (dst_name) != 0 && errno != ENOENT) - { - error (0, errno, _("cannot remove %s"), quote (dst_name)); - return false; - } - new_dst = true; - if (x->verbose) - printf (_("removed %s\n"), quote (dst_name)); - } - } + { /* Here, we know that dst_name exists, at least to the point + that it is stat'able or lstat'able. */ + bool return_now; + bool unlink_src; + + have_dst_lstat = !use_stat; + if (! same_file_ok (src_name, &src_sb, dst_name, &dst_sb, + x, &return_now, &unlink_src)) + { + error (0, 0, _("%s and %s are the same file"), + quote_n (0, src_name), quote_n (1, dst_name)); + return false; + } + + if (!S_ISDIR (src_mode) && x->update) + { + /* When preserving time stamps (but not moving within a file + system), don't worry if the destination time stamp is + less than the source merely because of time stamp + truncation. */ + int options = ((x->preserve_timestamps + && ! (x->move_mode + && dst_sb.st_dev == src_sb.st_dev)) + ? UTIMECMP_TRUNCATE_SOURCE + : 0); + + if (0 <= utimecmp (dst_name, &dst_sb, &src_sb, options)) + { + /* We're using --update and the destination is not older + than the source, so do not copy or move. Pretend the + rename succeeded, so the caller (if it's mv) doesn't + end up removing the source file. */ + if (rename_succeeded) + *rename_succeeded = true; + return true; + } + } + + /* When there is an existing destination file, we may end up + returning early, and hence not copying/moving the file. + This may be due to an interactive `negative' reply to the + prompt about the existing file. It may also be due to the + use of the --reply=no option. + + cp and mv treat -i and -f differently. */ + if (x->move_mode) + { + if (abandon_move (x, dst_name, &dst_sb) + || (unlink_src && unlink (src_name) == 0)) + { + /* Pretend the rename succeeded, so the caller (mv) + doesn't end up removing the source file. */ + if (rename_succeeded) + *rename_succeeded = true; + if (unlink_src && x->verbose) + printf (_("removed %s\n"), quote (src_name)); + return true; + } + if (unlink_src) + { + error (0, errno, _("cannot remove %s"), quote (src_name)); + return false; + } + } + else + { + if (! S_ISDIR (src_mode) + && (x->interactive == I_ALWAYS_NO + || (x->interactive == I_ASK_USER + && (overwrite_prompt (dst_name, &dst_sb), 1) + && ! yesno ()))) + return true; + } + + if (return_now) + return true; + + if (!S_ISDIR (dst_sb.st_mode)) + { + if (S_ISDIR (src_mode)) + { + if (x->move_mode && x->backup_type != no_backups) + { + /* Moving a directory onto an existing + non-directory is ok only with --backup. */ + } + else + { + error (0, 0, + _("cannot overwrite non-directory %s with directory %s"), + quote_n (0, dst_name), quote_n (1, src_name)); + return false; + } + } + + /* Don't let the user destroy their data, even if they try hard: + This mv command must fail (likewise for cp): + rm -rf a b c; mkdir a b c; touch a/f b/f; mv a/f b/f c + Otherwise, the contents of b/f would be lost. + In the case of `cp', b/f would be lost if the user simulated + a move using cp and rm. + Note that it works fine if you use --backup=numbered. */ + if (command_line_arg + && x->backup_type != numbered_backups + && seen_file (x->dest_info, dst_name, &dst_sb)) + { + error (0, 0, + _("will not overwrite just-created %s with %s"), + quote_n (0, dst_name), quote_n (1, src_name)); + return false; + } + } + + if (!S_ISDIR (src_mode)) + { + if (S_ISDIR (dst_sb.st_mode)) + { + if (x->move_mode && x->backup_type != no_backups) + { + /* Moving a non-directory onto an existing + directory is ok only with --backup. */ + } + else + { + error (0, 0, + _("cannot overwrite directory %s with non-directory"), + quote (dst_name)); + return false; + } + } + } + + if (x->move_mode) + { + /* Don't allow user to move a directory onto a non-directory. */ + if (S_ISDIR (src_sb.st_mode) && !S_ISDIR (dst_sb.st_mode) + && x->backup_type == no_backups) + { + error (0, 0, + _("cannot move directory onto non-directory: %s -> %s"), + quote_n (0, src_name), quote_n (0, dst_name)); + return false; + } + } + + if (x->backup_type != no_backups + /* Don't try to back up a destination if the last + component of src_name is "." or "..". */ + && ! dot_or_dotdot (last_component (src_name)) + /* Create a backup of each destination directory in move mode, + but not in copy mode. FIXME: it might make sense to add an + option to suppress backup creation also for move mode. + That would let one use mv to merge new content into an + existing hierarchy. */ + && (x->move_mode || ! S_ISDIR (dst_sb.st_mode))) + { + char *tmp_backup = find_backup_file_name (dst_name, + x->backup_type); + + /* Detect (and fail) when creating the backup file would + destroy the source file. Before, running the commands + cd /tmp; rm -f a a~; : > a; echo A > a~; cp --b=simple a~ a + would leave two zero-length files: a and a~. */ + /* FIXME: but simply change e.g., the final a~ to `./a~' + and the source will still be destroyed. */ + if (STREQ (tmp_backup, src_name)) + { + const char *fmt; + fmt = (x->move_mode + ? _("backing up %s would destroy source; %s not moved") + : _("backing up %s would destroy source; %s not copied")); + error (0, 0, fmt, + quote_n (0, dst_name), + quote_n (1, src_name)); + free (tmp_backup); + return false; + } + + /* FIXME: use fts: + Using alloca for a file name that may be arbitrarily + long is not recommended. In fact, even forming such a name + should be discouraged. Eventually, this code will be rewritten + to use fts, so using alloca here will be less of a problem. */ + ASSIGN_STRDUPA (dst_backup, tmp_backup); + free (tmp_backup); + if (rename (dst_name, dst_backup) != 0) + { + if (errno != ENOENT) + { + error (0, errno, _("cannot backup %s"), quote (dst_name)); + return false; + } + else + { + dst_backup = NULL; + } + } + else + { + backup_succeeded = true; + } + new_dst = true; + } + else if (! S_ISDIR (dst_sb.st_mode) + /* Never unlink dst_name when in move mode. */ + && ! x->move_mode + && (x->unlink_dest_before_opening + || (x->preserve_links && 1 < dst_sb.st_nlink) + || (x->dereference == DEREF_NEVER + && ! S_ISREG (src_sb.st_mode)) + )) + { + if (unlink (dst_name) != 0 && errno != ENOENT) + { + error (0, errno, _("cannot remove %s"), quote (dst_name)); + return false; + } + new_dst = true; + if (x->verbose) + printf (_("removed %s\n"), quote (dst_name)); + } + } } /* Ensure we don't try to copy through a symlink that was @@ -1540,27 +1540,27 @@ copy_internal (char const *src_name, char const *dst_name, struct stat *dst_lstat_sb; /* If we called lstat above, good: use that data. - Otherwise, call lstat here, in case dst_name is a symlink. */ + Otherwise, call lstat here, in case dst_name is a symlink. */ if (have_dst_lstat) - dst_lstat_sb = &dst_sb; + dst_lstat_sb = &dst_sb; else - { - if (lstat (dst_name, &tmp_buf) == 0) - dst_lstat_sb = &tmp_buf; - else - lstat_ok = false; - } + { + if (lstat (dst_name, &tmp_buf) == 0) + dst_lstat_sb = &tmp_buf; + else + lstat_ok = false; + } /* Never copy through a symlink we've just created. */ if (lstat_ok - && S_ISLNK (dst_lstat_sb->st_mode) - && seen_file (x->dest_info, dst_name, dst_lstat_sb)) - { - error (0, 0, - _("will not copy %s through just-created symlink %s"), - quote_n (0, src_name), quote_n (1, dst_name)); - return false; - } + && S_ISLNK (dst_lstat_sb->st_mode) + && seen_file (x->dest_info, dst_name, dst_lstat_sb)) + { + error (0, 0, + _("will not copy %s through just-created symlink %s"), + quote_n (0, src_name), quote_n (1, dst_name)); + return false; + } } /* If the source is a directory, we don't always create the destination @@ -1581,20 +1581,20 @@ copy_internal (char const *src_name, char const *dst_name, Sometimes, when preserving links, we have to record dev/ino even though st_nlink == 1: - when in move_mode, since we may be moving a group of N hard-linked - files (via two or more command line arguments) to a different - partition; the links may be distributed among the command line - arguments (possibly hierarchies) so that the link count of - the final, once-linked source file is reduced to 1 when it is - considered below. But in this case (for mv) we don't need to - incur the expense of recording the dev/ino => name mapping; all we - really need is a lookup, to see if the dev/ino pair has already - been copied. + files (via two or more command line arguments) to a different + partition; the links may be distributed among the command line + arguments (possibly hierarchies) so that the link count of + the final, once-linked source file is reduced to 1 when it is + considered below. But in this case (for mv) we don't need to + incur the expense of recording the dev/ino => name mapping; all we + really need is a lookup, to see if the dev/ino pair has already + been copied. - when using -H and processing a command line argument; - that command line argument could be a symlink pointing to another - command line argument. With `cp -H --preserve=link', we hard-link - those two destination files. + that command line argument could be a symlink pointing to another + command line argument. With `cp -H --preserve=link', we hard-link + those two destination files. - likewise for -L except that it applies to all files, not just - command line arguments. + command line arguments. Also, with --recursive, record dev/ino of each command-line directory. We'll use that info to detect this problem: cp -R dir dir. */ @@ -1604,20 +1604,20 @@ copy_internal (char const *src_name, char const *dst_name, earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev); } else if (x->preserve_links - && !x->hard_link - && (1 < src_sb.st_nlink - || (command_line_arg - && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS) - || x->dereference == DEREF_ALWAYS)) + && !x->hard_link + && (1 < src_sb.st_nlink + || (command_line_arg + && x->dereference == DEREF_COMMAND_LINE_ARGUMENTS) + || x->dereference == DEREF_ALWAYS)) { earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev); } else if (x->recursive && S_ISDIR (src_mode)) { if (command_line_arg) - earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev); + earlier_file = remember_copied (dst_name, src_sb.st_ino, src_sb.st_dev); else - earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev); + earlier_file = src_to_dest_lookup (src_sb.st_ino, src_sb.st_dev); } /* Did we copy this inode somewhere else (in this command line argument) @@ -1626,161 +1626,161 @@ copy_internal (char const *src_name, char const *dst_name, if (earlier_file) { /* Avoid damaging the destination file system by refusing to preserve - hard-linked directories (which are found at least in Netapp snapshot - directories). */ + hard-linked directories (which are found at least in Netapp snapshot + directories). */ if (S_ISDIR (src_mode)) - { - /* If src_name and earlier_file refer to the same directory entry, - then warn about copying a directory into itself. */ - if (same_name (src_name, earlier_file)) - { - error (0, 0, _("cannot copy a directory, %s, into itself, %s"), - quote_n (0, top_level_src_name), - quote_n (1, top_level_dst_name)); - *copy_into_self = true; - goto un_backup; - } - else if (x->dereference == DEREF_ALWAYS) - { - /* This happens when e.g., encountering a directory for the - second or subsequent time via symlinks when cp is invoked - with -R and -L. E.g., - rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b; - cp -RL a b d - */ - } - else - { - error (0, 0, _("will not create hard link %s to directory %s"), - quote_n (0, dst_name), quote_n (1, earlier_file)); - goto un_backup; - } - } + { + /* If src_name and earlier_file refer to the same directory entry, + then warn about copying a directory into itself. */ + if (same_name (src_name, earlier_file)) + { + error (0, 0, _("cannot copy a directory, %s, into itself, %s"), + quote_n (0, top_level_src_name), + quote_n (1, top_level_dst_name)); + *copy_into_self = true; + goto un_backup; + } + else if (x->dereference == DEREF_ALWAYS) + { + /* This happens when e.g., encountering a directory for the + second or subsequent time via symlinks when cp is invoked + with -R and -L. E.g., + rm -rf a b c d; mkdir a b c d; ln -s ../c a; ln -s ../c b; + cp -RL a b d + */ + } + else + { + error (0, 0, _("will not create hard link %s to directory %s"), + quote_n (0, dst_name), quote_n (1, earlier_file)); + goto un_backup; + } + } else - { - bool link_failed = (link (earlier_file, dst_name) != 0); - - /* If the link failed because of an existing destination, - remove that file and then call link again. */ - if (link_failed && errno == EEXIST) - { - if (unlink (dst_name) != 0) - { - error (0, errno, _("cannot remove %s"), quote (dst_name)); - goto un_backup; - } - if (x->verbose) - printf (_("removed %s\n"), quote (dst_name)); - link_failed = (link (earlier_file, dst_name) != 0); - } - - if (link_failed) - { - error (0, errno, _("cannot create hard link %s to %s"), - quote_n (0, dst_name), quote_n (1, earlier_file)); - goto un_backup; - } - - return true; - } + { + bool link_failed = (link (earlier_file, dst_name) != 0); + + /* If the link failed because of an existing destination, + remove that file and then call link again. */ + if (link_failed && errno == EEXIST) + { + if (unlink (dst_name) != 0) + { + error (0, errno, _("cannot remove %s"), quote (dst_name)); + goto un_backup; + } + if (x->verbose) + printf (_("removed %s\n"), quote (dst_name)); + link_failed = (link (earlier_file, dst_name) != 0); + } + + if (link_failed) + { + error (0, errno, _("cannot create hard link %s to %s"), + quote_n (0, dst_name), quote_n (1, earlier_file)); + goto un_backup; + } + + return true; + } } if (x->move_mode) { if (rename (src_name, dst_name) == 0) - { - if (x->verbose && S_ISDIR (src_mode)) - emit_verbose (src_name, dst_name, - backup_succeeded ? dst_backup : NULL); - - if (rename_succeeded) - *rename_succeeded = true; - - if (command_line_arg) - { - /* Record destination dev/ino/name, so that if we are asked - to overwrite that file again, we can detect it and fail. */ - /* It's fine to use the _source_ stat buffer (src_sb) to get the - _destination_ dev/ino, since the rename above can't have - changed those, and `mv' always uses lstat. - We could limit it further by operating - only on non-directories. */ - record_file (x->dest_info, dst_name, &src_sb); - } - - return true; - } + { + if (x->verbose && S_ISDIR (src_mode)) + emit_verbose (src_name, dst_name, + backup_succeeded ? dst_backup : NULL); + + if (rename_succeeded) + *rename_succeeded = true; + + if (command_line_arg) + { + /* Record destination dev/ino/name, so that if we are asked + to overwrite that file again, we can detect it and fail. */ + /* It's fine to use the _source_ stat buffer (src_sb) to get the + _destination_ dev/ino, since the rename above can't have + changed those, and `mv' always uses lstat. + We could limit it further by operating + only on non-directories. */ + record_file (x->dest_info, dst_name, &src_sb); + } + + return true; + } /* FIXME: someday, consider what to do when moving a directory into - itself but when source and destination are on different devices. */ + itself but when source and destination are on different devices. */ /* This happens when attempting to rename a directory to a - subdirectory of itself. */ + subdirectory of itself. */ if (errno == EINVAL) - { - /* FIXME: this is a little fragile in that it relies on rename(2) - failing with a specific errno value. Expect problems on - non-POSIX systems. */ - error (0, 0, _("cannot move %s to a subdirectory of itself, %s"), - quote_n (0, top_level_src_name), - quote_n (1, top_level_dst_name)); - - /* Note that there is no need to call forget_created here, - (compare with the other calls in this file) since the - destination directory didn't exist before. */ - - *copy_into_self = true; - /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly. - The only caller that uses this code (mv.c) ends up setting its - exit status to nonzero when copy_into_self is nonzero. */ - return true; - } + { + /* FIXME: this is a little fragile in that it relies on rename(2) + failing with a specific errno value. Expect problems on + non-POSIX systems. */ + error (0, 0, _("cannot move %s to a subdirectory of itself, %s"), + quote_n (0, top_level_src_name), + quote_n (1, top_level_dst_name)); + + /* Note that there is no need to call forget_created here, + (compare with the other calls in this file) since the + destination directory didn't exist before. */ + + *copy_into_self = true; + /* FIXME-cleanup: Don't return true here; adjust mv.c accordingly. + The only caller that uses this code (mv.c) ends up setting its + exit status to nonzero when copy_into_self is nonzero. */ + return true; + } /* WARNING: there probably exist systems for which an inter-device - rename fails with a value of errno not handled here. - If/as those are reported, add them to the condition below. - If this happens to you, please do the following and send the output - to the bug-reporting address (e.g., in the output of cp --help): - touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"' - where your current directory is on one partion and /tmp is the other. - Also, please try to find the E* errno macro name corresponding to - the diagnostic and parenthesized integer, and include that in your - e-mail. One way to do that is to run a command like this - find /usr/include/. -type f \ - | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null - where you'd replace `18' with the integer in parentheses that - was output from the perl one-liner above. - If necessary, of course, change `/tmp' to some other directory. */ + rename fails with a value of errno not handled here. + If/as those are reported, add them to the condition below. + If this happens to you, please do the following and send the output + to the bug-reporting address (e.g., in the output of cp --help): + touch k; perl -e 'rename "k","/tmp/k" or print "$!(",$!+0,")\n"' + where your current directory is on one partion and /tmp is the other. + Also, please try to find the E* errno macro name corresponding to + the diagnostic and parenthesized integer, and include that in your + e-mail. One way to do that is to run a command like this + find /usr/include/. -type f \ + | xargs grep 'define.*\<E[A-Z]*\>.*\<18\>' /dev/null + where you'd replace `18' with the integer in parentheses that + was output from the perl one-liner above. + If necessary, of course, change `/tmp' to some other directory. */ if (errno != EXDEV) - { - /* There are many ways this can happen due to a race condition. - When something happens between the initial XSTAT and the - subsequent rename, we can get many different types of errors. - For example, if the destination is initially a non-directory - or non-existent, but it is created as a directory, the rename - fails. If two `mv' commands try to rename the same file at - about the same time, one will succeed and the other will fail. - If the permissions on the directory containing the source or - destination file are made too restrictive, the rename will - fail. Etc. */ - error (0, errno, - _("cannot move %s to %s"), - quote_n (0, src_name), quote_n (1, dst_name)); - forget_created (src_sb.st_ino, src_sb.st_dev); - return false; - } + { + /* There are many ways this can happen due to a race condition. + When something happens between the initial XSTAT and the + subsequent rename, we can get many different types of errors. + For example, if the destination is initially a non-directory + or non-existent, but it is created as a directory, the rename + fails. If two `mv' commands try to rename the same file at + about the same time, one will succeed and the other will fail. + If the permissions on the directory containing the source or + destination file are made too restrictive, the rename will + fail. Etc. */ + error (0, errno, + _("cannot move %s to %s"), + quote_n (0, src_name), quote_n (1, dst_name)); + forget_created (src_sb.st_ino, src_sb.st_dev); + return false; + } /* The rename attempt has failed. Remove any existing destination - file so that a cross-device `mv' acts as if it were really using - the rename syscall. */ + file so that a cross-device `mv' acts as if it were really using + the rename syscall. */ if (unlink (dst_name) != 0 && errno != ENOENT) - { - error (0, errno, - _("inter-device move failed: %s to %s; unable to remove target"), - quote_n (0, src_name), quote_n (1, dst_name)); - forget_created (src_sb.st_ino, src_sb.st_dev); - return false; - } + { + error (0, errno, + _("inter-device move failed: %s to %s; unable to remove target"), + quote_n (0, src_name), quote_n (1, dst_name)); + forget_created (src_sb.st_ino, src_sb.st_dev); + return false; + } new_dst = true; } @@ -1793,8 +1793,8 @@ copy_internal (char const *src_name, char const *dst_name, omitted_permissions = (dst_mode_bits & (x->preserve_ownership ? S_IRWXG | S_IRWXO - : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH - : 0)); + : S_ISDIR (src_mode) ? S_IWGRP | S_IWOTH + : 0)); delayed_ok = true; @@ -1803,33 +1803,33 @@ copy_internal (char const *src_name, char const *dst_name, security_context_t con; if (0 <= lgetfilecon (src_name, &con)) - { - if (setfscreatecon (con) < 0) - { - if (!x->reduce_diagnostics || x->require_preserve_context) - error (0, errno, - _("failed to set default file creation context to %s"), - quote (con)); - if (x->require_preserve_context) - { - freecon (con); - return false; - } - } - freecon (con); - } + { + if (setfscreatecon (con) < 0) + { + if (!x->reduce_diagnostics || x->require_preserve_context) + error (0, errno, + _("failed to set default file creation context to %s"), + quote (con)); + if (x->require_preserve_context) + { + freecon (con); + return false; + } + } + freecon (con); + } else - { + { if (!errno_unsupported (errno) || x->require_preserve_context) - { - if (!x->reduce_diagnostics || x->require_preserve_context) - error (0, errno, - _("failed to get security context of %s"), - quote (src_name)); - if (x->require_preserve_context) - return false; - } - } + { + if (!x->reduce_diagnostics || x->require_preserve_context) + error (0, errno, + _("failed to get security context of %s"), + quote (src_name)); + if (x->require_preserve_context) + return false; + } + } } if (S_ISDIR (src_mode)) @@ -1842,11 +1842,11 @@ copy_internal (char const *src_name, char const *dst_name, continue to copy this, unless we've got an infinite disk. */ if (is_ancestor (&src_sb, ancestors)) - { - error (0, 0, _("cannot copy cyclic symbolic link %s"), - quote (src_name)); - goto un_backup; - } + { + error (0, 0, _("cannot copy cyclic symbolic link %s"), + quote (src_name)); + goto un_backup; + } /* Insert the current directory in the list of parents. */ @@ -1856,109 +1856,109 @@ copy_internal (char const *src_name, char const *dst_name, dir->dev = src_sb.st_dev; if (new_dst || !S_ISDIR (dst_sb.st_mode)) - { - /* POSIX says mkdir's behavior is implementation-defined when - (src_mode & ~S_IRWXUGO) != 0. However, common practice is - to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir - decide what to do with S_ISUID | S_ISGID | S_ISVTX. */ - if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0) - { - error (0, errno, _("cannot create directory %s"), - quote (dst_name)); - goto un_backup; - } - - /* We need search and write permissions to the new directory - for writing the directory's contents. Check if these - permissions are there. */ - - if (lstat (dst_name, &dst_sb) != 0) - { - error (0, errno, _("cannot stat %s"), quote (dst_name)); - goto un_backup; - } - else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU) - { - /* Make the new directory searchable and writable. */ - - dst_mode = dst_sb.st_mode; - restore_dst_mode = true; - - if (lchmod (dst_name, dst_mode | S_IRWXU) != 0) - { - error (0, errno, _("setting permissions for %s"), - quote (dst_name)); - goto un_backup; - } - } - - /* Record the created directory's inode and device numbers into - the search structure, so that we can avoid copying it again. - Do this only for the first directory that is created for each - source command line argument. */ - if (!*first_dir_created_per_command_line_arg) - { - remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev); - *first_dir_created_per_command_line_arg = true; - } - - if (x->verbose) - emit_verbose (src_name, dst_name, NULL); - } + { + /* POSIX says mkdir's behavior is implementation-defined when + (src_mode & ~S_IRWXUGO) != 0. However, common practice is + to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir + decide what to do with S_ISUID | S_ISGID | S_ISVTX. */ + if (mkdir (dst_name, dst_mode_bits & ~omitted_permissions) != 0) + { + error (0, errno, _("cannot create directory %s"), + quote (dst_name)); + goto un_backup; + } + + /* We need search and write permissions to the new directory + for writing the directory's contents. Check if these + permissions are there. */ + + if (lstat (dst_name, &dst_sb) != 0) + { + error (0, errno, _("cannot stat %s"), quote (dst_name)); + goto un_backup; + } + else if ((dst_sb.st_mode & S_IRWXU) != S_IRWXU) + { + /* Make the new directory searchable and writable. */ + + dst_mode = dst_sb.st_mode; + restore_dst_mode = true; + + if (lchmod (dst_name, dst_mode | S_IRWXU) != 0) + { + error (0, errno, _("setting permissions for %s"), + quote (dst_name)); + goto un_backup; + } + } + + /* Record the created directory's inode and device numbers into + the search structure, so that we can avoid copying it again. + Do this only for the first directory that is created for each + source command line argument. */ + if (!*first_dir_created_per_command_line_arg) + { + remember_copied (dst_name, dst_sb.st_ino, dst_sb.st_dev); + *first_dir_created_per_command_line_arg = true; + } + + if (x->verbose) + emit_verbose (src_name, dst_name, NULL); + } /* Decide whether to copy the contents of the directory. */ if (x->one_file_system && device != 0 && device != src_sb.st_dev) - { - /* Here, we are crossing a file system boundary and cp's -x option - is in effect: so don't copy the contents of this directory. */ - } + { + /* Here, we are crossing a file system boundary and cp's -x option + is in effect: so don't copy the contents of this directory. */ + } else - { - /* Copy the contents of the directory. Don't just return if - this fails -- otherwise, the failure to read a single file - in a source directory would cause the containing destination - directory not to have owner/perms set properly. */ - delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x, - first_dir_created_per_command_line_arg, - copy_into_self); - } + { + /* Copy the contents of the directory. Don't just return if + this fails -- otherwise, the failure to read a single file + in a source directory would cause the containing destination + directory not to have owner/perms set properly. */ + delayed_ok = copy_dir (src_name, dst_name, new_dst, &src_sb, dir, x, + first_dir_created_per_command_line_arg, + copy_into_self); + } } else if (x->symbolic_link) { dest_is_symlink = true; if (*src_name != '/') - { - /* Check that DST_NAME denotes a file in the current directory. */ - struct stat dot_sb; - struct stat dst_parent_sb; - char *dst_parent; - bool in_current_dir; - - dst_parent = dir_name (dst_name); - - in_current_dir = (STREQ (".", dst_parent) - /* If either stat call fails, it's ok not to report - the failure and say dst_name is in the current - directory. Other things will fail later. */ - || stat (".", &dot_sb) != 0 - || stat (dst_parent, &dst_parent_sb) != 0 - || SAME_INODE (dot_sb, dst_parent_sb)); - free (dst_parent); - - if (! in_current_dir) - { - error (0, 0, - _("%s: can make relative symbolic links only in current directory"), - quote (dst_name)); - goto un_backup; - } - } + { + /* Check that DST_NAME denotes a file in the current directory. */ + struct stat dot_sb; + struct stat dst_parent_sb; + char *dst_parent; + bool in_current_dir; + + dst_parent = dir_name (dst_name); + + in_current_dir = (STREQ (".", dst_parent) + /* If either stat call fails, it's ok not to report + the failure and say dst_name is in the current + directory. Other things will fail later. */ + || stat (".", &dot_sb) != 0 + || stat (dst_parent, &dst_parent_sb) != 0 + || SAME_INODE (dot_sb, dst_parent_sb)); + free (dst_parent); + + if (! in_current_dir) + { + error (0, 0, + _("%s: can make relative symbolic links only in current directory"), + quote (dst_name)); + goto un_backup; + } + } if (symlink (src_name, dst_name) != 0) - { - error (0, errno, _("cannot create symbolic link %s to %s"), - quote_n (0, dst_name), quote_n (1, src_name)); - goto un_backup; - } + { + error (0, errno, _("cannot create symbolic link %s to %s"), + quote_n (0, dst_name), quote_n (1, src_name)); + goto un_backup; + } } else if (x->hard_link @@ -1973,113 +1973,113 @@ copy_internal (char const *src_name, char const *dst_name, copying code below. When link operates on the symlinks themselves, we use this block and just call link(). */ - && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER) + && !(S_ISLNK (src_mode) && x->dereference == DEREF_NEVER) #endif - ) + ) { if (link (src_name, dst_name)) - { - error (0, errno, _("cannot create link %s"), quote (dst_name)); - goto un_backup; - } + { + error (0, errno, _("cannot create link %s"), quote (dst_name)); + goto un_backup; + } } else if (S_ISREG (src_mode) - || (x->copy_as_regular && !S_ISLNK (src_mode))) + || (x->copy_as_regular && !S_ISLNK (src_mode))) { copied_as_regular = true; /* POSIX says the permission bits of the source file must be - used as the 3rd argument in the open call. Historical - practice passed all the source mode bits to 'open', but the extra - bits were ignored, so it should be the same either way. */ + used as the 3rd argument in the open call. Historical + practice passed all the source mode bits to 'open', but the extra + bits were ignored, so it should be the same either way. */ if (! copy_reg (src_name, dst_name, x, src_mode & S_IRWXUGO, - omitted_permissions, &new_dst, &src_sb)) - goto un_backup; + omitted_permissions, &new_dst, &src_sb)) + goto un_backup; } else if (S_ISFIFO (src_mode)) { /* Use mknod, rather than mkfifo, because the former preserves - the special mode bits of a fifo on Solaris 10, while mkfifo - does not. But fall back on mkfifo, because on some BSD systems, - mknod always fails when asked to create a FIFO. */ + the special mode bits of a fifo on Solaris 10, while mkfifo + does not. But fall back on mkfifo, because on some BSD systems, + mknod always fails when asked to create a FIFO. */ if (mknod (dst_name, src_mode & ~omitted_permissions, 0) != 0) - if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0) - { - error (0, errno, _("cannot create fifo %s"), quote (dst_name)); - goto un_backup; - } + if (mkfifo (dst_name, src_mode & ~S_IFIFO & ~omitted_permissions) != 0) + { + error (0, errno, _("cannot create fifo %s"), quote (dst_name)); + goto un_backup; + } } else if (S_ISBLK (src_mode) || S_ISCHR (src_mode) || S_ISSOCK (src_mode)) { if (mknod (dst_name, src_mode & ~omitted_permissions, src_sb.st_rdev) - != 0) - { - error (0, errno, _("cannot create special file %s"), - quote (dst_name)); - goto un_backup; - } + != 0) + { + error (0, errno, _("cannot create special file %s"), + quote (dst_name)); + goto un_backup; + } } else if (S_ISLNK (src_mode)) { char *src_link_val = areadlink_with_size (src_name, src_sb.st_size); dest_is_symlink = true; if (src_link_val == NULL) - { - error (0, errno, _("cannot read symbolic link %s"), quote (src_name)); - goto un_backup; - } + { + error (0, errno, _("cannot read symbolic link %s"), quote (src_name)); + goto un_backup; + } if (symlink (src_link_val, dst_name) == 0) - free (src_link_val); + free (src_link_val); else - { - int saved_errno = errno; - bool same_link = false; - if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode) - && dst_sb.st_size == strlen (src_link_val)) - { - /* See if the destination is already the desired symlink. - FIXME: This behavior isn't documented, and seems wrong - in some cases, e.g., if the destination symlink has the - wrong ownership, permissions, or time stamps. */ - char *dest_link_val = - areadlink_with_size (dst_name, dst_sb.st_size); - if (dest_link_val && STREQ (dest_link_val, src_link_val)) - same_link = true; - free (dest_link_val); - } - free (src_link_val); - - if (! same_link) - { - error (0, saved_errno, _("cannot create symbolic link %s"), - quote (dst_name)); - goto un_backup; - } - } + { + int saved_errno = errno; + bool same_link = false; + if (x->update && !new_dst && S_ISLNK (dst_sb.st_mode) + && dst_sb.st_size == strlen (src_link_val)) + { + /* See if the destination is already the desired symlink. + FIXME: This behavior isn't documented, and seems wrong + in some cases, e.g., if the destination symlink has the + wrong ownership, permissions, or time stamps. */ + char *dest_link_val = + areadlink_with_size (dst_name, dst_sb.st_size); + if (dest_link_val && STREQ (dest_link_val, src_link_val)) + same_link = true; + free (dest_link_val); + } + free (src_link_val); + + if (! same_link) + { + error (0, saved_errno, _("cannot create symbolic link %s"), + quote (dst_name)); + goto un_backup; + } + } if (x->preserve_security_context) - restore_default_fscreatecon_or_die (); + restore_default_fscreatecon_or_die (); if (x->preserve_ownership) - { - /* Preserve the owner and group of the just-`copied' - symbolic link, if possible. */ - if (HAVE_LCHOWN - && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0 - && ! chown_failure_ok (x)) - { - error (0, errno, _("failed to preserve ownership for %s"), - dst_name); - goto un_backup; - } - else - { - /* Can't preserve ownership of symlinks. - FIXME: maybe give a warning or even error for symlinks - in directories with the sticky bit set -- there, not - preserving owner/group is a potential security problem. */ - } - } + { + /* Preserve the owner and group of the just-`copied' + symbolic link, if possible. */ + if (HAVE_LCHOWN + && lchown (dst_name, src_sb.st_uid, src_sb.st_gid) != 0 + && ! chown_failure_ok (x)) + { + error (0, errno, _("failed to preserve ownership for %s"), + dst_name); + goto un_backup; + } + else + { + /* Can't preserve ownership of symlinks. + FIXME: maybe give a warning or even error for symlinks + in directories with the sticky bit set -- there, not + preserving owner/group is a potential security problem. */ + } + } } else { @@ -2090,10 +2090,10 @@ copy_internal (char const *src_name, char const *dst_name, if (command_line_arg && x->dest_info) { /* Now that the destination file is very likely to exist, - add its info to the set. */ + add its info to the set. */ struct stat sb; if (lstat (dst_name, &sb) == 0) - record_file (x->dest_info, dst_name, &sb); + record_file (x->dest_info, dst_name, &sb); } /* If we've just created a hard-link due to cp's --link option, @@ -2123,14 +2123,14 @@ copy_internal (char const *src_name, char const *dst_name, timespec[1] = get_stat_mtime (&src_sb); if ((dest_is_symlink - ? utimens_symlink (dst_name, timespec) - : utimens (dst_name, timespec)) - != 0) - { - error (0, errno, _("preserving times for %s"), quote (dst_name)); - if (x->require_preserve) - return false; - } + ? utimens_symlink (dst_name, timespec) + : utimens (dst_name, timespec)) + != 0) + { + error (0, errno, _("preserving times for %s"), quote (dst_name)); + if (x->require_preserve) + return false; + } } /* The operations beyond this point may dereference a symlink. */ @@ -2142,14 +2142,14 @@ copy_internal (char const *src_name, char const *dst_name, && (new_dst || !SAME_OWNER_AND_GROUP (src_sb, dst_sb))) { switch (set_owner (x, dst_name, -1, &src_sb, new_dst, &dst_sb)) - { - case -1: - return false; - - case 0: - src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX); - break; - } + { + case -1: + return false; + + case 0: + src_mode &= ~ (S_ISUID | S_ISGID | S_ISVTX); + break; + } } set_author (dst_name, -1, &src_sb); @@ -2161,49 +2161,49 @@ copy_internal (char const *src_name, char const *dst_name, if (x->preserve_mode || x->move_mode) { if (copy_acl (src_name, -1, dst_name, -1, src_mode) != 0 - && x->require_preserve) - return false; + && x->require_preserve) + return false; } else if (x->set_mode) { if (set_acl (dst_name, -1, x->mode) != 0) - return false; + return false; } else { if (omitted_permissions) - { - omitted_permissions &= ~ cached_umask (); - - if (omitted_permissions && !restore_dst_mode) - { - /* Permissions were deliberately omitted when the file - was created due to security concerns. See whether - they need to be re-added now. It'd be faster to omit - the lstat, but deducing the current destination mode - is tricky in the presence of implementation-defined - rules for special mode bits. */ - if (new_dst && lstat (dst_name, &dst_sb) != 0) - { - error (0, errno, _("cannot stat %s"), quote (dst_name)); - return false; - } - dst_mode = dst_sb.st_mode; - if (omitted_permissions & ~dst_mode) - restore_dst_mode = true; - } - } + { + omitted_permissions &= ~ cached_umask (); + + if (omitted_permissions && !restore_dst_mode) + { + /* Permissions were deliberately omitted when the file + was created due to security concerns. See whether + they need to be re-added now. It'd be faster to omit + the lstat, but deducing the current destination mode + is tricky in the presence of implementation-defined + rules for special mode bits. */ + if (new_dst && lstat (dst_name, &dst_sb) != 0) + { + error (0, errno, _("cannot stat %s"), quote (dst_name)); + return false; + } + dst_mode = dst_sb.st_mode; + if (omitted_permissions & ~dst_mode) + restore_dst_mode = true; + } + } if (restore_dst_mode) - { - if (lchmod (dst_name, dst_mode | omitted_permissions) != 0) - { - error (0, errno, _("preserving permissions for %s"), - quote (dst_name)); - if (x->require_preserve) - return false; - } - } + { + if (lchmod (dst_name, dst_mode | omitted_permissions) != 0) + { + error (0, errno, _("preserving permissions for %s"), + quote (dst_name)); + if (x->require_preserve) + return false; + } + } } return delayed_ok; @@ -2225,13 +2225,13 @@ un_backup: if (dst_backup) { if (rename (dst_backup, dst_name) != 0) - error (0, errno, _("cannot un-backup %s"), quote (dst_name)); + error (0, errno, _("cannot un-backup %s"), quote (dst_name)); else - { - if (x->verbose) - printf (_("%s -> %s (unbackup)\n"), - quote_n (0, dst_backup), quote_n (1, dst_name)); - } + { + if (x->verbose) + printf (_("%s -> %s (unbackup)\n"), + quote_n (0, dst_backup), quote_n (1, dst_name)); + } } return false; } @@ -2275,9 +2275,9 @@ copy (char const *src_name, char const *dst_name, bool first_dir_created_per_command_line_arg = false; return copy_internal (src_name, dst_name, nonexistent_dst, 0, NULL, - options, true, - &first_dir_created_per_command_line_arg, - copy_into_self, rename_succeeded); + options, true, + &first_dir_created_per_command_line_arg, + copy_into_self, rename_succeeded); } /* Set *X to the default options for a value of type struct cp_options. */ @@ -2293,8 +2293,8 @@ cp_options_default (struct cp_options *x) xalloc_die (); if (getppriv (PRIV_EFFECTIVE, pset) == 0) { - x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN); - x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER); + x->chown_privileges = priv_ismember (pset, PRIV_FILE_CHOWN); + x->owner_privileges = priv_ismember (pset, PRIV_FILE_OWNER); } priv_freeset (pset); } diff --git a/src/copy.h b/src/copy.h index ddf4f4e2c..cdef64a7f 100644 --- a/src/copy.h +++ b/src/copy.h @@ -252,8 +252,8 @@ int rpl_rename (const char *, const char *); # endif bool copy (char const *src_name, char const *dst_name, - bool nonexistent_dst, const struct cp_options *options, - bool *copy_into_self, bool *rename_succeeded); + bool nonexistent_dst, const struct cp_options *options, + bool *copy_into_self, bool *rename_succeeded); void dest_info_init (struct cp_options *); void src_info_init (struct cp_options *); diff --git a/src/cp-hash.c b/src/cp-hash.c index 858be07fa..b929d9ab9 100644 --- a/src/cp-hash.c +++ b/src/cp-hash.c @@ -148,9 +148,9 @@ extern void hash_init (void) { src_to_dest = hash_initialize (INITIAL_TABLE_SIZE, NULL, - src_to_dest_hash, - src_to_dest_compare, - src_to_dest_free); + src_to_dest_hash, + src_to_dest_compare, + src_to_dest_free); if (src_to_dest == NULL) xalloc_die (); } @@ -139,7 +139,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -147,7 +147,7 @@ Usage: %s [OPTION]... [-T] SOURCE DEST\n\ or: %s [OPTION]... SOURCE... DIRECTORY\n\ or: %s [OPTION]... -t DIRECTORY SOURCE...\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.\n\ \n\ @@ -270,7 +270,7 @@ regular file.\n\ static bool re_protect (char const *const_dst_name, size_t src_offset, - struct dir_attr *attr_list, const struct cp_options *x) + struct dir_attr *attr_list, const struct cp_options *x) { struct dir_attr *p; char *dst_name; /* A copy of CONST_DST_NAME we can change. */ @@ -284,26 +284,26 @@ re_protect (char const *const_dst_name, size_t src_offset, dst_name[p->slash_offset] = '\0'; /* Adjust the times (and if possible, ownership) for the copy. - chown turns off set[ug]id bits for non-root, - so do the chmod last. */ + chown turns off set[ug]id bits for non-root, + so do the chmod last. */ if (x->preserve_timestamps) - { - struct timespec timespec[2]; + { + struct timespec timespec[2]; - timespec[0] = get_stat_atime (&p->st); - timespec[1] = get_stat_mtime (&p->st); + timespec[0] = get_stat_atime (&p->st); + timespec[1] = get_stat_mtime (&p->st); - if (utimens (dst_name, timespec)) - { - error (0, errno, _("failed to preserve times for %s"), - quote (dst_name)); - return false; - } - } + if (utimens (dst_name, timespec)) + { + error (0, errno, _("failed to preserve times for %s"), + quote (dst_name)); + return false; + } + } if (x->preserve_ownership) - { + { if (lchown (dst_name, p->st.st_uid, p->st.st_gid) != 0) { if (! chown_failure_ok (x)) @@ -316,22 +316,22 @@ re_protect (char const *const_dst_name, size_t src_offset, the group, but ignore the possible error. */ ignore_value (lchown (dst_name, -1, p->st.st_gid)); } - } + } if (x->preserve_mode) - { - if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0) - return false; - } + { + if (copy_acl (src_name, -1, dst_name, -1, p->st.st_mode) != 0) + return false; + } else if (p->restore_mode) - { - if (lchmod (dst_name, p->st.st_mode) != 0) - { - error (0, errno, _("failed to preserve permissions for %s"), - quote (dst_name)); - return false; - } - } + { + if (lchmod (dst_name, p->st.st_mode) != 0) + { + error (0, errno, _("failed to preserve permissions for %s"), + quote (dst_name)); + return false; + } + } dst_name[p->slash_offset] = '/'; } @@ -359,9 +359,9 @@ re_protect (char const *const_dst_name, size_t src_offset, static bool make_dir_parents_private (char const *const_dir, size_t src_offset, - char const *verbose_fmt_string, - struct dir_attr **attr_list, bool *new_dst, - const struct cp_options *x) + char const *verbose_fmt_string, + struct dir_attr **attr_list, bool *new_dst, + const struct cp_options *x) { struct stat stats; char *dir; /* A copy of CONST_DIR we can change. */ @@ -383,139 +383,139 @@ make_dir_parents_private (char const *const_dir, size_t src_offset, if (stat (dst_dir, &stats) != 0) { /* A parent of CONST_DIR does not exist. - Make all missing intermediate directories. */ + Make all missing intermediate directories. */ char *slash; slash = src; while (*slash == '/') - slash++; + slash++; while ((slash = strchr (slash, '/'))) - { - struct dir_attr *new IF_LINT (= NULL); - bool missing_dir; - - *slash = '\0'; - missing_dir = (stat (dir, &stats) != 0); - - if (missing_dir | x->preserve_ownership | x->preserve_mode - | x->preserve_timestamps) - { - /* Add this directory to the list of directories whose - modes might need fixing later. */ - struct stat src_st; - int src_errno = (stat (src, &src_st) != 0 - ? errno - : S_ISDIR (src_st.st_mode) - ? 0 - : ENOTDIR); - if (src_errno) - { - error (0, src_errno, _("failed to get attributes of %s"), - quote (src)); - return false; - } - - new = xmalloc (sizeof *new); - new->st = src_st; - new->slash_offset = slash - dir; - new->restore_mode = false; - new->next = *attr_list; - *attr_list = new; - } - - if (missing_dir) - { - mode_t src_mode; - mode_t omitted_permissions; - mode_t mkdir_mode; - - /* This component does not exist. We must set - *new_dst and new->st.st_mode inside this loop because, - for example, in the command `cp --parents ../a/../b/c e_dir', - make_dir_parents_private creates only e_dir/../a if - ./b already exists. */ - *new_dst = true; - src_mode = new->st.st_mode; - - /* If the ownership or special mode bits might change, - omit some permissions at first, so unauthorized users - cannot nip in before the file is ready. */ - omitted_permissions = (src_mode - & (x->preserve_ownership - ? S_IRWXG | S_IRWXO - : x->preserve_mode - ? S_IWGRP | S_IWOTH - : 0)); - - /* POSIX says mkdir's behavior is implementation-defined when - (src_mode & ~S_IRWXUGO) != 0. However, common practice is - to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir - decide what to do with S_ISUID | S_ISGID | S_ISVTX. */ - mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions; - if (mkdir (dir, mkdir_mode) != 0) - { - error (0, errno, _("cannot make directory %s"), - quote (dir)); - return false; - } - else - { - if (verbose_fmt_string != NULL) - printf (verbose_fmt_string, src, dir); - } - - /* We need search and write permissions to the new directory - for writing the directory's contents. Check if these - permissions are there. */ - - if (lstat (dir, &stats)) - { - error (0, errno, _("failed to get attributes of %s"), - quote (dir)); - return false; - } - - - if (! x->preserve_mode) - { - if (omitted_permissions & ~stats.st_mode) - omitted_permissions &= ~ cached_umask (); - if (omitted_permissions & ~stats.st_mode - || (stats.st_mode & S_IRWXU) != S_IRWXU) - { - new->st.st_mode = stats.st_mode | omitted_permissions; - new->restore_mode = true; - } - } - - if ((stats.st_mode & S_IRWXU) != S_IRWXU) - { - /* Make the new directory searchable and writable. - The original permissions will be restored later. */ - - if (lchmod (dir, stats.st_mode | S_IRWXU) != 0) - { - error (0, errno, _("setting permissions for %s"), - quote (dir)); - return false; - } - } - } - else if (!S_ISDIR (stats.st_mode)) - { - error (0, 0, _("%s exists but is not a directory"), - quote (dir)); - return false; - } - else - *new_dst = false; - *slash++ = '/'; - - /* Avoid unnecessary calls to `stat' when given - file names containing multiple adjacent slashes. */ - while (*slash == '/') - slash++; - } + { + struct dir_attr *new IF_LINT (= NULL); + bool missing_dir; + + *slash = '\0'; + missing_dir = (stat (dir, &stats) != 0); + + if (missing_dir | x->preserve_ownership | x->preserve_mode + | x->preserve_timestamps) + { + /* Add this directory to the list of directories whose + modes might need fixing later. */ + struct stat src_st; + int src_errno = (stat (src, &src_st) != 0 + ? errno + : S_ISDIR (src_st.st_mode) + ? 0 + : ENOTDIR); + if (src_errno) + { + error (0, src_errno, _("failed to get attributes of %s"), + quote (src)); + return false; + } + + new = xmalloc (sizeof *new); + new->st = src_st; + new->slash_offset = slash - dir; + new->restore_mode = false; + new->next = *attr_list; + *attr_list = new; + } + + if (missing_dir) + { + mode_t src_mode; + mode_t omitted_permissions; + mode_t mkdir_mode; + + /* This component does not exist. We must set + *new_dst and new->st.st_mode inside this loop because, + for example, in the command `cp --parents ../a/../b/c e_dir', + make_dir_parents_private creates only e_dir/../a if + ./b already exists. */ + *new_dst = true; + src_mode = new->st.st_mode; + + /* If the ownership or special mode bits might change, + omit some permissions at first, so unauthorized users + cannot nip in before the file is ready. */ + omitted_permissions = (src_mode + & (x->preserve_ownership + ? S_IRWXG | S_IRWXO + : x->preserve_mode + ? S_IWGRP | S_IWOTH + : 0)); + + /* POSIX says mkdir's behavior is implementation-defined when + (src_mode & ~S_IRWXUGO) != 0. However, common practice is + to ask mkdir to copy all the CHMOD_MODE_BITS, letting mkdir + decide what to do with S_ISUID | S_ISGID | S_ISVTX. */ + mkdir_mode = src_mode & CHMOD_MODE_BITS & ~omitted_permissions; + if (mkdir (dir, mkdir_mode) != 0) + { + error (0, errno, _("cannot make directory %s"), + quote (dir)); + return false; + } + else + { + if (verbose_fmt_string != NULL) + printf (verbose_fmt_string, src, dir); + } + + /* We need search and write permissions to the new directory + for writing the directory's contents. Check if these + permissions are there. */ + + if (lstat (dir, &stats)) + { + error (0, errno, _("failed to get attributes of %s"), + quote (dir)); + return false; + } + + + if (! x->preserve_mode) + { + if (omitted_permissions & ~stats.st_mode) + omitted_permissions &= ~ cached_umask (); + if (omitted_permissions & ~stats.st_mode + || (stats.st_mode & S_IRWXU) != S_IRWXU) + { + new->st.st_mode = stats.st_mode | omitted_permissions; + new->restore_mode = true; + } + } + + if ((stats.st_mode & S_IRWXU) != S_IRWXU) + { + /* Make the new directory searchable and writable. + The original permissions will be restored later. */ + + if (lchmod (dir, stats.st_mode | S_IRWXU) != 0) + { + error (0, errno, _("setting permissions for %s"), + quote (dir)); + return false; + } + } + } + else if (!S_ISDIR (stats.st_mode)) + { + error (0, 0, _("%s exists but is not a directory"), + quote (dir)); + return false; + } + else + *new_dst = false; + *slash++ = '/'; + + /* Avoid unnecessary calls to `stat' when given + file names containing multiple adjacent slashes. */ + while (*slash == '/') + slash++; + } } /* We get here if the parent of DIR already exists. */ @@ -549,7 +549,7 @@ target_directory_operand (char const *file, struct stat *st, bool *new_dst) if (err) { if (err != ENOENT) - error (EXIT_FAILURE, err, _("accessing %s"), quote (file)); + error (EXIT_FAILURE, err, _("accessing %s"), quote (file)); *new_dst = true; } return is_a_dir; @@ -560,7 +560,7 @@ target_directory_operand (char const *file, struct stat *st, bool *new_dst) static bool do_copy (int n_files, char **file, const char *target_directory, - bool no_target_directory, struct cp_options *x) + bool no_target_directory, struct cp_options *x) { struct stat sb; bool new_dst = false; @@ -569,131 +569,131 @@ do_copy (int n_files, char **file, const char *target_directory, if (n_files <= !target_directory) { if (n_files <= 0) - error (0, 0, _("missing file operand")); + error (0, 0, _("missing file operand")); else - error (0, 0, _("missing destination file operand after %s"), - quote (file[0])); + error (0, 0, _("missing destination file operand after %s"), + quote (file[0])); usage (EXIT_FAILURE); } if (no_target_directory) { if (target_directory) - error (EXIT_FAILURE, 0, - _("cannot combine --target-directory (-t) " - "and --no-target-directory (-T)")); + error (EXIT_FAILURE, 0, + _("cannot combine --target-directory (-t) " + "and --no-target-directory (-T)")); if (2 < n_files) - { - error (0, 0, _("extra operand %s"), quote (file[2])); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (file[2])); + usage (EXIT_FAILURE); + } } else if (!target_directory) { if (2 <= n_files - && target_directory_operand (file[n_files - 1], &sb, &new_dst)) - target_directory = file[--n_files]; + && target_directory_operand (file[n_files - 1], &sb, &new_dst)) + target_directory = file[--n_files]; else if (2 < n_files) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (file[n_files - 1])); + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (file[n_files - 1])); } if (target_directory) { /* cp file1...filen edir - Copy the files `file1' through `filen' - to the existing directory `edir'. */ + Copy the files `file1' through `filen' + to the existing directory `edir'. */ int i; /* Initialize these hash tables only if we'll need them. - The problems they're used to detect can arise only if - there are two or more files to copy. */ + The problems they're used to detect can arise only if + there are two or more files to copy. */ if (2 <= n_files) - { - dest_info_init (x); - src_info_init (x); - } + { + dest_info_init (x); + src_info_init (x); + } for (i = 0; i < n_files; i++) - { - char *dst_name; - bool parent_exists = true; /* True if dir_name (dst_name) exists. */ - struct dir_attr *attr_list; - char *arg_in_concat = NULL; - char *arg = file[i]; - - /* Trailing slashes are meaningful (i.e., maybe worth preserving) - only in the source file names. */ - if (remove_trailing_slashes) - strip_trailing_slashes (arg); - - if (parents_option) - { - char *arg_no_trailing_slash; - - /* Use `arg' without trailing slashes in constructing destination - file names. Otherwise, we can end up trying to create a - directory via `mkdir ("dst/foo/"...', which is not portable. - It fails, due to the trailing slash, on at least - NetBSD 1.[34] systems. */ - ASSIGN_STRDUPA (arg_no_trailing_slash, arg); - strip_trailing_slashes (arg_no_trailing_slash); - - /* Append all of `arg' (minus any trailing slash) to `dest'. */ - dst_name = file_name_concat (target_directory, - arg_no_trailing_slash, - &arg_in_concat); - - /* For --parents, we have to make sure that the directory - dir_name (dst_name) exists. We may have to create a few - leading directories. */ - parent_exists = - (make_dir_parents_private - (dst_name, arg_in_concat - dst_name, - (x->verbose ? "%s -> %s\n" : NULL), - &attr_list, &new_dst, x)); - } - else - { - char *arg_base; - /* Append the last component of `arg' to `target_directory'. */ - - ASSIGN_BASENAME_STRDUPA (arg_base, arg); - /* For `cp -R source/.. dest', don't copy into `dest/..'. */ - dst_name = (STREQ (arg_base, "..") - ? xstrdup (target_directory) - : file_name_concat (target_directory, arg_base, - NULL)); - } - - if (!parent_exists) - { - /* make_dir_parents_private failed, so don't even - attempt the copy. */ - ok = false; - } - else - { - bool copy_into_self; - ok &= copy (arg, dst_name, new_dst, x, ©_into_self, NULL); - - if (parents_option) - ok &= re_protect (dst_name, arg_in_concat - dst_name, - attr_list, x); - } - - if (parents_option) - { - while (attr_list) - { - struct dir_attr *p = attr_list; - attr_list = attr_list->next; - free (p); - } - } - - free (dst_name); - } + { + char *dst_name; + bool parent_exists = true; /* True if dir_name (dst_name) exists. */ + struct dir_attr *attr_list; + char *arg_in_concat = NULL; + char *arg = file[i]; + + /* Trailing slashes are meaningful (i.e., maybe worth preserving) + only in the source file names. */ + if (remove_trailing_slashes) + strip_trailing_slashes (arg); + + if (parents_option) + { + char *arg_no_trailing_slash; + + /* Use `arg' without trailing slashes in constructing destination + file names. Otherwise, we can end up trying to create a + directory via `mkdir ("dst/foo/"...', which is not portable. + It fails, due to the trailing slash, on at least + NetBSD 1.[34] systems. */ + ASSIGN_STRDUPA (arg_no_trailing_slash, arg); + strip_trailing_slashes (arg_no_trailing_slash); + + /* Append all of `arg' (minus any trailing slash) to `dest'. */ + dst_name = file_name_concat (target_directory, + arg_no_trailing_slash, + &arg_in_concat); + + /* For --parents, we have to make sure that the directory + dir_name (dst_name) exists. We may have to create a few + leading directories. */ + parent_exists = + (make_dir_parents_private + (dst_name, arg_in_concat - dst_name, + (x->verbose ? "%s -> %s\n" : NULL), + &attr_list, &new_dst, x)); + } + else + { + char *arg_base; + /* Append the last component of `arg' to `target_directory'. */ + + ASSIGN_BASENAME_STRDUPA (arg_base, arg); + /* For `cp -R source/.. dest', don't copy into `dest/..'. */ + dst_name = (STREQ (arg_base, "..") + ? xstrdup (target_directory) + : file_name_concat (target_directory, arg_base, + NULL)); + } + + if (!parent_exists) + { + /* make_dir_parents_private failed, so don't even + attempt the copy. */ + ok = false; + } + else + { + bool copy_into_self; + ok &= copy (arg, dst_name, new_dst, x, ©_into_self, NULL); + + if (parents_option) + ok &= re_protect (dst_name, arg_in_concat - dst_name, + attr_list, x); + } + + if (parents_option) + { + while (attr_list) + { + struct dir_attr *p = attr_list; + attr_list = attr_list->next; + free (p); + } + } + + free (dst_name); + } } else /* !target_directory */ { @@ -703,39 +703,39 @@ do_copy (int n_files, char **file, const char *target_directory, bool unused; if (parents_option) - { - error (0, 0, - _("with --parents, the destination must be a directory")); - usage (EXIT_FAILURE); - } + { + error (0, 0, + _("with --parents, the destination must be a directory")); + usage (EXIT_FAILURE); + } /* When the force and backup options have been specified and - the source and destination are the same name for an existing - regular file, convert the user's command, e.g., - `cp --force --backup foo foo' to `cp --force foo fooSUFFIX' - where SUFFIX is determined by any version control options used. */ + the source and destination are the same name for an existing + regular file, convert the user's command, e.g., + `cp --force --backup foo foo' to `cp --force foo fooSUFFIX' + where SUFFIX is determined by any version control options used. */ if (x->unlink_dest_after_failed_open - && x->backup_type != no_backups - && STREQ (source, dest) - && !new_dst && S_ISREG (sb.st_mode)) - { - static struct cp_options x_tmp; - - new_dest = find_backup_file_name (dest, x->backup_type); - /* Set x->backup_type to `no_backups' so that the normal backup - mechanism is not used when performing the actual copy. - backup_type must be set to `no_backups' only *after* the above - call to find_backup_file_name -- that function uses - backup_type to determine the suffix it applies. */ - x_tmp = *x; - x_tmp.backup_type = no_backups; - x = &x_tmp; - } + && x->backup_type != no_backups + && STREQ (source, dest) + && !new_dst && S_ISREG (sb.st_mode)) + { + static struct cp_options x_tmp; + + new_dest = find_backup_file_name (dest, x->backup_type); + /* Set x->backup_type to `no_backups' so that the normal backup + mechanism is not used when performing the actual copy. + backup_type must be set to `no_backups' only *after* the above + call to find_backup_file_name -- that function uses + backup_type to determine the suffix it applies. */ + x_tmp = *x; + x_tmp.backup_type = no_backups; + x = &x_tmp; + } else - { - new_dest = dest; - } + { + new_dest = dest; + } ok = copy (source, new_dest, 0, x, &unused, NULL); } @@ -829,51 +829,51 @@ decode_preserve_arg (char const *arg, struct cp_options *x, bool on_off) /* If we found a comma, put a NUL in its place and advance. */ if (comma) - *comma++ = 0; + *comma++ = 0; /* process S. */ val = XARGMATCH ("--preserve", s, preserve_args, preserve_vals); switch (val) - { - case PRESERVE_MODE: - x->preserve_mode = on_off; - break; - - case PRESERVE_TIMESTAMPS: - x->preserve_timestamps = on_off; - break; - - case PRESERVE_OWNERSHIP: - x->preserve_ownership = on_off; - break; - - case PRESERVE_LINK: - x->preserve_links = on_off; - break; - - case PRESERVE_CONTEXT: - x->preserve_security_context = on_off; - x->require_preserve_context = on_off; - break; - - case PRESERVE_XATTR: - x->preserve_xattr = on_off; - x->require_preserve_xattr = on_off; - break; - - case PRESERVE_ALL: - x->preserve_mode = on_off; - x->preserve_timestamps = on_off; - x->preserve_ownership = on_off; - x->preserve_links = on_off; - if (selinux_enabled) - x->preserve_security_context = on_off; - x->preserve_xattr = on_off; - break; - - default: - abort (); - } + { + case PRESERVE_MODE: + x->preserve_mode = on_off; + break; + + case PRESERVE_TIMESTAMPS: + x->preserve_timestamps = on_off; + break; + + case PRESERVE_OWNERSHIP: + x->preserve_ownership = on_off; + break; + + case PRESERVE_LINK: + x->preserve_links = on_off; + break; + + case PRESERVE_CONTEXT: + x->preserve_security_context = on_off; + x->require_preserve_context = on_off; + break; + + case PRESERVE_XATTR: + x->preserve_xattr = on_off; + x->require_preserve_xattr = on_off; + break; + + case PRESERVE_ALL: + x->preserve_mode = on_off; + x->preserve_timestamps = on_off; + x->preserve_ownership = on_off; + x->preserve_links = on_off; + if (selinux_enabled) + x->preserve_security_context = on_off; + x->preserve_xattr = on_off; + break; + + default: + abort (); + } s = comma; } while (s); @@ -910,165 +910,165 @@ main (int argc, char **argv) backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX"); while ((c = getopt_long (argc, argv, "abdfHilLnprst:uvxPRS:T", - long_opts, NULL)) - != -1) + long_opts, NULL)) + != -1) { switch (c) - { - case SPARSE_OPTION: - x.sparse_mode = XARGMATCH ("--sparse", optarg, - sparse_type_string, sparse_type); - break; - - case REFLINK_OPTION: - x.reflink = true; - break; - - case 'a': /* Like -dR --preserve=all with reduced failure diagnostics. */ - x.dereference = DEREF_NEVER; - x.preserve_links = true; - x.preserve_ownership = true; - x.preserve_mode = true; - x.preserve_timestamps = true; - x.require_preserve = true; - if (selinux_enabled) - x.preserve_security_context = true; - x.preserve_xattr = true; - x.reduce_diagnostics = true; - x.recursive = true; - break; - - case 'b': - make_backups = true; - if (optarg) - version_control_string = optarg; - break; - - case COPY_CONTENTS_OPTION: - copy_contents = true; - break; - - case 'd': - x.preserve_links = true; - x.dereference = DEREF_NEVER; - break; - - case 'f': - x.unlink_dest_after_failed_open = true; - break; - - case 'H': - x.dereference = DEREF_COMMAND_LINE_ARGUMENTS; - break; - - case 'i': - x.interactive = I_ASK_USER; - break; - - case 'l': - x.hard_link = true; - break; - - case 'L': - x.dereference = DEREF_ALWAYS; - break; - - case 'n': - x.interactive = I_ALWAYS_NO; - break; - - case 'P': - x.dereference = DEREF_NEVER; - break; - - case NO_PRESERVE_ATTRIBUTES_OPTION: - decode_preserve_arg (optarg, &x, false); - break; - - case PRESERVE_ATTRIBUTES_OPTION: - if (optarg == NULL) - { - /* Fall through to the case for `p' below. */ - } - else - { - decode_preserve_arg (optarg, &x, true); - x.require_preserve = true; - break; - } - - case 'p': - x.preserve_ownership = true; - x.preserve_mode = true; - x.preserve_timestamps = true; - x.require_preserve = true; - break; - - case PARENTS_OPTION: - parents_option = true; - break; - - case 'r': - case 'R': - x.recursive = true; - break; - - case UNLINK_DEST_BEFORE_OPENING: - x.unlink_dest_before_opening = true; - break; - - case STRIP_TRAILING_SLASHES_OPTION: - remove_trailing_slashes = true; - break; - - case 's': - x.symbolic_link = true; - break; - - case 't': - if (target_directory) - error (EXIT_FAILURE, 0, - _("multiple target directories specified")); - else - { - struct stat st; - if (stat (optarg, &st) != 0) - error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); - if (! S_ISDIR (st.st_mode)) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (optarg)); - } - target_directory = optarg; - break; - - case 'T': - no_target_directory = true; - break; - - case 'u': - x.update = true; - break; - - case 'v': - x.verbose = true; - break; - - case 'x': - x.one_file_system = true; - break; - - case 'S': - make_backups = true; - backup_suffix_string = optarg; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case SPARSE_OPTION: + x.sparse_mode = XARGMATCH ("--sparse", optarg, + sparse_type_string, sparse_type); + break; + + case REFLINK_OPTION: + x.reflink = true; + break; + + case 'a': /* Like -dR --preserve=all with reduced failure diagnostics. */ + x.dereference = DEREF_NEVER; + x.preserve_links = true; + x.preserve_ownership = true; + x.preserve_mode = true; + x.preserve_timestamps = true; + x.require_preserve = true; + if (selinux_enabled) + x.preserve_security_context = true; + x.preserve_xattr = true; + x.reduce_diagnostics = true; + x.recursive = true; + break; + + case 'b': + make_backups = true; + if (optarg) + version_control_string = optarg; + break; + + case COPY_CONTENTS_OPTION: + copy_contents = true; + break; + + case 'd': + x.preserve_links = true; + x.dereference = DEREF_NEVER; + break; + + case 'f': + x.unlink_dest_after_failed_open = true; + break; + + case 'H': + x.dereference = DEREF_COMMAND_LINE_ARGUMENTS; + break; + + case 'i': + x.interactive = I_ASK_USER; + break; + + case 'l': + x.hard_link = true; + break; + + case 'L': + x.dereference = DEREF_ALWAYS; + break; + + case 'n': + x.interactive = I_ALWAYS_NO; + break; + + case 'P': + x.dereference = DEREF_NEVER; + break; + + case NO_PRESERVE_ATTRIBUTES_OPTION: + decode_preserve_arg (optarg, &x, false); + break; + + case PRESERVE_ATTRIBUTES_OPTION: + if (optarg == NULL) + { + /* Fall through to the case for `p' below. */ + } + else + { + decode_preserve_arg (optarg, &x, true); + x.require_preserve = true; + break; + } + + case 'p': + x.preserve_ownership = true; + x.preserve_mode = true; + x.preserve_timestamps = true; + x.require_preserve = true; + break; + + case PARENTS_OPTION: + parents_option = true; + break; + + case 'r': + case 'R': + x.recursive = true; + break; + + case UNLINK_DEST_BEFORE_OPENING: + x.unlink_dest_before_opening = true; + break; + + case STRIP_TRAILING_SLASHES_OPTION: + remove_trailing_slashes = true; + break; + + case 's': + x.symbolic_link = true; + break; + + case 't': + if (target_directory) + error (EXIT_FAILURE, 0, + _("multiple target directories specified")); + else + { + struct stat st; + if (stat (optarg, &st) != 0) + error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); + if (! S_ISDIR (st.st_mode)) + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (optarg)); + } + target_directory = optarg; + break; + + case 'T': + no_target_directory = true; + break; + + case 'u': + x.update = true; + break; + + case 'v': + x.verbose = true; + break; + + case 'x': + x.one_file_system = true; + break; + + case 'S': + make_backups = true; + backup_suffix_string = optarg; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (x.hard_link & x.symbolic_link) @@ -1080,7 +1080,7 @@ main (int argc, char **argv) if (make_backups && x.interactive == I_ALWAYS_NO) { error (0, 0, - _("options --backup and --no-clobber are mutually exclusive")); + _("options --backup and --no-clobber are mutually exclusive")); usage (EXIT_FAILURE); } @@ -1094,17 +1094,17 @@ main (int argc, char **argv) simple_backup_suffix = xstrdup (backup_suffix_string); x.backup_type = (make_backups - ? xget_version (_("backup type"), - version_control_string) - : no_backups); + ? xget_version (_("backup type"), + version_control_string) + : no_backups); if (x.dereference == DEREF_UNDEFINED) { if (x.recursive) - /* This is compatible with FreeBSD. */ - x.dereference = DEREF_NEVER; + /* This is compatible with FreeBSD. */ + x.dereference = DEREF_NEVER; else - x.dereference = DEREF_ALWAYS; + x.dereference = DEREF_ALWAYS; } if (x.recursive) @@ -1118,15 +1118,15 @@ main (int argc, char **argv) if (x.preserve_security_context) { if (!selinux_enabled) - error (EXIT_FAILURE, 0, - _("cannot preserve security context " - "without an SELinux-enabled kernel")); + error (EXIT_FAILURE, 0, + _("cannot preserve security context " + "without an SELinux-enabled kernel")); } #if !USE_XATTR if (x.require_preserve_xattr) error (EXIT_FAILURE, 0, _("cannot preserve extended attributes, cp is " - "built without xattr support")); + "built without xattr support")); #endif /* Allocate space for remembering copied and created files. */ @@ -1134,7 +1134,7 @@ main (int argc, char **argv) hash_init (); ok = do_copy (argc - optind, argv + optind, - target_directory, no_target_directory, &x); + target_directory, no_target_directory, &x); forget_all (); diff --git a/src/csplit.c b/src/csplit.c index b2892c917..ba93d2b59 100644 --- a/src/csplit.c +++ b/src/csplit.c @@ -346,7 +346,7 @@ record_line_starts (struct buffer_record *b) { line_end = memchr (line_start, '\n', bytes_left); if (line_end == NULL) - break; + break; line_length = line_end - line_start + 1; keep_new_line (b, line_start, line_length); bytes_left -= line_length; @@ -358,12 +358,12 @@ record_line_starts (struct buffer_record *b) if (bytes_left) { if (have_read_eof) - { - keep_new_line (b, line_start, bytes_left); - lines++; - } + { + keep_new_line (b, line_start, bytes_left); + lines++; + } else - save_to_hold_area (xmemdup (line_start, bytes_left), bytes_left); + save_to_hold_area (xmemdup (line_start, bytes_left), bytes_left); } b->num_lines = lines; @@ -438,7 +438,7 @@ save_buffer (struct buffer_record *buf) else { for (p = head; p->next; p = p->next) - /* Do nothing. */ ; + /* Do nothing. */ ; p->next = buf; } } @@ -481,25 +481,25 @@ load_buffer (void) /* First check the `holding' area for a partial line. */ if (hold_count) - { - memcpy (p, hold_area, hold_count); - p += hold_count; - b->bytes_used += hold_count; - bytes_avail -= hold_count; - hold_count = 0; - } + { + memcpy (p, hold_area, hold_count); + p += hold_count; + b->bytes_used += hold_count; + bytes_avail -= hold_count; + hold_count = 0; + } b->bytes_used += read_input (p, bytes_avail); lines_found = record_line_starts (b); if (!lines_found) - free_buffer (b); + free_buffer (b); if (lines_found || have_read_eof) - break; + break; if (xalloc_oversized (2, b->bytes_alloc)) - xalloc_die (); + xalloc_die (); bytes_wanted = 2 * b->bytes_alloc; free_buffer (b); free (b); @@ -563,13 +563,13 @@ remove_line (void) /* Go on to the next line record. */ head->curr_line = l->next; if (head->curr_line == NULL || head->curr_line->used == 0) - { - /* Go on to the next data block. - but first record the current one so we can free it - once the line we're returning has been processed. */ - prev_buf = head; - head = head->next; - } + { + /* Go on to the next data block. + but first record the current one so we can free it + once the line we're returning has been processed. */ + prev_buf = head; + head = head->next; + } } return line; @@ -592,23 +592,23 @@ find_line (uintmax_t linenum) for (b = head;;) { if (linenum < b->start_line + b->num_lines) - { - /* The line is in this buffer. */ - struct line *l; - size_t offset; /* How far into the buffer the line is. */ - - l = b->line_start; - offset = linenum - b->start_line; - /* Find the control record. */ - while (offset >= CTRL_SIZE) - { - l = l->next; - offset -= CTRL_SIZE; - } - return &l->starts[offset]; - } + { + /* The line is in this buffer. */ + struct line *l; + size_t offset; /* How far into the buffer the line is. */ + + l = b->line_start; + offset = linenum - b->start_line; + /* Find the control record. */ + while (offset >= CTRL_SIZE) + { + l = l->next; + offset -= CTRL_SIZE; + } + return &l->starts[offset]; + } if (b->next == NULL && !load_buffer ()) - return NULL; + return NULL; b = b->next; /* Try the next data block. */ } } @@ -657,12 +657,12 @@ write_to_file (uintmax_t last_line, bool ignore, int argnum) { line = remove_line (); if (line == NULL) - { - error (0, 0, _("%s: line number out of range"), global_argv[argnum]); - cleanup_fatal (); - } + { + error (0, 0, _("%s: line number out of range"), global_argv[argnum]); + cleanup_fatal (); + } if (!ignore) - save_line_to_file (line); + save_line_to_file (line); } } @@ -688,7 +688,7 @@ handle_line_error (const struct control *p, uintmax_t repetition) char buf[INT_BUFSIZE_BOUND (uintmax_t)]; fprintf (stderr, _("%s: %s: line number out of range"), - program_name, quote (umaxtostr (p->lines_required, buf))); + program_name, quote (umaxtostr (p->lines_required, buf))); if (repetition) fprintf (stderr, _(" on repetition %s\n"), umaxtostr (repetition, buf)); else @@ -717,7 +717,7 @@ process_line_count (const struct control *p, uintmax_t repetition) { line = remove_line (); if (line == NULL) - handle_line_error (p, repetition); + handle_line_error (p, repetition); save_line_to_file (line); } @@ -734,7 +734,7 @@ static void regexp_error (struct control *p, uintmax_t repetition, bool ignore) { fprintf (stderr, _("%s: %s: match not found"), - program_name, quote (global_argv[p->argnum])); + program_name, quote (global_argv[p->argnum])); if (repetition) { @@ -774,75 +774,75 @@ process_regexp (struct control *p, uintmax_t repetition) if (p->offset >= 0) { for (;;) - { - line = find_line (++current_line); - if (line == NULL) - { - if (p->repeat_forever) - { - if (!ignore) - { - dump_rest_of_file (); - close_output_file (); - } - exit (EXIT_SUCCESS); - } - else - regexp_error (p, repetition, ignore); - } - line_len = line->len; - if (line->str[line_len - 1] == '\n') - line_len--; - ret = re_search (&p->re_compiled, line->str, line_len, - 0, line_len, NULL); - if (ret == -2) - { - error (0, 0, _("error in regular expression search")); - cleanup_fatal (); - } - if (ret == -1) - { - line = remove_line (); - if (!ignore) - save_line_to_file (line); - } - else - break; - } + { + line = find_line (++current_line); + if (line == NULL) + { + if (p->repeat_forever) + { + if (!ignore) + { + dump_rest_of_file (); + close_output_file (); + } + exit (EXIT_SUCCESS); + } + else + regexp_error (p, repetition, ignore); + } + line_len = line->len; + if (line->str[line_len - 1] == '\n') + line_len--; + ret = re_search (&p->re_compiled, line->str, line_len, + 0, line_len, NULL); + if (ret == -2) + { + error (0, 0, _("error in regular expression search")); + cleanup_fatal (); + } + if (ret == -1) + { + line = remove_line (); + if (!ignore) + save_line_to_file (line); + } + else + break; + } } else { /* Buffer the lines. */ for (;;) - { - line = find_line (++current_line); - if (line == NULL) - { - if (p->repeat_forever) - { - if (!ignore) - { - dump_rest_of_file (); - close_output_file (); - } - exit (EXIT_SUCCESS); - } - else - regexp_error (p, repetition, ignore); - } - line_len = line->len; - if (line->str[line_len - 1] == '\n') - line_len--; - ret = re_search (&p->re_compiled, line->str, line_len, - 0, line_len, NULL); - if (ret == -2) - { - error (0, 0, _("error in regular expression search")); - cleanup_fatal (); - } - if (ret != -1) - break; - } + { + line = find_line (++current_line); + if (line == NULL) + { + if (p->repeat_forever) + { + if (!ignore) + { + dump_rest_of_file (); + close_output_file (); + } + exit (EXIT_SUCCESS); + } + else + regexp_error (p, repetition, ignore); + } + line_len = line->len; + if (line->str[line_len - 1] == '\n') + line_len--; + ret = re_search (&p->re_compiled, line->str, line_len, + 0, line_len, NULL); + if (ret == -2) + { + error (0, 0, _("error in regular expression search")); + cleanup_fatal (); + } + if (ret != -1) + break; + } } /* Account for any offset from this regexp. */ @@ -868,17 +868,17 @@ split_file (void) { uintmax_t j; if (controls[i].regexpr) - { - for (j = 0; (controls[i].repeat_forever - || j <= controls[i].repeat); j++) - process_regexp (&controls[i], j); - } + { + for (j = 0; (controls[i].repeat_forever + || j <= controls[i].repeat); j++) + process_regexp (&controls[i], j); + } else - { - for (j = 0; (controls[i].repeat_forever - || j <= controls[i].repeat); j++) - process_line_count (&controls[i], j); - } + { + for (j = 0; (controls[i].repeat_forever + || j <= controls[i].repeat); j++) + process_line_count (&controls[i], j); + } } create_output_file (); @@ -946,7 +946,7 @@ delete_all_files (bool in_signal_handler) { const char *name = make_filename (i); if (unlink (name) != 0 && !in_signal_handler) - error (0, errno, "%s", name); + error (0, errno, "%s", name); } files_created = 0; @@ -961,41 +961,41 @@ close_output_file (void) if (output_stream) { if (ferror (output_stream)) - { - error (0, 0, _("write error for %s"), quote (output_filename)); - output_stream = NULL; - cleanup_fatal (); - } + { + error (0, 0, _("write error for %s"), quote (output_filename)); + output_stream = NULL; + cleanup_fatal (); + } if (fclose (output_stream) != 0) - { - error (0, errno, "%s", output_filename); - output_stream = NULL; - cleanup_fatal (); - } + { + error (0, errno, "%s", output_filename); + output_stream = NULL; + cleanup_fatal (); + } if (bytes_written == 0 && elide_empty_files) - { - sigset_t oldset; - bool unlink_ok; - int unlink_errno; - - /* Remove the output file in a critical section, to avoid races. */ - sigprocmask (SIG_BLOCK, &caught_signals, &oldset); - unlink_ok = (unlink (output_filename) == 0); - unlink_errno = errno; - files_created -= unlink_ok; - sigprocmask (SIG_SETMASK, &oldset, NULL); - - if (! unlink_ok) - error (0, unlink_errno, "%s", output_filename); - } + { + sigset_t oldset; + bool unlink_ok; + int unlink_errno; + + /* Remove the output file in a critical section, to avoid races. */ + sigprocmask (SIG_BLOCK, &caught_signals, &oldset); + unlink_ok = (unlink (output_filename) == 0); + unlink_errno = errno; + files_created -= unlink_ok; + sigprocmask (SIG_SETMASK, &oldset, NULL); + + if (! unlink_ok) + error (0, unlink_errno, "%s", output_filename); + } else - { - if (!suppress_count) - { - char buf[INT_BUFSIZE_BOUND (uintmax_t)]; - fprintf (stdout, "%s\n", umaxtostr (bytes_written, buf)); - } - } + { + if (!suppress_count) + { + char buf[INT_BUFSIZE_BOUND (uintmax_t)]; + fprintf (stdout, "%s\n", umaxtostr (bytes_written, buf)); + } + } output_stream = NULL; } } @@ -1062,11 +1062,11 @@ parse_repeat_count (int argnum, struct control *p, char *str) else { if (xstrtoumax (str + 1, NULL, 10, &val, "") != LONGINT_OK) - { - error (EXIT_FAILURE, 0, - _("%s}: integer required between `{' and `}'"), - global_argv[argnum]); - } + { + error (EXIT_FAILURE, 0, + _("%s}: integer required between `{' and `}'"), + global_argv[argnum]); + } p->repeat = val; } @@ -1091,7 +1091,7 @@ extract_regexp (int argnum, bool ignore, char const *str) closing_delim = strrchr (str + 1, delim); if (closing_delim == NULL) error (EXIT_FAILURE, 0, - _("%s: closing delimiter `%c' missing"), str, delim); + _("%s: closing delimiter `%c' missing"), str, delim); len = closing_delim - str - 1; p = new_control_record (); @@ -1132,44 +1132,44 @@ parse_patterns (int argc, int start, char **argv) for (i = start; i < argc; i++) { if (*argv[i] == '/' || *argv[i] == '%') - { - p = extract_regexp (i, *argv[i] == '%', argv[i]); - } + { + p = extract_regexp (i, *argv[i] == '%', argv[i]); + } else - { - p = new_control_record (); - p->argnum = i; - - if (xstrtoumax (argv[i], NULL, 10, &val, "") != LONGINT_OK) - error (EXIT_FAILURE, 0, _("%s: invalid pattern"), argv[i]); - if (val == 0) - error (EXIT_FAILURE, 0, - _("%s: line number must be greater than zero"), - argv[i]); - if (val < last_val) - { - char buf[INT_BUFSIZE_BOUND (uintmax_t)]; - error (EXIT_FAILURE, 0, - _("line number %s is smaller than preceding line number, %s"), - quote (argv[i]), umaxtostr (last_val, buf)); - } - - if (val == last_val) - error (0, 0, - _("warning: line number %s is the same as preceding line number"), - quote (argv[i])); - - last_val = val; - - p->lines_required = val; - } + { + p = new_control_record (); + p->argnum = i; + + if (xstrtoumax (argv[i], NULL, 10, &val, "") != LONGINT_OK) + error (EXIT_FAILURE, 0, _("%s: invalid pattern"), argv[i]); + if (val == 0) + error (EXIT_FAILURE, 0, + _("%s: line number must be greater than zero"), + argv[i]); + if (val < last_val) + { + char buf[INT_BUFSIZE_BOUND (uintmax_t)]; + error (EXIT_FAILURE, 0, + _("line number %s is smaller than preceding line number, %s"), + quote (argv[i]), umaxtostr (last_val, buf)); + } + + if (val == last_val) + error (0, 0, + _("warning: line number %s is the same as preceding line number"), + quote (argv[i])); + + last_val = val; + + p->lines_required = val; + } if (i + 1 < argc && *argv[i + 1] == '{') - { - /* We have a repeat count. */ - i++; - parse_repeat_count (i, p, argv[i]); - } + { + /* We have a repeat count. */ + i++; + parse_repeat_count (i, p, argv[i]); + } } } @@ -1181,22 +1181,22 @@ get_format_flags (char **format_ptr) for (; **format_ptr; (*format_ptr)++) { switch (**format_ptr) - { - case '-': - break; - - case '+': - case ' ': - count |= 1; - break; - - case '#': - count |= 2; /* Allow for 0x prefix preceding an `x' conversion. */ - break; - - default: - return count; - } + { + case '-': + break; + + case '+': + case ' ': + count |= 1; + break; + + case '#': + count |= 2; /* Allow for 0x prefix preceding an `x' conversion. */ + break; + + default: + return count; + } } return count; } @@ -1208,7 +1208,7 @@ get_format_width (char **format_ptr) if (ISDIGIT (**format_ptr) && (xstrtoul (*format_ptr, format_ptr, 10, &val, NULL) != LONGINT_OK - || SIZE_MAX < val)) + || SIZE_MAX < val)) error (EXIT_FAILURE, 0, _("invalid format width")); /* Allow for enough octal digits to represent the value of UINT_MAX, @@ -1229,8 +1229,8 @@ get_format_prec (char **format_ptr) { unsigned long int val; if (xstrtoul (*format_ptr, format_ptr, 10, &val, NULL) != LONGINT_OK - || SIZE_MAX < val) - error (EXIT_FAILURE, 0, _("invalid format precision")); + || SIZE_MAX < val) + error (EXIT_FAILURE, 0, _("invalid format precision")); return val; } } @@ -1257,10 +1257,10 @@ get_format_conv_type (char **format_ptr) default: if (isprint (ch)) error (EXIT_FAILURE, 0, - _("invalid conversion specifier in suffix: %c"), ch); + _("invalid conversion specifier in suffix: %c"), ch); else - error (EXIT_FAILURE, 0, - _("invalid conversion specifier in suffix: \\%.3o"), ch); + error (EXIT_FAILURE, 0, + _("invalid conversion specifier in suffix: \\%.3o"), ch); } } @@ -1275,30 +1275,30 @@ max_out (char *format) if (*format++ != '%') out_count++; else if (*format == '%') - { - format++; - out_count++; - } + { + format++; + out_count++; + } else - { - if (percent) - error (EXIT_FAILURE, 0, - _("too many %% conversion specifications in suffix")); - percent = true; - out_count += get_format_flags (&format); - { - size_t width = get_format_width (&format); - size_t prec = get_format_prec (&format); - - out_count += MAX (width, prec); - } - get_format_conv_type (&format); - } + { + if (percent) + error (EXIT_FAILURE, 0, + _("too many %% conversion specifications in suffix")); + percent = true; + out_count += get_format_flags (&format); + { + size_t width = get_format_width (&format); + size_t prec = get_format_prec (&format); + + out_count += MAX (width, prec); + } + get_format_conv_type (&format); + } } if (! percent) error (EXIT_FAILURE, 0, - _("missing %% conversion specification in suffix")); + _("missing %% conversion specification in suffix")); return out_count; } @@ -1328,47 +1328,47 @@ main (int argc, char **argv) switch (optc) { case 'f': - prefix = optarg; - break; + prefix = optarg; + break; case 'b': - suffix = optarg; - break; + suffix = optarg; + break; case 'k': - remove_files = false; - break; + remove_files = false; + break; case 'n': - if (xstrtoul (optarg, NULL, 10, &val, "") != LONGINT_OK - || val > INT_MAX) - error (EXIT_FAILURE, 0, _("%s: invalid number"), optarg); - digits = val; - break; + if (xstrtoul (optarg, NULL, 10, &val, "") != LONGINT_OK + || val > INT_MAX) + error (EXIT_FAILURE, 0, _("%s: invalid number"), optarg); + digits = val; + break; case 's': case 'q': - suppress_count = true; - break; + suppress_count = true; + break; case 'z': - elide_empty_files = true; - break; + elide_empty_files = true; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } if (argc - optind < 2) { if (argc <= optind) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } @@ -1385,22 +1385,22 @@ main (int argc, char **argv) int i; static int const sig[] = { - /* The usual suspects. */ - SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM, + /* The usual suspects. */ + SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM, #ifdef SIGPOLL - SIGPOLL, + SIGPOLL, #endif #ifdef SIGPROF - SIGPROF, + SIGPROF, #endif #ifdef SIGVTALRM - SIGVTALRM, + SIGVTALRM, #endif #ifdef SIGXCPU - SIGXCPU, + SIGXCPU, #endif #ifdef SIGXFSZ - SIGXFSZ, + SIGXFSZ, #endif }; enum { nsigs = ARRAY_CARDINALITY (sig) }; @@ -1410,9 +1410,9 @@ main (int argc, char **argv) sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { - sigaction (sig[i], NULL, &act); - if (act.sa_handler != SIG_IGN) - sigaddset (&caught_signals, sig[i]); + sigaction (sig[i], NULL, &act); + if (act.sa_handler != SIG_IGN) + sigaddset (&caught_signals, sig[i]); } act.sa_handler = interrupt_handler; @@ -1421,7 +1421,7 @@ main (int argc, char **argv) for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, sig[i])) - sigaction (sig[i], &act, NULL); + sigaction (sig[i], &act, NULL); } split_file (); @@ -1440,13 +1440,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... FILE PATTERN...\n\ "), - program_name); + program_name); fputs (_("\ Output pieces of FILE separated by PATTERN(s) to files `xx00', `xx01', ...,\n\ and output byte counts of each piece to standard output.\n\ @@ -60,11 +60,11 @@ do \ { \ if (low == 0 || high == 0) \ - FATAL_ERROR (_("fields and positions are numbered from 1")); \ + FATAL_ERROR (_("fields and positions are numbered from 1")); \ if (n_rp >= n_rp_allocated) \ - { \ - (rp) = X2NREALLOC (rp, &n_rp_allocated); \ - } \ + { \ + (rp) = X2NREALLOC (rp, &n_rp_allocated); \ + } \ rp[n_rp].lo = (low); \ rp[n_rp].hi = (high); \ ++n_rp; \ @@ -183,13 +183,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s OPTION... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Print selected parts of lines from each FILE to standard output.\n\ \n\ @@ -347,7 +347,7 @@ set_fields (const char *fieldstr) bool rhs_specified = false; bool dash_found = false; /* True if a '-' is found in this field. */ bool field_found = false; /* True if at least one field spec - has been processed. */ + has been processed. */ struct range_pair *rp = NULL; size_t n_rp = 0; @@ -361,139 +361,139 @@ set_fields (const char *fieldstr) for (;;) { if (*fieldstr == '-') - { - in_digits = false; - /* Starting a range. */ - if (dash_found) - FATAL_ERROR (_("invalid byte or field list")); - dash_found = true; - fieldstr++; - - initial = (lhs_specified ? value : 1); - value = 0; - } + { + in_digits = false; + /* Starting a range. */ + if (dash_found) + FATAL_ERROR (_("invalid byte or field list")); + dash_found = true; + fieldstr++; + + initial = (lhs_specified ? value : 1); + value = 0; + } else if (*fieldstr == ',' || - isblank (to_uchar (*fieldstr)) || *fieldstr == '\0') - { - in_digits = false; - /* Ending the string, or this field/byte sublist. */ - if (dash_found) - { - dash_found = false; - - if (!lhs_specified && !rhs_specified) - FATAL_ERROR (_("invalid range with no endpoint: -")); - - /* A range. Possibilities: -n, m-n, n-. - In any case, `initial' contains the start of the range. */ - if (!rhs_specified) - { - /* `n-'. From `initial' to end of line. */ - eol_range_start = initial; - field_found = true; - } - else - { - /* `m-n' or `-n' (1-n). */ - if (value < initial) - FATAL_ERROR (_("invalid decreasing range")); - - /* Is there already a range going to end of line? */ - if (eol_range_start != 0) - { - /* Yes. Is the new sequence already contained - in the old one? If so, no processing is - necessary. */ - if (initial < eol_range_start) - { - /* No, the new sequence starts before the - old. Does the old range going to end of line - extend into the new range? */ - if (eol_range_start <= value) - { - /* Yes. Simply move the end of line marker. */ - eol_range_start = initial; - } - else - { - /* No. A simple range, before and disjoint from - the range going to end of line. Fill it. */ - ADD_RANGE_PAIR (rp, initial, value); - } - - /* In any case, some fields were selected. */ - field_found = true; - } - } - else - { - /* There is no range going to end of line. */ - ADD_RANGE_PAIR (rp, initial, value); - field_found = true; - } - value = 0; - } - } - else - { - /* A simple field number, not a range. */ - ADD_RANGE_PAIR (rp, value, value); - value = 0; - field_found = true; - } - - if (*fieldstr == '\0') - { - break; - } - - fieldstr++; - lhs_specified = false; - rhs_specified = false; - } + isblank (to_uchar (*fieldstr)) || *fieldstr == '\0') + { + in_digits = false; + /* Ending the string, or this field/byte sublist. */ + if (dash_found) + { + dash_found = false; + + if (!lhs_specified && !rhs_specified) + FATAL_ERROR (_("invalid range with no endpoint: -")); + + /* A range. Possibilities: -n, m-n, n-. + In any case, `initial' contains the start of the range. */ + if (!rhs_specified) + { + /* `n-'. From `initial' to end of line. */ + eol_range_start = initial; + field_found = true; + } + else + { + /* `m-n' or `-n' (1-n). */ + if (value < initial) + FATAL_ERROR (_("invalid decreasing range")); + + /* Is there already a range going to end of line? */ + if (eol_range_start != 0) + { + /* Yes. Is the new sequence already contained + in the old one? If so, no processing is + necessary. */ + if (initial < eol_range_start) + { + /* No, the new sequence starts before the + old. Does the old range going to end of line + extend into the new range? */ + if (eol_range_start <= value) + { + /* Yes. Simply move the end of line marker. */ + eol_range_start = initial; + } + else + { + /* No. A simple range, before and disjoint from + the range going to end of line. Fill it. */ + ADD_RANGE_PAIR (rp, initial, value); + } + + /* In any case, some fields were selected. */ + field_found = true; + } + } + else + { + /* There is no range going to end of line. */ + ADD_RANGE_PAIR (rp, initial, value); + field_found = true; + } + value = 0; + } + } + else + { + /* A simple field number, not a range. */ + ADD_RANGE_PAIR (rp, value, value); + value = 0; + field_found = true; + } + + if (*fieldstr == '\0') + { + break; + } + + fieldstr++; + lhs_specified = false; + rhs_specified = false; + } else if (ISDIGIT (*fieldstr)) - { - /* Record beginning of digit string, in case we have to - complain about it. */ - static char const *num_start; - if (!in_digits || !num_start) - num_start = fieldstr; - in_digits = true; - - if (dash_found) - rhs_specified = 1; - else - lhs_specified = 1; - - /* Detect overflow. */ - if (!DECIMAL_DIGIT_ACCUMULATE (value, *fieldstr - '0', size_t)) - { - /* In case the user specified -c$(echo 2^64|bc),22, - complain only about the first number. */ - /* Determine the length of the offending number. */ - size_t len = strspn (num_start, "0123456789"); - char *bad_num = xstrndup (num_start, len); - if (operating_mode == byte_mode) - error (0, 0, - _("byte offset %s is too large"), quote (bad_num)); - else - error (0, 0, - _("field number %s is too large"), quote (bad_num)); - free (bad_num); - exit (EXIT_FAILURE); - } - - fieldstr++; - } + { + /* Record beginning of digit string, in case we have to + complain about it. */ + static char const *num_start; + if (!in_digits || !num_start) + num_start = fieldstr; + in_digits = true; + + if (dash_found) + rhs_specified = 1; + else + lhs_specified = 1; + + /* Detect overflow. */ + if (!DECIMAL_DIGIT_ACCUMULATE (value, *fieldstr - '0', size_t)) + { + /* In case the user specified -c$(echo 2^64|bc),22, + complain only about the first number. */ + /* Determine the length of the offending number. */ + size_t len = strspn (num_start, "0123456789"); + char *bad_num = xstrndup (num_start, len); + if (operating_mode == byte_mode) + error (0, 0, + _("byte offset %s is too large"), quote (bad_num)); + else + error (0, 0, + _("field number %s is too large"), quote (bad_num)); + free (bad_num); + exit (EXIT_FAILURE); + } + + fieldstr++; + } else - FATAL_ERROR (_("invalid byte or field list")); + FATAL_ERROR (_("invalid byte or field list")); } max_range_endpoint = 0; for (i = 0; i < n_rp; i++) { if (rp[i].hi > max_range_endpoint) - max_range_endpoint = rp[i].hi; + max_range_endpoint = rp[i].hi; } /* Allocate an array large enough so that it may be indexed by @@ -511,14 +511,14 @@ set_fields (const char *fieldstr) size_t rsi_candidate; /* Record the range-start indices, i.e., record each start - index that is not part of any other (lo..hi] range. */ + index that is not part of any other (lo..hi] range. */ rsi_candidate = complement ? rp[i].hi + 1 : rp[i].lo; if (output_delimiter_specified - && !is_printable_field (rsi_candidate)) - mark_range_start (rsi_candidate); + && !is_printable_field (rsi_candidate)) + mark_range_start (rsi_candidate); for (j = rp[i].lo; j <= rp[i].hi; j++) - mark_printable_field (j); + mark_printable_field (j); } if (output_delimiter_specified @@ -550,32 +550,32 @@ cut_bytes (FILE *stream) c = getc (stream); if (c == '\n') - { - putchar ('\n'); - byte_idx = 0; - print_delimiter = false; - } + { + putchar ('\n'); + byte_idx = 0; + print_delimiter = false; + } else if (c == EOF) - { - if (byte_idx > 0) - putchar ('\n'); - break; - } + { + if (byte_idx > 0) + putchar ('\n'); + break; + } else - { - bool range_start; - bool *rs = output_delimiter_specified ? &range_start : NULL; - if (print_kth (++byte_idx, rs)) - { - if (rs && *rs && print_delimiter) - { - fwrite (output_delimiter_string, sizeof (char), - output_delimiter_length, stdout); - } - print_delimiter = true; - putchar (c); - } - } + { + bool range_start; + bool *rs = output_delimiter_specified ? &range_start : NULL; + if (print_kth (++byte_idx, rs)) + { + if (rs && *rs && print_delimiter) + { + fwrite (output_delimiter_string, sizeof (char), + output_delimiter_length, stdout); + } + print_delimiter = true; + putchar (c); + } + } } } @@ -606,98 +606,98 @@ cut_fields (FILE *stream) while (1) { if (field_idx == 1 && buffer_first_field) - { - ssize_t len; - size_t n_bytes; - - len = getndelim2 (&field_1_buffer, &field_1_bufsize, 0, - GETNLINE_NO_LIMIT, delim, '\n', stream); - if (len < 0) - { - free (field_1_buffer); - field_1_buffer = NULL; - if (ferror (stream) || feof (stream)) - break; - xalloc_die (); - } - - n_bytes = len; - assert (n_bytes != 0); - - /* If the first field extends to the end of line (it is not - delimited) and we are printing all non-delimited lines, - print this one. */ - if (to_uchar (field_1_buffer[n_bytes - 1]) != delim) - { - if (suppress_non_delimited) - { - /* Empty. */ - } - else - { - fwrite (field_1_buffer, sizeof (char), n_bytes, stdout); - /* Make sure the output line is newline terminated. */ - if (field_1_buffer[n_bytes - 1] != '\n') - putchar ('\n'); - } - continue; - } - if (print_kth (1, NULL)) - { - /* Print the field, but not the trailing delimiter. */ - fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout); - found_any_selected_field = true; - } - ++field_idx; - } + { + ssize_t len; + size_t n_bytes; + + len = getndelim2 (&field_1_buffer, &field_1_bufsize, 0, + GETNLINE_NO_LIMIT, delim, '\n', stream); + if (len < 0) + { + free (field_1_buffer); + field_1_buffer = NULL; + if (ferror (stream) || feof (stream)) + break; + xalloc_die (); + } + + n_bytes = len; + assert (n_bytes != 0); + + /* If the first field extends to the end of line (it is not + delimited) and we are printing all non-delimited lines, + print this one. */ + if (to_uchar (field_1_buffer[n_bytes - 1]) != delim) + { + if (suppress_non_delimited) + { + /* Empty. */ + } + else + { + fwrite (field_1_buffer, sizeof (char), n_bytes, stdout); + /* Make sure the output line is newline terminated. */ + if (field_1_buffer[n_bytes - 1] != '\n') + putchar ('\n'); + } + continue; + } + if (print_kth (1, NULL)) + { + /* Print the field, but not the trailing delimiter. */ + fwrite (field_1_buffer, sizeof (char), n_bytes - 1, stdout); + found_any_selected_field = true; + } + ++field_idx; + } if (c != EOF) - { - if (print_kth (field_idx, NULL)) - { - if (found_any_selected_field) - { - fwrite (output_delimiter_string, sizeof (char), - output_delimiter_length, stdout); - } - found_any_selected_field = true; - - while ((c = getc (stream)) != delim && c != '\n' && c != EOF) - { - putchar (c); - } - } - else - { - while ((c = getc (stream)) != delim && c != '\n' && c != EOF) - { - /* Empty. */ - } - } - } + { + if (print_kth (field_idx, NULL)) + { + if (found_any_selected_field) + { + fwrite (output_delimiter_string, sizeof (char), + output_delimiter_length, stdout); + } + found_any_selected_field = true; + + while ((c = getc (stream)) != delim && c != '\n' && c != EOF) + { + putchar (c); + } + } + else + { + while ((c = getc (stream)) != delim && c != '\n' && c != EOF) + { + /* Empty. */ + } + } + } if (c == '\n') - { - c = getc (stream); - if (c != EOF) - { - ungetc (c, stream); - c = '\n'; - } - } + { + c = getc (stream); + if (c != EOF) + { + ungetc (c, stream); + c = '\n'; + } + } if (c == delim) - ++field_idx; + ++field_idx; else if (c == '\n' || c == EOF) - { - if (found_any_selected_field - || !(suppress_non_delimited && field_idx == 1)) - putchar ('\n'); - if (c == EOF) - break; - field_idx = 1; - found_any_selected_field = false; - } + { + if (found_any_selected_field + || !(suppress_non_delimited && field_idx == 1)) + putchar ('\n'); + if (c == EOF) + break; + field_idx = 1; + found_any_selected_field = false; + } } } @@ -727,10 +727,10 @@ cut_file (char const *file) { stream = fopen (file, "r"); if (stream == NULL) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } } cut_stream (stream); @@ -777,60 +777,60 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "b:c:d:f:ns", longopts, NULL)) != -1) { switch (optc) - { - case 'b': - case 'c': - /* Build the byte list. */ - if (operating_mode != undefined_mode) - FATAL_ERROR (_("only one type of list may be specified")); - operating_mode = byte_mode; - spec_list_string = optarg; - break; - - case 'f': - /* Build the field list. */ - if (operating_mode != undefined_mode) - FATAL_ERROR (_("only one type of list may be specified")); - operating_mode = field_mode; - spec_list_string = optarg; - break; - - case 'd': - /* New delimiter. */ - /* Interpret -d '' to mean `use the NUL byte as the delimiter.' */ - if (optarg[0] != '\0' && optarg[1] != '\0') - FATAL_ERROR (_("the delimiter must be a single character")); - delim = optarg[0]; - delim_specified = true; - break; - - case OUTPUT_DELIMITER_OPTION: - output_delimiter_specified = true; - /* Interpret --output-delimiter='' to mean - `use the NUL byte as the delimiter.' */ - output_delimiter_length = (optarg[0] == '\0' - ? 1 : strlen (optarg)); - output_delimiter_string = xstrdup (optarg); - break; - - case 'n': - break; - - case 's': - suppress_non_delimited = true; - break; - - case COMPLEMENT_OPTION: - complement = true; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'b': + case 'c': + /* Build the byte list. */ + if (operating_mode != undefined_mode) + FATAL_ERROR (_("only one type of list may be specified")); + operating_mode = byte_mode; + spec_list_string = optarg; + break; + + case 'f': + /* Build the field list. */ + if (operating_mode != undefined_mode) + FATAL_ERROR (_("only one type of list may be specified")); + operating_mode = field_mode; + spec_list_string = optarg; + break; + + case 'd': + /* New delimiter. */ + /* Interpret -d '' to mean `use the NUL byte as the delimiter.' */ + if (optarg[0] != '\0' && optarg[1] != '\0') + FATAL_ERROR (_("the delimiter must be a single character")); + delim = optarg[0]; + delim_specified = true; + break; + + case OUTPUT_DELIMITER_OPTION: + output_delimiter_specified = true; + /* Interpret --output-delimiter='' to mean + `use the NUL byte as the delimiter.' */ + output_delimiter_length = (optarg[0] == '\0' + ? 1 : strlen (optarg)); + output_delimiter_string = xstrdup (optarg); + break; + + case 'n': + break; + + case 's': + suppress_non_delimited = true; + break; + + case COMPLEMENT_OPTION: + complement = true; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (operating_mode == undefined_mode) @@ -847,19 +847,19 @@ main (int argc, char **argv) if (output_delimiter_specified) { range_start_ht = hash_initialize (HT_RANGE_START_INDEX_INITIAL_CAPACITY, - NULL, hash_int, - hash_compare_ints, NULL); + NULL, hash_int, + hash_compare_ints, NULL); if (range_start_ht == NULL) - xalloc_die (); + xalloc_die (); } if (! set_fields (spec_list_string)) { if (operating_mode == field_mode) - FATAL_ERROR (_("missing list of fields")); + FATAL_ERROR (_("missing list of fields")); else - FATAL_ERROR (_("missing list of positions")); + FATAL_ERROR (_("missing list of positions")); } if (!delim_specified) diff --git a/src/date.c b/src/date.c index 022107d40..cbc53e6a5 100644 --- a/src/date.c +++ b/src/date.c @@ -118,14 +118,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [+FORMAT]\n\ or: %s [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Display the current time in the given FORMAT, or set the system date.\n\ \n\ @@ -264,9 +264,9 @@ batch_convert (const char *input_filename, const char *format) { in_stream = fopen (input_filename, "r"); if (in_stream == NULL) - { - error (EXIT_FAILURE, errno, "%s", quote (input_filename)); - } + { + error (EXIT_FAILURE, errno, "%s", quote (input_filename)); + } } line = NULL; @@ -276,22 +276,22 @@ batch_convert (const char *input_filename, const char *format) { ssize_t line_length = getline (&line, &buflen, in_stream); if (line_length < 0) - { - /* FIXME: detect/handle error here. */ - break; - } + { + /* FIXME: detect/handle error here. */ + break; + } if (! get_date (&when, line, NULL)) - { - if (line[line_length - 1] == '\n') - line[line_length - 1] = '\0'; - error (0, 0, _("invalid date %s"), quote (line)); - ok = false; - } + { + if (line[line_length - 1] == '\n') + line[line_length - 1] = '\0'; + error (0, 0, _("invalid date %s"), quote (line)); + ok = false; + } else - { - ok &= show_date (format, when); - } + { + ok &= show_date (format, when); + } } if (fclose (in_stream) == EOF) @@ -326,138 +326,138 @@ main (int argc, char **argv) atexit (close_stdout); while ((optc = getopt_long (argc, argv, short_options, long_options, NULL)) - != -1) + != -1) { char const *new_format = NULL; switch (optc) - { - case 'd': - datestr = optarg; - break; - case 'f': - batch_file = optarg; - break; - case RFC_3339_OPTION: - { - static char const rfc_3339_format[][32] = - { - "%Y-%m-%d", - "%Y-%m-%d %H:%M:%S%:z", - "%Y-%m-%d %H:%M:%S.%N%:z" - }; - enum Time_spec i = - XARGMATCH ("--rfc-3339", optarg, - time_spec_string + 2, time_spec + 2); - new_format = rfc_3339_format[i]; - break; - } - case 'I': - { - static char const iso_8601_format[][32] = - { - "%Y-%m-%d", - "%Y-%m-%dT%H:%M:%S%z", - "%Y-%m-%dT%H:%M:%S,%N%z", - "%Y-%m-%dT%H%z", - "%Y-%m-%dT%H:%M%z" - }; - enum Time_spec i = - (optarg - ? XARGMATCH ("--iso-8601", optarg, time_spec_string, time_spec) - : TIME_SPEC_DATE); - new_format = iso_8601_format[i]; - break; - } - case 'r': - reference = optarg; - break; - case 'R': - new_format = rfc_2822_format; - break; - case 's': - set_datestr = optarg; - set_date = true; - break; - case 'u': - /* POSIX says that `date -u' is equivalent to setting the TZ - environment variable, so this option should do nothing other - than setting TZ. */ - if (putenv (bad_cast ("TZ=UTC0")) != 0) - xalloc_die (); - TZSET; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'd': + datestr = optarg; + break; + case 'f': + batch_file = optarg; + break; + case RFC_3339_OPTION: + { + static char const rfc_3339_format[][32] = + { + "%Y-%m-%d", + "%Y-%m-%d %H:%M:%S%:z", + "%Y-%m-%d %H:%M:%S.%N%:z" + }; + enum Time_spec i = + XARGMATCH ("--rfc-3339", optarg, + time_spec_string + 2, time_spec + 2); + new_format = rfc_3339_format[i]; + break; + } + case 'I': + { + static char const iso_8601_format[][32] = + { + "%Y-%m-%d", + "%Y-%m-%dT%H:%M:%S%z", + "%Y-%m-%dT%H:%M:%S,%N%z", + "%Y-%m-%dT%H%z", + "%Y-%m-%dT%H:%M%z" + }; + enum Time_spec i = + (optarg + ? XARGMATCH ("--iso-8601", optarg, time_spec_string, time_spec) + : TIME_SPEC_DATE); + new_format = iso_8601_format[i]; + break; + } + case 'r': + reference = optarg; + break; + case 'R': + new_format = rfc_2822_format; + break; + case 's': + set_datestr = optarg; + set_date = true; + break; + case 'u': + /* POSIX says that `date -u' is equivalent to setting the TZ + environment variable, so this option should do nothing other + than setting TZ. */ + if (putenv (bad_cast ("TZ=UTC0")) != 0) + xalloc_die (); + TZSET; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } if (new_format) - { - if (format) - error (EXIT_FAILURE, 0, _("multiple output formats specified")); - format = new_format; - } + { + if (format) + error (EXIT_FAILURE, 0, _("multiple output formats specified")); + format = new_format; + } } option_specified_date = ((datestr ? 1 : 0) - + (batch_file ? 1 : 0) - + (reference ? 1 : 0)); + + (batch_file ? 1 : 0) + + (reference ? 1 : 0)); if (option_specified_date > 1) { error (0, 0, - _("the options to specify dates for printing are mutually exclusive")); + _("the options to specify dates for printing are mutually exclusive")); usage (EXIT_FAILURE); } if (set_date && option_specified_date) { error (0, 0, - _("the options to print and set the time may not be used together")); + _("the options to print and set the time may not be used together")); usage (EXIT_FAILURE); } if (optind < argc) { if (optind + 1 < argc) - { - error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); + usage (EXIT_FAILURE); + } if (argv[optind][0] == '+') - { - if (format) - error (EXIT_FAILURE, 0, _("multiple output formats specified")); - format = argv[optind++] + 1; - } + { + if (format) + error (EXIT_FAILURE, 0, _("multiple output formats specified")); + format = argv[optind++] + 1; + } else if (set_date || option_specified_date) - { - error (0, 0, - _("the argument %s lacks a leading `+';\n" - "when using an option to specify date(s), any non-option\n" - "argument must be a format string beginning with `+'"), - quote (argv[optind])); - usage (EXIT_FAILURE); - } + { + error (0, 0, + _("the argument %s lacks a leading `+';\n" + "when using an option to specify date(s), any non-option\n" + "argument must be a format string beginning with `+'"), + quote (argv[optind])); + usage (EXIT_FAILURE); + } } if (!format) { format = DATE_FMT_LANGINFO (); if (! *format) - { - /* Do not wrap the following literal format string with _(...). - For example, suppose LC_ALL is unset, LC_TIME="POSIX", - and LANG="ko_KR". In that case, POSIX says that LC_TIME - determines the format and contents of date and time strings - written by date, which means "date" must generate output - using the POSIX locale; but adding _() would cause "date" - to use a Korean translation of the format. */ - format = "%a %b %e %H:%M:%S %Z %Y"; - } + { + /* Do not wrap the following literal format string with _(...). + For example, suppose LC_ALL is unset, LC_TIME="POSIX", + and LANG="ko_KR". In that case, POSIX says that LC_TIME + determines the format and contents of date and time strings + written by date, which means "date" must generate output + using the POSIX locale; but adding _() would cause "date" + to use a Korean translation of the format. */ + format = "%a %b %e %H:%M:%S %Z %Y"; + } } if (batch_file != NULL) @@ -468,55 +468,55 @@ main (int argc, char **argv) ok = true; if (!option_specified_date && !set_date) - { - if (optind < argc) - { - /* Prepare to set system clock to the specified date/time - given in the POSIX-format. */ - set_date = true; - datestr = argv[optind]; - valid_date = posixtime (&when.tv_sec, - datestr, - (PDS_TRAILING_YEAR - | PDS_CENTURY | PDS_SECONDS)); - when.tv_nsec = 0; /* FIXME: posixtime should set this. */ - } - else - { - /* Prepare to print the current date/time. */ - gettime (&when); - } - } + { + if (optind < argc) + { + /* Prepare to set system clock to the specified date/time + given in the POSIX-format. */ + set_date = true; + datestr = argv[optind]; + valid_date = posixtime (&when.tv_sec, + datestr, + (PDS_TRAILING_YEAR + | PDS_CENTURY | PDS_SECONDS)); + when.tv_nsec = 0; /* FIXME: posixtime should set this. */ + } + else + { + /* Prepare to print the current date/time. */ + gettime (&when); + } + } else - { - /* (option_specified_date || set_date) */ - if (reference != NULL) - { - if (stat (reference, &refstats) != 0) - error (EXIT_FAILURE, errno, "%s", reference); - when = get_stat_mtime (&refstats); - } - else - { - if (set_datestr) - datestr = set_datestr; - valid_date = get_date (&when, datestr, NULL); - } - } + { + /* (option_specified_date || set_date) */ + if (reference != NULL) + { + if (stat (reference, &refstats) != 0) + error (EXIT_FAILURE, errno, "%s", reference); + when = get_stat_mtime (&refstats); + } + else + { + if (set_datestr) + datestr = set_datestr; + valid_date = get_date (&when, datestr, NULL); + } + } if (! valid_date) - error (EXIT_FAILURE, 0, _("invalid date %s"), quote (datestr)); + error (EXIT_FAILURE, 0, _("invalid date %s"), quote (datestr)); if (set_date) - { - /* Set the system clock to the specified date, then regardless of - the success of that operation, format and print that date. */ - if (settime (&when) != 0) - { - error (0, errno, _("cannot set date")); - ok = false; - } - } + { + /* Set the system clock to the specified date, then regardless of + the success of that operation, format and print that date. */ + if (settime (&when) != 0) + { + error (0, errno, _("cannot set date")); + ok = false; + } + } ok &= show_date (format, when); } @@ -82,7 +82,7 @@ static void process_signals (void); { \ obuf[oc++] = (c); \ if (oc >= output_blocksize) \ - write_output (); \ + write_output (); \ } \ while (0) @@ -457,14 +457,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPERAND]...\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Copy a file, converting and formatting according to the operands.\n\ \n\ @@ -522,36 +522,36 @@ Each FLAG symbol may be:\n\ append append mode (makes sense only for output; conv=notrunc suggested)\n\ "), stdout); if (O_CIO) - fputs (_(" cio use concurrent I/O for data\n"), stdout); + fputs (_(" cio use concurrent I/O for data\n"), stdout); if (O_DIRECT) - fputs (_(" direct use direct I/O for data\n"), stdout); + fputs (_(" direct use direct I/O for data\n"), stdout); if (O_DIRECTORY) - fputs (_(" directory fail unless a directory\n"), stdout); + fputs (_(" directory fail unless a directory\n"), stdout); if (O_DSYNC) - fputs (_(" dsync use synchronized I/O for data\n"), stdout); + fputs (_(" dsync use synchronized I/O for data\n"), stdout); if (O_SYNC) - fputs (_(" sync likewise, but also for metadata\n"), stdout); + fputs (_(" sync likewise, but also for metadata\n"), stdout); fputs (_(" fullblock accumulate full blocks of input (iflag only)\n"), - stdout); + stdout); if (O_NONBLOCK) - fputs (_(" nonblock use non-blocking I/O\n"), stdout); + fputs (_(" nonblock use non-blocking I/O\n"), stdout); if (O_NOATIME) - fputs (_(" noatime do not update access time\n"), stdout); + fputs (_(" noatime do not update access time\n"), stdout); if (O_NOCTTY) - fputs (_(" noctty do not assign controlling terminal from file\n"), - stdout); + fputs (_(" noctty do not assign controlling terminal from file\n"), + stdout); if (HAVE_WORKING_O_NOFOLLOW) - fputs (_(" nofollow do not follow symlinks\n"), stdout); + fputs (_(" nofollow do not follow symlinks\n"), stdout); if (O_NOLINKS) - fputs (_(" nolinks fail if multiply-linked\n"), stdout); + fputs (_(" nolinks fail if multiply-linked\n"), stdout); if (O_BINARY) - fputs (_(" binary use binary I/O for data\n"), stdout); + fputs (_(" binary use binary I/O for data\n"), stdout); if (O_TEXT) - fputs (_(" text use text I/O for data\n"), stdout); + fputs (_(" text use text I/O for data\n"), stdout); { - char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO"); - printf (_("\ + char const *siginfo_name = (SIGINFO == SIGUSR1 ? "USR1" : "INFO"); + printf (_("\ \n\ Sending a %s signal to a running `dd' process makes it\n\ print I/O statistics to standard error and then resume copying.\n\ @@ -565,7 +565,7 @@ print I/O statistics to standard error and then resume copying.\n\ Options are:\n\ \n\ "), - siginfo_name, siginfo_name); + siginfo_name, siginfo_name); } fputs (HELP_OPTION_DESCRIPTION, stdout); @@ -607,16 +607,16 @@ print_stats (void) char const *bytes_per_second; fprintf (stderr, - _("%"PRIuMAX"+%"PRIuMAX" records in\n" - "%"PRIuMAX"+%"PRIuMAX" records out\n"), - r_full, r_partial, w_full, w_partial); + _("%"PRIuMAX"+%"PRIuMAX" records in\n" + "%"PRIuMAX"+%"PRIuMAX" records out\n"), + r_full, r_partial, w_full, w_partial); if (r_truncate != 0) fprintf (stderr, - ngettext ("%"PRIuMAX" truncated record\n", - "%"PRIuMAX" truncated records\n", - select_plural (r_truncate)), - r_truncate); + ngettext ("%"PRIuMAX" truncated record\n", + "%"PRIuMAX" truncated records\n", + select_plural (r_truncate)), + r_truncate); if (status_flags & STATUS_NOXFER) return; @@ -625,11 +625,11 @@ print_stats (void) since that makes it easy to use SI abbreviations. */ fprintf (stderr, - ngettext ("%"PRIuMAX" byte (%s) copied", - "%"PRIuMAX" bytes (%s) copied", - select_plural (w_bytes)), - w_bytes, - human_readable (w_bytes, hbuf, human_opts, 1, 1)); + ngettext ("%"PRIuMAX" byte (%s) copied", + "%"PRIuMAX" bytes (%s) copied", + select_plural (w_bytes)), + w_bytes, + human_readable (w_bytes, hbuf, human_opts, 1, 1)); if (start_time < now) { @@ -638,7 +638,7 @@ print_stats (void) delta_xtime -= start_time; delta_s = delta_xtime / XTIME_PRECISIONe0; bytes_per_second = human_readable (w_bytes, hbuf, human_opts, - XTIME_PRECISION, delta_xtime); + XTIME_PRECISION, delta_xtime); } else { @@ -664,14 +664,14 @@ cleanup (void) { if (close (STDIN_FILENO) < 0) error (EXIT_FAILURE, errno, - _("closing input file %s"), quote (input_file)); + _("closing input file %s"), quote (input_file)); /* Don't remove this call to close, even though close_stdout closes standard output. This close is necessary when cleanup is called as part of a signal handler. */ if (close (STDOUT_FILENO) < 0) error (EXIT_FAILURE, errno, - _("closing output file %s"), quote (output_file)); + _("closing output file %s"), quote (output_file)); } static void ATTRIBUTE_NORETURN @@ -718,7 +718,7 @@ install_signal_handlers (void) { sigaction (SIGINFO, NULL, &act); if (act.sa_handler != SIG_IGN) - sigaddset (&caught_signals, SIGINFO); + sigaddset (&caught_signals, SIGINFO); } sigaction (SIGINT, NULL, &act); if (act.sa_handler != SIG_IGN) @@ -735,8 +735,8 @@ install_signal_handlers (void) if (sigismember (&caught_signals, SIGINT)) { /* POSIX 1003.1-2001 says SA_RESETHAND implies SA_NODEFER, - but this is not true on Solaris 8 at least. It doesn't - hurt to use SA_NODEFER here, so leave it in. */ + but this is not true on Solaris 8 at least. It doesn't + hurt to use SA_NODEFER here, so leave it in. */ act.sa_handler = interrupt_handler; act.sa_flags = SA_NODEFER | SA_RESETHAND; sigaction (SIGINT, &act, NULL); @@ -773,20 +773,20 @@ process_signals (void) sigprocmask (SIG_BLOCK, &caught_signals, &oldset); /* Reload interrupt_signal and info_signal_count, in case a new - signal was handled before sigprocmask took effect. */ + signal was handled before sigprocmask took effect. */ interrupt = interrupt_signal; infos = info_signal_count; if (infos) - info_signal_count = infos - 1; + info_signal_count = infos - 1; sigprocmask (SIG_SETMASK, &oldset, NULL); if (interrupt) - cleanup (); + cleanup (); print_stats (); if (interrupt) - raise (interrupt); + raise (interrupt); } } @@ -803,7 +803,7 @@ iread (int fd, char *buf, size_t size) process_signals (); nread = read (fd, buf, size); if (! (nread < 0 && errno == EINTR)) - return nread; + return nread; } } @@ -817,9 +817,9 @@ iread_fullblock (int fd, char *buf, size_t size) { ssize_t ncurr = iread (fd, buf, size); if (ncurr < 0) - return ncurr; + return ncurr; if (ncurr == 0) - break; + break; nread += ncurr; buf += ncurr; size -= ncurr; @@ -868,20 +868,20 @@ iwrite (int fd, char const *buf, size_t size) process_signals (); nwritten = write (fd, buf + total_written, size - total_written); if (nwritten < 0) - { - if (errno != EINTR) - break; - } + { + if (errno != EINTR) + break; + } else if (nwritten == 0) - { - /* Some buggy drivers return 0 when one tries to write beyond - a device's end. (Example: Linux kernel 1.2.13 on /dev/fd0.) - Set errno to ENOSPC so they get a sensible diagnostic. */ - errno = ENOSPC; - break; - } + { + /* Some buggy drivers return 0 when one tries to write beyond + a device's end. (Example: Linux kernel 1.2.13 on /dev/fd0.) + Set errno to ENOSPC so they get a sensible diagnostic. */ + errno = ENOSPC; + break; + } else - total_written += nwritten; + total_written += nwritten; } return total_written; @@ -898,7 +898,7 @@ write_output (void) { error (0, errno, _("writing to %s"), quote (output_file)); if (nwritten != 0) - w_partial++; + w_partial++; quit (EXIT_FAILURE); } else @@ -923,7 +923,7 @@ operand_matches (char const *str, char const *pattern, char delim) static int parse_symbols (char const *str, struct symbol_value const *table, - char const *error_msgid) + char const *error_msgid) { int value = 0; @@ -933,21 +933,21 @@ parse_symbols (char const *str, struct symbol_value const *table, struct symbol_value const *entry; for (entry = table; - ! (operand_matches (str, entry->symbol, ',') && entry->value); - entry++) - { - if (! entry->symbol[0]) - { - size_t slen = strcomma ? strcomma - str : strlen (str); - error (0, 0, "%s: %s", _(error_msgid), - quotearg_n_style_mem (0, locale_quoting_style, str, slen)); - usage (EXIT_FAILURE); - } - } + ! (operand_matches (str, entry->symbol, ',') && entry->value); + entry++) + { + if (! entry->symbol[0]) + { + size_t slen = strcomma ? strcomma - str : strlen (str); + error (0, 0, "%s: %s", _(error_msgid), + quotearg_n_style_mem (0, locale_quoting_style, str, slen)); + usage (EXIT_FAILURE); + } + } value |= entry->value; if (!strcomma) - break; + break; str = strcomma + 1; } @@ -970,10 +970,10 @@ parse_integer (const char *str, bool *invalid) uintmax_t multiplier = parse_integer (suffix + 1, invalid); if (multiplier != 0 && n * multiplier / multiplier != n) - { - *invalid = true; - return 0; - } + { + *invalid = true; + return 0; + } n *= multiplier; } @@ -1006,68 +1006,68 @@ scanargs (int argc, char *const *argv) char const *val = strchr (name, '='); if (val == NULL) - { - error (0, 0, _("unrecognized operand %s"), quote (name)); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("unrecognized operand %s"), quote (name)); + usage (EXIT_FAILURE); + } val++; if (operand_is (name, "if")) - input_file = val; + input_file = val; else if (operand_is (name, "of")) - output_file = val; + output_file = val; else if (operand_is (name, "conv")) - conversions_mask |= parse_symbols (val, conversions, - N_("invalid conversion")); + conversions_mask |= parse_symbols (val, conversions, + N_("invalid conversion")); else if (operand_is (name, "iflag")) - input_flags |= parse_symbols (val, flags, - N_("invalid input flag")); + input_flags |= parse_symbols (val, flags, + N_("invalid input flag")); else if (operand_is (name, "oflag")) - output_flags |= parse_symbols (val, flags, - N_("invalid output flag")); + output_flags |= parse_symbols (val, flags, + N_("invalid output flag")); else if (operand_is (name, "status")) - status_flags |= parse_symbols (val, statuses, - N_("invalid status flag")); + status_flags |= parse_symbols (val, statuses, + N_("invalid status flag")); else - { - bool invalid = false; - uintmax_t n = parse_integer (val, &invalid); - - if (operand_is (name, "ibs")) - { - invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP)); - input_blocksize = n; - } - else if (operand_is (name, "obs")) - { - invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP)); - output_blocksize = n; - } - else if (operand_is (name, "bs")) - { - invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP)); - blocksize = n; - } - else if (operand_is (name, "cbs")) - { - invalid |= ! (0 < n && n <= SIZE_MAX); - conversion_blocksize = n; - } - else if (operand_is (name, "skip")) - skip_records = n; - else if (operand_is (name, "seek")) - seek_records = n; - else if (operand_is (name, "count")) - max_records = n; - else - { - error (0, 0, _("unrecognized operand %s"), quote (name)); - usage (EXIT_FAILURE); - } - - if (invalid) - error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val)); - } + { + bool invalid = false; + uintmax_t n = parse_integer (val, &invalid); + + if (operand_is (name, "ibs")) + { + invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP)); + input_blocksize = n; + } + else if (operand_is (name, "obs")) + { + invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (OUTPUT_BLOCK_SLOP)); + output_blocksize = n; + } + else if (operand_is (name, "bs")) + { + invalid |= ! (0 < n && n <= MAX_BLOCKSIZE (INPUT_BLOCK_SLOP)); + blocksize = n; + } + else if (operand_is (name, "cbs")) + { + invalid |= ! (0 < n && n <= SIZE_MAX); + conversion_blocksize = n; + } + else if (operand_is (name, "skip")) + skip_records = n; + else if (operand_is (name, "seek")) + seek_records = n; + else if (operand_is (name, "count")) + max_records = n; + else + { + error (0, 0, _("unrecognized operand %s"), quote (name)); + usage (EXIT_FAILURE); + } + + if (invalid) + error (EXIT_FAILURE, 0, _("invalid number %s"), quote (val)); + } } if (blocksize) @@ -1075,7 +1075,7 @@ scanargs (int argc, char *const *argv) else { /* POSIX says dd aggregates short reads into - output_blocksize if bs= is not specified. */ + output_blocksize if bs= is not specified. */ conversions_mask |= C_TWOBUFS; } @@ -1095,8 +1095,8 @@ scanargs (int argc, char *const *argv) usage (EXIT_FAILURE); } iread_fnc = ((input_flags & O_FULLBLOCK) - ? iread_fullblock - : iread); + ? iread_fullblock + : iread); input_flags &= ~O_FULLBLOCK; if (multiple_bits_set (conversions_mask & (C_ASCII | C_EBCDIC | C_IBM))) @@ -1122,13 +1122,13 @@ apply_translations (void) if (conversions_mask & C_UCASE) { for (i = 0; i < 256; i++) - trans_table[i] = toupper (trans_table[i]); + trans_table[i] = toupper (trans_table[i]); translation_needed = true; } else if (conversions_mask & C_LCASE) { for (i = 0; i < 256; i++) - trans_table[i] = tolower (trans_table[i]); + trans_table[i] = tolower (trans_table[i]); translation_needed = true; } @@ -1254,7 +1254,7 @@ skip_via_lseek (char const *filename, int fdesc, off_t offset, int whence) { error (0, 0, _("warning: working around lseek kernel bug for file (%s)\n\ of mt_type=0x%0lx -- see <sys/mtio.h> for the list of types"), - filename, s2.mt_type); + filename, s2.mt_type); errno = 0; new_position = -1; } @@ -1288,20 +1288,20 @@ skip (int fdesc, char const *file, uintmax_t records, size_t blocksize, { if (fdesc == STDIN_FILENO) { - struct stat st; - if (fstat (STDIN_FILENO, &st) != 0) - error (EXIT_FAILURE, errno, _("cannot fstat %s"), quote (file)); - if (S_ISREG (st.st_mode) && st.st_size < (input_offset + offset)) - { - /* When skipping past EOF, return the number of _full_ blocks - * that are not skipped, and set offset to EOF, so the caller - * can determine the requested skip was not satisfied. */ - records = ( offset - st.st_size ) / blocksize; - offset = st.st_size - input_offset; - } - else - records = 0; - advance_input_offset (offset); + struct stat st; + if (fstat (STDIN_FILENO, &st) != 0) + error (EXIT_FAILURE, errno, _("cannot fstat %s"), quote (file)); + if (S_ISREG (st.st_mode) && st.st_size < (input_offset + offset)) + { + /* When skipping past EOF, return the number of _full_ blocks + * that are not skipped, and set offset to EOF, so the caller + * can determine the requested skip was not satisfied. */ + records = ( offset - st.st_size ) / blocksize; + offset = st.st_size - input_offset; + } + else + records = 0; + advance_input_offset (offset); } else records = 0; @@ -1318,56 +1318,56 @@ skip (int fdesc, char const *file, uintmax_t records, size_t blocksize, Therefore try to seek to the end of the file, to avoid redundant reading. */ if ((soffset = skip_via_lseek (file, fdesc, 0, SEEK_END)) >= 0) - { - /* File is seekable, and we're at the end of it, and - size <= OFF_T_MAX. So there's no point using read to advance. */ - - if (!lseek_errno) - { - /* The original seek was not attempted as offset > OFF_T_MAX. - We should error for write as can't get to the desired - location, even if OFF_T_MAX < max file size. - For read we're not going to read any data anyway, - so we should error for consistency. - It would be nice to not error for /dev/{zero,null} - for any offset, but that's not a significant issue. */ - lseek_errno = EOVERFLOW; - } - - if (fdesc == STDIN_FILENO) - error (0, lseek_errno, _("%s: cannot skip"), quote (file)); - else - error (0, lseek_errno, _("%s: cannot seek"), quote (file)); - /* If the file has a specific size and we've asked - to skip/seek beyond the max allowable, then quit. */ - quit (EXIT_FAILURE); - } + { + /* File is seekable, and we're at the end of it, and + size <= OFF_T_MAX. So there's no point using read to advance. */ + + if (!lseek_errno) + { + /* The original seek was not attempted as offset > OFF_T_MAX. + We should error for write as can't get to the desired + location, even if OFF_T_MAX < max file size. + For read we're not going to read any data anyway, + so we should error for consistency. + It would be nice to not error for /dev/{zero,null} + for any offset, but that's not a significant issue. */ + lseek_errno = EOVERFLOW; + } + + if (fdesc == STDIN_FILENO) + error (0, lseek_errno, _("%s: cannot skip"), quote (file)); + else + error (0, lseek_errno, _("%s: cannot seek"), quote (file)); + /* If the file has a specific size and we've asked + to skip/seek beyond the max allowable, then quit. */ + quit (EXIT_FAILURE); + } /* else file_size && offset > OFF_T_MAX or file ! seekable */ do - { - ssize_t nread = iread_fnc (fdesc, buf, blocksize); - if (nread < 0) - { - if (fdesc == STDIN_FILENO) - { - error (0, errno, _("reading %s"), quote (file)); - if (conversions_mask & C_NOERROR) - { - print_stats (); - continue; - } - } - else - error (0, lseek_errno, _("%s: cannot seek"), quote (file)); - quit (EXIT_FAILURE); - } - - if (nread == 0) - break; - if (fdesc == STDIN_FILENO) - advance_input_offset (nread); - } + { + ssize_t nread = iread_fnc (fdesc, buf, blocksize); + if (nread < 0) + { + if (fdesc == STDIN_FILENO) + { + error (0, errno, _("reading %s"), quote (file)); + if (conversions_mask & C_NOERROR) + { + print_stats (); + continue; + } + } + else + error (0, lseek_errno, _("%s: cannot seek"), quote (file)); + quit (EXIT_FAILURE); + } + + if (nread == 0) + break; + if (fdesc == STDIN_FILENO) + advance_input_offset (nread); + } while (--records != 0); return records; @@ -1386,7 +1386,7 @@ advance_input_after_read_error (size_t nbytes) if (! input_seekable) { if (input_seek_errno == ESPIPE) - return true; + return true; errno = input_seek_errno; } else @@ -1395,25 +1395,25 @@ advance_input_after_read_error (size_t nbytes) advance_input_offset (nbytes); input_offset_overflow |= (OFF_T_MAX < input_offset); if (input_offset_overflow) - { - error (0, 0, _("offset overflow while reading file %s"), - quote (input_file)); - return false; - } + { + error (0, 0, _("offset overflow while reading file %s"), + quote (input_file)); + return false; + } offset = lseek (STDIN_FILENO, 0, SEEK_CUR); if (0 <= offset) - { - off_t diff; - if (offset == input_offset) - return true; - diff = input_offset - offset; - if (! (0 <= diff && diff <= nbytes)) - error (0, 0, _("warning: invalid file offset after failed read")); - if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR)) - return true; - if (errno == 0) - error (0, 0, _("cannot work around kernel bug after all")); - } + { + off_t diff; + if (offset == input_offset) + return true; + diff = input_offset - offset; + if (! (0 <= diff && diff <= nbytes)) + error (0, 0, _("warning: invalid file offset after failed read")); + if (0 <= skip_via_lseek (input_file, STDIN_FILENO, diff, SEEK_CUR)) + return true; + if (errno == 0) + error (0, 0, _("cannot work around kernel bug after all")); + } } error (0, errno, _("%s: cannot seek"), quote (input_file)); @@ -1437,7 +1437,7 @@ copy_simple (char const *buf, size_t nread) start += nfree; oc += nfree; if (oc >= output_blocksize) - write_output (); + write_output (); } while (nread != 0); } @@ -1454,23 +1454,23 @@ copy_with_block (char const *buf, size_t nread) for (i = nread; i; i--, buf++) { if (*buf == newline_character) - { - if (col < conversion_blocksize) - { - size_t j; - for (j = col; j < conversion_blocksize; j++) - output_char (space_character); - } - col = 0; - } + { + if (col < conversion_blocksize) + { + size_t j; + for (j = col; j < conversion_blocksize; j++) + output_char (space_character); + } + col = 0; + } else - { - if (col == conversion_blocksize) - r_truncate++; - else if (col < conversion_blocksize) - output_char (*buf); - col++; - } + { + if (col == conversion_blocksize) + r_truncate++; + else if (col < conversion_blocksize) + output_char (*buf); + col++; + } } } @@ -1490,24 +1490,24 @@ copy_with_unblock (char const *buf, size_t nread) c = buf[i]; if (col++ >= conversion_blocksize) - { - col = pending_spaces = 0; /* Wipe out any pending spaces. */ - i--; /* Push the char back; get it later. */ - output_char (newline_character); - } + { + col = pending_spaces = 0; /* Wipe out any pending spaces. */ + i--; /* Push the char back; get it later. */ + output_char (newline_character); + } else if (c == space_character) - pending_spaces++; + pending_spaces++; else - { - /* `c' is the character after a run of spaces that were not - at the end of the conversion buffer. Output them. */ - while (pending_spaces) - { - output_char (space_character); - --pending_spaces; - } - output_char (c); - } + { + /* `c' is the character after a run of spaces that were not + at the end of the conversion buffer. Output them. */ + while (pending_spaces) + { + output_char (space_character); + --pending_spaces; + } + output_char (c); + } } } @@ -1526,36 +1526,36 @@ set_fd_flags (int fd, int add_flags, char const *name) int new_flags = old_flags | add_flags; bool ok = true; if (old_flags < 0) - ok = false; + ok = false; else if (old_flags != new_flags) - { - if (new_flags & (O_DIRECTORY | O_NOLINKS)) - { - /* NEW_FLAGS contains at least one file creation flag that - requires some checking of the open file descriptor. */ - struct stat st; - if (fstat (fd, &st) != 0) - ok = false; - else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode)) - { - errno = ENOTDIR; - ok = false; - } - else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink) - { - errno = EMLINK; - ok = false; - } - new_flags &= ~ (O_DIRECTORY | O_NOLINKS); - } - - if (ok && old_flags != new_flags - && fcntl (fd, F_SETFL, new_flags) == -1) - ok = false; - } + { + if (new_flags & (O_DIRECTORY | O_NOLINKS)) + { + /* NEW_FLAGS contains at least one file creation flag that + requires some checking of the open file descriptor. */ + struct stat st; + if (fstat (fd, &st) != 0) + ok = false; + else if ((new_flags & O_DIRECTORY) && ! S_ISDIR (st.st_mode)) + { + errno = ENOTDIR; + ok = false; + } + else if ((new_flags & O_NOLINKS) && 1 < st.st_nlink) + { + errno = EMLINK; + ok = false; + } + new_flags &= ~ (O_DIRECTORY | O_NOLINKS); + } + + if (ok && old_flags != new_flags + && fcntl (fd, F_SETFL, new_flags) == -1) + ok = false; + } if (!ok) - error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name)); + error (EXIT_FAILURE, errno, _("setting flags for %s"), quote (name)); } } @@ -1617,40 +1617,40 @@ dd_copy (void) { uintmax_t us_bytes = input_offset + (skip_records * input_blocksize); uintmax_t us_blocks = skip (STDIN_FILENO, input_file, - skip_records, input_blocksize, ibuf); + skip_records, input_blocksize, ibuf); us_bytes -= input_offset; /* POSIX doesn't say what to do when dd detects it has been - asked to skip past EOF, so I assume it's non-fatal. - There are 3 reasons why there might be unskipped blocks/bytes: - 1. file is too small - 2. pipe has not enough data - 3. short reads */ + asked to skip past EOF, so I assume it's non-fatal. + There are 3 reasons why there might be unskipped blocks/bytes: + 1. file is too small + 2. pipe has not enough data + 3. short reads */ if (us_blocks || (!input_offset_overflow && us_bytes)) - { - error (0, 0, - _("%s: cannot skip to specified offset"), quote (input_file)); - } + { + error (0, 0, + _("%s: cannot skip to specified offset"), quote (input_file)); + } } if (seek_records != 0) { uintmax_t write_records = skip (STDOUT_FILENO, output_file, - seek_records, output_blocksize, obuf); + seek_records, output_blocksize, obuf); if (write_records != 0) - { - memset (obuf, 0, output_blocksize); - - do - if (iwrite (STDOUT_FILENO, obuf, output_blocksize) - != output_blocksize) - { - error (0, errno, _("writing to %s"), quote (output_file)); - quit (EXIT_FAILURE); - } - while (--write_records != 0); - } + { + memset (obuf, 0, output_blocksize); + + do + if (iwrite (STDOUT_FILENO, obuf, output_blocksize) + != output_blocksize) + { + error (0, errno, _("writing to %s"), quote (output_file)); + quit (EXIT_FAILURE); + } + while (--write_records != 0); + } } if (max_records == 0) @@ -1659,106 +1659,106 @@ dd_copy (void) while (1) { if (r_partial + r_full >= max_records) - break; + break; /* Zero the buffer before reading, so that if we get a read error, - whatever data we are able to read is followed by zeros. - This minimizes data loss. */ + whatever data we are able to read is followed by zeros. + This minimizes data loss. */ if ((conversions_mask & C_SYNC) && (conversions_mask & C_NOERROR)) - memset (ibuf, - (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0', - input_blocksize); + memset (ibuf, + (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0', + input_blocksize); nread = iread_fnc (STDIN_FILENO, ibuf, input_blocksize); if (nread == 0) - break; /* EOF. */ + break; /* EOF. */ if (nread < 0) - { - error (0, errno, _("reading %s"), quote (input_file)); - if (conversions_mask & C_NOERROR) - { - print_stats (); - /* Seek past the bad block if possible. */ - if (!advance_input_after_read_error (input_blocksize - partread)) - { - exit_status = EXIT_FAILURE; - - /* Suppress duplicate diagnostics. */ - input_seekable = false; - input_seek_errno = ESPIPE; - } - if ((conversions_mask & C_SYNC) && !partread) - /* Replace the missing input with null bytes and - proceed normally. */ - nread = 0; - else - continue; - } - else - { - /* Write any partial block. */ - exit_status = EXIT_FAILURE; - break; - } - } + { + error (0, errno, _("reading %s"), quote (input_file)); + if (conversions_mask & C_NOERROR) + { + print_stats (); + /* Seek past the bad block if possible. */ + if (!advance_input_after_read_error (input_blocksize - partread)) + { + exit_status = EXIT_FAILURE; + + /* Suppress duplicate diagnostics. */ + input_seekable = false; + input_seek_errno = ESPIPE; + } + if ((conversions_mask & C_SYNC) && !partread) + /* Replace the missing input with null bytes and + proceed normally. */ + nread = 0; + else + continue; + } + else + { + /* Write any partial block. */ + exit_status = EXIT_FAILURE; + break; + } + } n_bytes_read = nread; advance_input_offset (nread); if (n_bytes_read < input_blocksize) - { - r_partial++; - partread = n_bytes_read; - if (conversions_mask & C_SYNC) - { - if (!(conversions_mask & C_NOERROR)) - /* If C_NOERROR, we zeroed the block before reading. */ - memset (ibuf + n_bytes_read, - (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0', - input_blocksize - n_bytes_read); - n_bytes_read = input_blocksize; - } - } + { + r_partial++; + partread = n_bytes_read; + if (conversions_mask & C_SYNC) + { + if (!(conversions_mask & C_NOERROR)) + /* If C_NOERROR, we zeroed the block before reading. */ + memset (ibuf + n_bytes_read, + (conversions_mask & (C_BLOCK | C_UNBLOCK)) ? ' ' : '\0', + input_blocksize - n_bytes_read); + n_bytes_read = input_blocksize; + } + } else - { - r_full++; - partread = 0; - } + { + r_full++; + partread = 0; + } if (ibuf == obuf) /* If not C_TWOBUFS. */ - { - size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read); - w_bytes += nwritten; - if (nwritten != n_bytes_read) - { - error (0, errno, _("writing %s"), quote (output_file)); - return EXIT_FAILURE; - } - else if (n_bytes_read == input_blocksize) - w_full++; - else - w_partial++; - continue; - } + { + size_t nwritten = iwrite (STDOUT_FILENO, obuf, n_bytes_read); + w_bytes += nwritten; + if (nwritten != n_bytes_read) + { + error (0, errno, _("writing %s"), quote (output_file)); + return EXIT_FAILURE; + } + else if (n_bytes_read == input_blocksize) + w_full++; + else + w_partial++; + continue; + } /* Do any translations on the whole buffer at once. */ if (translation_needed) - translate_buffer (ibuf, n_bytes_read); + translate_buffer (ibuf, n_bytes_read); if (conversions_mask & C_SWAB) - bufstart = swab_buffer (ibuf, &n_bytes_read); + bufstart = swab_buffer (ibuf, &n_bytes_read); else - bufstart = ibuf; + bufstart = ibuf; if (conversions_mask & C_BLOCK) copy_with_block (bufstart, n_bytes_read); else if (conversions_mask & C_UNBLOCK) - copy_with_unblock (bufstart, n_bytes_read); + copy_with_unblock (bufstart, n_bytes_read); else - copy_simple (bufstart, n_bytes_read); + copy_simple (bufstart, n_bytes_read); } /* If we have a char left as a result of conv=swab, output it. */ @@ -1767,18 +1767,18 @@ dd_copy (void) if (conversions_mask & C_BLOCK) copy_with_block (&saved_char, 1); else if (conversions_mask & C_UNBLOCK) - copy_with_unblock (&saved_char, 1); + copy_with_unblock (&saved_char, 1); else - output_char (saved_char); + output_char (saved_char); } if ((conversions_mask & C_BLOCK) && col > 0) { /* If the final input line didn't end with a '\n', pad - the output block to `conversion_blocksize' chars. */ + the output block to `conversion_blocksize' chars. */ size_t i; for (i = col; i < conversion_blocksize; i++) - output_char (space_character); + output_char (space_character); } if ((conversions_mask & C_UNBLOCK) && col == conversion_blocksize) @@ -1792,31 +1792,31 @@ dd_copy (void) size_t nwritten = iwrite (STDOUT_FILENO, obuf, oc); w_bytes += nwritten; if (nwritten != 0) - w_partial++; + w_partial++; if (nwritten != oc) - { - error (0, errno, _("writing %s"), quote (output_file)); - return EXIT_FAILURE; - } + { + error (0, errno, _("writing %s"), quote (output_file)); + return EXIT_FAILURE; + } } if ((conversions_mask & C_FDATASYNC) && fdatasync (STDOUT_FILENO) != 0) { if (errno != ENOSYS && errno != EINVAL) - { - error (0, errno, _("fdatasync failed for %s"), quote (output_file)); - exit_status = EXIT_FAILURE; - } + { + error (0, errno, _("fdatasync failed for %s"), quote (output_file)); + exit_status = EXIT_FAILURE; + } conversions_mask |= C_FSYNC; } if (conversions_mask & C_FSYNC) while (fsync (STDOUT_FILENO) != 0) if (errno != EINTR) - { - error (0, errno, _("fsync failed for %s"), quote (output_file)); - return EXIT_FAILURE; - } + { + error (0, errno, _("fsync failed for %s"), quote (output_file)); + return EXIT_FAILURE; + } return exit_status; } @@ -1842,7 +1842,7 @@ main (int argc, char **argv) page_size = getpagesize (); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); close_stdout_required = false; if (getopt_long (argc, argv, "", NULL, NULL) != -1) @@ -1865,7 +1865,7 @@ main (int argc, char **argv) else { if (fd_reopen (STDIN_FILENO, input_file, O_RDONLY | input_flags, 0) < 0) - error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file)); + error (EXIT_FAILURE, errno, _("opening %s"), quote (input_file)); } offset = lseek (STDIN_FILENO, 0, SEEK_CUR); @@ -1882,52 +1882,52 @@ main (int argc, char **argv) { mode_t perms = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; int opts - = (output_flags - | (conversions_mask & C_NOCREAT ? 0 : O_CREAT) - | (conversions_mask & C_EXCL ? O_EXCL : 0) - | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC)); + = (output_flags + | (conversions_mask & C_NOCREAT ? 0 : O_CREAT) + | (conversions_mask & C_EXCL ? O_EXCL : 0) + | (seek_records || (conversions_mask & C_NOTRUNC) ? 0 : O_TRUNC)); /* Open the output file with *read* access only if we might - need to read to satisfy a `seek=' request. If we can't read - the file, go ahead with write-only access; it might work. */ + need to read to satisfy a `seek=' request. If we can't read + the file, go ahead with write-only access; it might work. */ if ((! seek_records - || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0) - && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms) - < 0)) - error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file)); + || fd_reopen (STDOUT_FILENO, output_file, O_RDWR | opts, perms) < 0) + && (fd_reopen (STDOUT_FILENO, output_file, O_WRONLY | opts, perms) + < 0)) + error (EXIT_FAILURE, errno, _("opening %s"), quote (output_file)); if (seek_records != 0 && !(conversions_mask & C_NOTRUNC)) - { - uintmax_t size = seek_records * output_blocksize; - unsigned long int obs = output_blocksize; - - if (OFF_T_MAX / output_blocksize < seek_records) - error (EXIT_FAILURE, 0, - _("offset too large: " - "cannot truncate to a length of seek=%"PRIuMAX"" - " (%lu-byte) blocks"), - seek_records, obs); - - if (ftruncate (STDOUT_FILENO, size) != 0) - { - /* Complain only when ftruncate fails on a regular file, a - directory, or a shared memory object, as POSIX 1003.1-2004 - specifies ftruncate's behavior only for these file types. - For example, do not complain when Linux kernel 2.4 ftruncate - fails on /dev/fd0. */ - int ftruncate_errno = errno; - struct stat stdout_stat; - if (fstat (STDOUT_FILENO, &stdout_stat) != 0) - error (EXIT_FAILURE, errno, _("cannot fstat %s"), - quote (output_file)); - if (S_ISREG (stdout_stat.st_mode) - || S_ISDIR (stdout_stat.st_mode) - || S_TYPEISSHM (&stdout_stat)) - error (EXIT_FAILURE, ftruncate_errno, + { + uintmax_t size = seek_records * output_blocksize; + unsigned long int obs = output_blocksize; + + if (OFF_T_MAX / output_blocksize < seek_records) + error (EXIT_FAILURE, 0, + _("offset too large: " + "cannot truncate to a length of seek=%"PRIuMAX"" + " (%lu-byte) blocks"), + seek_records, obs); + + if (ftruncate (STDOUT_FILENO, size) != 0) + { + /* Complain only when ftruncate fails on a regular file, a + directory, or a shared memory object, as POSIX 1003.1-2004 + specifies ftruncate's behavior only for these file types. + For example, do not complain when Linux kernel 2.4 ftruncate + fails on /dev/fd0. */ + int ftruncate_errno = errno; + struct stat stdout_stat; + if (fstat (STDOUT_FILENO, &stdout_stat) != 0) + error (EXIT_FAILURE, errno, _("cannot fstat %s"), + quote (output_file)); + if (S_ISREG (stdout_stat.st_mode) + || S_ISDIR (stdout_stat.st_mode) + || S_TYPEISSHM (&stdout_stat)) + error (EXIT_FAILURE, ftruncate_errno, _("failed to truncate to %"PRIuMAX" bytes in output file %s"), - size, quote (output_file)); - } - } + size, quote (output_file)); + } + } } start_time = gethrxtime (); @@ -158,22 +158,22 @@ print_header (void) else if (human_output_opts & human_autoscale) { if (human_output_opts & human_base_1024) - printf (_(" Size Used Avail Use%%")); + printf (_(" Size Used Avail Use%%")); else - printf (_(" Size Used Avail Use%%")); + printf (_(" Size Used Avail Use%%")); } else if (posix_format) printf (_(" %s-blocks Used Available Capacity"), - umaxtostr (output_block_size, buf)); + umaxtostr (output_block_size, buf)); else { int opts = (human_suppress_point_zero - | human_autoscale | human_SI - | (human_output_opts - & (human_group_digits | human_base_1024 | human_B))); + | human_autoscale | human_SI + | (human_output_opts + & (human_group_digits | human_base_1024 | human_B))); /* Prefer the base that makes the human-readable value more exact, - if there is a difference. */ + if there is a difference. */ uintmax_t q1000 = output_block_size; uintmax_t q1024 = output_block_size; @@ -181,21 +181,21 @@ print_header (void) bool divisible_by_1024; do - { - divisible_by_1000 = q1000 % 1000 == 0; q1000 /= 1000; - divisible_by_1024 = q1024 % 1024 == 0; q1024 /= 1024; - } + { + divisible_by_1000 = q1000 % 1000 == 0; q1000 /= 1000; + divisible_by_1024 = q1024 % 1024 == 0; q1024 /= 1024; + } while (divisible_by_1000 & divisible_by_1024); if (divisible_by_1000 < divisible_by_1024) - opts |= human_base_1024; + opts |= human_base_1024; if (divisible_by_1024 < divisible_by_1000) - opts &= ~human_base_1024; + opts &= ~human_base_1024; if (! (opts & human_base_1024)) - opts |= human_B; + opts |= human_B; printf (_(" %4s-blocks Used Available Use%%"), - human_readable (output_block_size, buf, opts, 1, 1)); + human_readable (output_block_size, buf, opts, 1, 1)); } printf (_(" Mounted on\n")); @@ -250,16 +250,16 @@ known_value (uintmax_t n) static char const * df_readable (bool negative, uintmax_t n, char *buf, - uintmax_t input_units, uintmax_t output_units) + uintmax_t input_units, uintmax_t output_units) { if (! known_value (n) && !negative) return "-"; else { char *p = human_readable (negative ? -n : n, buf + negative, - human_output_opts, input_units, output_units); + human_output_opts, input_units, output_units); if (negative) - *--p = '-'; + *--p = '-'; return p; } } @@ -273,7 +273,7 @@ df_readable (bool negative, uintmax_t n, char *buf, how the negation flag is used. */ static void add_uint_with_neg_flag (uintmax_t *dest, bool *dest_neg, - uintmax_t src, bool src_neg) + uintmax_t src, bool src_neg) { if (LOG_EQ (*dest_neg, src_neg)) { @@ -314,9 +314,9 @@ add_uint_with_neg_flag (uintmax_t *dest, bool *dest_neg, static void show_dev (char const *disk, char const *mount_point, - char const *stat_file, char const *fstype, - bool me_dummy, bool me_remote, - const struct fs_usage *force_fsu) + char const *stat_file, char const *fstype, + bool me_dummy, bool me_remote, + const struct fs_usage *force_fsu) { struct fs_usage fsu; char buf[3][LONGEST_HUMAN_READABLE + 2]; @@ -379,18 +379,18 @@ show_dev (char const *disk, char const *mount_point, size_t disk_name_len = strlen (disk); size_t fstype_len = strlen (fstype); if (disk_name_len + fstype_len < 18) - printf ("%s%*s ", disk, 18 - (int) disk_name_len, fstype); + printf ("%s%*s ", disk, 18 - (int) disk_name_len, fstype); else if (!posix_format) - printf ("%s\n%18s ", disk, fstype); + printf ("%s\n%18s ", disk, fstype); else - printf ("%s %s", disk, fstype); + printf ("%s %s", disk, fstype); } else { if (strlen (disk) > 20 && !posix_format) - printf ("%s\n%20s", disk, ""); + printf ("%s\n%20s", disk, ""); else - printf ("%-20s", disk); + printf ("%-20s", disk); } if (inode_format) @@ -404,44 +404,44 @@ show_dev (char const *disk, char const *mount_point, available_to_root = available; if (known_value (total)) - grand_fsu.fsu_files += total; + grand_fsu.fsu_files += total; if (known_value (available)) - grand_fsu.fsu_ffree += available; + grand_fsu.fsu_ffree += available; } else { if (human_output_opts & human_autoscale) - width = 5 + ! (human_output_opts & human_base_1024); + width = 5 + ! (human_output_opts & human_base_1024); else - { - width = 9; - if (posix_format) - { - uintmax_t b; - col1_adjustment = -3; - for (b = output_block_size; 9 < b; b /= 10) - col1_adjustment++; - } - } + { + width = 9; + if (posix_format) + { + uintmax_t b; + col1_adjustment = -3; + for (b = output_block_size; 9 < b; b /= 10) + col1_adjustment++; + } + } use_width = ((posix_format - && ! (human_output_opts & human_autoscale)) - ? 8 : 4); + && ! (human_output_opts & human_autoscale)) + ? 8 : 4); input_units = fsu.fsu_blocksize; output_units = output_block_size; total = fsu.fsu_blocks; available = fsu.fsu_bavail; negate_available = (fsu.fsu_bavail_top_bit_set - & known_value (available)); + & known_value (available)); available_to_root = fsu.fsu_bfree; if (known_value (total)) - grand_fsu.fsu_blocks += input_units * total; + grand_fsu.fsu_blocks += input_units * total; if (known_value (available_to_root)) - grand_fsu.fsu_bfree += input_units * available_to_root; + grand_fsu.fsu_bfree += input_units * available_to_root; if (known_value (available)) - add_uint_with_neg_flag (&grand_fsu.fsu_bavail, - &grand_fsu.fsu_bavail_top_bit_set, - input_units * available, negate_available); + add_uint_with_neg_flag (&grand_fsu.fsu_bavail, + &grand_fsu.fsu_bavail_top_bit_set, + input_units * available, negate_available); } used = UINTMAX_MAX; @@ -453,20 +453,20 @@ show_dev (char const *disk, char const *mount_point, } printf (" %*s %*s %*s ", - width + col1_adjustment, - df_readable (false, total, - buf[0], input_units, output_units), - width, df_readable (negate_used, used, - buf[1], input_units, output_units), - width, df_readable (negate_available, available, - buf[2], input_units, output_units)); + width + col1_adjustment, + df_readable (false, total, + buf[0], input_units, output_units), + width, df_readable (negate_used, used, + buf[1], input_units, output_units), + width, df_readable (negate_available, available, + buf[2], input_units, output_units)); if (! known_value (used) || ! known_value (available)) ; else if (!negate_used - && used <= TYPE_MAXIMUM (uintmax_t) / 100 - && used + available != 0 - && (used + available < used) == negate_available) + && used <= TYPE_MAXIMUM (uintmax_t) / 100 + && used + available != 0 + && (used + available < used) == negate_available) { uintmax_t u100 = used * 100; uintmax_t nonroot_total = used + available; @@ -475,23 +475,23 @@ show_dev (char const *disk, char const *mount_point, else { /* The calculation cannot be done easily with integer - arithmetic. Fall back on floating point. This can suffer - from minor rounding errors, but doing it exactly requires - multiple precision arithmetic, and it's not worth the - aggravation. */ + arithmetic. Fall back on floating point. This can suffer + from minor rounding errors, but doing it exactly requires + multiple precision arithmetic, and it's not worth the + aggravation. */ double u = negate_used ? - (double) - used : used; double a = negate_available ? - (double) - available : available; double nonroot_total = u + a; if (nonroot_total) - { - long int lipct = pct = u * 100 / nonroot_total; - double ipct = lipct; - - /* Like `pct = ceil (dpct);', but avoid ceil so that - the math library needn't be linked. */ - if (ipct - 1 < pct && pct <= ipct + 1) - pct = ipct + (ipct < pct); - } + { + long int lipct = pct = u * 100 / nonroot_total; + double ipct = lipct; + + /* Like `pct = ceil (dpct);', but avoid ceil so that + the math library needn't be linked. */ + if (ipct - 1 < pct && pct <= ipct + 1) + pct = ipct + (ipct < pct); + } } if (0 <= pct) @@ -503,12 +503,12 @@ show_dev (char const *disk, char const *mount_point, { #ifdef HIDE_AUTOMOUNT_PREFIX /* Don't print the first directory name in MOUNT_POINT if it's an - artifact of an automounter. This is a bit too aggressive to be - the default. */ + artifact of an automounter. This is a bit too aggressive to be + the default. */ if (strncmp ("/auto/", mount_point, 6) == 0) - mount_point += 5; + mount_point += 5; else if (strncmp ("/tmp_mnt/", mount_point, 9) == 0) - mount_point += 8; + mount_point += 8; #endif printf (" %s", mount_point); } @@ -537,10 +537,10 @@ find_mount_point (const char *file, const struct stat *file_stat) { last_stat = *file_stat; if (chdir (file) < 0) - { - error (0, errno, _("cannot change to directory %s"), quote (file)); - return NULL; - } + { + error (0, errno, _("cannot change to directory %s"), quote (file)); + return NULL; + } } else /* FILE is some other kind of file; use its directory. */ @@ -551,17 +551,17 @@ find_mount_point (const char *file, const struct stat *file_stat) free (xdir); if (chdir (dir) < 0) - { - error (0, errno, _("cannot change to directory %s"), quote (dir)); - return NULL; - } + { + error (0, errno, _("cannot change to directory %s"), quote (dir)); + return NULL; + } if (stat (".", &last_stat) < 0) - { - error (0, errno, _("cannot stat current directory (now %s)"), - quote (dir)); - goto done; - } + { + error (0, errno, _("cannot stat current directory (now %s)"), + quote (dir)); + goto done; + } } /* Now walk up FILE's parents until we find another file system or /, @@ -571,18 +571,18 @@ find_mount_point (const char *file, const struct stat *file_stat) { struct stat st; if (stat ("..", &st) < 0) - { - error (0, errno, _("cannot stat %s"), quote ("..")); - goto done; - } + { + error (0, errno, _("cannot stat %s"), quote ("..")); + goto done; + } if (st.st_dev != last_stat.st_dev || st.st_ino == last_stat.st_ino) - /* cwd is the mount point. */ - break; + /* cwd is the mount point. */ + break; if (chdir ("..") < 0) - { - error (0, errno, _("cannot change to directory %s"), quote ("..")); - goto done; - } + { + error (0, errno, _("cannot change to directory %s"), quote ("..")); + goto done; + } last_stat = st; } @@ -595,7 +595,7 @@ done: int save_errno = errno; if (restore_cwd (&cwd) != 0) error (EXIT_FAILURE, errno, - _("failed to return to initial working directory")); + _("failed to return to initial working directory")); free_cwd (&cwd); errno = save_errno; } @@ -618,8 +618,8 @@ show_disk (char const *disk) if (best_match) { show_dev (best_match->me_devname, best_match->me_mountdir, NULL, - best_match->me_type, best_match->me_dummy, - best_match->me_remote, NULL); + best_match->me_type, best_match->me_dummy, + best_match->me_remote, NULL); return true; } @@ -641,12 +641,12 @@ show_point (const char *point, const struct stat *statp) if (*point == '/') { /* Find the best match: prefer non-dummies, and then prefer the - last match if there are ties. */ + last match if there are ties. */ for (me = mount_list; me; me = me->me_next) - if (STREQ (me->me_mountdir, point) && !STREQ (me->me_type, "lofs") - && (!best_match || best_match->me_dummy || !me->me_dummy)) - best_match = me; + if (STREQ (me->me_mountdir, point) && !STREQ (me->me_type, "lofs") + && (!best_match || best_match->me_dummy || !me->me_dummy)) + best_match = me; } /* Calculate the real absolute file name for POINT, and use that to find @@ -657,87 +657,87 @@ show_point (const char *point, const struct stat *statp) char *resolved = canonicalize_file_name (point); if (resolved && resolved[0] == '/') - { - size_t resolved_len = strlen (resolved); - size_t best_match_len = 0; - - for (me = mount_list; me; me = me->me_next) - if (!STREQ (me->me_type, "lofs") - && (!best_match || best_match->me_dummy || !me->me_dummy)) - { - size_t len = strlen (me->me_mountdir); - if (best_match_len <= len && len <= resolved_len - && (len == 1 /* root file system */ - || ((len == resolved_len || resolved[len] == '/') - && strncmp (me->me_mountdir, resolved, len) == 0))) - { - best_match = me; - best_match_len = len; - } - } - } + { + size_t resolved_len = strlen (resolved); + size_t best_match_len = 0; + + for (me = mount_list; me; me = me->me_next) + if (!STREQ (me->me_type, "lofs") + && (!best_match || best_match->me_dummy || !me->me_dummy)) + { + size_t len = strlen (me->me_mountdir); + if (best_match_len <= len && len <= resolved_len + && (len == 1 /* root file system */ + || ((len == resolved_len || resolved[len] == '/') + && strncmp (me->me_mountdir, resolved, len) == 0))) + { + best_match = me; + best_match_len = len; + } + } + } free (resolved); if (best_match - && (stat (best_match->me_mountdir, &disk_stats) != 0 - || disk_stats.st_dev != statp->st_dev)) - best_match = NULL; + && (stat (best_match->me_mountdir, &disk_stats) != 0 + || disk_stats.st_dev != statp->st_dev)) + best_match = NULL; } if (! best_match) for (me = mount_list; me; me = me->me_next) { - if (me->me_dev == (dev_t) -1) - { - if (stat (me->me_mountdir, &disk_stats) == 0) - me->me_dev = disk_stats.st_dev; - else - { - /* Report only I/O errors. Other errors might be - caused by shadowed mount points, which means POINT - can't possibly be on this file system. */ - if (errno == EIO) - { - error (0, errno, "%s", quote (me->me_mountdir)); - exit_status = EXIT_FAILURE; - } - - /* So we won't try and fail repeatedly. */ - me->me_dev = (dev_t) -2; - } - } - - if (statp->st_dev == me->me_dev - && !STREQ (me->me_type, "lofs") - && (!best_match || best_match->me_dummy || !me->me_dummy)) - { - /* Skip bogus mtab entries. */ - if (stat (me->me_mountdir, &disk_stats) != 0 - || disk_stats.st_dev != me->me_dev) - me->me_dev = (dev_t) -2; - else - best_match = me; - } + if (me->me_dev == (dev_t) -1) + { + if (stat (me->me_mountdir, &disk_stats) == 0) + me->me_dev = disk_stats.st_dev; + else + { + /* Report only I/O errors. Other errors might be + caused by shadowed mount points, which means POINT + can't possibly be on this file system. */ + if (errno == EIO) + { + error (0, errno, "%s", quote (me->me_mountdir)); + exit_status = EXIT_FAILURE; + } + + /* So we won't try and fail repeatedly. */ + me->me_dev = (dev_t) -2; + } + } + + if (statp->st_dev == me->me_dev + && !STREQ (me->me_type, "lofs") + && (!best_match || best_match->me_dummy || !me->me_dummy)) + { + /* Skip bogus mtab entries. */ + if (stat (me->me_mountdir, &disk_stats) != 0 + || disk_stats.st_dev != me->me_dev) + me->me_dev = (dev_t) -2; + else + best_match = me; + } } if (best_match) show_dev (best_match->me_devname, best_match->me_mountdir, point, - best_match->me_type, best_match->me_dummy, best_match->me_remote, - NULL); + best_match->me_type, best_match->me_dummy, best_match->me_remote, + NULL); else { /* We couldn't find the mount entry corresponding to POINT. Go ahead and - print as much info as we can; methods that require the device to be - present will fail at a later point. */ + print as much info as we can; methods that require the device to be + present will fail at a later point. */ /* Find the actual mount point. */ char *mp = find_mount_point (point, statp); if (mp) - { - show_dev (NULL, mp, NULL, NULL, false, false, NULL); - free (mp); - } + { + show_dev (NULL, mp, NULL, NULL, false, false, NULL); + free (mp); + } } } @@ -764,7 +764,7 @@ show_all_entries (void) for (me = mount_list; me; me = me->me_next) show_dev (me->me_devname, me->me_mountdir, NULL, me->me_type, - me->me_dummy, me->me_remote, NULL); + me->me_dummy, me->me_remote, NULL); } /* Add FSTYPE to the list of file system types to display. */ @@ -798,7 +798,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name); @@ -872,93 +872,93 @@ main (int argc, char **argv) { int oi = -1; int c = getopt_long (argc, argv, "aB:iF:hHklmPTt:vx:", long_options, - &oi); + &oi); if (c == -1) - break; + break; switch (c) - { - case 'a': - show_all_fs = true; - break; - case 'B': - { - enum strtol_error e = human_options (optarg, &human_output_opts, - &output_block_size); - if (e != LONGINT_OK) - xstrtol_fatal (e, oi, c, long_options, optarg); - } - break; - case 'i': - inode_format = true; - break; - case 'h': - human_output_opts = human_autoscale | human_SI | human_base_1024; - output_block_size = 1; - break; - case 'H': - human_output_opts = human_autoscale | human_SI; - output_block_size = 1; - break; - case 'k': - human_output_opts = 0; - output_block_size = 1024; - break; - case 'l': - show_local_fs = true; - break; - case 'm': /* obsolescent */ - human_output_opts = 0; - output_block_size = 1024 * 1024; - break; - case 'T': - print_type = true; - break; - case 'P': - posix_format = true; - break; - case SYNC_OPTION: - require_sync = true; - break; - case NO_SYNC_OPTION: - require_sync = false; - break; - - case 'F': - /* Accept -F as a synonym for -t for compatibility with Solaris. */ - case 't': - add_fs_type (optarg); - break; - - case 'v': /* For SysV compatibility. */ - /* ignore */ - break; - case 'x': - add_excluded_fs_type (optarg); - break; - - case 'c': - print_grand_total = true; - break; - - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'a': + show_all_fs = true; + break; + case 'B': + { + enum strtol_error e = human_options (optarg, &human_output_opts, + &output_block_size); + if (e != LONGINT_OK) + xstrtol_fatal (e, oi, c, long_options, optarg); + } + break; + case 'i': + inode_format = true; + break; + case 'h': + human_output_opts = human_autoscale | human_SI | human_base_1024; + output_block_size = 1; + break; + case 'H': + human_output_opts = human_autoscale | human_SI; + output_block_size = 1; + break; + case 'k': + human_output_opts = 0; + output_block_size = 1024; + break; + case 'l': + show_local_fs = true; + break; + case 'm': /* obsolescent */ + human_output_opts = 0; + output_block_size = 1024 * 1024; + break; + case 'T': + print_type = true; + break; + case 'P': + posix_format = true; + break; + case SYNC_OPTION: + require_sync = true; + break; + case NO_SYNC_OPTION: + require_sync = false; + break; + + case 'F': + /* Accept -F as a synonym for -t for compatibility with Solaris. */ + case 't': + add_fs_type (optarg); + break; + + case 'v': /* For SysV compatibility. */ + /* ignore */ + break; + case 'x': + add_excluded_fs_type (optarg); + break; + + case 'c': + print_grand_total = true; + break; + + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (human_output_opts == -1) { if (posix_format) - { - human_output_opts = 0; - output_block_size = (getenv ("POSIXLY_CORRECT") ? 512 : 1024); - } + { + human_output_opts = 0; + output_block_size = (getenv ("POSIXLY_CORRECT") ? 512 : 1024); + } else - human_options (getenv ("DF_BLOCK_SIZE"), - &human_output_opts, &output_block_size); + human_options (getenv ("DF_BLOCK_SIZE"), + &human_output_opts, &output_block_size); } /* Fail if the same file system type was both selected and excluded. */ @@ -967,18 +967,18 @@ main (int argc, char **argv) struct fs_type_list *fs_incl; for (fs_incl = fs_select_list; fs_incl; fs_incl = fs_incl->fs_next) { - struct fs_type_list *fs_excl; - for (fs_excl = fs_exclude_list; fs_excl; fs_excl = fs_excl->fs_next) - { - if (STREQ (fs_incl->fs_name, fs_excl->fs_name)) - { - error (0, 0, - _("file system type %s both selected and excluded"), - quote (fs_incl->fs_name)); - match = true; - break; - } - } + struct fs_type_list *fs_excl; + for (fs_excl = fs_exclude_list; fs_excl; fs_excl = fs_excl->fs_next) + { + if (STREQ (fs_incl->fs_name, fs_excl->fs_name)) + { + error (0, 0, + _("file system type %s both selected and excluded"), + quote (fs_incl->fs_name)); + match = true; + break; + } + } } if (match) exit (EXIT_FAILURE); @@ -989,38 +989,38 @@ main (int argc, char **argv) int i; /* Open each of the given entries to make sure any corresponding - partition is automounted. This must be done before reading the - file system table. */ + partition is automounted. This must be done before reading the + file system table. */ stats = xnmalloc (argc - optind, sizeof *stats); for (i = optind; i < argc; ++i) - { - int fd = open (argv[i], O_RDONLY | O_NOCTTY); - if (fd < 0 || fstat (fd, &stats[i - optind])) - { - error (0, errno, "%s", quote (argv[i])); - exit_status = EXIT_FAILURE; - argv[i] = NULL; - } - if (0 <= fd) - close (fd); - } + { + int fd = open (argv[i], O_RDONLY | O_NOCTTY); + if (fd < 0 || fstat (fd, &stats[i - optind])) + { + error (0, errno, "%s", quote (argv[i])); + exit_status = EXIT_FAILURE; + argv[i] = NULL; + } + if (0 <= fd) + close (fd); + } } mount_list = read_file_system_list ((fs_select_list != NULL - || fs_exclude_list != NULL - || print_type - || show_local_fs)); + || fs_exclude_list != NULL + || print_type + || show_local_fs)); if (mount_list == NULL) { /* Couldn't read the table of mounted file systems. - Fail if df was invoked with no file name arguments; - Otherwise, merely give a warning and proceed. */ + Fail if df was invoked with no file name arguments; + Otherwise, merely give a warning and proceed. */ int status = (optind < argc ? 0 : EXIT_FAILURE); const char *warning = (optind < argc ? _("Warning: ") : ""); error (status, errno, "%s%s", warning, - _("cannot read table of mounted file systems")); + _("cannot read table of mounted file systems")); } if (require_sync) @@ -1034,8 +1034,8 @@ main (int argc, char **argv) show_listed_fs = true; for (i = optind; i < argc; ++i) - if (argv[i]) - show_entry (argv[i], &stats[i - optind]); + if (argv[i]) + show_entry (argv[i], &stats[i - optind]); } else show_all_entries (); @@ -1043,7 +1043,7 @@ main (int argc, char **argv) if (print_grand_total) { if (inode_format) - grand_fsu.fsu_blocks = 1; + grand_fsu.fsu_blocks = 1; show_dev ("total", NULL, NULL, NULL, false, false, &grand_fsu); } diff --git a/src/dircolors.c b/src/dircolors.c index 39c8e64b7..b72415592 100644 --- a/src/dircolors.c +++ b/src/dircolors.c @@ -198,29 +198,29 @@ append_quoted (const char *str) while (*str != '\0') { switch (*str) - { - case '\'': - APPEND_CHAR ('\''); - APPEND_CHAR ('\\'); - APPEND_CHAR ('\''); - need_backslash = true; - break; - - case '\\': - case '^': - need_backslash = !need_backslash; - break; - - case ':': - case '=': - if (need_backslash) - APPEND_CHAR ('\\'); - /* Fall through */ - - default: - need_backslash = true; - break; - } + { + case '\'': + APPEND_CHAR ('\''); + APPEND_CHAR ('\\'); + APPEND_CHAR ('\''); + need_backslash = true; + break; + + case '\\': + case '^': + need_backslash = !need_backslash; + break; + + case ':': + case '=': + if (need_backslash) + APPEND_CHAR ('\\'); + /* Fall through */ + + default: + need_backslash = true; + break; + } APPEND_CHAR (*str); ++str; @@ -261,106 +261,106 @@ dc_parse_stream (FILE *fp, const char *filename) ++line_number; if (fp) - { - if (getline (&input_line, &input_line_size, fp) <= 0) - { - free (input_line); - break; - } - line = input_line; - } + { + if (getline (&input_line, &input_line_size, fp) <= 0) + { + free (input_line); + break; + } + line = input_line; + } else - { - if (next_G_line == G_line + sizeof G_line) - break; - line = next_G_line; - next_G_line += strlen (next_G_line) + 1; - } + { + if (next_G_line == G_line + sizeof G_line) + break; + line = next_G_line; + next_G_line += strlen (next_G_line) + 1; + } parse_line (line, &keywd, &arg); if (keywd == NULL) - continue; + continue; if (arg == NULL) - { - error (0, 0, _("%s:%lu: invalid line; missing second token"), - filename, (unsigned long int) line_number); - ok = false; - free (keywd); - continue; - } + { + error (0, 0, _("%s:%lu: invalid line; missing second token"), + filename, (unsigned long int) line_number); + ok = false; + free (keywd); + continue; + } unrecognized = false; if (c_strcasecmp (keywd, "TERM") == 0) - { - if (STREQ (arg, term)) - state = ST_TERMSURE; - else if (state != ST_TERMSURE) - state = ST_TERMNO; - } + { + if (STREQ (arg, term)) + state = ST_TERMSURE; + else if (state != ST_TERMSURE) + state = ST_TERMNO; + } else - { - if (state == ST_TERMSURE) - state = ST_TERMYES; /* Another TERM can cancel */ - - if (state != ST_TERMNO) - { - if (keywd[0] == '.') - { - APPEND_CHAR ('*'); - append_quoted (keywd); - APPEND_CHAR ('='); - append_quoted (arg); - APPEND_CHAR (':'); - } - else if (keywd[0] == '*') - { - append_quoted (keywd); - APPEND_CHAR ('='); - append_quoted (arg); - APPEND_CHAR (':'); - } - else if (c_strcasecmp (keywd, "OPTIONS") == 0 - || c_strcasecmp (keywd, "COLOR") == 0 - || c_strcasecmp (keywd, "EIGHTBIT") == 0) - { - /* Ignore. */ - } - else - { - int i; - - for (i = 0; slack_codes[i] != NULL; ++i) - if (c_strcasecmp (keywd, slack_codes[i]) == 0) - break; - - if (slack_codes[i] != NULL) - { - APPEND_TWO_CHAR_STRING (ls_codes[i]); - APPEND_CHAR ('='); - append_quoted (arg); - APPEND_CHAR (':'); - } - else - { - unrecognized = true; - } - } - } - else - { - unrecognized = true; - } - } + { + if (state == ST_TERMSURE) + state = ST_TERMYES; /* Another TERM can cancel */ + + if (state != ST_TERMNO) + { + if (keywd[0] == '.') + { + APPEND_CHAR ('*'); + append_quoted (keywd); + APPEND_CHAR ('='); + append_quoted (arg); + APPEND_CHAR (':'); + } + else if (keywd[0] == '*') + { + append_quoted (keywd); + APPEND_CHAR ('='); + append_quoted (arg); + APPEND_CHAR (':'); + } + else if (c_strcasecmp (keywd, "OPTIONS") == 0 + || c_strcasecmp (keywd, "COLOR") == 0 + || c_strcasecmp (keywd, "EIGHTBIT") == 0) + { + /* Ignore. */ + } + else + { + int i; + + for (i = 0; slack_codes[i] != NULL; ++i) + if (c_strcasecmp (keywd, slack_codes[i]) == 0) + break; + + if (slack_codes[i] != NULL) + { + APPEND_TWO_CHAR_STRING (ls_codes[i]); + APPEND_CHAR ('='); + append_quoted (arg); + APPEND_CHAR (':'); + } + else + { + unrecognized = true; + } + } + } + else + { + unrecognized = true; + } + } if (unrecognized && (state == ST_TERMSURE || state == ST_TERMYES)) - { - error (0, 0, _("%s:%lu: unrecognized keyword %s"), - (filename ? quote (filename) : _("<internal>")), - (unsigned long int) line_number, keywd); - ok = false; - } + { + error (0, 0, _("%s:%lu: unrecognized keyword %s"), + (filename ? quote (filename) : _("<internal>")), + (unsigned long int) line_number, keywd); + ok = false; + } free (keywd); free (arg); @@ -411,23 +411,23 @@ main (int argc, char **argv) switch (optc) { case 'b': /* Bourne shell syntax. */ - syntax = SHELL_SYNTAX_BOURNE; - break; + syntax = SHELL_SYNTAX_BOURNE; + break; case 'c': /* C shell syntax. */ - syntax = SHELL_SYNTAX_C; - break; + syntax = SHELL_SYNTAX_C; + break; case 'p': - print_database = true; - break; + print_database = true; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } argc -= optind; @@ -438,7 +438,7 @@ main (int argc, char **argv) if (print_database && syntax != SHELL_SYNTAX_UNKNOWN) { error (0, 0, - _("the options to output dircolors' internal database and\n\ + _("the options to output dircolors' internal database and\n\ to select a shell syntax are mutually exclusive")); usage (EXIT_FAILURE); } @@ -447,9 +447,9 @@ to select a shell syntax are mutually exclusive")); { error (0, 0, _("extra operand %s"), quote (argv[!print_database])); if (print_database) - fprintf (stderr, "%s\n", - _("file operands cannot be combined with " - "--print-database (-p)")); + fprintf (stderr, "%s\n", + _("file operands cannot be combined with " + "--print-database (-p)")); usage (EXIT_FAILURE); } @@ -457,51 +457,51 @@ to select a shell syntax are mutually exclusive")); { char const *p = G_line; while (p < G_line + sizeof G_line) - { - puts (p); - p += strlen (p) + 1; - } + { + puts (p); + p += strlen (p) + 1; + } } else { /* If shell syntax was not explicitly specified, try to guess it. */ if (syntax == SHELL_SYNTAX_UNKNOWN) - { - syntax = guess_shell_syntax (); - if (syntax == SHELL_SYNTAX_UNKNOWN) - { - error (EXIT_FAILURE, 0, - _("no SHELL environment variable, and no shell type option given")); - } - } + { + syntax = guess_shell_syntax (); + if (syntax == SHELL_SYNTAX_UNKNOWN) + { + error (EXIT_FAILURE, 0, + _("no SHELL environment variable, and no shell type option given")); + } + } obstack_init (&lsc_obstack); if (argc == 0) - ok = dc_parse_stream (NULL, NULL); + ok = dc_parse_stream (NULL, NULL); else - ok = dc_parse_file (argv[0]); + ok = dc_parse_file (argv[0]); if (ok) - { - size_t len = obstack_object_size (&lsc_obstack); - char *s = obstack_finish (&lsc_obstack); - const char *prefix; - const char *suffix; - - if (syntax == SHELL_SYNTAX_BOURNE) - { - prefix = "LS_COLORS='"; - suffix = "';\nexport LS_COLORS\n"; - } - else - { - prefix = "setenv LS_COLORS '"; - suffix = "'\n"; - } - fputs (prefix, stdout); - fwrite (s, 1, len, stdout); - fputs (suffix, stdout); - } + { + size_t len = obstack_object_size (&lsc_obstack); + char *s = obstack_finish (&lsc_obstack); + const char *prefix; + const char *suffix; + + if (syntax == SHELL_SYNTAX_BOURNE) + { + prefix = "LS_COLORS='"; + suffix = "';\nexport LS_COLORS\n"; + } + else + { + prefix = "setenv LS_COLORS '"; + suffix = "'\n"; + } + fputs (prefix, stdout); + fwrite (s, 1, len, stdout); + fputs (suffix, stdout); + } } exit (ok ? EXIT_SUCCESS : EXIT_FAILURE); diff --git a/src/dircolors.hin b/src/dircolors.hin index 30fd87856..91ddcb65a 100644 --- a/src/dircolors.hin +++ b/src/dircolors.hin @@ -69,7 +69,7 @@ TERM xterm-debian RESET 0 # reset to "normal" color DIR 01;34 # directory LINK 01;36 # symbolic link. (If you set this to 'target' instead of a - # numerical value, the color is as for the file pointed to.) + # numerical value, the color is as for the file pointed to.) MULTIHARDLINK 00 # regular file with more than one link FIFO 40;33 # pipe SOCK 01;35 # socket diff --git a/src/dirname.c b/src/dirname.c index c0fc01717..53d0bdc7d 100644 --- a/src/dirname.c +++ b/src/dirname.c @@ -39,14 +39,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s NAME\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Print NAME with its trailing /component removed; if NAME contains no /'s,\n\ output `.' (meaning the current directory).\n\ @@ -60,7 +60,7 @@ Examples:\n\ %s /usr/bin/sort Output \"/usr/bin\".\n\ %s stdio.h Output \".\".\n\ "), - program_name, program_name); + program_name, program_name); emit_bug_reporting_address (); } exit (status); @@ -82,7 +82,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "+", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -262,7 +262,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -396,7 +396,7 @@ static void hash_init (void) { htab = hash_initialize (INITIAL_TABLE_SIZE, NULL, - entry_hash, entry_compare, free); + entry_hash, entry_compare, free); if (htab == NULL) xalloc_die (); } @@ -427,7 +427,7 @@ print_only_size (uintmax_t n_bytes) { char buf[LONGEST_HUMAN_READABLE + 1]; fputs (human_readable (n_bytes, buf, human_output_opts, - 1, output_block_size), stdout); + 1, output_block_size), stdout); } /* Print size (and optionally time) indicated by *PDUI, followed by STRING. */ @@ -492,7 +492,7 @@ process_file (FTS *fts, FTSENT *ent) case FTS_DNR: /* Don't return just yet, since although the directory is not readable, - we were able to stat it, so we do have a size. */ + we were able to stat it, so we do have a size. */ error (0, ent->fts_errno, _("cannot read directory %s"), quote (file)); ok = false; break; @@ -512,25 +512,25 @@ process_file (FTS *fts, FTSENT *ent) via a hard link, then don't let it contribute to the sums. */ if (skip || (!opt_count_all - && ! S_ISDIR (sb->st_mode) - && 1 < sb->st_nlink - && ! hash_ins (sb->st_ino, sb->st_dev))) + && ! S_ISDIR (sb->st_mode) + && 1 < sb->st_nlink + && ! hash_ins (sb->st_ino, sb->st_dev))) { /* Note that we must not simply return here. - We still have to update prev_level and maybe propagate - some sums up the hierarchy. */ + We still have to update prev_level and maybe propagate + some sums up the hierarchy. */ duinfo_init (&dui); print = false; } else { duinfo_set (&dui, - (apparent_size - ? sb->st_size - : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE), - (time_type == time_mtime ? get_stat_mtime (sb) - : time_type == time_atime ? get_stat_atime (sb) - : get_stat_ctime (sb))); + (apparent_size + ? sb->st_size + : (uintmax_t) ST_NBLOCKS (*sb) * ST_NBLOCKSIZE), + (time_type == time_mtime ? get_stat_mtime (sb) + : time_type == time_atime ? get_stat_atime (sb) + : get_stat_ctime (sb))); } level = ent->fts_level; @@ -544,44 +544,44 @@ process_file (FTS *fts, FTSENT *ent) else { if (level == prev_level) - { - /* This is usually the most common case. Do nothing. */ - } + { + /* This is usually the most common case. Do nothing. */ + } else if (level > prev_level) - { - /* Descending the hierarchy. - Clear the accumulators for *all* levels between prev_level - and the current one. The depth may change dramatically, - e.g., from 1 to 10. */ - size_t i; - - if (n_alloc <= level) - { - dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl); - n_alloc = level * 2; - } - - for (i = prev_level + 1; i <= level; i++) - { - duinfo_init (&dulvl[i].ent); - duinfo_init (&dulvl[i].subdir); - } - } + { + /* Descending the hierarchy. + Clear the accumulators for *all* levels between prev_level + and the current one. The depth may change dramatically, + e.g., from 1 to 10. */ + size_t i; + + if (n_alloc <= level) + { + dulvl = xnrealloc (dulvl, level, 2 * sizeof *dulvl); + n_alloc = level * 2; + } + + for (i = prev_level + 1; i <= level; i++) + { + duinfo_init (&dulvl[i].ent); + duinfo_init (&dulvl[i].subdir); + } + } else /* level < prev_level */ - { - /* Ascending the hierarchy. - Process a directory only after all entries in that - directory have been processed. When the depth decreases, - propagate sums from the children (prev_level) to the parent. - Here, the current level is always one smaller than the - previous one. */ - assert (level == prev_level - 1); - duinfo_add (&dui_to_print, &dulvl[prev_level].ent); - if (!opt_separate_dirs) - duinfo_add (&dui_to_print, &dulvl[prev_level].subdir); - duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent); - duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir); - } + { + /* Ascending the hierarchy. + Process a directory only after all entries in that + directory have been processed. When the depth decreases, + propagate sums from the children (prev_level) to the parent. + Here, the current level is always one smaller than the + previous one. */ + assert (level == prev_level - 1); + duinfo_add (&dui_to_print, &dulvl[prev_level].ent); + if (!opt_separate_dirs) + duinfo_add (&dui_to_print, &dulvl[prev_level].subdir); + duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].ent); + duinfo_add (&dulvl[level].subdir, &dulvl[prev_level].subdir); + } } prev_level = level; @@ -623,28 +623,28 @@ du_files (char **files, int bit_flags) FTS *fts = xfts_open (files, bit_flags, NULL); while (1) - { - FTSENT *ent; - - ent = fts_read (fts); - if (ent == NULL) - { - if (errno != 0) - { - /* FIXME: try to give a better message */ - error (0, errno, _("fts_read failed")); - ok = false; - } - break; - } - FTS_CROSS_CHECK (fts); - - ok &= process_file (fts, ent); - } + { + FTSENT *ent; + + ent = fts_read (fts); + if (ent == NULL) + { + if (errno != 0) + { + /* FIXME: try to give a better message */ + error (0, errno, _("fts_read failed")); + ok = false; + } + break; + } + FTS_CROSS_CHECK (fts); + + ok &= process_file (fts, ent); + } /* Ignore failure, since the only way it can do so is in failing to - return to the original directory, and since we're about to exit, - that doesn't matter. */ + return to the original directory, and since we're about to exit, + that doesn't matter. */ fts_close (fts); } @@ -683,162 +683,162 @@ main (int argc, char **argv) exclude = new_exclude (); human_options (getenv ("DU_BLOCK_SIZE"), - &human_output_opts, &output_block_size); + &human_output_opts, &output_block_size); for (;;) { int oi = -1; int c = getopt_long (argc, argv, DEBUG_OPT "0abchHklmsxB:DLPSX:", - long_options, &oi); + long_options, &oi); if (c == -1) - break; + break; switch (c) - { + { #if DU_DEBUG - case 'd': - fts_debug = true; - break; + case 'd': + fts_debug = true; + break; #endif - case '0': - opt_nul_terminate_output = true; - break; - - case 'a': - opt_all = true; - break; - - case APPARENT_SIZE_OPTION: - apparent_size = true; - break; - - case 'b': - apparent_size = true; - human_output_opts = 0; - output_block_size = 1; - break; - - case 'c': - print_grand_total = true; - break; - - case 'h': - human_output_opts = human_autoscale | human_SI | human_base_1024; - output_block_size = 1; - break; - - case HUMAN_SI_OPTION: - human_output_opts = human_autoscale | human_SI; - output_block_size = 1; - break; - - case 'k': - human_output_opts = 0; - output_block_size = 1024; - break; - - case MAX_DEPTH_OPTION: /* --max-depth=N */ - { - unsigned long int tmp_ulong; - if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK - && tmp_ulong <= SIZE_MAX) - { - max_depth_specified = true; - max_depth = tmp_ulong; - } - else - { - error (0, 0, _("invalid maximum depth %s"), - quote (optarg)); - ok = false; - } - } - break; - - case MEGABYTES_LONG_OPTION: /* FIXME: remove in 2009 */ - error (0, 0, - _("the --megabytes option is deprecated; use -m instead")); - /* fall through */ - case 'm': - human_output_opts = 0; - output_block_size = 1024 * 1024; - break; - - case 'l': - opt_count_all = true; - break; - - case 's': - opt_summarize_only = true; - break; - - case 'x': - bit_flags |= FTS_XDEV; - break; - - case 'B': - { - enum strtol_error e = human_options (optarg, &human_output_opts, - &output_block_size); - if (e != LONGINT_OK) - xstrtol_fatal (e, oi, c, long_options, optarg); - } - break; - - case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */ - case 'D': - symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL; - break; - - case 'L': /* --dereference */ - symlink_deref_bits = FTS_LOGICAL; - break; - - case 'P': /* --no-dereference */ - symlink_deref_bits = FTS_PHYSICAL; - break; - - case 'S': - opt_separate_dirs = true; - break; - - case 'X': - if (add_exclude_file (add_exclude, exclude, optarg, - EXCLUDE_WILDCARDS, '\n')) - { - error (0, errno, "%s", quotearg_colon (optarg)); - ok = false; - } - break; - - case FILES0_FROM_OPTION: - files_from = optarg; - break; - - case EXCLUDE_OPTION: - add_exclude (exclude, optarg, EXCLUDE_WILDCARDS); - break; - - case TIME_OPTION: - opt_time = true; - time_type = - (optarg - ? XARGMATCH ("--time", optarg, time_args, time_types) - : time_mtime); - break; - - case TIME_STYLE_OPTION: - time_style = optarg; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - ok = false; - } + case '0': + opt_nul_terminate_output = true; + break; + + case 'a': + opt_all = true; + break; + + case APPARENT_SIZE_OPTION: + apparent_size = true; + break; + + case 'b': + apparent_size = true; + human_output_opts = 0; + output_block_size = 1; + break; + + case 'c': + print_grand_total = true; + break; + + case 'h': + human_output_opts = human_autoscale | human_SI | human_base_1024; + output_block_size = 1; + break; + + case HUMAN_SI_OPTION: + human_output_opts = human_autoscale | human_SI; + output_block_size = 1; + break; + + case 'k': + human_output_opts = 0; + output_block_size = 1024; + break; + + case MAX_DEPTH_OPTION: /* --max-depth=N */ + { + unsigned long int tmp_ulong; + if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK + && tmp_ulong <= SIZE_MAX) + { + max_depth_specified = true; + max_depth = tmp_ulong; + } + else + { + error (0, 0, _("invalid maximum depth %s"), + quote (optarg)); + ok = false; + } + } + break; + + case MEGABYTES_LONG_OPTION: /* FIXME: remove in 2009 */ + error (0, 0, + _("the --megabytes option is deprecated; use -m instead")); + /* fall through */ + case 'm': + human_output_opts = 0; + output_block_size = 1024 * 1024; + break; + + case 'l': + opt_count_all = true; + break; + + case 's': + opt_summarize_only = true; + break; + + case 'x': + bit_flags |= FTS_XDEV; + break; + + case 'B': + { + enum strtol_error e = human_options (optarg, &human_output_opts, + &output_block_size); + if (e != LONGINT_OK) + xstrtol_fatal (e, oi, c, long_options, optarg); + } + break; + + case 'H': /* NOTE: before 2008-12, -H was equivalent to --si. */ + case 'D': + symlink_deref_bits = FTS_COMFOLLOW | FTS_PHYSICAL; + break; + + case 'L': /* --dereference */ + symlink_deref_bits = FTS_LOGICAL; + break; + + case 'P': /* --no-dereference */ + symlink_deref_bits = FTS_PHYSICAL; + break; + + case 'S': + opt_separate_dirs = true; + break; + + case 'X': + if (add_exclude_file (add_exclude, exclude, optarg, + EXCLUDE_WILDCARDS, '\n')) + { + error (0, errno, "%s", quotearg_colon (optarg)); + ok = false; + } + break; + + case FILES0_FROM_OPTION: + files_from = optarg; + break; + + case EXCLUDE_OPTION: + add_exclude (exclude, optarg, EXCLUDE_WILDCARDS); + break; + + case TIME_OPTION: + opt_time = true; + time_type = + (optarg + ? XARGMATCH ("--time", optarg, time_args, time_types) + : time_mtime); + break; + + case TIME_STYLE_OPTION: + time_style = optarg; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + ok = false; + } } if (!ok) @@ -853,7 +853,7 @@ main (int argc, char **argv) if (opt_summarize_only && max_depth_specified && max_depth == 0) { error (0, 0, - _("warning: summarizing is the same as using --max-depth=0")); + _("warning: summarizing is the same as using --max-depth=0")); } if (opt_summarize_only && max_depth_specified && max_depth != 0) @@ -870,48 +870,48 @@ main (int argc, char **argv) if (opt_time) { if (! time_style) - { - time_style = getenv ("TIME_STYLE"); - - /* Ignore TIMESTYLE="locale", for compatibility with ls. */ - if (! time_style || STREQ (time_style, "locale")) - time_style = "long-iso"; - else if (*time_style == '+') - { - /* Ignore anything after a newline, for compatibility - with ls. */ - char *p = strchr (time_style, '\n'); - if (p) - *p = '\0'; - } - else - { - /* Ignore "posix-" prefix, for compatibility with ls. */ - static char const posix_prefix[] = "posix-"; - while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1) - == 0) - time_style += sizeof posix_prefix - 1; - } - } + { + time_style = getenv ("TIME_STYLE"); + + /* Ignore TIMESTYLE="locale", for compatibility with ls. */ + if (! time_style || STREQ (time_style, "locale")) + time_style = "long-iso"; + else if (*time_style == '+') + { + /* Ignore anything after a newline, for compatibility + with ls. */ + char *p = strchr (time_style, '\n'); + if (p) + *p = '\0'; + } + else + { + /* Ignore "posix-" prefix, for compatibility with ls. */ + static char const posix_prefix[] = "posix-"; + while (strncmp (time_style, posix_prefix, sizeof posix_prefix - 1) + == 0) + time_style += sizeof posix_prefix - 1; + } + } if (*time_style == '+') - time_format = time_style + 1; + time_format = time_style + 1; else { switch (XARGMATCH ("time style", time_style, time_style_args, time_style_types)) { - case full_iso_time_style: - time_format = "%Y-%m-%d %H:%M:%S.%N %z"; - break; + case full_iso_time_style: + time_format = "%Y-%m-%d %H:%M:%S.%N %z"; + break; - case long_iso_time_style: - time_format = "%Y-%m-%d %H:%M"; - break; + case long_iso_time_style: + time_format = "%Y-%m-%d %H:%M"; + break; - case iso_time_style: - time_format = "%Y-%m-%d"; - break; + case iso_time_style: + time_format = "%Y-%m-%d"; + break; } } } @@ -920,18 +920,18 @@ main (int argc, char **argv) if (files_from) { /* When using --files0-from=F, you may not specify any files - on the command-line. */ + on the command-line. */ if (optind < argc) - { - error (0, 0, _("extra operand %s"), quote (argv[optind])); - fprintf (stderr, "%s\n", - _("file operands cannot be combined with --files0-from")); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (argv[optind])); + fprintf (stderr, "%s\n", + _("file operands cannot be combined with --files0-from")); + usage (EXIT_FAILURE); + } if (! (STREQ (files_from, "-") || freopen (files_from, "r", stdin))) - error (EXIT_FAILURE, errno, _("cannot open %s for reading"), - quote (files_from)); + error (EXIT_FAILURE, errno, _("cannot open %s for reading"), + quote (files_from)); ai = argv_iter_init_stream (stdin); } @@ -956,64 +956,64 @@ main (int argc, char **argv) enum argv_iter_err ai_err; char *file_name = argv_iter (ai, &ai_err); if (ai_err == AI_ERR_EOF) - break; + break; if (!file_name) - { - switch (ai_err) - { - case AI_ERR_READ: - error (0, errno, _("%s: read error"), quote (files_from)); - skip_file = true; - continue; - - case AI_ERR_MEM: - xalloc_die (); - - default: - assert (!"unexpected error code from argv_iter"); - } - } + { + switch (ai_err) + { + case AI_ERR_READ: + error (0, errno, _("%s: read error"), quote (files_from)); + skip_file = true; + continue; + + case AI_ERR_MEM: + xalloc_die (); + + default: + assert (!"unexpected error code from argv_iter"); + } + } if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-")) - { - /* Give a better diagnostic in an unusual case: - printf - | du --files0-from=- */ - error (0, 0, _("when reading file names from stdin, " - "no file name of %s allowed"), - quote (file_name)); - skip_file = true; - } + { + /* Give a better diagnostic in an unusual case: + printf - | du --files0-from=- */ + error (0, 0, _("when reading file names from stdin, " + "no file name of %s allowed"), + quote (file_name)); + skip_file = true; + } /* Report and skip any empty file names before invoking fts. - This works around a glitch in fts, which fails immediately - (without looking at the other file names) when given an empty - file name. */ + This works around a glitch in fts, which fails immediately + (without looking at the other file names) when given an empty + file name. */ if (!file_name[0]) - { - /* Diagnose a zero-length file name. When it's one - among many, knowing the record number may help. - FIXME: currently print the record number only with - --files0-from=FILE. Maybe do it for argv, too? */ - if (files_from == NULL) - error (0, 0, "%s", _("invalid zero-length file name")); - else - { - /* Using the standard `filename:line-number:' prefix here is - not totally appropriate, since NUL is the separator, not NL, - but it might be better than nothing. */ - unsigned long int file_number = argv_iter_n_args (ai); - error (0, 0, "%s:%lu: %s", quotearg_colon (files_from), - file_number, _("invalid zero-length file name")); - } - skip_file = true; - } + { + /* Diagnose a zero-length file name. When it's one + among many, knowing the record number may help. + FIXME: currently print the record number only with + --files0-from=FILE. Maybe do it for argv, too? */ + if (files_from == NULL) + error (0, 0, "%s", _("invalid zero-length file name")); + else + { + /* Using the standard `filename:line-number:' prefix here is + not totally appropriate, since NUL is the separator, not NL, + but it might be better than nothing. */ + unsigned long int file_number = argv_iter_n_args (ai); + error (0, 0, "%s:%lu: %s", quotearg_colon (files_from), + file_number, _("invalid zero-length file name")); + } + skip_file = true; + } if (skip_file) - ok = false; + ok = false; else - { - temp_argv[0] = file_name; - ok &= du_files (temp_argv, bit_flags); - } + { + temp_argv[0] = file_name; + ok &= du_files (temp_argv, bit_flags); + } } argv_iter_free (ai); diff --git a/src/echo.c b/src/echo.c index 7b069e0e5..210352ca7 100644 --- a/src/echo.c +++ b/src/echo.c @@ -37,7 +37,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -50,13 +50,13 @@ Echo the STRING(s) to standard output.\n\ -n do not output the trailing newline\n\ "), stdout); fputs (_(DEFAULT_ECHO_TO_XPG - ? N_("\ + ? N_("\ -e enable interpretation of backslash escapes (default)\n\ -E disable interpretation of backslash escapes\n") - : N_("\ + : N_("\ -e enable interpretation of backslash escapes\n\ -E disable interpretation of backslash escapes (default)\n")), - stdout); + stdout); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); fputs (_("\ @@ -128,14 +128,14 @@ main (int argc, char **argv) if (allow_options && argc == 2) { if (STREQ (argv[1], "--help")) - usage (EXIT_SUCCESS); + usage (EXIT_SUCCESS); if (STREQ (argv[1], "--version")) - { - version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, - (char *) NULL); - exit (EXIT_SUCCESS); - } + { + version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, + (char *) NULL); + exit (EXIT_SUCCESS); + } } --argc; @@ -144,45 +144,45 @@ main (int argc, char **argv) if (allow_options) while (argc > 0 && *argv[0] == '-') { - char const *temp = argv[0] + 1; - size_t i; + char const *temp = argv[0] + 1; + size_t i; - /* 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. */ + /* 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. */ - for (i = 0; temp[i]; i++) - switch (temp[i]) - { - case 'e': case 'E': case 'n': - break; - default: - goto just_echo; - } + for (i = 0; temp[i]; i++) + switch (temp[i]) + { + case 'e': case 'E': case 'n': + break; + default: + goto just_echo; + } - if (i == 0) - goto just_echo; + if (i == 0) + goto just_echo; - /* All of the options in TEMP are valid options to ECHO. - Handle them. */ - while (*temp) - switch (*temp++) - { - case 'e': - do_v9 = true; - break; + /* All of the options in TEMP are valid options to ECHO. + Handle them. */ + while (*temp) + switch (*temp++) + { + case 'e': + do_v9 = true; + break; - case 'E': - do_v9 = false; - break; + case 'E': + do_v9 = false; + break; - case 'n': - display_return = false; - break; - } + case 'n': + display_return = false; + break; + } - argc--; - argv++; + argc--; + argv++; } just_echo: @@ -190,77 +190,77 @@ just_echo: if (do_v9) { while (argc > 0) - { - char const *s = argv[0]; - unsigned char c; + { + char const *s = argv[0]; + unsigned char c; - while ((c = *s++)) - { - if (c == '\\' && *s) - { - switch (c = *s++) - { - case 'a': c = '\a'; break; - case 'b': c = '\b'; break; - case 'c': exit (EXIT_SUCCESS); - case 'f': c = '\f'; break; - case 'n': c = '\n'; break; - case 'r': c = '\r'; break; - case 't': c = '\t'; break; - case 'v': c = '\v'; break; - case 'x': - { - unsigned char ch = *s; - if (! isxdigit (ch)) - goto not_an_escape; - s++; - c = hextobin (ch); - ch = *s; - if (isxdigit (ch)) - { - s++; - c = c * 16 + hextobin (ch); - } - } - break; - case '0': - c = 0; - if (! ('0' <= *s && *s <= '7')) - break; - c = *s++; - /* Fall through. */ - case '1': case '2': case '3': - case '4': case '5': case '6': case '7': - c -= '0'; - if ('0' <= *s && *s <= '7') - c = c * 8 + (*s++ - '0'); - if ('0' <= *s && *s <= '7') - c = c * 8 + (*s++ - '0'); - break; - case '\\': break; + while ((c = *s++)) + { + if (c == '\\' && *s) + { + switch (c = *s++) + { + case 'a': c = '\a'; break; + case 'b': c = '\b'; break; + case 'c': exit (EXIT_SUCCESS); + case 'f': c = '\f'; break; + case 'n': c = '\n'; break; + case 'r': c = '\r'; break; + case 't': c = '\t'; break; + case 'v': c = '\v'; break; + case 'x': + { + unsigned char ch = *s; + if (! isxdigit (ch)) + goto not_an_escape; + s++; + c = hextobin (ch); + ch = *s; + if (isxdigit (ch)) + { + s++; + c = c * 16 + hextobin (ch); + } + } + break; + case '0': + c = 0; + if (! ('0' <= *s && *s <= '7')) + break; + c = *s++; + /* Fall through. */ + case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + c -= '0'; + if ('0' <= *s && *s <= '7') + c = c * 8 + (*s++ - '0'); + if ('0' <= *s && *s <= '7') + c = c * 8 + (*s++ - '0'); + break; + case '\\': break; - not_an_escape: - default: putchar ('\\'); break; - } - } - putchar (c); - } - argc--; - argv++; - if (argc > 0) - putchar (' '); - } + not_an_escape: + default: putchar ('\\'); break; + } + } + putchar (c); + } + argc--; + argv++; + if (argc > 0) + putchar (' '); + } } else { while (argc > 0) - { - fputs (argv[0], stdout); - argc--; - argv++; - if (argc > 0) - putchar (' '); - } + { + fputs (argv[0], stdout); + argc--; + argv++; + if (argc > 0) + putchar (' '); + } } if (display_return) @@ -20,24 +20,24 @@ - -i --ignore-environment - Construct a new environment from scratch; normally the - environment is inherited from the parent process, except as - modified by other options. + Construct a new environment from scratch; normally the + environment is inherited from the parent process, except as + modified by other options. -u variable --unset=variable - Unset variable VARIABLE (remove it from the environment). - If VARIABLE was not set, does nothing. + Unset variable VARIABLE (remove it from the environment). + If VARIABLE was not set, does nothing. variable=value (an arg containing a "=" character) - Set the environment variable VARIABLE to value VALUE. VALUE - may be of zero length ("variable="). Setting a variable to a - zero-length value is different from unsetting it. + Set the environment variable VARIABLE to value VALUE. VALUE + may be of zero length ("variable="). Setting a variable to a + zero-length value is different from unsetting it. -- - Indicate that the following argument is the program - to invoke. This is necessary when the program's name - begins with "-" or contains a "=". + Indicate that the following argument is the program + to invoke. This is necessary when the program's name + begins with "-" or contains a "=". The first remaining argument specifies a program to invoke; it is searched for according to the specification of the PATH @@ -51,29 +51,29 @@ Examples: If the environment passed to "env" is - { LOGNAME=rms EDITOR=emacs PATH=.:/gnubin:/hacks } + { LOGNAME=rms EDITOR=emacs PATH=.:/gnubin:/hacks } env - foo - runs "foo" in a null environment. + runs "foo" in a null environment. env foo - runs "foo" in the environment - { LOGNAME=rms EDITOR=emacs PATH=.:/gnubin:/hacks } + runs "foo" in the environment + { LOGNAME=rms EDITOR=emacs PATH=.:/gnubin:/hacks } env DISPLAY=gnu:0 nemacs - runs "nemacs" in the environment - { LOGNAME=rms EDITOR=emacs PATH=.:/gnubin:/hacks DISPLAY=gnu:0 } + runs "nemacs" in the environment + { LOGNAME=rms EDITOR=emacs PATH=.:/gnubin:/hacks DISPLAY=gnu:0 } env - LOGNAME=foo /hacks/hack bar baz - runs the "hack" program on arguments "bar" and "baz" in an - environment in which the only variable is "LOGNAME". Note that - the "-" option clears out the PATH variable, so one should be - careful to specify in which directory to find the program to - call. + runs the "hack" program on arguments "bar" and "baz" in an + environment in which the only variable is "LOGNAME". Note that + the "-" option clears out the PATH variable, so one should be + careful to specify in which directory to find the program to + call. env -u EDITOR LOGNAME=foo PATH=/energy -- e=mc2 bar baz - runs the program "/energy/e=mc2" with environment - { LOGNAME=foo PATH=/energy } + runs the program "/energy/e=mc2" with environment + { LOGNAME=foo PATH=/energy } */ #include <config.h> @@ -107,12 +107,12 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [-] [NAME=VALUE]... [COMMAND [ARG]...]\n"), - program_name); + program_name); fputs (_("\ Set each NAME to VALUE in the environment and run COMMAND.\n\ \n\ @@ -148,17 +148,17 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "+iu:", longopts, NULL)) != -1) { switch (optc) - { - case 'i': - ignore_environment = true; - break; - case 'u': - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'i': + ignore_environment = true; + break; + case 'u': + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (optind < argc && STREQ (argv[optind], "-")) @@ -186,7 +186,7 @@ main (int argc, char **argv) { char *const *e = environ; while (*e) - puts (*e++); + puts (*e++); exit (EXIT_SUCCESS); } diff --git a/src/expand.c b/src/expand.c index 10f36430d..c8648335a 100644 --- a/src/expand.c +++ b/src/expand.c @@ -23,10 +23,10 @@ --tabs=tab1[,tab2[,...]] -t tab1[,tab2[,...]] -tab1[,tab2[,...]] If only one tab stop is given, set the tabs tab1 - columns apart instead of the default 8. Otherwise, - set the tabs at columns tab1, tab2, etc. (numbered from - 0); replace any tabs beyond the tab stops given with - single spaces. + columns apart instead of the default 8. Otherwise, + set the tabs at columns tab1, tab2, etc. (numbered from + 0); replace any tabs beyond the tab stops given with + single spaces. --initial -i Only convert initial tabs on each line to spaces. @@ -97,13 +97,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Convert tabs in each FILE to spaces, writing to standard output.\n\ With no FILE, or when FILE is -, read standard input.\n\ @@ -150,38 +150,38 @@ parse_tab_stops (char const *stops) for (; *stops; stops++) { if (*stops == ',' || isblank (to_uchar (*stops))) - { - if (have_tabval) - add_tab_stop (tabval); - have_tabval = false; - } + { + if (have_tabval) + add_tab_stop (tabval); + have_tabval = false; + } else if (ISDIGIT (*stops)) - { - if (!have_tabval) - { - tabval = 0; - have_tabval = true; - num_start = stops; - } - - /* Detect overflow. */ - if (!DECIMAL_DIGIT_ACCUMULATE (tabval, *stops - '0', uintmax_t)) - { - size_t len = strspn (num_start, "0123456789"); - char *bad_num = xstrndup (num_start, len); - error (0, 0, _("tab stop is too large %s"), quote (bad_num)); - free (bad_num); - ok = false; - stops = num_start + len - 1; - } - } + { + if (!have_tabval) + { + tabval = 0; + have_tabval = true; + num_start = stops; + } + + /* Detect overflow. */ + if (!DECIMAL_DIGIT_ACCUMULATE (tabval, *stops - '0', uintmax_t)) + { + size_t len = strspn (num_start, "0123456789"); + char *bad_num = xstrndup (num_start, len); + error (0, 0, _("tab stop is too large %s"), quote (bad_num)); + free (bad_num); + ok = false; + stops = num_start + len - 1; + } + } else - { - error (0, 0, _("tab size contains invalid character(s): %s"), - quote (stops)); - ok = false; - break; - } + { + error (0, 0, _("tab size contains invalid character(s): %s"), + quote (stops)); + ok = false; + break; + } } if (!ok) @@ -203,9 +203,9 @@ validate_tab_stops (uintmax_t const *tabs, size_t entries) for (i = 0; i < entries; i++) { if (tabs[i] == 0) - error (EXIT_FAILURE, 0, _("tab size cannot be 0")); + error (EXIT_FAILURE, 0, _("tab size cannot be 0")); if (tabs[i] <= prev_tab) - error (EXIT_FAILURE, 0, _("tab sizes must be ascending")); + error (EXIT_FAILURE, 0, _("tab sizes must be ascending")); prev_tab = tabs[i]; } } @@ -224,33 +224,33 @@ next_file (FILE *fp) if (fp) { if (ferror (fp)) - { - error (0, errno, "%s", prev_file); - exit_status = EXIT_FAILURE; - } + { + error (0, errno, "%s", prev_file); + exit_status = EXIT_FAILURE; + } if (STREQ (prev_file, "-")) - clearerr (fp); /* Also clear EOF. */ + clearerr (fp); /* Also clear EOF. */ else if (fclose (fp) != 0) - { - error (0, errno, "%s", prev_file); - exit_status = EXIT_FAILURE; - } + { + error (0, errno, "%s", prev_file); + exit_status = EXIT_FAILURE; + } } while ((file = *file_list++) != NULL) { if (STREQ (file, "-")) - { - have_read_stdin = true; - prev_file = file; - return stdin; - } + { + have_read_stdin = true; + prev_file = file; + return stdin; + } fp = fopen (file, "r"); if (fp) - { - prev_file = file; - return fp; - } + { + prev_file = file; + return fp; + } error (0, errno, "%s", file); exit_status = EXIT_FAILURE; } @@ -279,7 +279,7 @@ expand (void) /* The following variables have valid values only when CONVERT - is true: */ + is true: */ /* Column of next input character. */ uintmax_t column = 0; @@ -291,68 +291,68 @@ expand (void) /* Convert a line of text. */ do - { - while ((c = getc (fp)) < 0 && (fp = next_file (fp))) - continue; - - if (convert) - { - if (c == '\t') - { - /* Column the next input tab stop is on. */ - uintmax_t next_tab_column; - - if (tab_size) - next_tab_column = column + (tab_size - column % tab_size); - else - for (;;) - if (tab_index == first_free_tab) - { - next_tab_column = column + 1; - break; - } - else - { - uintmax_t tab = tab_list[tab_index++]; - if (column < tab) - { - next_tab_column = tab; - break; - } - } - - if (next_tab_column < column) - error (EXIT_FAILURE, 0, _("input line is too long")); - - while (++column < next_tab_column) - if (putchar (' ') < 0) - error (EXIT_FAILURE, errno, _("write error")); - - c = ' '; - } - else if (c == '\b') - { - /* Go back one column, and force recalculation of the - next tab stop. */ - column -= !!column; - tab_index -= !!tab_index; - } - else - { - column++; - if (!column) - error (EXIT_FAILURE, 0, _("input line is too long")); - } - - convert &= convert_entire_line | !! isblank (c); - } - - if (c < 0) - return; - - if (putchar (c) < 0) - error (EXIT_FAILURE, errno, _("write error")); - } + { + while ((c = getc (fp)) < 0 && (fp = next_file (fp))) + continue; + + if (convert) + { + if (c == '\t') + { + /* Column the next input tab stop is on. */ + uintmax_t next_tab_column; + + if (tab_size) + next_tab_column = column + (tab_size - column % tab_size); + else + for (;;) + if (tab_index == first_free_tab) + { + next_tab_column = column + 1; + break; + } + else + { + uintmax_t tab = tab_list[tab_index++]; + if (column < tab) + { + next_tab_column = tab; + break; + } + } + + if (next_tab_column < column) + error (EXIT_FAILURE, 0, _("input line is too long")); + + while (++column < next_tab_column) + if (putchar (' ') < 0) + error (EXIT_FAILURE, errno, _("write error")); + + c = ' '; + } + else if (c == '\b') + { + /* Go back one column, and force recalculation of the + next tab stop. */ + column -= !!column; + tab_index -= !!tab_index; + } + else + { + column++; + if (!column) + error (EXIT_FAILURE, 0, _("input line is too long")); + } + + convert &= convert_entire_line | !! isblank (c); + } + + if (c < 0) + return; + + if (putchar (c) < 0) + error (EXIT_FAILURE, errno, _("write error")); + } while (c != '\n'); } } @@ -379,35 +379,35 @@ main (int argc, char **argv) while ((c = getopt_long (argc, argv, shortopts, longopts, NULL)) != -1) { switch (c) - { - case 'i': - convert_entire_line = false; - break; - - case 't': - parse_tab_stops (optarg); - break; - - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - if (optarg) - parse_tab_stops (optarg - 1); - else - { - char tab_stop[2]; - tab_stop[0] = c; - tab_stop[1] = '\0'; - parse_tab_stops (tab_stop); - } - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'i': + convert_entire_line = false; + break; + + case 't': + parse_tab_stops (optarg); + break; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + if (optarg) + parse_tab_stops (optarg - 1); + else + { + char tab_stop[2]; + tab_stop[0] = c; + tab_stop[1] = '\0'; + parse_tab_stops (tab_stop); + } + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } validate_tab_stops (tab_list, first_free_tab); diff --git a/src/expr.c b/src/expr.c index ac3f4c3f2..11bf7ed47 100644 --- a/src/expr.c +++ b/src/expr.c @@ -89,7 +89,7 @@ mpz_mul (mpz_t r, mpz_t a0, mpz_t b0) intmax_t b = b0[0]; intmax_t val = a * b; if (! (a == 0 || b == 0 - || ((val < 0) == ((a < 0) ^ (b < 0)) && val / a == b))) + || ((val < 0) == ((a < 0) ^ (b < 0)) && val / a == b))) integer_overflow ('*'); r[0] = val; } @@ -196,14 +196,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s EXPRESSION\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); putchar ('\n'); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); @@ -231,7 +231,7 @@ separates increasing precedence groups. EXPRESSION may be:\n\ ARG1 - ARG2 arithmetic difference of ARG1 and ARG2\n\ "), stdout); /* Tell xgettext that the "% A" below is not a printf-style - format string: xgettext:no-c-format */ + format string: xgettext:no-c-format */ fputs (_("\ \n\ ARG1 * ARG2 arithmetic product of ARG1 and ARG2\n\ @@ -309,7 +309,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, VERSION, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); /* The above handles --help and --version. Since there is no other invocation of getopt, handle `--' here. */ if (argc > 1 && STREQ (argv[1], "--")) @@ -398,20 +398,20 @@ null (VALUE *v) return mpz_sgn (v->u.i) == 0; case string: { - char const *cp = v->u.s; - if (*cp == '\0') - return true; + char const *cp = v->u.s; + if (*cp == '\0') + return true; - cp += (*cp == '-'); + cp += (*cp == '-'); - do - { - if (*cp != '0') - return false; - } - while (*++cp); + do + { + if (*cp != '0') + return false; + } + while (*++cp); - return true; + return true; } default: abort (); @@ -442,10 +442,10 @@ tostring (VALUE *v) { case integer: { - char *s = mpz_get_str (NULL, 10, v->u.i); - mpz_clear (v->u.i); - v->u.s = s; - v->type = string; + char *s = mpz_get_str (NULL, 10, v->u.i); + mpz_clear (v->u.i); + v->u.s = s; + v->type = string; } break; case string: @@ -466,15 +466,15 @@ toarith (VALUE *v) return true; case string: { - char *s = v->u.s; - - if (! looks_like_integer (s)) - return false; - if (mpz_init_set_str (v->u.i, s, 10) != 0 && !HAVE_GMP) - error (EXPR_FAILURE, ERANGE, "%s", s); - free (s); - v->type = integer; - return true; + char *s = v->u.s; + + if (! looks_like_integer (s)) + return false; + if (mpz_init_set_str (v->u.i, s, 10) != 0 && !HAVE_GMP) + error (EXPR_FAILURE, ERANGE, "%s", s); + free (s); + v->type = integer; + return true; } default: abort (); @@ -493,7 +493,7 @@ getsize (mpz_t i) { unsigned long int ul = mpz_get_ui (i); if (ul < SIZE_MAX) - return ul; + return ul; } return SIZE_MAX - 1; } @@ -575,25 +575,25 @@ docolon (VALUE *sv, VALUE *pv) { /* Were \(...\) used? */ if (re_buffer.re_nsub > 0) - { - sv->u.s[re_regs.end[1]] = '\0'; - v = str_value (sv->u.s + re_regs.start[1]); - } + { + sv->u.s[re_regs.end[1]] = '\0'; + v = str_value (sv->u.s + re_regs.start[1]); + } else - v = int_value (matchlen); + v = int_value (matchlen); } else if (matchlen == -1) { /* Match failed -- return the right kind of null. */ if (re_buffer.re_nsub > 0) - v = str_value (""); + v = str_value (""); else - v = int_value (0); + v = int_value (0); } else error (EXPR_FAILURE, - (matchlen == -2 ? errno : EOVERFLOW), - _("error in regular expression matcher")); + (matchlen == -2 ? errno : EOVERFLOW), + _("error in regular expression matcher")); if (0 < re_regs.num_regs) { @@ -622,7 +622,7 @@ eval7 (bool evaluate) { v = eval (evaluate); if (!nextarg (")")) - syntax_error (); + syntax_error (); return v; } @@ -649,7 +649,7 @@ eval6 (bool evaluate) if (nextarg ("+")) { if (nomoreargs ()) - syntax_error (); + syntax_error (); return str_value (*args++); } else if (nextarg ("length")) @@ -665,12 +665,12 @@ eval6 (bool evaluate) l = eval6 (evaluate); r = eval6 (evaluate); if (evaluate) - { - v = docolon (l, r); - freev (l); - } + { + v = docolon (l, r); + freev (l); + } else - v = l; + v = l; freev (r); return v; } @@ -698,25 +698,25 @@ eval6 (bool evaluate) llen = strlen (l->u.s); if (!toarith (i1) || !toarith (i2)) - v = str_value (""); + v = str_value (""); else - { - size_t pos = getsize (i1->u.i); - size_t len = getsize (i2->u.i); - - if (llen < pos || pos == 0 || len == 0 || len == SIZE_MAX) - v = str_value (""); - else - { - size_t vlen = MIN (len, llen - pos + 1); - char *vlim; - v = xmalloc (sizeof *v); - v->type = string; - v->u.s = xmalloc (vlen + 1); - vlim = mempcpy (v->u.s, l->u.s + pos - 1, vlen); - *vlim = '\0'; - } - } + { + size_t pos = getsize (i1->u.i); + size_t len = getsize (i2->u.i); + + if (llen < pos || pos == 0 || len == 0 || len == SIZE_MAX) + v = str_value (""); + else + { + size_t vlen = MIN (len, llen - pos + 1); + char *vlim; + v = xmalloc (sizeof *v); + v->type = string; + v->u.s = xmalloc (vlen + 1); + vlim = mempcpy (v->u.s, l->u.s + pos - 1, vlen); + *vlim = '\0'; + } + } freev (l); freev (i1); freev (i2); @@ -743,18 +743,18 @@ eval5 (bool evaluate) while (1) { if (nextarg (":")) - { - r = eval6 (evaluate); - if (evaluate) - { - v = docolon (l, r); - freev (l); - l = v; - } - freev (r); - } + { + r = eval6 (evaluate); + if (evaluate) + { + v = docolon (l, r); + freev (l); + l = v; + } + freev (r); + } else - return l; + return l; } } @@ -774,25 +774,25 @@ eval4 (bool evaluate) while (1) { if (nextarg ("*")) - fxn = multiply; + fxn = multiply; else if (nextarg ("/")) - fxn = divide; + fxn = divide; else if (nextarg ("%")) - fxn = mod; + fxn = mod; else - return l; + return l; r = eval5 (evaluate); if (evaluate) - { - if (!toarith (l) || !toarith (r)) - error (EXPR_INVALID, 0, _("non-numeric argument")); - if (fxn != multiply && mpz_sgn (r->u.i) == 0) - error (EXPR_INVALID, 0, _("division by zero")); - ((fxn == multiply ? mpz_mul - : fxn == divide ? mpz_tdiv_q - : mpz_tdiv_r) - (l->u.i, l->u.i, r->u.i)); - } + { + if (!toarith (l) || !toarith (r)) + error (EXPR_INVALID, 0, _("non-numeric argument")); + if (fxn != multiply && mpz_sgn (r->u.i) == 0) + error (EXPR_INVALID, 0, _("division by zero")); + ((fxn == multiply ? mpz_mul + : fxn == divide ? mpz_tdiv_q + : mpz_tdiv_r) + (l->u.i, l->u.i, r->u.i)); + } freev (r); } } @@ -813,18 +813,18 @@ eval3 (bool evaluate) while (1) { if (nextarg ("+")) - fxn = plus; + fxn = plus; else if (nextarg ("-")) - fxn = minus; + fxn = minus; else - return l; + return l; r = eval4 (evaluate); if (evaluate) - { - if (!toarith (l) || !toarith (r)) - error (EXPR_INVALID, 0, _("non-numeric argument")); - (fxn == plus ? mpz_add : mpz_sub) (l->u.i, l->u.i, r->u.i); - } + { + if (!toarith (l) || !toarith (r)) + error (EXPR_INVALID, 0, _("non-numeric argument")); + (fxn == plus ? mpz_add : mpz_sub) (l->u.i, l->u.i, r->u.i); + } freev (r); } } @@ -844,62 +844,62 @@ eval2 (bool evaluate) { VALUE *r; enum - { - less_than, less_equal, equal, not_equal, greater_equal, greater_than - } fxn; + { + less_than, less_equal, equal, not_equal, greater_equal, greater_than + } fxn; bool val = false; if (nextarg ("<")) - fxn = less_than; + fxn = less_than; else if (nextarg ("<=")) - fxn = less_equal; + fxn = less_equal; else if (nextarg ("=") || nextarg ("==")) - fxn = equal; + fxn = equal; else if (nextarg ("!=")) - fxn = not_equal; + fxn = not_equal; else if (nextarg (">=")) - fxn = greater_equal; + fxn = greater_equal; else if (nextarg (">")) - fxn = greater_than; + fxn = greater_than; else - return l; + return l; r = eval3 (evaluate); if (evaluate) - { - int cmp; - tostring (l); - tostring (r); - - if (looks_like_integer (l->u.s) && looks_like_integer (r->u.s)) - cmp = strintcmp (l->u.s, r->u.s); - else - { - errno = 0; - cmp = strcoll (l->u.s, r->u.s); - - if (errno) - { - error (0, errno, _("string comparison failed")); - error (0, 0, _("set LC_ALL='C' to work around the problem")); - error (EXPR_INVALID, 0, - _("the strings compared were %s and %s"), - quotearg_n_style (0, locale_quoting_style, l->u.s), - quotearg_n_style (1, locale_quoting_style, r->u.s)); - } - } - - switch (fxn) - { - case less_than: val = (cmp < 0); break; - case less_equal: val = (cmp <= 0); break; - case equal: val = (cmp == 0); break; - case not_equal: val = (cmp != 0); break; - case greater_equal: val = (cmp >= 0); break; - case greater_than: val = (cmp > 0); break; - default: abort (); - } - } + { + int cmp; + tostring (l); + tostring (r); + + if (looks_like_integer (l->u.s) && looks_like_integer (r->u.s)) + cmp = strintcmp (l->u.s, r->u.s); + else + { + errno = 0; + cmp = strcoll (l->u.s, r->u.s); + + if (errno) + { + error (0, errno, _("string comparison failed")); + error (0, 0, _("set LC_ALL='C' to work around the problem")); + error (EXPR_INVALID, 0, + _("the strings compared were %s and %s"), + quotearg_n_style (0, locale_quoting_style, l->u.s), + quotearg_n_style (1, locale_quoting_style, r->u.s)); + } + } + + switch (fxn) + { + case less_than: val = (cmp < 0); break; + case less_equal: val = (cmp <= 0); break; + case equal: val = (cmp == 0); break; + case not_equal: val = (cmp != 0); break; + case greater_equal: val = (cmp >= 0); break; + case greater_than: val = (cmp > 0); break; + default: abort (); + } + } freev (l); freev (r); @@ -922,19 +922,19 @@ eval1 (bool evaluate) while (1) { if (nextarg ("&")) - { - r = eval2 (evaluate & ~ null (l)); - if (null (l) || null (r)) - { - freev (l); - freev (r); - l = int_value (0); - } - else - freev (r); - } + { + r = eval2 (evaluate & ~ null (l)); + if (null (l) || null (r)) + { + freev (l); + freev (r); + l = int_value (0); + } + else + freev (r); + } else - return l; + return l; } } @@ -953,22 +953,22 @@ eval (bool evaluate) while (1) { if (nextarg ("|")) - { - r = eval1 (evaluate & null (l)); - if (null (l)) - { - freev (l); - l = r; - if (null (l)) - { - freev (l); - l = int_value (0); - } - } - else - freev (r); - } + { + r = eval1 (evaluate & null (l)); + if (null (l)) + { + freev (l); + l = r; + if (null (l)) + { + freev (l); + l = int_value (0); + } + } + else + freev (r); + } else - return l; + return l; } } diff --git a/src/extract-magic b/src/extract-magic index 8daf59d22..dfea3d5fd 100644 --- a/src/extract-magic +++ b/src/extract-magic @@ -114,10 +114,10 @@ EOF while (defined (my $line = <FH>)) { $line =~ /^[ \t]+case S_MAGIC_/ - or next; + or next; $line =~ m!^[ \t]+case (S_MAGIC_\w+): /\* (0x[0-9A-Fa-f]+) \*/$! - or (warn "$ME:$file:$.: malformed case S_MAGIC_... line"), - $fail = 1, next; + or (warn "$ME:$file:$.: malformed case S_MAGIC_... line"), + $fail = 1, next; my $name = $1; my $value = $2; print "# define $name $value\n"; diff --git a/src/factor.c b/src/factor.c index 9ac703ce8..59fe1f45f 100644 --- a/src/factor.c +++ b/src/factor.c @@ -110,7 +110,7 @@ factor_using_division (mpz_t t, unsigned int limit) { mpz_tdiv_qr_ui (q, r, t, 3); if (mpz_cmp_ui (r, 0) != 0) - break; + break; mpz_set (t, q); emit_ul_factor (3); } @@ -119,7 +119,7 @@ factor_using_division (mpz_t t, unsigned int limit) { mpz_tdiv_qr_ui (q, r, t, 5); if (mpz_cmp_ui (r, 0) != 0) - break; + break; mpz_set (t, q); emit_ul_factor (5); } @@ -131,21 +131,21 @@ factor_using_division (mpz_t t, unsigned int limit) { mpz_tdiv_qr_ui (q, r, t, f); if (mpz_cmp_ui (r, 0) != 0) - { - f += addv[ai]; - if (mpz_cmp_ui (q, f) < 0) - break; - ai = (ai + 1) & 7; - failures++; - if (failures > limit) - break; - } + { + f += addv[ai]; + if (mpz_cmp_ui (q, f) < 0) + break; + ai = (ai + 1) & 7; + failures++; + if (failures > limit) + break; + } else - { - mpz_swap (t, q); - emit_ul_factor (f); - failures = 0; - } + { + mpz_swap (t, q); + emit_ul_factor (f); + failures = 0; + } } mpz_clear (q); @@ -184,67 +184,67 @@ S2: mpz_sub (t1, x1, x); mpz_mul (t2, P, t1); mpz_mod (P, t2, n); c++; if (c == 20) - { - c = 0; - mpz_gcd (g, P, n); - if (mpz_cmp_ui (g, 1) != 0) - goto S4; - mpz_set (y, x); - } + { + c = 0; + mpz_gcd (g, P, n); + if (mpz_cmp_ui (g, 1) != 0) + goto S4; + mpz_set (y, x); + } k--; if (k > 0) - goto S2; + goto S2; mpz_gcd (g, P, n); if (mpz_cmp_ui (g, 1) != 0) - goto S4; + goto S4; mpz_set (x1, x); k = l; l = 2 * l; for (i = 0; i < k; i++) - { - mpz_mul (x, x, x); mpz_add (x, x, a); mpz_mod (x, x, n); - } + { + mpz_mul (x, x, x); mpz_add (x, x, a); mpz_mod (x, x, n); + } mpz_set (y, x); c = 0; goto S2; S4: do - { - mpz_mul (y, y, y); mpz_add (y, y, a); mpz_mod (y, y, n); - mpz_sub (t1, x1, y); mpz_gcd (g, t1, n); - } + { + mpz_mul (y, y, y); mpz_add (y, y, a); mpz_mod (y, y, n); + mpz_sub (t1, x1, y); mpz_gcd (g, t1, n); + } while (mpz_cmp_ui (g, 1) == 0); mpz_div (n, n, g); /* divide by g, before g is overwritten */ if (!mpz_probab_prime_p (g, 3)) - { - do - { - mp_limb_t a_limb; - mpn_random (&a_limb, (mp_size_t) 1); - a_int = (int) a_limb; - } - while (a_int == -2 || a_int == 0); - - debug ("[composite factor--restarting pollard-rho] "); - factor_using_pollard_rho (g, a_int); - } + { + do + { + mp_limb_t a_limb; + mpn_random (&a_limb, (mp_size_t) 1); + a_int = (int) a_limb; + } + while (a_int == -2 || a_int == 0); + + debug ("[composite factor--restarting pollard-rho] "); + factor_using_pollard_rho (g, a_int); + } else - { - emit_factor (g); - } + { + emit_factor (g); + } mpz_mod (x, x, n); mpz_mod (x1, x1, n); mpz_mod (y, y, n); if (mpz_probab_prime_p (n, 3)) - { - emit_factor (n); - break; - } + { + emit_factor (n); + break; + } } mpz_clear (g); @@ -309,15 +309,15 @@ factor_wheel (uintmax_t n0, size_t max_n_factors, uintmax_t *factors) { q = n / d; while (n == q * d) - { - assert (n_factors < max_n_factors); - factors[n_factors++] = d; - n = q; - q = n / d; - } + { + assert (n_factors < max_n_factors); + factors[n_factors++] = d; + n = q; + q = n / d; + } d += *(w++); if (w == WHEEL_END) - w = WHEEL_START; + w = WHEEL_START; } while (d <= q); @@ -407,13 +407,13 @@ print_factors_multi (mpz_t t) factor_using_division (t, division_limit); if (mpz_cmp_ui (t, 1) != 0) - { - debug ("[is number prime?] "); - if (mpz_probab_prime_p (t, 3)) - emit_factor (t); - else - factor_using_pollard_rho (t, 1); - } + { + debug ("[is number prime?] "); + if (mpz_probab_prime_p (t, 3)) + emit_factor (t); + else + factor_using_pollard_rho (t, 1); + } } mpz_clear (t); @@ -443,11 +443,11 @@ print_factors (char const *s) mpz_t t; mpz_init (t); if (gmp_sscanf (s, "%Zd", t) == 1) - { - debug ("[%s]", _("using arbitrary-precision arithmetic")); - print_factors_multi (t); - return true; - } + { + debug ("[%s]", _("using arbitrary-precision arithmetic")); + print_factors_multi (t); + return true; + } err = LONGINT_INVALID; } #endif @@ -487,14 +487,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [NUMBER]...\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Print the prime factors of each specified integer NUMBER. If none\n\ are specified on the command line, read them from standard input.\n\ @@ -518,9 +518,9 @@ do_stdin (void) for (;;) { size_t token_length = readtoken (stdin, DELIM, sizeof (DELIM) - 1, - &tokenbuffer); + &tokenbuffer); if (token_length == (size_t) -1) - break; + break; ok &= print_factors (tokenbuffer.buffer); } free (tokenbuffer.buffer); @@ -545,18 +545,18 @@ main (int argc, char **argv) while ((c = getopt_long (argc, argv, "", long_options, NULL)) != -1) { switch (c) - { - case VERBOSE_OPTION: - verbose = true; - break; + { + case VERBOSE_OPTION: + verbose = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (argc <= optind) @@ -566,8 +566,8 @@ main (int argc, char **argv) int i; ok = true; for (i = optind; i < argc; i++) - if (! print_factors (argv[i])) - ok = false; + if (! print_factors (argv[i])) + ok = false; } #if HAVE_GMP free (factor); @@ -263,7 +263,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [-WIDTH] [OPTION]... [FILE]...\n"), program_name); @@ -281,7 +281,7 @@ Mandatory arguments to long options are mandatory for short options too.\n\ reattaching the prefix to reformatted lines\n\ -s, --split-only split long lines, but do not refill\n\ "), - stdout); + stdout); fputs (_("\ -t, --tagged-paragraph indentation of first line different from second\n\ -u, --uniform-spacing one space between words, two after sentences\n\ @@ -292,7 +292,7 @@ Mandatory arguments to long options are mandatory for short options too.\n\ fputs (_("\ \n\ With no FILE, or when FILE is -, read standard input.\n"), - stdout); + stdout); emit_bug_reporting_address (); } exit (status); @@ -345,40 +345,40 @@ main (int argc, char **argv) } while ((optchar = getopt_long (argc, argv, "0123456789cstuw:p:", - long_options, NULL)) - != -1) + long_options, NULL)) + != -1) switch (optchar) { default: - if (ISDIGIT (optchar)) - error (0, 0, _("invalid option -- %c; -WIDTH is recognized\ + if (ISDIGIT (optchar)) + error (0, 0, _("invalid option -- %c; -WIDTH is recognized\ only when it is the first\noption; use -w N instead"), - optchar); - usage (EXIT_FAILURE); + optchar); + usage (EXIT_FAILURE); case 'c': - crown = true; - break; + crown = true; + break; case 's': - split = true; - break; + split = true; + break; case 't': - tagged = true; - break; + tagged = true; + break; case 'u': - uniform = true; - break; + uniform = true; + break; case 'w': - max_width_option = optarg; - break; + max_width_option = optarg; + break; case 'p': - set_prefix (optarg); - break; + set_prefix (optarg); + break; case_GETOPT_HELP_CHAR; @@ -389,12 +389,12 @@ main (int argc, char **argv) if (max_width_option) { /* Limit max_width to MAXCHARS / 2; otherwise, the resulting - output can be quite ugly. */ + output can be quite ugly. */ unsigned long int tmp; if (! (xstrtoul (max_width_option, NULL, 10, &tmp, "") == LONGINT_OK - && tmp <= MAXCHARS / 2)) - error (EXIT_FAILURE, 0, _("invalid width: %s"), - quote (max_width_option)); + && tmp <= MAXCHARS / 2)) + error (EXIT_FAILURE, 0, _("invalid width: %s"), + quote (max_width_option)); max_width = tmp; } @@ -405,31 +405,31 @@ main (int argc, char **argv) else { for (; optind < argc; optind++) - { - char *file = argv[optind]; - if (STREQ (file, "-")) - fmt (stdin); - else - { - FILE *in_stream; - in_stream = fopen (file, "r"); - if (in_stream != NULL) - { - fmt (in_stream); - if (fclose (in_stream) == EOF) - { - error (0, errno, "%s", file); - ok = false; - } - } - else - { - error (0, errno, _("cannot open %s for reading"), - quote (file)); - ok = false; - } - } - } + { + char *file = argv[optind]; + if (STREQ (file, "-")) + fmt (stdin); + else + { + FILE *in_stream; + in_stream = fopen (file, "r"); + if (in_stream != NULL) + { + fmt (in_stream); + if (fclose (in_stream) == EOF) + { + error (0, errno, "%s", file); + ok = false; + } + } + else + { + error (0, errno, _("cannot open %s for reading"), + quote (file)); + ok = false; + } + } + } } exit (ok ? EXIT_SUCCESS : EXIT_FAILURE); @@ -488,9 +488,9 @@ set_other_indent (bool same_paragraph) else if (tagged) { if (same_paragraph && in_column != first_indent) - { - other_indent = in_column; - } + { + other_indent = in_column; + } /* Only one line: use the secondary indent from last time if it splits, or 0 if there have been no multi-line paragraphs in the @@ -498,7 +498,7 @@ set_other_indent (bool same_paragraph) pick a new secondary indent. */ else if (other_indent == first_indent) - other_indent = first_indent == 0 ? DEF_INDENT : 0; + other_indent = first_indent == 0 ? DEF_INDENT : 0; } else { @@ -532,15 +532,15 @@ get_paragraph (FILE *f) /* Scan (and copy) blank lines, and lines not introduced by the prefix. */ while (c == '\n' || c == EOF - || next_prefix_indent < prefix_lead_space - || in_column < next_prefix_indent + prefix_full_length) + || next_prefix_indent < prefix_lead_space + || in_column < next_prefix_indent + prefix_full_length) { c = copy_rest (f, c); if (c == EOF) - { - next_char = EOF; - return false; - } + { + next_char = EOF; + return false; + } putchar ('\n'); c = get_prefix (f); } @@ -563,29 +563,29 @@ get_paragraph (FILE *f) else if (crown) { if (same_para (c)) - { - do - { /* for each line till the end of the para */ - c = get_line (f, c); - } - while (same_para (c) && in_column == other_indent); - } + { + do + { /* for each line till the end of the para */ + c = get_line (f, c); + } + while (same_para (c) && in_column == other_indent); + } } else if (tagged) { if (same_para (c) && in_column != first_indent) - { - do - { /* for each line till the end of the para */ - c = get_line (f, c); - } - while (same_para (c) && in_column == other_indent); - } + { + do + { /* for each line till the end of the para */ + c = get_line (f, c); + } + while (same_para (c) && in_column == other_indent); + } } else { while (same_para (c) && in_column == other_indent) - c = get_line (f, c); + c = get_line (f, c); } (word_limit - 1)->period = (word_limit - 1)->final = true; next_char = c; @@ -607,11 +607,11 @@ copy_rest (FILE *f, int c) { put_space (next_prefix_indent); for (s = prefix; out_column != in_column && *s; out_column++) - putchar (*s++); + putchar (*s++); if (c != EOF && c != '\n') - put_space (in_column - out_column); + put_space (in_column - out_column); if (c == EOF && in_column >= next_prefix_indent + prefix_length) - putchar ('\n'); + putchar ('\n'); } while (c != '\n' && c != EOF) { @@ -629,8 +629,8 @@ static bool same_para (int c) { return (next_prefix_indent == prefix_indent - && in_column >= next_prefix_indent + prefix_full_length - && c != '\n' && c != EOF); + && in_column >= next_prefix_indent + prefix_full_length + && c != '\n' && c != EOF); } /* Read a line from input file F, given first non-blank character C @@ -658,15 +658,15 @@ get_line (FILE *f, int c) word_limit->text = wptr; do - { - if (wptr == end_of_parabuf) - { - set_other_indent (true); - flush_paragraph (); - } - *wptr++ = c; - c = getc (f); - } + { + if (wptr == end_of_parabuf) + { + set_other_indent (true); + flush_paragraph (); + } + *wptr++ = c; + c = getc (f); + } while (c != EOF && !isspace (c)); in_column += word_limit->length = wptr - word_limit->text; check_punctuation (word_limit); @@ -677,15 +677,15 @@ get_line (FILE *f, int c) c = get_space (f, c); word_limit->space = in_column - start; word_limit->final = (c == EOF - || (word_limit->period - && (c == '\n' || word_limit->space > 1))); + || (word_limit->period + && (c == '\n' || word_limit->space > 1))); if (c == '\n' || c == EOF || uniform) - word_limit->space = word_limit->final ? 2 : 1; + word_limit->space = word_limit->final ? 2 : 1; if (word_limit == end_of_word) - { - set_other_indent (true); - flush_paragraph (); - } + { + set_other_indent (true); + flush_paragraph (); + } word_limit++; } while (c != '\n' && c != EOF); @@ -710,13 +710,13 @@ get_prefix (FILE *f) const char *p; next_prefix_indent = in_column; for (p = prefix; *p != '\0'; p++) - { - unsigned char pc = *p; - if (c != pc) - return c; - in_column++; - c = getc (f); - } + { + unsigned char pc = *p; + if (c != pc) + return c; + in_column++; + c = getc (f); + } c = get_space (f, c); } return c; @@ -731,14 +731,14 @@ get_space (FILE *f, int c) for (;;) { if (c == ' ') - in_column++; + in_column++; else if (c == '\t') - { - tabs = true; - in_column = (in_column / TABWIDTH + 1) * TABWIDTH; - } + { + tabs = true; + in_column = (in_column / TABWIDTH + 1) * TABWIDTH; + } else - return c; + return c; c = getc (f); } } @@ -794,12 +794,12 @@ flush_paragraph (void) for (w = word->next_break; w != word_limit; w = w->next_break) { if (w->best_cost - w->next_break->best_cost < best_break) - { - split_point = w; - best_break = w->best_cost - w->next_break->best_cost; - } + { + split_point = w; + best_break = w->best_cost - w->next_break->best_cost; + } if (best_break <= MAXCOST - LINE_CREDIT) - best_break += LINE_CREDIT; + best_break += LINE_CREDIT; } put_paragraph (split_point); @@ -848,30 +848,30 @@ fmt_paragraph (void) w = start; len += w->length; do - { - w++; - - /* Consider breaking before w. */ - - wcost = line_cost (w, len) + w->best_cost; - if (start == word && last_line_length > 0) - wcost += RAGGED_COST (len - last_line_length); - if (wcost < best) - { - best = wcost; - start->next_break = w; - start->line_length = len; - } - - /* This is a kludge to keep us from computing `len' as the - sum of the sentinel length and some non-zero number. - Since the sentinel w->length may be INT_MAX, adding - to that would give a negative result. */ - if (w == word_limit) - break; - - len += (w - 1)->space + w->length; /* w > start >= word */ - } + { + w++; + + /* Consider breaking before w. */ + + wcost = line_cost (w, len) + w->best_cost; + if (start == word && last_line_length > 0) + wcost += RAGGED_COST (len - last_line_length); + if (wcost < best) + { + best = wcost; + start->next_break = w; + start->line_length = len; + } + + /* This is a kludge to keep us from computing `len' as the + sum of the sentinel length and some non-zero number. + Since the sentinel w->length may be INT_MAX, adding + to that would give a negative result. */ + if (w == word_limit) + break; + + len += (w - 1)->space + w->length; /* w > start >= word */ + } while (len < max_width); start->best_cost = best + base_cost (start); } @@ -892,16 +892,16 @@ base_cost (WORD *this) if (this > word) { if ((this - 1)->period) - { - if ((this - 1)->final) - cost -= SENTENCE_BONUS; - else - cost += NOBREAK_COST; - } + { + if ((this - 1)->final) + cost -= SENTENCE_BONUS; + else + cost += NOBREAK_COST; + } else if ((this - 1)->punct) - cost -= PUNCT_BONUS; + cost -= PUNCT_BONUS; else if (this > word + 1 && (this - 2)->final) - cost += WIDOW_COST ((this - 1)->length); + cost += WIDOW_COST ((this - 1)->length); } if (this->paren) @@ -997,11 +997,11 @@ put_space (int space) { tab_target = space_target / TABWIDTH * TABWIDTH; if (out_column + 1 < tab_target) - while (out_column < tab_target) - { - putchar ('\t'); - out_column = (out_column / TABWIDTH + 1) * TABWIDTH; - } + while (out_column < tab_target) + { + putchar ('\t'); + out_column = (out_column / TABWIDTH + 1) * TABWIDTH; + } } while (out_column < space_target) { diff --git a/src/fold.c b/src/fold.c index b9c909f8d..52322657a 100644 --- a/src/fold.c +++ b/src/fold.c @@ -60,13 +60,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Wrap input lines in each FILE (standard input by default), writing to\n\ standard output.\n\ @@ -97,16 +97,16 @@ adjust_column (size_t column, char c) if (!count_bytes) { if (c == '\b') - { - if (column > 0) - column--; - } + { + if (column > 0) + column--; + } else if (c == '\r') - column = 0; + column = 0; else if (c == '\t') - column += TAB_WIDTH - column % TAB_WIDTH; + column += TAB_WIDTH - column % TAB_WIDTH; else /* if (isprint (c)) */ - column++; + column++; } else column++; @@ -145,71 +145,71 @@ fold_file (char const *filename, size_t width) while ((c = getc (istream)) != EOF) { if (offset_out + 1 >= allocated_out) - line_out = X2REALLOC (line_out, &allocated_out); + line_out = X2REALLOC (line_out, &allocated_out); if (c == '\n') - { - line_out[offset_out++] = c; - fwrite (line_out, sizeof (char), offset_out, stdout); - column = offset_out = 0; - continue; - } + { + line_out[offset_out++] = c; + fwrite (line_out, sizeof (char), offset_out, stdout); + column = offset_out = 0; + continue; + } rescan: column = adjust_column (column, c); if (column > width) - { - /* This character would make the line too long. - Print the line plus a newline, and make this character - start the next line. */ - if (break_spaces) - { - bool found_blank = false; - size_t logical_end = offset_out; - - /* Look for the last blank. */ - while (logical_end) - { - --logical_end; - if (isblank (to_uchar (line_out[logical_end]))) - { - found_blank = true; - break; - } - } - - if (found_blank) - { - size_t i; - - /* Found a blank. Don't output the part after it. */ - logical_end++; - fwrite (line_out, sizeof (char), (size_t) logical_end, - stdout); - putchar ('\n'); - /* Move the remainder to the beginning of the next line. - The areas being copied here might overlap. */ - memmove (line_out, line_out + logical_end, - offset_out - logical_end); - offset_out -= logical_end; - for (column = i = 0; i < offset_out; i++) - column = adjust_column (column, line_out[i]); - goto rescan; - } - } - - if (offset_out == 0) - { - line_out[offset_out++] = c; - continue; - } - - line_out[offset_out++] = '\n'; - fwrite (line_out, sizeof (char), (size_t) offset_out, stdout); - column = offset_out = 0; - goto rescan; - } + { + /* This character would make the line too long. + Print the line plus a newline, and make this character + start the next line. */ + if (break_spaces) + { + bool found_blank = false; + size_t logical_end = offset_out; + + /* Look for the last blank. */ + while (logical_end) + { + --logical_end; + if (isblank (to_uchar (line_out[logical_end]))) + { + found_blank = true; + break; + } + } + + if (found_blank) + { + size_t i; + + /* Found a blank. Don't output the part after it. */ + logical_end++; + fwrite (line_out, sizeof (char), (size_t) logical_end, + stdout); + putchar ('\n'); + /* Move the remainder to the beginning of the next line. + The areas being copied here might overlap. */ + memmove (line_out, line_out + logical_end, + offset_out - logical_end); + offset_out -= logical_end; + for (column = i = 0; i < offset_out; i++) + column = adjust_column (column, line_out[i]); + goto rescan; + } + } + + if (offset_out == 0) + { + line_out[offset_out++] = c; + continue; + } + + line_out[offset_out++] = '\n'; + fwrite (line_out, sizeof (char), (size_t) offset_out, stdout); + column = offset_out = 0; + goto rescan; + } line_out[offset_out++] = c; } @@ -223,7 +223,7 @@ fold_file (char const *filename, size_t width) { error (0, saved_errno, "%s", filename); if (!STREQ (filename, "-")) - fclose (istream); + fclose (istream); return false; } if (!STREQ (filename, "-") && fclose (istream) == EOF) @@ -258,44 +258,44 @@ main (int argc, char **argv) char optargbuf[2]; switch (optc) - { - case 'b': /* Count bytes rather than columns. */ - count_bytes = true; - break; - - case 's': /* Break at word boundaries. */ - break_spaces = true; - break; - - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - if (optarg) - optarg--; - else - { - optargbuf[0] = optc; - optargbuf[1] = '\0'; - optarg = optargbuf; - } - /* Fall through. */ - case 'w': /* Line width. */ - { - unsigned long int tmp_ulong; - if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK - && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH)) - error (EXIT_FAILURE, 0, - _("invalid number of columns: %s"), quote (optarg)); - width = tmp_ulong; - } - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'b': /* Count bytes rather than columns. */ + count_bytes = true; + break; + + case 's': /* Break at word boundaries. */ + break_spaces = true; + break; + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + if (optarg) + optarg--; + else + { + optargbuf[0] = optc; + optargbuf[1] = '\0'; + optarg = optargbuf; + } + /* Fall through. */ + case 'w': /* Line width. */ + { + unsigned long int tmp_ulong; + if (! (xstrtoul (optarg, NULL, 10, &tmp_ulong, "") == LONGINT_OK + && 0 < tmp_ulong && tmp_ulong < SIZE_MAX - TAB_WIDTH)) + error (EXIT_FAILURE, 0, + _("invalid number of columns: %s"), quote (optarg)); + width = tmp_ulong; + } + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (argc == optind) @@ -304,7 +304,7 @@ main (int argc, char **argv) { ok = true; for (i = optind; i < argc; i++) - ok &= fold_file (argv[i], width); + ok &= fold_file (argv[i], width); } if (have_read_stdin && fclose (stdin) == EOF) diff --git a/src/head.c b/src/head.c index c96f91009..f01438809 100644 --- a/src/head.c +++ b/src/head.c @@ -102,13 +102,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Print the first 10 lines of each FILE to standard output.\n\ With more than one FILE, precede each with a header giving the file name.\n\ @@ -186,15 +186,15 @@ copy_fd (int src_fd, FILE *o_stream, uintmax_t n_bytes) size_t n_to_read = MIN (buf_size, n_bytes); size_t n_read = safe_read (src_fd, buf, n_to_read); if (n_read == SAFE_READ_ERROR) - return COPY_FD_READ_ERROR; + return COPY_FD_READ_ERROR; n_bytes -= n_read; if (n_read == 0 && n_bytes != 0) - return COPY_FD_UNEXPECTED_EOF; + return COPY_FD_UNEXPECTED_EOF; if (fwrite (buf, 1, n_read, o_stream) < n_read) - return COPY_FD_WRITE_ERROR; + return COPY_FD_WRITE_ERROR; } return COPY_FD_OK; @@ -229,7 +229,7 @@ elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0) { char umax_buf[INT_BUFSIZE_BOUND (uintmax_t)]; error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"), - umaxtostr (n_elide_0, umax_buf)); + umaxtostr (n_elide_0, umax_buf)); } /* Two cases to consider... @@ -255,54 +255,54 @@ elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0) b[1] = b[0] + n_to_read; for (i = false; ! eof ; i = !i) - { - size_t n_read = full_read (fd, b[i], n_to_read); - size_t delta = 0; - if (n_read < n_to_read) - { - if (errno != 0) - { - error (0, errno, _("error reading %s"), quote (filename)); - ok = false; - break; - } - - /* reached EOF */ - if (n_read <= n_elide) - { - if (first) - { - /* The input is no larger than the number of bytes - to elide. So there's nothing to output, and - we're done. */ - } - else - { - delta = n_elide - n_read; - } - } - eof = true; - } - - /* Output any (but maybe just part of the) elided data from - the previous round. */ - if ( ! first) - { - /* Don't bother checking for errors here. - If there's a failure, the test of the following - fwrite or in close_stdout will catch it. */ - fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout); - } - first = false; - - if (n_elide < n_read - && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide) - { - error (0, errno, _("write error")); - ok = false; - break; - } - } + { + size_t n_read = full_read (fd, b[i], n_to_read); + size_t delta = 0; + if (n_read < n_to_read) + { + if (errno != 0) + { + error (0, errno, _("error reading %s"), quote (filename)); + ok = false; + break; + } + + /* reached EOF */ + if (n_read <= n_elide) + { + if (first) + { + /* The input is no larger than the number of bytes + to elide. So there's nothing to output, and + we're done. */ + } + else + { + delta = n_elide - n_read; + } + } + eof = true; + } + + /* Output any (but maybe just part of the) elided data from + the previous round. */ + if ( ! first) + { + /* Don't bother checking for errors here. + If there's a failure, the test of the following + fwrite or in close_stdout will catch it. */ + fwrite (b[!i] + READ_BUFSIZE, 1, n_elide - delta, stdout); + } + first = false; + + if (n_elide < n_read + && fwrite (b[i], 1, n_read - n_elide, stdout) < n_read - n_elide) + { + error (0, errno, _("write error")); + ok = false; + break; + } + } free (b[0]); return ok; @@ -310,7 +310,7 @@ elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0) else { /* Read blocks of size READ_BUFSIZE, until we've read at least n_elide - bytes. Then, for each new buffer we read, also write an old one. */ + bytes. Then, for each new buffer we read, also write an old one. */ bool ok = true; bool eof = false; @@ -326,74 +326,74 @@ elide_tail_bytes_pipe (const char *filename, int fd, uintmax_t n_elide_0) buffered_enough = false; for (i = 0, i_next = 1; !eof; i = i_next, i_next = (i_next + 1) % n_bufs) - { - if (b[i] == NULL) - b[i] = xmalloc (READ_BUFSIZE); - n_read = full_read (fd, b[i], READ_BUFSIZE); - if (n_read < READ_BUFSIZE) - { - if (errno != 0) - { - error (0, errno, _("error reading %s"), quote (filename)); - ok = false; - goto free_mem; - } - eof = true; - } - - if (i + 1 == n_bufs) - buffered_enough = true; - - if (buffered_enough) - { - if (fwrite (b[i_next], 1, n_read, stdout) < n_read) - { - error (0, errno, _("write error")); - ok = false; - goto free_mem; - } - } - } + { + if (b[i] == NULL) + b[i] = xmalloc (READ_BUFSIZE); + n_read = full_read (fd, b[i], READ_BUFSIZE); + if (n_read < READ_BUFSIZE) + { + if (errno != 0) + { + error (0, errno, _("error reading %s"), quote (filename)); + ok = false; + goto free_mem; + } + eof = true; + } + + if (i + 1 == n_bufs) + buffered_enough = true; + + if (buffered_enough) + { + if (fwrite (b[i_next], 1, n_read, stdout) < n_read) + { + error (0, errno, _("write error")); + ok = false; + goto free_mem; + } + } + } /* Output any remainder: rem bytes from b[i] + n_read. */ if (rem) - { - if (buffered_enough) - { - size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read; - if (rem < n_bytes_left_in_b_i) - { - fwrite (b[i] + n_read, 1, rem, stdout); - } - else - { - fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout); - fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout); - } - } - else if (i + 1 == n_bufs) - { - /* This happens when n_elide < file_size < n_elide_round. - - |READ_BUF.| - | | rem | - |---------!---------!---------!---------| - |---- n_elide ---------| - | | x | - | |y | - |---- file size -----------| - | |n_read| - |---- n_elide_round ----------| - */ - size_t y = READ_BUFSIZE - rem; - size_t x = n_read - y; - fwrite (b[i_next], 1, x, stdout); - } - } + { + if (buffered_enough) + { + size_t n_bytes_left_in_b_i = READ_BUFSIZE - n_read; + if (rem < n_bytes_left_in_b_i) + { + fwrite (b[i] + n_read, 1, rem, stdout); + } + else + { + fwrite (b[i] + n_read, 1, n_bytes_left_in_b_i, stdout); + fwrite (b[i_next], 1, rem - n_bytes_left_in_b_i, stdout); + } + } + else if (i + 1 == n_bufs) + { + /* This happens when n_elide < file_size < n_elide_round. + + |READ_BUF.| + | | rem | + |---------!---------!---------!---------| + |---- n_elide ---------| + | | x | + | |y | + |---- file size -----------| + | |n_read| + |---- n_elide_round ----------| + */ + size_t y = READ_BUFSIZE - rem; + size_t x = n_read - y; + fwrite (b[i_next], 1, x, stdout); + } + } free_mem:; for (i = 0; i < n_bufs; i++) - free (b[i]); + free (b[i]); free (b); return ok; @@ -424,31 +424,31 @@ elide_tail_bytes_file (const char *filename, int fd, uintmax_t n_elide) enum Copy_fd_status err; if ((current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) == -1 - || (end_pos = lseek (fd, (off_t) 0, SEEK_END)) == -1) - { - error (0, errno, _("cannot lseek %s"), quote (filename)); - return false; - } + || (end_pos = lseek (fd, (off_t) 0, SEEK_END)) == -1) + { + error (0, errno, _("cannot lseek %s"), quote (filename)); + return false; + } /* Be careful here. The current position may actually be - beyond the end of the file. */ + beyond the end of the file. */ bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff; if (bytes_remaining <= n_elide) - return true; + return true; /* Seek back to `current' position, then copy the required - number of bytes from fd. */ + number of bytes from fd. */ if (lseek (fd, (off_t) 0, current_pos) == -1) - { - error (0, errno, _("%s: cannot lseek back to original position"), - quote (filename)); - return false; - } + { + error (0, errno, _("%s: cannot lseek back to original position"), + quote (filename)); + return false; + } err = copy_fd (fd, stdout, bytes_remaining - n_elide); if (err == COPY_FD_OK) - return true; + return true; diagnose_copy_fd_failure (err, filename); return false; @@ -488,20 +488,20 @@ elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide) { n_read = safe_read (fd, tmp->buffer, BUFSIZ); if (n_read == 0 || n_read == SAFE_READ_ERROR) - break; + break; tmp->nbytes = n_read; tmp->nlines = 0; tmp->next = NULL; /* Count the number of newlines just read. */ { - char const *buffer_end = tmp->buffer + n_read; - char const *p = tmp->buffer; - while ((p = memchr (p, '\n', buffer_end - p))) - { - ++p; - ++tmp->nlines; - } + char const *buffer_end = tmp->buffer + n_read; + char const *p = tmp->buffer; + while ((p = memchr (p, '\n', buffer_end - p))) + { + ++p; + ++tmp->nlines; + } } total_lines += tmp->nlines; @@ -509,29 +509,29 @@ elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide) one to it. This is because when reading from a pipe, `n_read' can often be very small. */ if (tmp->nbytes + last->nbytes < BUFSIZ) - { - memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); - last->nbytes += tmp->nbytes; - last->nlines += tmp->nlines; - } + { + memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); + last->nbytes += tmp->nbytes; + last->nlines += tmp->nlines; + } else - { - /* If there's not enough room, link the new buffer onto the end of - the list, then either free up the oldest buffer for the next - read if that would leave enough lines, or else malloc a new one. - Some compaction mechanism is possible but probably not - worthwhile. */ - last = last->next = tmp; - if (n_elide < total_lines - first->nlines) - { - fwrite (first->buffer, 1, first->nbytes, stdout); - tmp = first; - total_lines -= first->nlines; - first = first->next; - } - else - tmp = xmalloc (sizeof (LBUFFER)); - } + { + /* If there's not enough room, link the new buffer onto the end of + the list, then either free up the oldest buffer for the next + read if that would leave enough lines, or else malloc a new one. + Some compaction mechanism is possible but probably not + worthwhile. */ + last = last->next = tmp; + if (n_elide < total_lines - first->nlines) + { + fwrite (first->buffer, 1, first->nbytes, stdout); + tmp = first; + total_lines -= first->nlines; + first = first->next; + } + else + tmp = xmalloc (sizeof (LBUFFER)); + } } free (tmp); @@ -564,11 +564,11 @@ elide_tail_lines_pipe (const char *filename, int fd, uintmax_t n_elide) char const *buffer_end = tmp->buffer + tmp->nbytes; char const *p = tmp->buffer; while (n && (p = memchr (p, '\n', buffer_end - p))) - { - ++p; - ++tmp->nlines; - --n; - } + { + ++p; + ++tmp->nlines; + --n; + } fwrite (tmp->buffer, 1, p - tmp->buffer, stdout); } @@ -595,8 +595,8 @@ free_lbuffers: in a less efficient implementation or a messy interface. */ static bool elide_tail_lines_seekable (const char *pretty_filename, int fd, - uintmax_t n_lines, - off_t start_pos, off_t end_pos) + uintmax_t n_lines, + off_t start_pos, off_t end_pos) { char buffer[BUFSIZ]; size_t bytes_read; @@ -614,7 +614,7 @@ elide_tail_lines_seekable (const char *pretty_filename, int fd, { char offset_buf[INT_BUFSIZE_BOUND (off_t)]; error (0, errno, _("%s: cannot seek to offset %s"), - pretty_filename, offtostr (pos, offset_buf)); + pretty_filename, offtostr (pos, offset_buf)); return false; } bytes_read = safe_read (fd, buffer, bytes_read); @@ -634,72 +634,72 @@ elide_tail_lines_seekable (const char *pretty_filename, int fd, size_t n = bytes_read; while (n) - { - char const *nl; - nl = memrchr (buffer, '\n', n); - if (nl == NULL) - break; - n = nl - buffer; - if (n_lines-- == 0) - { - /* Found it. */ - /* If necessary, restore the file pointer and copy - input to output up to position, POS. */ - if (start_pos < pos) - { - enum Copy_fd_status err; - if (lseek (fd, start_pos, SEEK_SET) < 0) - { - /* Failed to reposition file pointer. */ - error (0, errno, - "%s: unable to restore file pointer to initial offset", - quote (pretty_filename)); - return false; - } - - err = copy_fd (fd, stdout, pos - start_pos); - if (err != COPY_FD_OK) - { - diagnose_copy_fd_failure (err, pretty_filename); - return false; - } - } - - /* Output the initial portion of the buffer - in which we found the desired newline byte. - Don't bother testing for failure for such a small amount. - Any failure will be detected upon close. */ - fwrite (buffer, 1, n + 1, stdout); - return true; - } - } + { + char const *nl; + nl = memrchr (buffer, '\n', n); + if (nl == NULL) + break; + n = nl - buffer; + if (n_lines-- == 0) + { + /* Found it. */ + /* If necessary, restore the file pointer and copy + input to output up to position, POS. */ + if (start_pos < pos) + { + enum Copy_fd_status err; + if (lseek (fd, start_pos, SEEK_SET) < 0) + { + /* Failed to reposition file pointer. */ + error (0, errno, + "%s: unable to restore file pointer to initial offset", + quote (pretty_filename)); + return false; + } + + err = copy_fd (fd, stdout, pos - start_pos); + if (err != COPY_FD_OK) + { + diagnose_copy_fd_failure (err, pretty_filename); + return false; + } + } + + /* Output the initial portion of the buffer + in which we found the desired newline byte. + Don't bother testing for failure for such a small amount. + Any failure will be detected upon close. */ + fwrite (buffer, 1, n + 1, stdout); + return true; + } + } /* Not enough newlines in that bufferfull. */ if (pos == start_pos) - { - /* Not enough lines in the file. */ - return true; - } + { + /* Not enough lines in the file. */ + return true; + } pos -= BUFSIZ; if (lseek (fd, pos, SEEK_SET) < 0) - { - char offset_buf[INT_BUFSIZE_BOUND (off_t)]; - error (0, errno, _("%s: cannot seek to offset %s"), - pretty_filename, offtostr (pos, offset_buf)); - return false; - } + { + char offset_buf[INT_BUFSIZE_BOUND (off_t)]; + error (0, errno, _("%s: cannot seek to offset %s"), + pretty_filename, offtostr (pos, offset_buf)); + return false; + } bytes_read = safe_read (fd, buffer, BUFSIZ); if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, _("error reading %s"), quote (pretty_filename)); - return false; - } + { + error (0, errno, _("error reading %s"), quote (pretty_filename)); + return false; + } /* FIXME: is this dead code? - Consider the test, pos == start_pos, above. */ + Consider the test, pos == start_pos, above. */ if (bytes_read == 0) - return true; + return true; } } @@ -713,24 +713,24 @@ elide_tail_lines_file (const char *filename, int fd, uintmax_t n_elide) if (!presume_input_pipe) { /* Find the offset, OFF, of the Nth newline from the end, - but not counting the last byte of the file. - If found, write from current position to OFF, inclusive. - Otherwise, just return true. */ + but not counting the last byte of the file. + If found, write from current position to OFF, inclusive. + Otherwise, just return true. */ off_t start_pos = lseek (fd, (off_t) 0, SEEK_CUR); off_t end_pos = lseek (fd, (off_t) 0, SEEK_END); if (0 <= start_pos && start_pos < end_pos) - { - /* If the file is empty, we're done. */ - if (end_pos == 0) - return true; + { + /* If the file is empty, we're done. */ + if (end_pos == 0) + return true; - return elide_tail_lines_seekable (filename, fd, n_elide, - start_pos, end_pos); - } + return elide_tail_lines_seekable (filename, fd, n_elide, + start_pos, end_pos); + } /* lseek failed or the end offset precedes start. - Fall through. */ + Fall through. */ } return elide_tail_lines_pipe (filename, fd, n_elide); @@ -746,17 +746,17 @@ head_bytes (const char *filename, int fd, uintmax_t bytes_to_write) { size_t bytes_read; if (bytes_to_write < bytes_to_read) - bytes_to_read = bytes_to_write; + bytes_to_read = bytes_to_write; bytes_read = safe_read (fd, buffer, bytes_to_read); if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, _("error reading %s"), quote (filename)); - return false; - } + { + error (0, errno, _("error reading %s"), quote (filename)); + return false; + } if (bytes_read == 0) - break; + break; if (fwrite (buffer, 1, bytes_read, stdout) < bytes_read) - error (EXIT_FAILURE, errno, _("write error")); + error (EXIT_FAILURE, errno, _("write error")); bytes_to_write -= bytes_read; } return true; @@ -773,31 +773,31 @@ head_lines (const char *filename, int fd, uintmax_t lines_to_write) size_t bytes_to_write = 0; if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, _("error reading %s"), quote (filename)); - return false; - } + { + error (0, errno, _("error reading %s"), quote (filename)); + return false; + } if (bytes_read == 0) - break; + break; while (bytes_to_write < bytes_read) - if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0) - { - off_t n_bytes_past_EOL = bytes_read - bytes_to_write; - /* If we have read more data than that on the specified number - of lines, try to seek back to the position we would have - gotten to had we been reading one byte at a time. */ - if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0) - { - int e = errno; - struct stat st; - if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode)) - error (0, e, _("cannot reposition file pointer for %s"), - quote (filename)); - } - break; - } + if (buffer[bytes_to_write++] == '\n' && --lines_to_write == 0) + { + off_t n_bytes_past_EOL = bytes_read - bytes_to_write; + /* If we have read more data than that on the specified number + of lines, try to seek back to the position we would have + gotten to had we been reading one byte at a time. */ + if (lseek (fd, -n_bytes_past_EOL, SEEK_CUR) < 0) + { + int e = errno; + struct stat st; + if (fstat (fd, &st) != 0 || S_ISREG (st.st_mode)) + error (0, e, _("cannot reposition file pointer for %s"), + quote (filename)); + } + break; + } if (fwrite (buffer, 1, bytes_to_write, stdout) < bytes_to_write) - error (EXIT_FAILURE, errno, _("write error")); + error (EXIT_FAILURE, errno, _("write error")); } return true; } @@ -812,13 +812,13 @@ head (const char *filename, int fd, uintmax_t n_units, bool count_lines, if (elide_from_end) { if (count_lines) - { - return elide_tail_lines_file (filename, fd, n_units); - } + { + return elide_tail_lines_file (filename, fd, n_units); + } else - { - return elide_tail_bytes_file (filename, fd, n_units); - } + { + return elide_tail_bytes_file (filename, fd, n_units); + } } if (count_lines) return head_lines (filename, fd, n_units); @@ -828,7 +828,7 @@ head (const char *filename, int fd, uintmax_t n_units, bool count_lines, static bool head_file (const char *filename, uintmax_t n_units, bool count_lines, - bool elide_from_end) + bool elide_from_end) { int fd; bool ok; @@ -840,16 +840,16 @@ head_file (const char *filename, uintmax_t n_units, bool count_lines, fd = STDIN_FILENO; filename = _("standard input"); if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); } else { fd = open (filename, O_RDONLY | O_BINARY); if (fd < 0) - { - error (0, errno, _("cannot open %s for reading"), quote (filename)); - return false; - } + { + error (0, errno, _("cannot open %s for reading"), quote (filename)); + return false; + } } ok = head (filename, fd, n_units, count_lines, elide_from_end); @@ -878,16 +878,16 @@ string_to_integer (bool count_lines, const char *n_string) if (s_err == LONGINT_OVERFLOW) { error (EXIT_FAILURE, 0, - _("%s: %s is so large that it is not representable"), n_string, - count_lines ? _("number of lines") : _("number of bytes")); + _("%s: %s is so large that it is not representable"), n_string, + count_lines ? _("number of lines") : _("number of bytes")); } if (s_err != LONGINT_OK) { error (EXIT_FAILURE, 0, "%s: %s", n_string, - (count_lines - ? _("invalid number of lines") - : _("invalid number of bytes"))); + (count_lines + ? _("invalid number of lines") + : _("invalid number of bytes"))); } return n; @@ -937,7 +937,7 @@ main (int argc, char **argv) char multiplier_char = 0; /* Old option syntax; a dash, one or more digits, and one or - more option letters. Move past the number. */ + more option letters. Move past the number. */ do ++a; while (ISDIGIT (*a)); @@ -946,44 +946,44 @@ main (int argc, char **argv) /* Parse any appended option letters. */ for (; *a; a++) - { - switch (*a) - { - case 'c': - count_lines = false; - multiplier_char = 0; - break; - - case 'b': - case 'k': - case 'm': - count_lines = false; - multiplier_char = *a; - break; - - case 'l': - count_lines = true; - break; - - case 'q': - header_mode = never; - break; - - case 'v': - header_mode = always; - break; - - default: - error (0, 0, _("invalid trailing option -- %c"), *a); - usage (EXIT_FAILURE); - } - } + { + switch (*a) + { + case 'c': + count_lines = false; + multiplier_char = 0; + break; + + case 'b': + case 'k': + case 'm': + count_lines = false; + multiplier_char = *a; + break; + + case 'l': + count_lines = true; + break; + + case 'q': + header_mode = never; + break; + + case 'v': + header_mode = always; + break; + + default: + error (0, 0, _("invalid trailing option -- %c"), *a); + usage (EXIT_FAILURE); + } + } /* Append the multiplier character (if any) onto the end of - the digit string. Then add NUL byte if necessary. */ + the digit string. Then add NUL byte if necessary. */ *end_n_string = multiplier_char; if (multiplier_char) - *(++end_n_string) = 0; + *(++end_n_string) = 0; n_units = string_to_integer (count_lines, n_string); @@ -994,47 +994,47 @@ main (int argc, char **argv) } while ((c = getopt_long (argc, argv, "c:n:qv0123456789", long_options, NULL)) - != -1) + != -1) { switch (c) - { - case PRESUME_INPUT_PIPE_OPTION: - presume_input_pipe = true; - break; - - case 'c': - count_lines = false; - elide_from_end = (*optarg == '-'); - if (elide_from_end) - ++optarg; - n_units = string_to_integer (count_lines, optarg); - break; - - case 'n': - count_lines = true; - elide_from_end = (*optarg == '-'); - if (elide_from_end) - ++optarg; - n_units = string_to_integer (count_lines, optarg); - break; - - case 'q': - header_mode = never; - break; - - case 'v': - header_mode = always; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - if (ISDIGIT (c)) - error (0, 0, _("invalid trailing option -- %c"), c); - usage (EXIT_FAILURE); - } + { + case PRESUME_INPUT_PIPE_OPTION: + presume_input_pipe = true; + break; + + case 'c': + count_lines = false; + elide_from_end = (*optarg == '-'); + if (elide_from_end) + ++optarg; + n_units = string_to_integer (count_lines, optarg); + break; + + case 'n': + count_lines = true; + elide_from_end = (*optarg == '-'); + if (elide_from_end) + ++optarg; + n_units = string_to_integer (count_lines, optarg); + break; + + case 'q': + header_mode = never; + break; + + case 'v': + header_mode = always; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + if (ISDIGIT (c)) + error (0, 0, _("invalid trailing option -- %c"), c); + usage (EXIT_FAILURE); + } } if (header_mode == always @@ -1045,12 +1045,12 @@ main (int argc, char **argv) { char umax_buf[INT_BUFSIZE_BOUND (uintmax_t)]; error (EXIT_FAILURE, 0, _("%s: number of bytes is too large"), - umaxtostr (n_units, umax_buf)); + umaxtostr (n_units, umax_buf)); } file_list = (optind < argc - ? (char const *const *) &argv[optind] - : default_file_list); + ? (char const *const *) &argv[optind] + : default_file_list); if (O_BINARY && ! isatty (STDOUT_FILENO)) xfreopen (NULL, "wb", stdout); diff --git a/src/hostid.c b/src/hostid.c index 1da5a0c5c..7c93f2e76 100644 --- a/src/hostid.c +++ b/src/hostid.c @@ -38,7 +38,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -67,7 +67,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); diff --git a/src/hostname.c b/src/hostname.c index 6572b320d..110014b3f 100644 --- a/src/hostname.c +++ b/src/hostname.c @@ -51,7 +51,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -82,7 +82,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -92,10 +92,10 @@ main (int argc, char **argv) /* Set hostname to operand. */ char const *name = argv[optind]; if (sethostname (name, strlen (name)) != 0) - error (EXIT_FAILURE, errno, _("cannot set name to %s"), quote (name)); + error (EXIT_FAILURE, errno, _("cannot set name to %s"), quote (name)); #else error (EXIT_FAILURE, 0, - _("cannot set hostname; this system lacks the functionality")); + _("cannot set hostname; this system lacks the functionality")); #endif } @@ -103,7 +103,7 @@ main (int argc, char **argv) { hostname = xgethostname (); if (hostname == NULL) - error (EXIT_FAILURE, errno, _("cannot determine hostname")); + error (EXIT_FAILURE, errno, _("cannot determine hostname")); printf ("%s\n", hostname); } @@ -76,7 +76,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [USERNAME]\n"), program_name); @@ -129,39 +129,39 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "agnruGZ", longopts, NULL)) != -1) { switch (optc) - { - case 'a': - /* Ignore -a, for compatibility with SVR4. */ - break; + { + case 'a': + /* Ignore -a, for compatibility with SVR4. */ + break; case 'Z': - /* politely decline if we're not on a selinux-enabled kernel. */ - if (!selinux_enabled) - error (EXIT_FAILURE, 0, - _("--context (-Z) works only on an SELinux-enabled kernel")); + /* politely decline if we're not on a selinux-enabled kernel. */ + if (!selinux_enabled) + error (EXIT_FAILURE, 0, + _("--context (-Z) works only on an SELinux-enabled kernel")); just_context = 1; break; - case 'g': - just_group = true; - break; - case 'n': - use_name = true; - break; - case 'r': - use_real = true; - break; - case 'u': - just_user = true; - break; - case 'G': - just_group_list = true; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + case 'g': + just_group = true; + break; + case 'n': + use_name = true; + break; + case 'r': + use_real = true; + break; + case 'u': + just_user = true; + break; + case 'G': + just_group_list = true; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (1 < argc - optind) @@ -172,7 +172,7 @@ main (int argc, char **argv) if (argc - optind == 1 && just_context) error (EXIT_FAILURE, 0, - _("cannot print security context when user specified")); + _("cannot print security context when user specified")); /* If we are on a selinux-enabled kernel and no user is specified, get our context. Otherwise, leave the context variable alone - @@ -189,13 +189,13 @@ main (int argc, char **argv) if (just_user + just_group + just_group_list == 0 && (use_real | use_name)) error (EXIT_FAILURE, 0, - _("cannot print only names or real IDs in default format")); + _("cannot print only names or real IDs in default format")); if (argc - optind == 1) { struct passwd *pwd = getpwnam (argv[optind]); if (pwd == NULL) - error (EXIT_FAILURE, 0, _("%s: No such user"), argv[optind]); + error (EXIT_FAILURE, 0, _("%s: No such user"), argv[optind]); ruid = euid = pwd->pw_uid; rgid = egid = pwd->pw_gid; } @@ -214,12 +214,12 @@ main (int argc, char **argv) else if (just_group) { if (!print_group (use_real ? rgid : egid, use_name)) - ok = false; + ok = false; } else if (just_group_list) { if (!print_group_list (argv[optind], ruid, rgid, egid, use_name)) - ok = false; + ok = false; } else if (just_context) { @@ -245,11 +245,11 @@ print_user (uid_t uid) { pwd = getpwuid (uid); if (pwd == NULL) - { - error (0, 0, _("cannot find name for user ID %lu"), - (unsigned long int) uid); - ok = false; - } + { + error (0, 0, _("cannot find name for user ID %lu"), + (unsigned long int) uid); + ok = false; + } } if (pwd == NULL) @@ -281,7 +281,7 @@ print_full_info (const char *username) printf (_(" euid=%lu"), (unsigned long int) euid); pwd = getpwuid (euid); if (pwd) - printf ("(%s)", pwd->pw_name); + printf ("(%s)", pwd->pw_name); } if (egid != rgid) @@ -289,7 +289,7 @@ print_full_info (const char *username) printf (_(" egid=%lu"), (unsigned long int) egid); grp = getgrgid (egid); if (grp) - printf ("(%s)", grp->gr_name); + printf ("(%s)", grp->gr_name); } #if HAVE_GETGROUPS @@ -298,32 +298,32 @@ print_full_info (const char *username) int i; int n_groups = mgetgroups (username, (pwd ? pwd->pw_gid : (gid_t) -1), - &groups); + &groups); if (n_groups < 0) { - if (username) - { - error (0, errno, _("failed to get groups for user %s"), - quote (username)); - } - else - { - error (0, errno, _("failed to get groups for the current process")); - } - ok = false; - return; + if (username) + { + error (0, errno, _("failed to get groups for user %s"), + quote (username)); + } + else + { + error (0, errno, _("failed to get groups for the current process")); + } + ok = false; + return; } if (n_groups > 0) fputs (_(" groups="), stdout); for (i = 0; i < n_groups; i++) { - if (i > 0) - putchar (','); - printf ("%lu", (unsigned long int) groups[i]); - grp = getgrgid (groups[i]); - if (grp) - printf ("(%s)", grp->gr_name); + if (i > 0) + putchar (','); + printf ("%lu", (unsigned long int) groups[i]); + grp = getgrgid (groups[i]); + if (grp) + printf ("(%s)", grp->gr_name); } free (groups); } diff --git a/src/install.c b/src/install.c index 19efb1d1b..a4e0cab32 100644 --- a/src/install.c +++ b/src/install.c @@ -74,18 +74,18 @@ static bool use_default_selinux_context = true; static bool change_timestamps (struct stat const *from_sb, char const *to); static bool change_attributes (char const *name); static bool copy_file (const char *from, const char *to, - const struct cp_options *x); + const struct cp_options *x); static bool install_file_in_file_parents (char const *from, char *to, - struct cp_options *x); + struct cp_options *x); static bool install_file_in_dir (const char *from, const char *to_dir, - const struct cp_options *x); + const struct cp_options *x); static bool install_file_in_file (const char *from, const char *to, - const struct cp_options *x); + const struct cp_options *x); static void get_ids (void); static void strip (char const *name); static void announce_mkdir (char const *dir, void *options); static int make_ancestor (char const *dir, char const *component, - void *options); + void *options); void usage (int status); /* The user name that will own the files, or NULL to make the owner @@ -195,7 +195,7 @@ extra_mode (mode_t input) /* Return true if copy of file SRC_NAME to file DEST_NAME is necessary. */ static bool need_copy (const char *src_name, const char *dest_name, - const struct cp_options *x) + const struct cp_options *x) { struct stat src_sb, dest_sb; int src_fd, dest_fd; @@ -229,20 +229,20 @@ need_copy (const char *src_name, const char *dest_name, bool scontext_match; if (getfilecon (src_name, &file_scontext) == -1) - return true; + return true; if (getfilecon (dest_name, &to_scontext) == -1) - { - freecon (file_scontext); - return true; - } + { + freecon (file_scontext); + return true; + } scontext_match = STREQ (file_scontext, to_scontext); freecon (file_scontext); freecon (to_scontext); if (!scontext_match) - return true; + return true; } /* compare files content */ @@ -328,37 +328,37 @@ setdefaultfilecon (char const *file) if (first_call && IS_ABSOLUTE_FILE_NAME (file)) { /* Calling matchpathcon_init_prefix (NULL, "/first_component/") - is an optimization to minimize the expense of the following - matchpathcon call. Do it only once, just before the first - matchpathcon call. We *could* call matchpathcon_fini after - the final matchpathcon call, but that's not necessary, since - by then we're about to exit, and besides, the buffers it - would free are still reachable. */ + is an optimization to minimize the expense of the following + matchpathcon call. Do it only once, just before the first + matchpathcon call. We *could* call matchpathcon_fini after + the final matchpathcon call, but that's not necessary, since + by then we're about to exit, and besides, the buffers it + would free are still reachable. */ char const *p0; char const *p = file + 1; while (ISSLASH (*p)) - ++p; + ++p; /* Record final leading slash, for when FILE starts with two or more. */ p0 = p - 1; if (*p) - { - char *prefix; - do - { - ++p; - } - while (*p && !ISSLASH (*p)); - - prefix = malloc (p - p0 + 2); - if (prefix) - { - stpcpy (stpncpy (prefix, p0, p - p0), "/"); - matchpathcon_init_prefix (NULL, prefix); - free (prefix); - } - } + { + char *prefix; + do + { + ++p; + } + while (*p && !ISSLASH (*p)); + + prefix = malloc (p - p0 + 2); + if (prefix) + { + stpcpy (stpncpy (prefix, p0, p - p0), "/"); + matchpathcon_init_prefix (NULL, prefix); + free (prefix); + } + } } first_call = false; @@ -368,14 +368,14 @@ setdefaultfilecon (char const *file) STREQ (scontext, "<<none>>")) { if (scontext != NULL) - freecon (scontext); + freecon (scontext); return; } if (lsetfilecon (file, scontext) < 0 && errno != ENOTSUP) error (0, errno, - _("warning: %s: failed to change context to %s"), - quotearg_colon (file), scontext); + _("warning: %s: failed to change context to %s"), + quotearg_colon (file), scontext); freecon (scontext); return; @@ -414,11 +414,11 @@ static int process_dir (char *dir, struct savewd *wd, void *options) { return (make_dir_parents (dir, wd, - make_ancestor, options, - dir_mode, announce_mkdir, - dir_mode_bits, owner_id, group_id, false) - ? EXIT_SUCCESS - : EXIT_FAILURE); + make_ancestor, options, + dir_mode, announce_mkdir, + dir_mode_bits, owner_id, group_id, false) + ? EXIT_SUCCESS + : EXIT_FAILURE); } int @@ -462,131 +462,131 @@ main (int argc, char **argv) backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX"); while ((optc = getopt_long (argc, argv, "bcCsDdg:m:o:pt:TvS:Z:", long_options, - NULL)) != -1) + NULL)) != -1) { switch (optc) - { - case 'b': - make_backups = true; - if (optarg) - version_control_string = optarg; - break; - case 'c': - break; - case 'C': - copy_only_if_needed = true; - break; - case 's': - strip_files = true; + { + case 'b': + make_backups = true; + if (optarg) + version_control_string = optarg; + break; + case 'c': + break; + case 'C': + copy_only_if_needed = true; + break; + case 's': + strip_files = true; #ifdef SIGCHLD - /* System V fork+wait does not work if SIGCHLD is ignored. */ - signal (SIGCHLD, SIG_DFL); + /* System V fork+wait does not work if SIGCHLD is ignored. */ + signal (SIGCHLD, SIG_DFL); #endif - break; - case STRIP_PROGRAM_OPTION: - strip_program = xstrdup (optarg); - strip_program_specified = true; - break; - case 'd': - dir_arg = true; - break; - case 'D': - mkdir_and_install = true; - break; - case 'v': - x.verbose = true; - break; - case 'g': - group_name = optarg; - break; - case 'm': - specified_mode = optarg; - break; - case 'o': - owner_name = optarg; - break; - case 'p': - x.preserve_timestamps = true; - break; - case 'S': - make_backups = true; - backup_suffix_string = optarg; - break; - case 't': - if (target_directory) - error (EXIT_FAILURE, 0, - _("multiple target directories specified")); - else - { - struct stat st; - if (stat (optarg, &st) != 0) - error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); - if (! S_ISDIR (st.st_mode)) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (optarg)); - } - target_directory = optarg; - break; - case 'T': - no_target_directory = true; - break; - - case PRESERVE_CONTEXT_OPTION_DEPRECATED: - error (0, 0, _("WARNING: --preserve_context is deprecated; " - "use --preserve-context instead")); - /* fall through */ - case PRESERVE_CONTEXT_OPTION: - if ( ! selinux_enabled) - { - error (0, 0, _("WARNING: ignoring --preserve-context; " - "this kernel is not SELinux-enabled")); - break; - } - x.preserve_security_context = true; - use_default_selinux_context = false; - break; - case 'Z': - if ( ! selinux_enabled) - { - error (0, 0, _("WARNING: ignoring --context (-Z); " - "this kernel is not SELinux-enabled")); - break; - } - scontext = optarg; - use_default_selinux_context = false; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + break; + case STRIP_PROGRAM_OPTION: + strip_program = xstrdup (optarg); + strip_program_specified = true; + break; + case 'd': + dir_arg = true; + break; + case 'D': + mkdir_and_install = true; + break; + case 'v': + x.verbose = true; + break; + case 'g': + group_name = optarg; + break; + case 'm': + specified_mode = optarg; + break; + case 'o': + owner_name = optarg; + break; + case 'p': + x.preserve_timestamps = true; + break; + case 'S': + make_backups = true; + backup_suffix_string = optarg; + break; + case 't': + if (target_directory) + error (EXIT_FAILURE, 0, + _("multiple target directories specified")); + else + { + struct stat st; + if (stat (optarg, &st) != 0) + error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); + if (! S_ISDIR (st.st_mode)) + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (optarg)); + } + target_directory = optarg; + break; + case 'T': + no_target_directory = true; + break; + + case PRESERVE_CONTEXT_OPTION_DEPRECATED: + error (0, 0, _("WARNING: --preserve_context is deprecated; " + "use --preserve-context instead")); + /* fall through */ + case PRESERVE_CONTEXT_OPTION: + if ( ! selinux_enabled) + { + error (0, 0, _("WARNING: ignoring --preserve-context; " + "this kernel is not SELinux-enabled")); + break; + } + x.preserve_security_context = true; + use_default_selinux_context = false; + break; + case 'Z': + if ( ! selinux_enabled) + { + error (0, 0, _("WARNING: ignoring --context (-Z); " + "this kernel is not SELinux-enabled")); + break; + } + scontext = optarg; + use_default_selinux_context = false; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } /* Check for invalid combinations of arguments. */ if (dir_arg & strip_files) error (EXIT_FAILURE, 0, - _("the strip option may not be used when installing a directory")); + _("the strip option may not be used when installing a directory")); if (dir_arg && target_directory) error (EXIT_FAILURE, 0, - _("target directory not allowed when installing a directory")); + _("target directory not allowed when installing a directory")); if (x.preserve_security_context && scontext != NULL) error (EXIT_FAILURE, 0, - _("cannot force target context to %s and preserve it"), - quote (scontext)); + _("cannot force target context to %s and preserve it"), + quote (scontext)); if (backup_suffix_string) simple_backup_suffix = xstrdup (backup_suffix_string); x.backup_type = (make_backups - ? xget_version (_("backup type"), - version_control_string) - : no_backups); + ? xget_version (_("backup type"), + version_control_string) + : no_backups); if (scontext && setfscreatecon (scontext) < 0) error (EXIT_FAILURE, errno, - _("failed to set default file creation context to %s"), - quote (scontext)); + _("failed to set default file creation context to %s"), + quote (scontext)); n_files = argc - optind; file = argv + optind; @@ -594,39 +594,39 @@ main (int argc, char **argv) if (n_files <= ! (dir_arg || target_directory)) { if (n_files <= 0) - error (0, 0, _("missing file operand")); + error (0, 0, _("missing file operand")); else - error (0, 0, _("missing destination file operand after %s"), - quote (file[0])); + error (0, 0, _("missing destination file operand after %s"), + quote (file[0])); usage (EXIT_FAILURE); } if (no_target_directory) { if (target_directory) - error (EXIT_FAILURE, 0, - _("cannot combine --target-directory (-t) " - "and --no-target-directory (-T)")); + error (EXIT_FAILURE, 0, + _("cannot combine --target-directory (-t) " + "and --no-target-directory (-T)")); if (2 < n_files) - { - error (0, 0, _("extra operand %s"), quote (file[2])); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (file[2])); + usage (EXIT_FAILURE); + } } else if (! (dir_arg || target_directory)) { if (2 <= n_files && target_directory_operand (file[n_files - 1])) - target_directory = file[--n_files]; + target_directory = file[--n_files]; else if (2 < n_files) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (file[n_files - 1])); + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (file[n_files - 1])); } if (specified_mode) { struct mode_change *change = mode_compile (specified_mode); if (!change) - error (EXIT_FAILURE, 0, _("invalid mode %s"), quote (specified_mode)); + error (EXIT_FAILURE, 0, _("invalid mode %s"), quote (specified_mode)); mode = mode_adjust (0, false, 0, change, NULL); dir_mode = mode_adjust (0, true, 0, change, &dir_mode_bits); free (change); @@ -634,25 +634,25 @@ main (int argc, char **argv) if (strip_program_specified && !strip_files) error (0, 0, _("WARNING: ignoring --strip-program option as -s option was " - "not specified")); + "not specified")); if (copy_only_if_needed && x.preserve_timestamps) { error (0, 0, _("options --compare (-C) and --preserve-timestamps are " - "mutually exclusive")); + "mutually exclusive")); usage (EXIT_FAILURE); } if (copy_only_if_needed && strip_files) { error (0, 0, _("options --compare (-C) and --strip are mutually " - "exclusive")); + "exclusive")); usage (EXIT_FAILURE); } if (copy_only_if_needed && extra_mode (mode)) error (0, 0, _("the --compare (-C) option is ignored when you" - " specify a mode with non-permission bits")); + " specify a mode with non-permission bits")); get_ids (); @@ -661,24 +661,24 @@ main (int argc, char **argv) else { /* FIXME: it's a little gross that this initialization is - required by copy.c::copy. */ + required by copy.c::copy. */ hash_init (); if (!target_directory) { if (! (mkdir_and_install - ? install_file_in_file_parents (file[0], file[1], &x) - : install_file_in_file (file[0], file[1], &x))) - exit_status = EXIT_FAILURE; - } + ? install_file_in_file_parents (file[0], file[1], &x) + : install_file_in_file (file[0], file[1], &x))) + exit_status = EXIT_FAILURE; + } else - { - int i; - dest_info_init (&x); - for (i = 0; i < n_files; i++) - if (! install_file_in_dir (file[i], target_directory, &x)) - exit_status = EXIT_FAILURE; - } + { + int i; + dest_info_init (&x); + for (i = 0; i < n_files; i++) + if (! install_file_in_dir (file[i], target_directory, &x)) + exit_status = EXIT_FAILURE; + } } exit (exit_status); @@ -689,7 +689,7 @@ main (int argc, char **argv) static bool install_file_in_file_parents (char const *from, char *to, - struct cp_options *x) + struct cp_options *x) { bool save_working_directory = ! (IS_ABSOLUTE_FILE_NAME (from) && IS_ABSOLUTE_FILE_NAME (to)); @@ -712,12 +712,12 @@ install_file_in_file_parents (char const *from, char *to, int restore_errno = errno; savewd_finish (&wd); if (EXIT_SUCCESS < restore_result) - return false; + return false; if (restore_result < 0 && status == EXIT_SUCCESS) - { - error (0, restore_errno, _("cannot create directory %s"), to); - return false; - } + { + error (0, restore_errno, _("cannot create directory %s"), to); + return false; + } } return (status == EXIT_SUCCESS && install_file_in_file (from, to, x)); @@ -729,7 +729,7 @@ install_file_in_file_parents (char const *from, char *to, static bool install_file_in_file (const char *from, const char *to, - const struct cp_options *x) + const struct cp_options *x) { struct stat from_sb; if (x->preserve_timestamps && stat (from, &from_sb) != 0) @@ -753,7 +753,7 @@ install_file_in_file (const char *from, const char *to, static bool install_file_in_dir (const char *from, const char *to_dir, - const struct cp_options *x) + const struct cp_options *x) { const char *from_base = last_component (from); char *to = file_name_concat (to_dir, from_base, NULL); @@ -856,9 +856,9 @@ strip (char const *name) break; default: /* Parent. */ if (waitpid (pid, &status, 0) < 0) - error (EXIT_FAILURE, errno, _("waiting for strip")); + error (EXIT_FAILURE, errno, _("waiting for strip")); else if (! WIFEXITED (status) || WEXITSTATUS (status)) - error (EXIT_FAILURE, 0, _("strip process terminated abnormally")); + error (EXIT_FAILURE, 0, _("strip process terminated abnormally")); break; } } @@ -875,15 +875,15 @@ get_ids (void) { pw = getpwnam (owner_name); if (pw == NULL) - { - unsigned long int tmp; - if (xstrtoul (owner_name, NULL, 0, &tmp, NULL) != LONGINT_OK - || UID_T_MAX < tmp) - error (EXIT_FAILURE, 0, _("invalid user %s"), quote (owner_name)); - owner_id = tmp; - } + { + unsigned long int tmp; + if (xstrtoul (owner_name, NULL, 0, &tmp, NULL) != LONGINT_OK + || UID_T_MAX < tmp) + error (EXIT_FAILURE, 0, _("invalid user %s"), quote (owner_name)); + owner_id = tmp; + } else - owner_id = pw->pw_uid; + owner_id = pw->pw_uid; endpwent (); } else @@ -893,15 +893,15 @@ get_ids (void) { gr = getgrnam (group_name); if (gr == NULL) - { - unsigned long int tmp; - if (xstrtoul (group_name, NULL, 0, &tmp, NULL) != LONGINT_OK - || GID_T_MAX < tmp) - error (EXIT_FAILURE, 0, _("invalid group %s"), quote (group_name)); - group_id = tmp; - } + { + unsigned long int tmp; + if (xstrtoul (group_name, NULL, 0, &tmp, NULL) != LONGINT_OK + || GID_T_MAX < tmp) + error (EXIT_FAILURE, 0, _("invalid group %s"), quote (group_name)); + group_id = tmp; + } else - group_id = gr->gr_gid; + group_id = gr->gr_gid; endgrent (); } else @@ -934,7 +934,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -943,7 +943,7 @@ Usage: %s [OPTION]... [-T] SOURCE DEST\n\ or: %s [OPTION]... -t DIRECTORY SOURCE...\n\ or: %s [OPTION]... -d DIRECTORY...\n\ "), - program_name, program_name, program_name, program_name); + program_name, program_name, program_name, program_name); fputs (_("\ \n\ This install program copies files (often just compiled) into destination\n\ diff --git a/src/join.c b/src/join.c index 756a7be6e..73e1f37bb 100644 --- a/src/join.c +++ b/src/join.c @@ -161,13 +161,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... FILE1 FILE2\n\ "), - program_name); + program_name); fputs (_("\ For each pair of input lines with identical join fields, write a line to\n\ standard output. The default join field is the first, delimited\n\ @@ -242,26 +242,26 @@ xfields (struct line *line) { char *sep; for (; (sep = memchr (ptr, tab, lim - ptr)) != NULL; ptr = sep + 1) - extract_field (line, ptr, sep - ptr); + extract_field (line, ptr, sep - ptr); } else { /* Skip leading blanks before the first field. */ while (isblank (to_uchar (*ptr))) - if (++ptr == lim) - return; + if (++ptr == lim) + return; do - { - char *sep; - for (sep = ptr + 1; sep != lim && ! isblank (to_uchar (*sep)); sep++) - continue; - extract_field (line, ptr, sep - ptr); - if (sep == lim) - return; - for (ptr = sep + 1; ptr != lim && isblank (to_uchar (*ptr)); ptr++) - continue; - } + { + char *sep; + for (sep = ptr + 1; sep != lim && ! isblank (to_uchar (*sep)); sep++) + continue; + extract_field (line, ptr, sep - ptr); + if (sep == lim) + return; + for (ptr = sep + 1; ptr != lim && isblank (to_uchar (*ptr)); ptr++) + continue; + } while (ptr != lim); } @@ -283,7 +283,7 @@ freeline (struct line *line) static int keycmp (struct line const *line1, struct line const *line2, - size_t jf_1, size_t jf_2) + size_t jf_1, size_t jf_2) { /* Start of field to compare in each file. */ char *beg1; @@ -329,7 +329,7 @@ keycmp (struct line const *line1, struct line const *line2, else { if (hard_LC_COLLATE) - return xmemcoll (beg1, len1, beg2, len2); + return xmemcoll (beg1, len1, beg2, len2); diff = memcmp (beg1, beg2, MIN (len1, len2)); } @@ -351,26 +351,26 @@ keycmp (struct line const *line1, struct line const *line2, static void check_order (const struct line *prev, - const struct line *current, - int whatfile) + const struct line *current, + int whatfile) { if (check_input_order != CHECK_ORDER_DISABLED && ((check_input_order == CHECK_ORDER_ENABLED) || seen_unpairable)) { if (!issued_disorder_warning[whatfile-1]) - { - size_t join_field = whatfile == 1 ? join_field_1 : join_field_2; - if (keycmp (prev, current, join_field, join_field) > 0) - { - error ((check_input_order == CHECK_ORDER_ENABLED - ? EXIT_FAILURE : 0), - 0, _("file %d is not in sorted order"), whatfile); - - /* If we get to here, the message was just a warning, but we - want only to issue it once. */ - issued_disorder_warning[whatfile-1] = true; - } - } + { + size_t join_field = whatfile == 1 ? join_field_1 : join_field_2; + if (keycmp (prev, current, join_field, join_field) > 0) + { + error ((check_input_order == CHECK_ORDER_ENABLED + ? EXIT_FAILURE : 0), + 0, _("file %d is not in sorted order"), whatfile); + + /* If we get to here, the message was just a warning, but we + want only to issue it once. */ + issued_disorder_warning[whatfile-1] = true; + } + } } } @@ -411,7 +411,7 @@ get_line (FILE *fp, struct line **linep, int which) if (! readlinebuffer (&line->buf, fp)) { if (ferror (fp)) - error (EXIT_FAILURE, errno, _("read error")); + error (EXIT_FAILURE, errno, _("read error")); freeline (line); return false; } @@ -433,10 +433,10 @@ free_spareline (void) for (i = 0; i < ARRAY_CARDINALITY (spareline); i++) { if (spareline[i]) - { - freeline (spareline[i]); - free (spareline[i]); - } + { + freeline (spareline[i]); + free (spareline[i]); + } } } @@ -458,7 +458,7 @@ getseq (FILE *fp, struct seq *seq, int whichfile) size_t i; seq->lines = X2NREALLOC (seq->lines, &seq->alloc); for (i = seq->count; i < seq->alloc; i++) - seq->lines[i] = NULL; + seq->lines[i] = NULL; } if (get_line (fp, &seq->lines[seq->count], whichfile)) @@ -487,9 +487,9 @@ delseq (struct seq *seq) for (i = 0; i < seq->alloc; i++) if (seq->lines[i]) { - if (seq->lines[i]->buf.buffer) - freeline (seq->lines[i]); - free (seq->lines[i]); + if (seq->lines[i]->buf.buffer) + freeline (seq->lines[i]); + free (seq->lines[i]); } free (seq->lines); } @@ -507,9 +507,9 @@ prfield (size_t n, struct line const *line) { len = line->fields[n].len; if (len) - fwrite (line->fields[n].beg, 1, len, stdout); + fwrite (line->fields[n].beg, 1, len, stdout); else if (empty_filler) - fputs (empty_filler, stdout); + fputs (empty_filler, stdout); } else if (empty_filler) fputs (empty_filler, stdout); @@ -530,34 +530,34 @@ prjoin (struct line const *line1, struct line const *line2) o = outlist; while (1) - { - size_t field; - struct line const *line; - - if (o->file == 0) - { - if (line1 == &uni_blank) - { - line = line2; - field = join_field_2; - } - else - { - line = line1; - field = join_field_1; - } - } - else - { - line = (o->file == 1 ? line1 : line2); - field = o->field; - } - prfield (field, line); - o = o->next; - if (o == NULL) - break; - putchar (output_separator); - } + { + size_t field; + struct line const *line; + + if (o->file == 0) + { + if (line1 == &uni_blank) + { + line = line2; + field = join_field_2; + } + else + { + line = line1; + field = join_field_1; + } + } + else + { + line = (o->file == 1 ? line1 : line2); + field = o->field; + } + prfield (field, line); + o = o->next; + if (o == NULL) + break; + putchar (output_separator); + } putchar ('\n'); } else @@ -565,34 +565,34 @@ prjoin (struct line const *line1, struct line const *line2) size_t i; if (line1 == &uni_blank) - { - struct line const *t; - t = line1; - line1 = line2; - line2 = t; - } + { + struct line const *t; + t = line1; + line1 = line2; + line2 = t; + } prfield (join_field_1, line1); for (i = 0; i < join_field_1 && i < line1->nfields; ++i) - { - putchar (output_separator); - prfield (i, line1); - } + { + putchar (output_separator); + prfield (i, line1); + } for (i = join_field_1 + 1; i < line1->nfields; ++i) - { - putchar (output_separator); - prfield (i, line1); - } + { + putchar (output_separator); + prfield (i, line1); + } for (i = 0; i < join_field_2 && i < line2->nfields; ++i) - { - putchar (output_separator); - prfield (i, line2); - } + { + putchar (output_separator); + prfield (i, line2); + } for (i = join_field_2 + 1; i < line2->nfields; ++i) - { - putchar (output_separator); - prfield (i, line2); - } + { + putchar (output_separator); + prfield (i, line2); + } putchar ('\n'); } } @@ -619,75 +619,75 @@ join (FILE *fp1, FILE *fp2) { size_t i; diff = keycmp (seq1.lines[0], seq2.lines[0], - join_field_1, join_field_2); + join_field_1, join_field_2); if (diff < 0) - { - if (print_unpairables_1) - prjoin (seq1.lines[0], &uni_blank); - advance_seq (fp1, &seq1, true, 1); - seen_unpairable = true; - continue; - } + { + if (print_unpairables_1) + prjoin (seq1.lines[0], &uni_blank); + advance_seq (fp1, &seq1, true, 1); + seen_unpairable = true; + continue; + } if (diff > 0) - { - if (print_unpairables_2) - prjoin (&uni_blank, seq2.lines[0]); - advance_seq (fp2, &seq2, true, 2); - seen_unpairable = true; - continue; - } + { + if (print_unpairables_2) + prjoin (&uni_blank, seq2.lines[0]); + advance_seq (fp2, &seq2, true, 2); + seen_unpairable = true; + continue; + } /* Keep reading lines from file1 as long as they continue to match the current line from file2. */ eof1 = false; do - if (!advance_seq (fp1, &seq1, false, 1)) - { - eof1 = true; - ++seq1.count; - break; - } + if (!advance_seq (fp1, &seq1, false, 1)) + { + eof1 = true; + ++seq1.count; + break; + } while (!keycmp (seq1.lines[seq1.count - 1], seq2.lines[0], - join_field_1, join_field_2)); + join_field_1, join_field_2)); /* Keep reading lines from file2 as long as they continue to match the current line from file1. */ eof2 = false; do - if (!advance_seq (fp2, &seq2, false, 2)) - { - eof2 = true; - ++seq2.count; - break; - } + if (!advance_seq (fp2, &seq2, false, 2)) + { + eof2 = true; + ++seq2.count; + break; + } while (!keycmp (seq1.lines[0], seq2.lines[seq2.count - 1], - join_field_1, join_field_2)); + join_field_1, join_field_2)); if (print_pairables) - { - for (i = 0; i < seq1.count - 1; ++i) - { - size_t j; - for (j = 0; j < seq2.count - 1; ++j) - prjoin (seq1.lines[i], seq2.lines[j]); - } - } + { + for (i = 0; i < seq1.count - 1; ++i) + { + size_t j; + for (j = 0; j < seq2.count - 1; ++j) + prjoin (seq1.lines[i], seq2.lines[j]); + } + } if (!eof1) - { - SWAPLINES (seq1.lines[0], seq1.lines[seq1.count - 1]); - seq1.count = 1; - } + { + SWAPLINES (seq1.lines[0], seq1.lines[seq1.count - 1]); + seq1.count = 1; + } else - seq1.count = 0; + seq1.count = 0; if (!eof2) - { - SWAPLINES (seq2.lines[0], seq2.lines[seq2.count - 1]); - seq2.count = 1; - } + { + SWAPLINES (seq2.lines[0], seq2.lines[seq2.count - 1]); + seq2.count = 1; + } else - seq2.count = 0; + seq2.count = 0; } /* If the user did not specify --check-order, and the we read the @@ -703,29 +703,29 @@ join (FILE *fp1, FILE *fp2) if ((print_unpairables_1 || checktail) && seq1.count) { if (print_unpairables_1) - prjoin (seq1.lines[0], &uni_blank); + prjoin (seq1.lines[0], &uni_blank); seen_unpairable = true; while (get_line (fp1, linep, 1)) - { - if (print_unpairables_1) - prjoin (*linep, &uni_blank); - if (issued_disorder_warning[0] && !print_unpairables_1) - break; - } + { + if (print_unpairables_1) + prjoin (*linep, &uni_blank); + if (issued_disorder_warning[0] && !print_unpairables_1) + break; + } } if ((print_unpairables_2 || checktail) && seq2.count) { if (print_unpairables_2) - prjoin (&uni_blank, seq2.lines[0]); + prjoin (&uni_blank, seq2.lines[0]); seen_unpairable = true; while (get_line (fp2, linep, 2)) - { - if (print_unpairables_2) - prjoin (&uni_blank, *linep); - if (issued_disorder_warning[1] && !print_unpairables_2) - break; - } + { + if (print_unpairables_2) + prjoin (&uni_blank, *linep); + if (issued_disorder_warning[1] && !print_unpairables_2) + break; + } } free (*linep); @@ -792,9 +792,9 @@ decode_field_spec (const char *s, int *file_index, size_t *field_index) case '0': if (s[1]) { - /* `0' must be all alone -- no `.FIELD'. */ - error (EXIT_FAILURE, 0, _("invalid field specifier: %s"), quote (s)); - } + /* `0' must be all alone -- no `.FIELD'. */ + error (EXIT_FAILURE, 0, _("invalid field specifier: %s"), quote (s)); + } *file_index = 0; *field_index = 0; break; @@ -802,18 +802,18 @@ decode_field_spec (const char *s, int *file_index, size_t *field_index) case '1': case '2': if (s[1] != '.') - error (EXIT_FAILURE, 0, _("invalid field specifier: %s"), quote (s)); + error (EXIT_FAILURE, 0, _("invalid field specifier: %s"), quote (s)); *file_index = s[0] - '0'; *field_index = string_to_join_field (s + 2); break; default: error (EXIT_FAILURE, 0, - _("invalid file number in field spec: %s"), quote (s)); + _("invalid file number in field spec: %s"), quote (s)); /* Tell gcc -W -Wall that we can't get beyond this point. - This avoids a warning (otherwise legit) that the caller's copies - of *file_index and *field_index might be used uninitialized. */ + This avoids a warning (otherwise legit) that the caller's copies + of *file_index and *field_index might be used uninitialized. */ abort (); break; @@ -853,7 +853,7 @@ set_join_field (size_t *var, size_t val) unsigned long int var1 = *var + 1; unsigned long int val1 = val + 1; error (EXIT_FAILURE, 0, _("incompatible join fields %lu, %lu"), - var1, val1); + var1, val1); } *var = val; } @@ -881,8 +881,8 @@ enum operand_status static void add_file_name (char *name, char *names[2], - int operand_status[2], int joption_count[2], int *nfiles, - int *prev_optc_status, int *optc_status) + int operand_status[2], int joption_count[2], int *nfiles, + int *prev_optc_status, int *optc_status) { int n = *nfiles; @@ -891,30 +891,30 @@ add_file_name (char *name, char *names[2], bool op0 = (operand_status[0] == MUST_BE_OPERAND); char *arg = names[op0]; switch (operand_status[op0]) - { - case MUST_BE_OPERAND: - error (0, 0, _("extra operand %s"), quote (name)); - usage (EXIT_FAILURE); - - case MIGHT_BE_J1_ARG: - joption_count[0]--; - set_join_field (&join_field_1, string_to_join_field (arg)); - break; - - case MIGHT_BE_J2_ARG: - joption_count[1]--; - set_join_field (&join_field_2, string_to_join_field (arg)); - break; - - case MIGHT_BE_O_ARG: - add_field_list (arg); - break; - } + { + case MUST_BE_OPERAND: + error (0, 0, _("extra operand %s"), quote (name)); + usage (EXIT_FAILURE); + + case MIGHT_BE_J1_ARG: + joption_count[0]--; + set_join_field (&join_field_1, string_to_join_field (arg)); + break; + + case MIGHT_BE_J2_ARG: + joption_count[1]--; + set_join_field (&join_field_2, string_to_join_field (arg)); + break; + + case MIGHT_BE_O_ARG: + add_field_list (arg); + break; + } if (!op0) - { - operand_status[0] = operand_status[1]; - names[0] = names[1]; - } + { + operand_status[0] = operand_status[1]; + names[0] = names[1]; + } n = 1; } @@ -954,110 +954,110 @@ main (int argc, char **argv) check_input_order = CHECK_ORDER_DEFAULT; while ((optc = getopt_long (argc, argv, "-a:e:i1:2:j:o:t:v:", - longopts, NULL)) - != -1) + longopts, NULL)) + != -1) { optc_status = MUST_BE_OPERAND; switch (optc) - { - case 'v': - print_pairables = false; - /* Fall through. */ - - case 'a': - { - unsigned long int val; - if (xstrtoul (optarg, NULL, 10, &val, "") != LONGINT_OK - || (val != 1 && val != 2)) - error (EXIT_FAILURE, 0, - _("invalid field number: %s"), quote (optarg)); - if (val == 1) - print_unpairables_1 = true; - else - print_unpairables_2 = true; - } - break; - - case 'e': - if (empty_filler && ! STREQ (empty_filler, optarg)) - error (EXIT_FAILURE, 0, - _("conflicting empty-field replacement strings")); - empty_filler = optarg; - break; - - case 'i': - ignore_case = true; - break; - - case '1': - set_join_field (&join_field_1, string_to_join_field (optarg)); - break; - - case '2': - set_join_field (&join_field_2, string_to_join_field (optarg)); - break; - - case 'j': - if ((optarg[0] == '1' || optarg[0] == '2') && !optarg[1] - && optarg == argv[optind - 1] + 2) - { - /* The argument was either "-j1" or "-j2". */ - bool is_j2 = (optarg[0] == '2'); - joption_count[is_j2]++; - optc_status = MIGHT_BE_J1_ARG + is_j2; - } - else - { - set_join_field (&join_field_1, string_to_join_field (optarg)); - set_join_field (&join_field_2, join_field_1); - } - break; - - case 'o': - add_field_list (optarg); - optc_status = MIGHT_BE_O_ARG; - break; - - case 't': - { - unsigned char newtab = optarg[0]; - if (! newtab) - error (EXIT_FAILURE, 0, _("empty tab")); - if (optarg[1]) - { - if (STREQ (optarg, "\\0")) - newtab = '\0'; - else - error (EXIT_FAILURE, 0, _("multi-character tab %s"), - quote (optarg)); - } - if (0 <= tab && tab != newtab) - error (EXIT_FAILURE, 0, _("incompatible tabs")); - tab = newtab; - } - break; - - case NOCHECK_ORDER_OPTION: - check_input_order = CHECK_ORDER_DISABLED; - break; - - case CHECK_ORDER_OPTION: - check_input_order = CHECK_ORDER_ENABLED; - break; - - case 1: /* Non-option argument. */ - add_file_name (optarg, names, operand_status, joption_count, - &nfiles, &prev_optc_status, &optc_status); - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'v': + print_pairables = false; + /* Fall through. */ + + case 'a': + { + unsigned long int val; + if (xstrtoul (optarg, NULL, 10, &val, "") != LONGINT_OK + || (val != 1 && val != 2)) + error (EXIT_FAILURE, 0, + _("invalid field number: %s"), quote (optarg)); + if (val == 1) + print_unpairables_1 = true; + else + print_unpairables_2 = true; + } + break; + + case 'e': + if (empty_filler && ! STREQ (empty_filler, optarg)) + error (EXIT_FAILURE, 0, + _("conflicting empty-field replacement strings")); + empty_filler = optarg; + break; + + case 'i': + ignore_case = true; + break; + + case '1': + set_join_field (&join_field_1, string_to_join_field (optarg)); + break; + + case '2': + set_join_field (&join_field_2, string_to_join_field (optarg)); + break; + + case 'j': + if ((optarg[0] == '1' || optarg[0] == '2') && !optarg[1] + && optarg == argv[optind - 1] + 2) + { + /* The argument was either "-j1" or "-j2". */ + bool is_j2 = (optarg[0] == '2'); + joption_count[is_j2]++; + optc_status = MIGHT_BE_J1_ARG + is_j2; + } + else + { + set_join_field (&join_field_1, string_to_join_field (optarg)); + set_join_field (&join_field_2, join_field_1); + } + break; + + case 'o': + add_field_list (optarg); + optc_status = MIGHT_BE_O_ARG; + break; + + case 't': + { + unsigned char newtab = optarg[0]; + if (! newtab) + error (EXIT_FAILURE, 0, _("empty tab")); + if (optarg[1]) + { + if (STREQ (optarg, "\\0")) + newtab = '\0'; + else + error (EXIT_FAILURE, 0, _("multi-character tab %s"), + quote (optarg)); + } + if (0 <= tab && tab != newtab) + error (EXIT_FAILURE, 0, _("incompatible tabs")); + tab = newtab; + } + break; + + case NOCHECK_ORDER_OPTION: + check_input_order = CHECK_ORDER_DISABLED; + break; + + case CHECK_ORDER_OPTION: + check_input_order = CHECK_ORDER_ENABLED; + break; + + case 1: /* Non-option argument. */ + add_file_name (optarg, names, operand_status, joption_count, + &nfiles, &prev_optc_status, &optc_status); + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } prev_optc_status = optc_status; } @@ -1066,14 +1066,14 @@ main (int argc, char **argv) prev_optc_status = MUST_BE_OPERAND; while (optind < argc) add_file_name (argv[optind++], names, operand_status, joption_count, - &nfiles, &prev_optc_status, &optc_status); + &nfiles, &prev_optc_status, &optc_status); if (nfiles != 2) { if (nfiles == 0) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); usage (EXIT_FAILURE); } @@ -1082,8 +1082,8 @@ main (int argc, char **argv) for (i = 0; i < 2; i++) if (joption_count[i] != 0) { - set_join_field (&join_field_1, i); - set_join_field (&join_field_2, i); + set_join_field (&join_field_1, i); + set_join_field (&join_field_2, i); } if (join_field_1 == SIZE_MAX) diff --git a/src/kill.c b/src/kill.c index 29b6d81a3..3429cb19d 100644 --- a/src/kill.c +++ b/src/kill.c @@ -52,8 +52,8 @@ # endif # if HAVE_DECL_SYS_SIGLIST || defined sys_siglist # define strsignal(signum) (0 <= (signum) && (signum) <= SIGNUM_BOUND \ - ? sys_siglist[signum] \ - : 0) + ? sys_siglist[signum] \ + : 0) # endif # ifndef strsignal # define strsignal(signum) 0 @@ -81,7 +81,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -89,7 +89,7 @@ Usage: %s [-s SIGNAL | -SIGNAL] PID...\n\ or: %s -l [SIGNAL]...\n\ or: %s -t [SIGNAL]...\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Send signals to processes, or list signals.\n\ \n\ @@ -122,11 +122,11 @@ PID is an integer; if negative it identifies a process group.\n\ static void print_table_row (unsigned int num_width, int signum, - unsigned int name_width, char const *signame) + unsigned int name_width, char const *signame) { char const *description = strsignal (signum); printf ("%*d %-*s %s\n", num_width, signum, name_width, signame, - description ? description : "?"); + description ? description : "?"); } /* Print a list of signal names. If TABLE, print a table. @@ -147,51 +147,51 @@ list_signals (bool table, char *const *argv) /* Compute the maximum width of a signal number. */ unsigned int num_width = 1; for (signum = 1; signum <= SIGNUM_BOUND / 10; signum *= 10) - num_width++; + num_width++; /* Compute the maximum width of a signal name. */ for (signum = 1; signum <= SIGNUM_BOUND; signum++) - if (sig2str (signum, signame) == 0) - { - size_t len = strlen (signame); - if (name_width < len) - name_width = len; - } + if (sig2str (signum, signame) == 0) + { + size_t len = strlen (signame); + if (name_width < len) + name_width = len; + } if (argv) - for (; *argv; argv++) - { - signum = operand2sig (*argv, signame); - if (signum < 0) - status = EXIT_FAILURE; - else - print_table_row (num_width, signum, name_width, signame); - } + for (; *argv; argv++) + { + signum = operand2sig (*argv, signame); + if (signum < 0) + status = EXIT_FAILURE; + else + print_table_row (num_width, signum, name_width, signame); + } else - for (signum = 1; signum <= SIGNUM_BOUND; signum++) - if (sig2str (signum, signame) == 0) - print_table_row (num_width, signum, name_width, signame); + for (signum = 1; signum <= SIGNUM_BOUND; signum++) + if (sig2str (signum, signame) == 0) + print_table_row (num_width, signum, name_width, signame); } else { if (argv) - for (; *argv; argv++) - { - signum = operand2sig (*argv, signame); - if (signum < 0) - status = EXIT_FAILURE; - else - { - if (ISDIGIT (**argv)) - puts (signame); - else - printf ("%d\n", signum); - } - } + for (; *argv; argv++) + { + signum = operand2sig (*argv, signame); + if (signum < 0) + status = EXIT_FAILURE; + else + { + if (ISDIGIT (**argv)) + puts (signame); + else + printf ("%d\n", signum); + } + } else - for (signum = 1; signum <= SIGNUM_BOUND; signum++) - if (sig2str (signum, signame) == 0) - puts (signame); + for (signum = 1; signum <= SIGNUM_BOUND; signum++) + if (sig2str (signum, signame) == 0) + puts (signame); } return status; @@ -213,15 +213,15 @@ send_signals (int signum, char *const *argv) pid_t pid = n; if (errno == ERANGE || pid != n || arg == endp || *endp) - { - error (0, 0, _("%s: invalid process id"), arg); - status = EXIT_FAILURE; - } + { + error (0, 0, _("%s: invalid process id"), arg); + status = EXIT_FAILURE; + } else if (kill (pid, signum) != 0) - { - error (0, errno, "%s", arg); - status = EXIT_FAILURE; - } + { + error (0, errno, "%s", arg); + status = EXIT_FAILURE; + } } while ((arg = *++argv)); @@ -246,61 +246,61 @@ main (int argc, char **argv) atexit (close_stdout); while ((optc = getopt_long (argc, argv, short_options, long_options, NULL)) - != -1) + != -1) switch (optc) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': - if (optind != 2) - { - /* This option is actually a process-id. */ - optind--; - goto no_more_options; - } - /* Fall through. */ + if (optind != 2) + { + /* This option is actually a process-id. */ + optind--; + goto no_more_options; + } + /* Fall through. */ case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': - if (! optarg) - optarg = argv[optind - 1] + strlen (argv[optind - 1]); - if (optarg != argv[optind - 1] + 2) - { - error (0, 0, _("invalid option -- %c"), optc); - usage (EXIT_FAILURE); - } - optarg--; - /* Fall through. */ + if (! optarg) + optarg = argv[optind - 1] + strlen (argv[optind - 1]); + if (optarg != argv[optind - 1] + 2) + { + error (0, 0, _("invalid option -- %c"), optc); + usage (EXIT_FAILURE); + } + optarg--; + /* Fall through. */ case 'n': /* -n is not documented, but is for Bash compatibility. */ case 's': - if (0 <= signum) - { - error (0, 0, _("%s: multiple signals specified"), optarg); - usage (EXIT_FAILURE); - } - signum = operand2sig (optarg, signame); - if (signum < 0) - usage (EXIT_FAILURE); - break; + if (0 <= signum) + { + error (0, 0, _("%s: multiple signals specified"), optarg); + usage (EXIT_FAILURE); + } + signum = operand2sig (optarg, signame); + if (signum < 0) + usage (EXIT_FAILURE); + break; case 't': - table = true; - /* Fall through. */ + table = true; + /* Fall through. */ case 'l': - if (list) - { - error (0, 0, _("multiple -l or -t options specified")); - usage (EXIT_FAILURE); - } - list = true; - break; + if (list) + { + error (0, 0, _("multiple -l or -t options specified")); + usage (EXIT_FAILURE); + } + list = true; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } no_more_options:; @@ -319,6 +319,6 @@ main (int argc, char **argv) } return (list - ? list_signals (table, optind < argc ? argv + optind : NULL) - : send_signals (signum, argv + optind)); + ? list_signals (table, optind < argc ? argv + optind : NULL) + : send_signals (signum, argv + optind)); } diff --git a/src/link.c b/src/link.c index 4376245f8..ead3ac2f5 100644 --- a/src/link.c +++ b/src/link.c @@ -40,7 +40,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -48,7 +48,7 @@ Usage: %s FILE1 FILE2\n\ or: %s OPTION\n"), program_name, program_name); fputs (_("Call the link function to create a link named FILE2\ to an existing FILE1.\n\n"), - stdout); + stdout); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); emit_bug_reporting_address (); @@ -68,16 +68,16 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); if (argc < optind + 2) { if (argc < optind + 1) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[optind])); + error (0, 0, _("missing operand after %s"), quote (argv[optind])); usage (EXIT_FAILURE); } @@ -89,7 +89,7 @@ main (int argc, char **argv) if (link (argv[optind], argv[optind + 1]) != 0) error (EXIT_FAILURE, errno, _("cannot create link %s to %s"), - quote_n (0, argv[optind + 1]), quote_n (1, argv[optind])); + quote_n (0, argv[optind + 1]), quote_n (1, argv[optind])); exit (EXIT_SUCCESS); } @@ -154,39 +154,39 @@ do_link (const char *source, const char *dest) if (!symbolic_link) { if (STAT_LIKE_LINK (source, &source_stats) != 0) - { - error (0, errno, _("accessing %s"), quote (source)); - return false; - } + { + error (0, errno, _("accessing %s"), quote (source)); + return false; + } if (ENABLE_HARD_LINK_TO_SYMLINK_WARNING - && S_ISLNK (source_stats.st_mode)) - { - error (0, 0, _("%s: warning: making a hard link to a symbolic link\ + && S_ISLNK (source_stats.st_mode)) + { + error (0, 0, _("%s: warning: making a hard link to a symbolic link\ is not portable"), - quote (source)); - } + quote (source)); + } if (S_ISDIR (source_stats.st_mode)) - { - source_is_dir = true; - if (! hard_dir_link) - { - error (0, 0, _("%s: hard link not allowed for directory"), - quote (source)); - return false; - } - } + { + source_is_dir = true; + if (! hard_dir_link) + { + error (0, 0, _("%s: hard link not allowed for directory"), + quote (source)); + return false; + } + } } if (remove_existing_files || interactive || backup_type != no_backups) { dest_lstat_ok = (lstat (dest, &dest_stats) == 0); if (!dest_lstat_ok && errno != ENOENT) - { - error (0, errno, _("accessing %s"), quote (dest)); - return false; - } + { + error (0, errno, _("accessing %s"), quote (dest)); + return false; + } } /* If the current target was created as a hard link to another @@ -196,8 +196,8 @@ do_link (const char *source, const char *dest) && seen_file (dest_set, dest, &dest_stats)) { error (0, 0, - _("will not overwrite just-created %s with %s"), - quote_n (0, dest), quote_n (1, source)); + _("will not overwrite just-created %s with %s"), + quote_n (0, dest), quote_n (1, source)); return false; } @@ -208,65 +208,65 @@ do_link (const char *source, const char *dest) anything and fail right here. */ if ((remove_existing_files /* Ensure that "ln --backup f f" fails here, with the - "... same file" diagnostic, below. Otherwise, subsequent - code would give a misleading "file not found" diagnostic. - This case is different than the others handled here, since - the command in question doesn't use --force. */ + "... same file" diagnostic, below. Otherwise, subsequent + code would give a misleading "file not found" diagnostic. + This case is different than the others handled here, since + the command in question doesn't use --force. */ || (!symbolic_link && backup_type != no_backups)) && dest_lstat_ok /* Allow `ln -sf --backup k k' to succeed in creating the - self-referential symlink, but don't allow the hard-linking - equivalent: `ln -f k k' (with or without --backup) to get - beyond this point, because the error message you'd get is - misleading. */ + self-referential symlink, but don't allow the hard-linking + equivalent: `ln -f k k' (with or without --backup) to get + beyond this point, because the error message you'd get is + misleading. */ && (backup_type == no_backups || !symbolic_link) && (!symbolic_link || stat (source, &source_stats) == 0) && SAME_INODE (source_stats, dest_stats) /* The following detects whether removing DEST will also remove - SOURCE. If the file has only one link then both are surely - the same link. Otherwise check whether they point to the same - name in the same directory. */ + SOURCE. If the file has only one link then both are surely + the same link. Otherwise check whether they point to the same + name in the same directory. */ && (source_stats.st_nlink == 1 || same_name (source, dest))) { error (0, 0, _("%s and %s are the same file"), - quote_n (0, source), quote_n (1, dest)); + quote_n (0, source), quote_n (1, dest)); return false; } if (dest_lstat_ok) { if (S_ISDIR (dest_stats.st_mode)) - { - error (0, 0, _("%s: cannot overwrite directory"), quote (dest)); - return false; - } + { + error (0, 0, _("%s: cannot overwrite directory"), quote (dest)); + return false; + } if (interactive) - { - fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest)); - if (!yesno ()) - return true; - remove_existing_files = true; - } + { + fprintf (stderr, _("%s: replace %s? "), program_name, quote (dest)); + if (!yesno ()) + return true; + remove_existing_files = true; + } if (backup_type != no_backups) - { - dest_backup = find_backup_file_name (dest, backup_type); - if (rename (dest, dest_backup) != 0) - { - int rename_errno = errno; - free (dest_backup); - dest_backup = NULL; - if (rename_errno != ENOENT) - { - error (0, rename_errno, _("cannot backup %s"), quote (dest)); - return false; - } - } - } + { + dest_backup = find_backup_file_name (dest, backup_type); + if (rename (dest, dest_backup) != 0) + { + int rename_errno = errno; + free (dest_backup); + dest_backup = NULL; + if (rename_errno != ENOENT) + { + error (0, rename_errno, _("cannot backup %s"), quote (dest)); + return false; + } + } + } } ok = ((symbolic_link ? symlink (source, dest) : link (source, dest)) - == 0); + == 0); /* If the attempt to create a link failed and we are removing or backing up destinations, unlink the destination and try again. @@ -289,50 +289,50 @@ do_link (const char *source, const char *dest) if (!ok && errno == EEXIST && (remove_existing_files || dest_backup)) { if (unlink (dest) != 0) - { - error (0, errno, _("cannot remove %s"), quote (dest)); - free (dest_backup); - return false; - } + { + error (0, errno, _("cannot remove %s"), quote (dest)); + free (dest_backup); + return false; + } ok = ((symbolic_link ? symlink (source, dest) : link (source, dest)) - == 0); + == 0); } if (ok) { /* Right after creating a hard link, do this: (note dest name and - source_stats, which are also the just-linked-destinations stats) */ + source_stats, which are also the just-linked-destinations stats) */ record_file (dest_set, dest, &source_stats); if (verbose) - { - if (dest_backup) - printf ("%s ~ ", quote (dest_backup)); - printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='), - quote_n (1, source)); - } + { + if (dest_backup) + printf ("%s ~ ", quote (dest_backup)); + printf ("%s %c> %s\n", quote_n (0, dest), (symbolic_link ? '-' : '='), + quote_n (1, source)); + } } else { error (0, errno, - (symbolic_link - ? (errno != ENAMETOOLONG && *source - ? _("creating symbolic link %s") - : _("creating symbolic link %s -> %s")) - : (errno == EMLINK && !source_is_dir - ? _("creating hard link to %.0s%s") - : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC - || errno == EROFS) - ? _("creating hard link %s") - : _("creating hard link %s => %s"))), - quote_n (0, dest), quote_n (1, source)); + (symbolic_link + ? (errno != ENAMETOOLONG && *source + ? _("creating symbolic link %s") + : _("creating symbolic link %s -> %s")) + : (errno == EMLINK && !source_is_dir + ? _("creating hard link to %.0s%s") + : (errno == EDQUOT || errno == EEXIST || errno == ENOSPC + || errno == EROFS) + ? _("creating hard link %s") + : _("creating hard link %s => %s"))), + quote_n (0, dest), quote_n (1, source)); if (dest_backup) - { - if (rename (dest_backup, dest) != 0) - error (0, errno, _("cannot un-backup %s"), quote (dest)); - } + { + if (rename (dest_backup, dest) != 0) + error (0, errno, _("cannot un-backup %s"), quote (dest)); + } } free (dest_backup); @@ -344,7 +344,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -353,7 +353,7 @@ Usage: %s [OPTION]... [-T] TARGET LINK_NAME (1st form)\n\ or: %s [OPTION]... TARGET... DIRECTORY (3rd form)\n\ or: %s [OPTION]... -t DIRECTORY TARGET... (4th form)\n\ "), - program_name, program_name, program_name, program_name); + program_name, program_name, program_name, program_name); fputs (_("\ In the 1st form, create a link to TARGET with the name LINK_NAME.\n\ In the 2nd form, create a link to TARGET in the current directory.\n\ @@ -437,63 +437,63 @@ main (int argc, char **argv) = hard_dir_link = false; while ((c = getopt_long (argc, argv, "bdfinst:vFS:T", long_options, NULL)) - != -1) + != -1) { switch (c) - { - case 'b': - make_backups = true; - if (optarg) - version_control_string = optarg; - break; - case 'd': - case 'F': - hard_dir_link = true; - break; - case 'f': - remove_existing_files = true; - interactive = false; - break; - case 'i': - remove_existing_files = false; - interactive = true; - break; - case 'n': - dereference_dest_dir_symlinks = false; - break; - case 's': - symbolic_link = true; - break; - case 't': - if (target_directory) - error (EXIT_FAILURE, 0, _("multiple target directories specified")); - else - { - struct stat st; - if (stat (optarg, &st) != 0) - error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); - if (! S_ISDIR (st.st_mode)) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (optarg)); - } - target_directory = optarg; - break; - case 'T': - no_target_directory = true; - break; - case 'v': - verbose = true; - break; - case 'S': - make_backups = true; - backup_suffix_string = optarg; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - break; - } + { + case 'b': + make_backups = true; + if (optarg) + version_control_string = optarg; + break; + case 'd': + case 'F': + hard_dir_link = true; + break; + case 'f': + remove_existing_files = true; + interactive = false; + break; + case 'i': + remove_existing_files = false; + interactive = true; + break; + case 'n': + dereference_dest_dir_symlinks = false; + break; + case 's': + symbolic_link = true; + break; + case 't': + if (target_directory) + error (EXIT_FAILURE, 0, _("multiple target directories specified")); + else + { + struct stat st; + if (stat (optarg, &st) != 0) + error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); + if (! S_ISDIR (st.st_mode)) + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (optarg)); + } + target_directory = optarg; + break; + case 'T': + no_target_directory = true; + break; + case 'v': + verbose = true; + break; + case 'S': + make_backups = true; + backup_suffix_string = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + break; + } } n_files = argc - optind; @@ -508,75 +508,75 @@ main (int argc, char **argv) if (no_target_directory) { if (target_directory) - error (EXIT_FAILURE, 0, - _("cannot combine --target-directory " - "and --no-target-directory")); + error (EXIT_FAILURE, 0, + _("cannot combine --target-directory " + "and --no-target-directory")); if (n_files != 2) - { - if (n_files < 2) - error (0, 0, - _("missing destination file operand after %s"), - quote (file[0])); - else - error (0, 0, _("extra operand %s"), quote (file[2])); - usage (EXIT_FAILURE); - } + { + if (n_files < 2) + error (0, 0, + _("missing destination file operand after %s"), + quote (file[0])); + else + error (0, 0, _("extra operand %s"), quote (file[2])); + usage (EXIT_FAILURE); + } } else if (!target_directory) { if (n_files < 2) - target_directory = "."; + target_directory = "."; else if (2 <= n_files && target_directory_operand (file[n_files - 1])) - target_directory = file[--n_files]; + target_directory = file[--n_files]; else if (2 < n_files) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (file[n_files - 1])); + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (file[n_files - 1])); } if (backup_suffix_string) simple_backup_suffix = xstrdup (backup_suffix_string); backup_type = (make_backups - ? xget_version (_("backup type"), version_control_string) - : no_backups); + ? xget_version (_("backup type"), version_control_string) + : no_backups); if (target_directory) { int i; /* Create the data structure we'll use to record which hard links we - create. Used to ensure that ln detects an obscure corner case that - might result in user data loss. Create it only if needed. */ + create. Used to ensure that ln detects an obscure corner case that + might result in user data loss. Create it only if needed. */ if (2 <= n_files - && remove_existing_files - /* Don't bother trying to protect symlinks, since ln clobbering - a just-created symlink won't ever lead to real data loss. */ - && ! symbolic_link - /* No destination hard link can be clobbered when making - numbered backups. */ - && backup_type != numbered_backups) - - { - dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY, - NULL, - triple_hash, - triple_compare, - triple_free); - if (dest_set == NULL) - xalloc_die (); - } + && remove_existing_files + /* Don't bother trying to protect symlinks, since ln clobbering + a just-created symlink won't ever lead to real data loss. */ + && ! symbolic_link + /* No destination hard link can be clobbered when making + numbered backups. */ + && backup_type != numbered_backups) + + { + dest_set = hash_initialize (DEST_INFO_INITIAL_CAPACITY, + NULL, + triple_hash, + triple_compare, + triple_free); + if (dest_set == NULL) + xalloc_die (); + } ok = true; for (i = 0; i < n_files; ++i) - { - char *dest_base; - char *dest = file_name_concat (target_directory, - last_component (file[i]), - &dest_base); - strip_trailing_slashes (dest_base); - ok &= do_link (file[i], dest); - free (dest); - } + { + char *dest_base; + char *dest = file_name_concat (target_directory, + last_component (file[i]), + &dest_base); + strip_trailing_slashes (dest_base); + ok &= do_link (file[i], dest); + free (dest); + } } else ok = do_link (file[0], file[1]); diff --git a/src/logname.c b/src/logname.c index 25350af43..8abb535f0 100644 --- a/src/logname.c +++ b/src/logname.c @@ -34,7 +34,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]\n"), program_name); @@ -63,7 +63,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -112,8 +112,8 @@ #include "mbsalign.h" #define PROGRAM_NAME (ls_mode == LS_LS ? "ls" \ - : (ls_mode == LS_MULTI_COL \ - ? "dir" : "vdir")) + : (ls_mode == LS_MULTI_COL \ + ? "dir" : "vdir")) #define AUTHORS \ proper_name ("Richard M. Stallman"), \ @@ -212,49 +212,49 @@ struct bin_str #endif static size_t quote_name (FILE *out, const char *name, - struct quoting_options const *options, - size_t *width); + struct quoting_options const *options, + size_t *width); static char *make_link_name (char const *name, char const *linkname); static int decode_switches (int argc, char **argv); static bool file_ignored (char const *name); static uintmax_t gobble_file (char const *name, enum filetype type, - ino_t inode, bool command_line_arg, - char const *dirname); + ino_t inode, bool command_line_arg, + char const *dirname); static bool print_color_indicator (const char *name, mode_t mode, int linkok, - bool stat_ok, enum filetype type, - nlink_t nlink); + bool stat_ok, enum filetype type, + nlink_t nlink); static void put_indicator (const struct bin_str *ind); static void add_ignore_pattern (const char *pattern); static void attach (char *dest, const char *dirname, const char *name); static void clear_files (void); static void extract_dirs_from_files (char const *dirname, - bool command_line_arg); + bool command_line_arg); static void get_link_name (char const *filename, struct fileinfo *f, - bool command_line_arg); + bool command_line_arg); static void indent (size_t from, size_t to); static size_t calculate_columns (bool by_columns); static void print_current_files (void); static void print_dir (char const *name, char const *realname, - bool command_line_arg); + bool command_line_arg); static size_t print_file_name_and_frills (const struct fileinfo *f, - size_t start_col); + size_t start_col); static void print_horizontal (void); static int format_user_width (uid_t u); static int format_group_width (gid_t g); static void print_long_format (const struct fileinfo *f); static void print_many_per_line (void); static size_t print_name_with_quoting (const char *p, mode_t mode, - int linkok, bool stat_ok, - enum filetype type, - struct obstack *stack, - nlink_t nlink, - size_t start_col); + int linkok, bool stat_ok, + enum filetype type, + struct obstack *stack, + nlink_t nlink, + size_t start_col); static void prep_non_filename_text (void); static bool print_type_indicator (bool stat_ok, mode_t mode, - enum filetype type); + enum filetype type); static void print_with_commas (void); static void queue_directory (char const *name, char const *realname, - bool command_line_arg); + bool command_line_arg); static void sort_files (void); static void parse_ls_color (void); void usage (int status); @@ -907,8 +907,8 @@ static size_t dired_pos; #define DIRED_INDENT() \ do \ { \ - if (dired) \ - DIRED_FPUTS_LITERAL (" ", stdout); \ + if (dired) \ + DIRED_FPUTS_LITERAL (" ", stdout); \ } \ while (0) @@ -927,7 +927,7 @@ static struct obstack subdired_obstack; do \ { \ if (dired) \ - obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \ + obstack_grow (obs, &dired_pos, sizeof (dired_pos)); \ } \ while (0) @@ -988,7 +988,7 @@ dired_dump_obstack (const char *prefix, struct obstack *os) pos = (size_t *) obstack_finish (os); fputs (prefix, stdout); for (i = 0; i < n_pos; i++) - printf (" %lu", (unsigned long int) pos[i]); + printf (" %lu", (unsigned long int) pos[i]); putchar ('\n'); } } @@ -1021,21 +1021,21 @@ abmon_init (void) curr_max_width = required_mon_width; required_mon_width = 0; for (int i = 0; i < 12; i++) - { - size_t width = curr_max_width; + { + size_t width = curr_max_width; - size_t req = mbsalign (nl_langinfo (ABMON_1 + i), - abmon[i], sizeof (abmon[i]), - &width, MBS_ALIGN_LEFT, 0); + size_t req = mbsalign (nl_langinfo (ABMON_1 + i), + abmon[i], sizeof (abmon[i]), + &width, MBS_ALIGN_LEFT, 0); - if (req == (size_t) -1 || req >= sizeof (abmon[i])) - { - required_mon_width = 0; /* ignore precomputed strings. */ - return required_mon_width; - } + if (req == (size_t) -1 || req >= sizeof (abmon[i])) + { + required_mon_width = 0; /* ignore precomputed strings. */ + return required_mon_width; + } - required_mon_width = MAX (required_mon_width, width); - } + required_mon_width = MAX (required_mon_width, width); + } } while (curr_max_width > required_mon_width); #endif @@ -1113,8 +1113,8 @@ is_colored (enum indicator_no type) size_t len = color_indicator[type].len; char const *s = color_indicator[type].string; return ! (len == 0 - || (len == 1 && strncmp (s, "0", 1) == 0) - || (len == 2 && strncmp (s, "00", 2) == 0)); + || (len == 1 && strncmp (s, "0", 1) == 0) + || (len == 2 && strncmp (s, "00", 2) == 0)); } static void @@ -1162,33 +1162,33 @@ process_signals (void) sigset_t oldset; if (used_color) - restore_default_color (); + restore_default_color (); fflush (stdout); sigprocmask (SIG_BLOCK, &caught_signals, &oldset); /* Reload interrupt_signal and stop_signal_count, in case a new - signal was handled before sigprocmask took effect. */ + signal was handled before sigprocmask took effect. */ sig = interrupt_signal; stops = stop_signal_count; /* SIGTSTP is special, since the application can receive that signal - more than once. In this case, don't set the signal handler to the - default. Instead, just raise the uncatchable SIGSTOP. */ + more than once. In this case, don't set the signal handler to the + default. Instead, just raise the uncatchable SIGSTOP. */ if (stops) - { - stop_signal_count = stops - 1; - sig = SIGSTOP; - } + { + stop_signal_count = stops - 1; + sig = SIGSTOP; + } else - signal (sig, SIG_DFL); + signal (sig, SIG_DFL); /* Exit or suspend the program. */ raise (sig); sigprocmask (SIG_SETMASK, &oldset, NULL); /* If execution reaches here, then the program has been - continued (after being suspended). */ + continued (after being suspended). */ } } @@ -1259,68 +1259,68 @@ main (int argc, char **argv) { /* Avoid following symbolic links when possible. */ if (is_colored (C_ORPHAN) - || (is_colored (C_EXEC) && color_symlink_as_referent) - || (is_colored (C_MISSING) && format == long_format)) - check_symlink_color = true; + || (is_colored (C_EXEC) && color_symlink_as_referent) + || (is_colored (C_MISSING) && format == long_format)) + check_symlink_color = true; /* If the standard output is a controlling terminal, watch out for signals, so that the colors can be restored to the default state if "ls" is suspended or interrupted. */ if (0 <= tcgetpgrp (STDOUT_FILENO)) - { - int j; + { + int j; #if SA_NOCLDSTOP - struct sigaction act; - - sigemptyset (&caught_signals); - for (j = 0; j < nsigs; j++) - { - sigaction (sig[j], NULL, &act); - if (act.sa_handler != SIG_IGN) - sigaddset (&caught_signals, sig[j]); - } - - act.sa_mask = caught_signals; - act.sa_flags = SA_RESTART; - - for (j = 0; j < nsigs; j++) - if (sigismember (&caught_signals, sig[j])) - { - act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler; - sigaction (sig[j], &act, NULL); - } + struct sigaction act; + + sigemptyset (&caught_signals); + for (j = 0; j < nsigs; j++) + { + sigaction (sig[j], NULL, &act); + if (act.sa_handler != SIG_IGN) + sigaddset (&caught_signals, sig[j]); + } + + act.sa_mask = caught_signals; + act.sa_flags = SA_RESTART; + + for (j = 0; j < nsigs; j++) + if (sigismember (&caught_signals, sig[j])) + { + act.sa_handler = sig[j] == SIGTSTP ? stophandler : sighandler; + sigaction (sig[j], &act, NULL); + } #else - for (j = 0; j < nsigs; j++) - { - caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN); - if (caught_sig[j]) - { - signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler); - siginterrupt (sig[j], 0); - } - } + for (j = 0; j < nsigs; j++) + { + caught_sig[j] = (signal (sig[j], SIG_IGN) != SIG_IGN); + if (caught_sig[j]) + { + signal (sig[j], sig[j] == SIGTSTP ? stophandler : sighandler); + siginterrupt (sig[j], 0); + } + } #endif - } + } } if (dereference == DEREF_UNDEFINED) dereference = ((immediate_dirs - || indicator_style == classify - || format == long_format) - ? DEREF_NEVER - : DEREF_COMMAND_LINE_SYMLINK_TO_DIR); + || indicator_style == classify + || format == long_format) + ? DEREF_NEVER + : DEREF_COMMAND_LINE_SYMLINK_TO_DIR); /* When using -R, initialize a data structure we'll use to detect any directory cycles. */ if (recursive) { active_dir_set = hash_initialize (INITIAL_TABLE_SIZE, NULL, - dev_ino_hash, - dev_ino_compare, - dev_ino_free); + dev_ino_hash, + dev_ino_compare, + dev_ino_free); if (active_dir_set == NULL) - xalloc_die (); + xalloc_die (); obstack_init (&dev_ino_obstack); } @@ -1330,10 +1330,10 @@ main (int argc, char **argv) || print_scontext || print_block_size; format_needs_type = (! format_needs_stat - && (recursive - || print_with_color - || indicator_style != none - || directories_first)); + && (recursive + || print_with_color + || indicator_style != none + || directories_first)); if (dired) { @@ -1352,9 +1352,9 @@ main (int argc, char **argv) if (n_files <= 0) { if (immediate_dirs) - gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, ""); + gobble_file (".", directory, NOT_AN_INODE_NUMBER, true, ""); else - queue_directory (".", NULL, true); + queue_directory (".", NULL, true); } else do @@ -1365,7 +1365,7 @@ main (int argc, char **argv) { sort_files (); if (!immediate_dirs) - extract_dirs_from_files (NULL, true); + extract_dirs_from_files (NULL, true); /* `cwd_n_used' might be zero now. */ } @@ -1377,7 +1377,7 @@ main (int argc, char **argv) { print_current_files (); if (pending_dirs) - DIRED_PUTCHAR ('\n'); + DIRED_PUTCHAR ('\n'); } else if (n_files <= 1 && pending_dirs && pending_dirs->next == 0) print_dir_name = false; @@ -1388,25 +1388,25 @@ main (int argc, char **argv) pending_dirs = pending_dirs->next; if (LOOP_DETECT) - { - if (thispend->name == NULL) - { - /* thispend->name == NULL means this is a marker entry - indicating we've finished processing the directory. - Use its dev/ino numbers to remove the corresponding - entry from the active_dir_set hash table. */ - struct dev_ino di = dev_ino_pop (); - struct dev_ino *found = hash_delete (active_dir_set, &di); - /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */ - assert (found); - dev_ino_free (found); - free_pending_ent (thispend); - continue; - } - } + { + if (thispend->name == NULL) + { + /* thispend->name == NULL means this is a marker entry + indicating we've finished processing the directory. + Use its dev/ino numbers to remove the corresponding + entry from the active_dir_set hash table. */ + struct dev_ino di = dev_ino_pop (); + struct dev_ino *found = hash_delete (active_dir_set, &di); + /* ASSERT_MATCHING_DEV_INO (thispend->realname, di); */ + assert (found); + dev_ino_free (found); + free_pending_ent (thispend); + continue; + } + } print_dir (thispend->name, thispend->realname, - thispend->command_line_arg); + thispend->command_line_arg); free_pending_ent (thispend); print_dir_name = true; @@ -1417,29 +1417,29 @@ main (int argc, char **argv) int j; if (used_color) - restore_default_color (); + restore_default_color (); fflush (stdout); /* Restore the default signal handling. */ #if SA_NOCLDSTOP for (j = 0; j < nsigs; j++) - if (sigismember (&caught_signals, sig[j])) - signal (sig[j], SIG_DFL); + if (sigismember (&caught_signals, sig[j])) + signal (sig[j], SIG_DFL); #else for (j = 0; j < nsigs; j++) - if (caught_sig[j]) - signal (sig[j], SIG_DFL); + if (caught_sig[j]) + signal (sig[j], SIG_DFL); #endif /* Act on any signals that arrived before the default was restored. - This can process signals out of order, but there doesn't seem to - be an easy way to do them in order, and the order isn't that - important anyway. */ + This can process signals out of order, but there doesn't seem to + be an easy way to do them in order, and the order isn't that + important anyway. */ for (j = stop_signal_count; j; j--) - raise (SIGSTOP); + raise (SIGSTOP); j = interrupt_signal; if (j) - raise (j); + raise (j); } if (dired) @@ -1448,7 +1448,7 @@ main (int argc, char **argv) dired_dump_obstack ("//DIRED//", &dired_obstack); dired_dump_obstack ("//SUBDIRED//", &subdired_obstack); printf ("//DIRED-OPTIONS// --quoting-style=%s\n", - quoting_style_args[get_quoting_style (filename_quoting_options)]); + quoting_style_args[get_quoting_style (filename_quoting_options)]); } if (LOOP_DETECT) @@ -1492,16 +1492,16 @@ decode_switches (int argc, char **argv) case LS_LS: /* This is for the `ls' program. */ if (isatty (STDOUT_FILENO)) - { - format = many_per_line; - /* See description of qmark_funny_chars, above. */ - qmark_funny_chars = true; - } + { + format = many_per_line; + /* See description of qmark_funny_chars, above. */ + qmark_funny_chars = true; + } else - { - format = one_per_line; - qmark_funny_chars = false; - } + { + format = one_per_line; + qmark_funny_chars = false; + } break; default: @@ -1528,20 +1528,20 @@ decode_switches (int argc, char **argv) char const *q_style = getenv ("QUOTING_STYLE"); if (q_style) { - int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals); - if (0 <= i) - set_quoting_style (NULL, quoting_style_vals[i]); - else - error (0, 0, - _("ignoring invalid value of environment variable QUOTING_STYLE: %s"), - quotearg (q_style)); + int i = ARGMATCH (q_style, quoting_style_args, quoting_style_vals); + if (0 <= i) + set_quoting_style (NULL, quoting_style_vals[i]); + else + error (0, 0, + _("ignoring invalid value of environment variable QUOTING_STYLE: %s"), + quotearg (q_style)); } } { char const *ls_block_size = getenv ("LS_BLOCK_SIZE"); human_options (ls_block_size, - &human_output_opts, &output_block_size); + &human_output_opts, &output_block_size); if (ls_block_size || getenv ("BLOCK_SIZE")) file_output_block_size = output_block_size; } @@ -1551,18 +1551,18 @@ decode_switches (int argc, char **argv) char const *p = getenv ("COLUMNS"); if (p && *p) { - unsigned long int tmp_ulong; - if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK - && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX) - { - line_length = tmp_ulong; - } - else - { - error (0, 0, - _("ignoring invalid width in environment variable COLUMNS: %s"), - quotearg (p)); - } + unsigned long int tmp_ulong; + if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK + && 0 < tmp_ulong && tmp_ulong <= SIZE_MAX) + { + line_length = tmp_ulong; + } + else + { + error (0, 0, + _("ignoring invalid width in environment variable COLUMNS: %s"), + quotearg (p)); + } } } @@ -1571,7 +1571,7 @@ decode_switches (int argc, char **argv) struct winsize ws; if (ioctl (STDOUT_FILENO, TIOCGWINSZ, &ws) != -1 - && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col) + && 0 < ws.ws_col && ws.ws_col == (size_t) ws.ws_col) line_length = ws.ws_col; } #endif @@ -1581,18 +1581,18 @@ decode_switches (int argc, char **argv) tabsize = 8; if (p) { - unsigned long int tmp_ulong; - if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK - && tmp_ulong <= SIZE_MAX) - { - tabsize = tmp_ulong; - } - else - { - error (0, 0, - _("ignoring invalid tab size in environment variable TABSIZE: %s"), - quotearg (p)); - } + unsigned long int tmp_ulong; + if (xstrtoul (p, NULL, 0, &tmp_ulong, NULL) == LONGINT_OK + && tmp_ulong <= SIZE_MAX) + { + tabsize = tmp_ulong; + } + else + { + error (0, 0, + _("ignoring invalid tab size in environment variable TABSIZE: %s"), + quotearg (p)); + } } } @@ -1600,319 +1600,319 @@ decode_switches (int argc, char **argv) { int oi = -1; int c = getopt_long (argc, argv, - "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1", - long_options, &oi); + "abcdfghiklmnopqrstuvw:xABCDFGHI:LNQRST:UXZ1", + long_options, &oi); if (c == -1) - break; + break; switch (c) - { - case 'a': - ignore_mode = IGNORE_MINIMAL; - break; - - case 'b': - set_quoting_style (NULL, escape_quoting_style); - break; - - case 'c': - time_type = time_ctime; - break; - - case 'd': - immediate_dirs = true; - break; - - case 'f': - /* Same as enabling -a -U and disabling -l -s. */ - ignore_mode = IGNORE_MINIMAL; - sort_type = sort_none; - sort_type_specified = true; - /* disable -l */ - if (format == long_format) - format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line); - print_block_size = false; /* disable -s */ - print_with_color = false; /* disable --color */ - break; - - case FILE_TYPE_INDICATOR_OPTION: /* --file-type */ - indicator_style = file_type; - break; - - case 'g': - format = long_format; - print_owner = false; - break; - - case 'h': - human_output_opts = human_autoscale | human_SI | human_base_1024; - file_output_block_size = output_block_size = 1; - break; - - case 'i': - print_inode = true; - break; - - case 'k': - human_output_opts = 0; - file_output_block_size = output_block_size = 1024; - break; - - case 'l': - format = long_format; - break; - - case 'm': - format = with_commas; - break; - - case 'n': - numeric_ids = true; - format = long_format; - break; - - case 'o': /* Just like -l, but don't display group info. */ - format = long_format; - print_group = false; - break; - - case 'p': - indicator_style = slash; - break; - - case 'q': - qmark_funny_chars = true; - break; - - case 'r': - sort_reverse = true; - break; - - case 's': - print_block_size = true; - break; - - case 't': - sort_type = sort_time; - sort_type_specified = true; - break; - - case 'u': - time_type = time_atime; - break; - - case 'v': - sort_type = sort_version; - sort_type_specified = true; - break; - - case 'w': - { - unsigned long int tmp_ulong; - if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK - || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX)) - error (LS_FAILURE, 0, _("invalid line width: %s"), - quotearg (optarg)); - line_length = tmp_ulong; - break; - } - - case 'x': - format = horizontal; - break; - - case 'A': - if (ignore_mode == IGNORE_DEFAULT) - ignore_mode = IGNORE_DOT_AND_DOTDOT; - break; - - case 'B': - add_ignore_pattern ("*~"); - add_ignore_pattern (".*~"); - break; - - case 'C': - format = many_per_line; - break; - - case 'D': - dired = true; - break; - - case 'F': - indicator_style = classify; - break; - - case 'G': /* inhibit display of group info */ - print_group = false; - break; - - case 'H': - dereference = DEREF_COMMAND_LINE_ARGUMENTS; - break; - - case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION: - dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR; - break; - - case 'I': - add_ignore_pattern (optarg); - break; - - case 'L': - dereference = DEREF_ALWAYS; - break; - - case 'N': - set_quoting_style (NULL, literal_quoting_style); - break; - - case 'Q': - set_quoting_style (NULL, c_quoting_style); - break; - - case 'R': - recursive = true; - break; - - case 'S': - sort_type = sort_size; - sort_type_specified = true; - break; - - case 'T': - { - unsigned long int tmp_ulong; - if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK - || SIZE_MAX < tmp_ulong) - error (LS_FAILURE, 0, _("invalid tab size: %s"), - quotearg (optarg)); - tabsize = tmp_ulong; - break; - } - - case 'U': - sort_type = sort_none; - sort_type_specified = true; - break; - - case 'X': - sort_type = sort_extension; - sort_type_specified = true; - break; - - case '1': - /* -1 has no effect after -l. */ - if (format != long_format) - format = one_per_line; - break; + { + case 'a': + ignore_mode = IGNORE_MINIMAL; + break; + + case 'b': + set_quoting_style (NULL, escape_quoting_style); + break; + + case 'c': + time_type = time_ctime; + break; + + case 'd': + immediate_dirs = true; + break; + + case 'f': + /* Same as enabling -a -U and disabling -l -s. */ + ignore_mode = IGNORE_MINIMAL; + sort_type = sort_none; + sort_type_specified = true; + /* disable -l */ + if (format == long_format) + format = (isatty (STDOUT_FILENO) ? many_per_line : one_per_line); + print_block_size = false; /* disable -s */ + print_with_color = false; /* disable --color */ + break; + + case FILE_TYPE_INDICATOR_OPTION: /* --file-type */ + indicator_style = file_type; + break; + + case 'g': + format = long_format; + print_owner = false; + break; + + case 'h': + human_output_opts = human_autoscale | human_SI | human_base_1024; + file_output_block_size = output_block_size = 1; + break; + + case 'i': + print_inode = true; + break; + + case 'k': + human_output_opts = 0; + file_output_block_size = output_block_size = 1024; + break; + + case 'l': + format = long_format; + break; + + case 'm': + format = with_commas; + break; + + case 'n': + numeric_ids = true; + format = long_format; + break; + + case 'o': /* Just like -l, but don't display group info. */ + format = long_format; + print_group = false; + break; + + case 'p': + indicator_style = slash; + break; + + case 'q': + qmark_funny_chars = true; + break; + + case 'r': + sort_reverse = true; + break; + + case 's': + print_block_size = true; + break; + + case 't': + sort_type = sort_time; + sort_type_specified = true; + break; + + case 'u': + time_type = time_atime; + break; + + case 'v': + sort_type = sort_version; + sort_type_specified = true; + break; + + case 'w': + { + unsigned long int tmp_ulong; + if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK + || ! (0 < tmp_ulong && tmp_ulong <= SIZE_MAX)) + error (LS_FAILURE, 0, _("invalid line width: %s"), + quotearg (optarg)); + line_length = tmp_ulong; + break; + } + + case 'x': + format = horizontal; + break; + + case 'A': + if (ignore_mode == IGNORE_DEFAULT) + ignore_mode = IGNORE_DOT_AND_DOTDOT; + break; + + case 'B': + add_ignore_pattern ("*~"); + add_ignore_pattern (".*~"); + break; + + case 'C': + format = many_per_line; + break; + + case 'D': + dired = true; + break; + + case 'F': + indicator_style = classify; + break; + + case 'G': /* inhibit display of group info */ + print_group = false; + break; + + case 'H': + dereference = DEREF_COMMAND_LINE_ARGUMENTS; + break; + + case DEREFERENCE_COMMAND_LINE_SYMLINK_TO_DIR_OPTION: + dereference = DEREF_COMMAND_LINE_SYMLINK_TO_DIR; + break; + + case 'I': + add_ignore_pattern (optarg); + break; + + case 'L': + dereference = DEREF_ALWAYS; + break; + + case 'N': + set_quoting_style (NULL, literal_quoting_style); + break; + + case 'Q': + set_quoting_style (NULL, c_quoting_style); + break; + + case 'R': + recursive = true; + break; + + case 'S': + sort_type = sort_size; + sort_type_specified = true; + break; + + case 'T': + { + unsigned long int tmp_ulong; + if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK + || SIZE_MAX < tmp_ulong) + error (LS_FAILURE, 0, _("invalid tab size: %s"), + quotearg (optarg)); + tabsize = tmp_ulong; + break; + } + + case 'U': + sort_type = sort_none; + sort_type_specified = true; + break; + + case 'X': + sort_type = sort_extension; + sort_type_specified = true; + break; + + case '1': + /* -1 has no effect after -l. */ + if (format != long_format) + format = one_per_line; + break; case AUTHOR_OPTION: print_author = true; break; - case HIDE_OPTION: - { - struct ignore_pattern *hide = xmalloc (sizeof *hide); - hide->pattern = optarg; - hide->next = hide_patterns; - hide_patterns = hide; - } - break; - - case SORT_OPTION: - sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types); - sort_type_specified = true; - break; - - case GROUP_DIRECTORIES_FIRST_OPTION: - directories_first = true; - break; - - case TIME_OPTION: - time_type = XARGMATCH ("--time", optarg, time_args, time_types); - break; - - case FORMAT_OPTION: - format = XARGMATCH ("--format", optarg, format_args, format_types); - break; - - case FULL_TIME_OPTION: - format = long_format; - time_style_option = bad_cast ("full-iso"); - break; - - case COLOR_OPTION: - { - int i; - if (optarg) - i = XARGMATCH ("--color", optarg, color_args, color_types); - else - /* Using --color with no argument is equivalent to using - --color=always. */ - i = color_always; - - print_with_color = (i == color_always - || (i == color_if_tty - && isatty (STDOUT_FILENO))); - - if (print_with_color) - { - /* Don't use TAB characters in output. Some terminal - emulators can't handle the combination of tabs and - color codes on the same line. */ - tabsize = 0; - } - break; - } - - case INDICATOR_STYLE_OPTION: - indicator_style = XARGMATCH ("--indicator-style", optarg, - indicator_style_args, - indicator_style_types); - break; - - case QUOTING_STYLE_OPTION: - set_quoting_style (NULL, - XARGMATCH ("--quoting-style", optarg, - quoting_style_args, - quoting_style_vals)); - break; - - case TIME_STYLE_OPTION: - time_style_option = optarg; - break; - - case SHOW_CONTROL_CHARS_OPTION: - qmark_funny_chars = false; - break; - - case BLOCK_SIZE_OPTION: - { - enum strtol_error e = human_options (optarg, &human_output_opts, - &output_block_size); - if (e != LONGINT_OK) - xstrtol_fatal (e, oi, 0, long_options, optarg); - file_output_block_size = output_block_size; - } - break; - - case SI_OPTION: - human_output_opts = human_autoscale | human_SI; - file_output_block_size = output_block_size = 1; - break; - - case 'Z': - print_scontext = true; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (LS_FAILURE); - } + case HIDE_OPTION: + { + struct ignore_pattern *hide = xmalloc (sizeof *hide); + hide->pattern = optarg; + hide->next = hide_patterns; + hide_patterns = hide; + } + break; + + case SORT_OPTION: + sort_type = XARGMATCH ("--sort", optarg, sort_args, sort_types); + sort_type_specified = true; + break; + + case GROUP_DIRECTORIES_FIRST_OPTION: + directories_first = true; + break; + + case TIME_OPTION: + time_type = XARGMATCH ("--time", optarg, time_args, time_types); + break; + + case FORMAT_OPTION: + format = XARGMATCH ("--format", optarg, format_args, format_types); + break; + + case FULL_TIME_OPTION: + format = long_format; + time_style_option = bad_cast ("full-iso"); + break; + + case COLOR_OPTION: + { + int i; + if (optarg) + i = XARGMATCH ("--color", optarg, color_args, color_types); + else + /* Using --color with no argument is equivalent to using + --color=always. */ + i = color_always; + + print_with_color = (i == color_always + || (i == color_if_tty + && isatty (STDOUT_FILENO))); + + if (print_with_color) + { + /* Don't use TAB characters in output. Some terminal + emulators can't handle the combination of tabs and + color codes on the same line. */ + tabsize = 0; + } + break; + } + + case INDICATOR_STYLE_OPTION: + indicator_style = XARGMATCH ("--indicator-style", optarg, + indicator_style_args, + indicator_style_types); + break; + + case QUOTING_STYLE_OPTION: + set_quoting_style (NULL, + XARGMATCH ("--quoting-style", optarg, + quoting_style_args, + quoting_style_vals)); + break; + + case TIME_STYLE_OPTION: + time_style_option = optarg; + break; + + case SHOW_CONTROL_CHARS_OPTION: + qmark_funny_chars = false; + break; + + case BLOCK_SIZE_OPTION: + { + enum strtol_error e = human_options (optarg, &human_output_opts, + &output_block_size); + if (e != LONGINT_OK) + xstrtol_fatal (e, oi, 0, long_options, optarg); + file_output_block_size = output_block_size; + } + break; + + case SI_OPTION: + human_output_opts = human_autoscale | human_SI; + file_output_block_size = output_block_size = 1; + break; + + case 'Z': + print_scontext = true; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (LS_FAILURE); + } } max_idx = MAX (1, line_length / MIN_COLUMN_WIDTH); @@ -1924,7 +1924,7 @@ decode_switches (int argc, char **argv) { char const *p; for (p = "*=>@|" + indicator_style - file_type; *p; p++) - set_char_quoting (filename_quoting_options, *p, 1); + set_char_quoting (filename_quoting_options, *p, 1); } dirname_quoting_options = clone_quoting_options (NULL); @@ -1956,72 +1956,72 @@ decode_switches (int argc, char **argv) static char const posix_prefix[] = "posix-"; if (! style) - if (! (style = getenv ("TIME_STYLE"))) - style = bad_cast ("locale"); + if (! (style = getenv ("TIME_STYLE"))) + style = bad_cast ("locale"); while (strncmp (style, posix_prefix, sizeof posix_prefix - 1) == 0) - { - if (! hard_locale (LC_TIME)) - return optind; - style += sizeof posix_prefix - 1; - } + { + if (! hard_locale (LC_TIME)) + return optind; + style += sizeof posix_prefix - 1; + } if (*style == '+') - { - char *p0 = style + 1; - char *p1 = strchr (p0, '\n'); - if (! p1) - p1 = p0; - else - { - if (strchr (p1 + 1, '\n')) - error (LS_FAILURE, 0, _("invalid time style format %s"), - quote (p0)); - *p1++ = '\0'; - } - long_time_format[0] = p0; - long_time_format[1] = p1; - } + { + char *p0 = style + 1; + char *p1 = strchr (p0, '\n'); + if (! p1) + p1 = p0; + else + { + if (strchr (p1 + 1, '\n')) + error (LS_FAILURE, 0, _("invalid time style format %s"), + quote (p0)); + *p1++ = '\0'; + } + long_time_format[0] = p0; + long_time_format[1] = p1; + } else - switch (XARGMATCH ("time style", style, - time_style_args, - time_style_types)) - { - case full_iso_time_style: - long_time_format[0] = long_time_format[1] = - "%Y-%m-%d %H:%M:%S.%N %z"; - break; - - case long_iso_time_style: - case_long_iso_time_style: - long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M"; - break; - - case iso_time_style: - long_time_format[0] = "%Y-%m-%d "; - long_time_format[1] = "%m-%d %H:%M"; - break; - - case locale_time_style: - if (hard_locale (LC_TIME)) - { - /* Ensure that the locale has translations for both - formats. If not, fall back on long-iso format. */ - int i; - for (i = 0; i < 2; i++) - { - char const *locale_format = - dcgettext (NULL, long_time_format[i], LC_TIME); - if (locale_format == long_time_format[i]) - goto case_long_iso_time_style; - long_time_format[i] = locale_format; - } - } - } + switch (XARGMATCH ("time style", style, + time_style_args, + time_style_types)) + { + case full_iso_time_style: + long_time_format[0] = long_time_format[1] = + "%Y-%m-%d %H:%M:%S.%N %z"; + break; + + case long_iso_time_style: + case_long_iso_time_style: + long_time_format[0] = long_time_format[1] = "%Y-%m-%d %H:%M"; + break; + + case iso_time_style: + long_time_format[0] = "%Y-%m-%d "; + long_time_format[1] = "%m-%d %H:%M"; + break; + + case locale_time_style: + if (hard_locale (LC_TIME)) + { + /* Ensure that the locale has translations for both + formats. If not, fall back on long-iso format. */ + int i; + for (i = 0; i < 2; i++) + { + char const *locale_format = + dcgettext (NULL, long_time_format[i], LC_TIME); + if (locale_format == long_time_format[i]) + goto case_long_iso_time_style; + long_time_format[i] = locale_format; + } + } + } /* Note we leave %5b etc. alone so user widths/flags are honored. */ if (strstr (long_time_format[0],"%b") || strstr (long_time_format[1],"%b")) - if (!abmon_init ()) - error (0, 0, _("error initializing month strings")); + if (!abmon_init ()) + error (0, 0, _("error initializing month strings")); } return optind; @@ -2042,7 +2042,7 @@ decode_switches (int argc, char **argv) static bool get_funky_string (char **dest, const char **src, bool equals_end, - size_t *output_count) + size_t *output_count) { char num; /* For numerical codes */ size_t count; /* Something to count with */ @@ -2062,170 +2062,170 @@ get_funky_string (char **dest, const char **src, bool equals_end, while (state < ST_END) { switch (state) - { - case ST_GND: /* Ground state (no escapes) */ - switch (*p) - { - case ':': - case '\0': - state = ST_END; /* End of string */ - break; - case '\\': - state = ST_BACKSLASH; /* Backslash scape sequence */ - ++p; - break; - case '^': - state = ST_CARET; /* Caret escape */ - ++p; - break; - case '=': - if (equals_end) - { - state = ST_END; /* End */ - break; - } - /* else fall through */ - default: - *(q++) = *(p++); - ++count; - break; - } - break; - - case ST_BACKSLASH: /* Backslash escaped character */ - switch (*p) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - state = ST_OCTAL; /* Octal sequence */ - num = *p - '0'; - break; - case 'x': - case 'X': - state = ST_HEX; /* Hex sequence */ - num = 0; - break; - case 'a': /* Bell */ - num = '\a'; - break; - case 'b': /* Backspace */ - num = '\b'; - break; - case 'e': /* Escape */ - num = 27; - break; - case 'f': /* Form feed */ - num = '\f'; - break; - case 'n': /* Newline */ - num = '\n'; - break; - case 'r': /* Carriage return */ - num = '\r'; - break; - case 't': /* Tab */ - num = '\t'; - break; - case 'v': /* Vtab */ - num = '\v'; - break; - case '?': /* Delete */ + { + case ST_GND: /* Ground state (no escapes) */ + switch (*p) + { + case ':': + case '\0': + state = ST_END; /* End of string */ + break; + case '\\': + state = ST_BACKSLASH; /* Backslash scape sequence */ + ++p; + break; + case '^': + state = ST_CARET; /* Caret escape */ + ++p; + break; + case '=': + if (equals_end) + { + state = ST_END; /* End */ + break; + } + /* else fall through */ + default: + *(q++) = *(p++); + ++count; + break; + } + break; + + case ST_BACKSLASH: /* Backslash escaped character */ + switch (*p) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + state = ST_OCTAL; /* Octal sequence */ + num = *p - '0'; + break; + case 'x': + case 'X': + state = ST_HEX; /* Hex sequence */ + num = 0; + break; + case 'a': /* Bell */ + num = '\a'; + break; + case 'b': /* Backspace */ + num = '\b'; + break; + case 'e': /* Escape */ + num = 27; + break; + case 'f': /* Form feed */ + num = '\f'; + break; + case 'n': /* Newline */ + num = '\n'; + break; + case 'r': /* Carriage return */ + num = '\r'; + break; + case 't': /* Tab */ + num = '\t'; + break; + case 'v': /* Vtab */ + num = '\v'; + break; + case '?': /* Delete */ num = 127; - break; - case '_': /* Space */ - num = ' '; - break; - case '\0': /* End of string */ - state = ST_ERROR; /* Error! */ - break; - default: /* Escaped character like \ ^ : = */ - num = *p; - break; - } - if (state == ST_BACKSLASH) - { - *(q++) = num; - ++count; - state = ST_GND; - } - ++p; - break; - - case ST_OCTAL: /* Octal sequence */ - if (*p < '0' || *p > '7') - { - *(q++) = num; - ++count; - state = ST_GND; - } - else - num = (num << 3) + (*(p++) - '0'); - break; - - case ST_HEX: /* Hex sequence */ - switch (*p) - { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - num = (num << 4) + (*(p++) - '0'); - break; - case 'a': - case 'b': - case 'c': - case 'd': - case 'e': - case 'f': - num = (num << 4) + (*(p++) - 'a') + 10; - break; - case 'A': - case 'B': - case 'C': - case 'D': - case 'E': - case 'F': - num = (num << 4) + (*(p++) - 'A') + 10; - break; - default: - *(q++) = num; - ++count; - state = ST_GND; - break; - } - break; - - case ST_CARET: /* Caret escape */ - state = ST_GND; /* Should be the next state... */ - if (*p >= '@' && *p <= '~') - { - *(q++) = *(p++) & 037; - ++count; - } - else if (*p == '?') - { - *(q++) = 127; - ++count; - } - else - state = ST_ERROR; - break; - - default: - abort (); - } + break; + case '_': /* Space */ + num = ' '; + break; + case '\0': /* End of string */ + state = ST_ERROR; /* Error! */ + break; + default: /* Escaped character like \ ^ : = */ + num = *p; + break; + } + if (state == ST_BACKSLASH) + { + *(q++) = num; + ++count; + state = ST_GND; + } + ++p; + break; + + case ST_OCTAL: /* Octal sequence */ + if (*p < '0' || *p > '7') + { + *(q++) = num; + ++count; + state = ST_GND; + } + else + num = (num << 3) + (*(p++) - '0'); + break; + + case ST_HEX: /* Hex sequence */ + switch (*p) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + num = (num << 4) + (*(p++) - '0'); + break; + case 'a': + case 'b': + case 'c': + case 'd': + case 'e': + case 'f': + num = (num << 4) + (*(p++) - 'a') + 10; + break; + case 'A': + case 'B': + case 'C': + case 'D': + case 'E': + case 'F': + num = (num << 4) + (*(p++) - 'A') + 10; + break; + default: + *(q++) = num; + ++count; + state = ST_GND; + break; + } + break; + + case ST_CARET: /* Caret escape */ + state = ST_GND; /* Should be the next state... */ + if (*p >= '@' && *p <= '~') + { + *(q++) = *(p++) & 037; + ++count; + } + else if (*p == '?') + { + *(q++) = 127; + ++count; + } + else + state = ST_ERROR; + break; + + default: + abort (); + } } *dest = q; @@ -2261,83 +2261,83 @@ parse_ls_color (void) while (state > 0) { switch (state) - { - case 1: /* First label character */ - switch (*p) - { - case ':': - ++p; - break; - - case '*': - /* Allocate new extension block and add to head of - linked list (this way a later definition will - override an earlier one, which can be useful for - having terminal-specific defs override global). */ - - ext = xmalloc (sizeof *ext); - ext->next = color_ext_list; - color_ext_list = ext; - - ++p; - ext->ext.string = buf; - - state = (get_funky_string (&buf, &p, true, &ext->ext.len) - ? 4 : -1); - break; - - case '\0': - state = 0; /* Done! */ - break; - - default: /* Assume it is file type label */ - label[0] = *(p++); - state = 2; - break; - } - break; - - case 2: /* Second label character */ - if (*p) - { - label[1] = *(p++); - state = 3; - } - else - state = -1; /* Error */ - break; - - case 3: /* Equal sign after indicator label */ - state = -1; /* Assume failure... */ - if (*(p++) == '=')/* It *should* be... */ - { - for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no) - { - if (STREQ (label, indicator_name[ind_no])) - { - color_indicator[ind_no].string = buf; - state = (get_funky_string (&buf, &p, false, - &color_indicator[ind_no].len) - ? 1 : -1); - break; - } - } - if (state == -1) - error (0, 0, _("unrecognized prefix: %s"), quotearg (label)); - } - break; - - case 4: /* Equal sign after *.ext */ - if (*(p++) == '=') - { - ext->seq.string = buf; - state = (get_funky_string (&buf, &p, false, &ext->seq.len) - ? 1 : -1); - } - else - state = -1; - break; - } + { + case 1: /* First label character */ + switch (*p) + { + case ':': + ++p; + break; + + case '*': + /* Allocate new extension block and add to head of + linked list (this way a later definition will + override an earlier one, which can be useful for + having terminal-specific defs override global). */ + + ext = xmalloc (sizeof *ext); + ext->next = color_ext_list; + color_ext_list = ext; + + ++p; + ext->ext.string = buf; + + state = (get_funky_string (&buf, &p, true, &ext->ext.len) + ? 4 : -1); + break; + + case '\0': + state = 0; /* Done! */ + break; + + default: /* Assume it is file type label */ + label[0] = *(p++); + state = 2; + break; + } + break; + + case 2: /* Second label character */ + if (*p) + { + label[1] = *(p++); + state = 3; + } + else + state = -1; /* Error */ + break; + + case 3: /* Equal sign after indicator label */ + state = -1; /* Assume failure... */ + if (*(p++) == '=')/* It *should* be... */ + { + for (ind_no = 0; indicator_name[ind_no] != NULL; ++ind_no) + { + if (STREQ (label, indicator_name[ind_no])) + { + color_indicator[ind_no].string = buf; + state = (get_funky_string (&buf, &p, false, + &color_indicator[ind_no].len) + ? 1 : -1); + break; + } + } + if (state == -1) + error (0, 0, _("unrecognized prefix: %s"), quotearg (label)); + } + break; + + case 4: /* Equal sign after *.ext */ + if (*(p++) == '=') + { + ext->seq.string = buf; + state = (get_funky_string (&buf, &p, false, &ext->seq.len) + ? 1 : -1); + } + else + state = -1; + break; + } } if (state < 0) @@ -2346,14 +2346,14 @@ parse_ls_color (void) struct color_ext_type *e2; error (0, 0, - _("unparsable value for LS_COLORS environment variable")); + _("unparsable value for LS_COLORS environment variable")); free (color_buf); for (e = color_ext_list; e != NULL; /* empty */) - { - e2 = e; - e = e->next; - free (e2); - } + { + e2 = e; + e = e->next; + free (e2); + } print_with_color = false; } @@ -2434,24 +2434,24 @@ print_dir (char const *name, char const *realname, bool command_line_arg) /* If dirfd failed, endure the overhead of using stat. */ if ((0 <= fd - ? fstat (fd, &dir_stat) - : stat (name, &dir_stat)) < 0) - { - file_failure (command_line_arg, - _("cannot determine device and inode of %s"), name); - closedir (dirp); - return; - } + ? fstat (fd, &dir_stat) + : stat (name, &dir_stat)) < 0) + { + file_failure (command_line_arg, + _("cannot determine device and inode of %s"), name); + closedir (dirp); + return; + } /* If we've already visited this dev/inode pair, warn that - we've found a loop, and do not process this directory. */ + we've found a loop, and do not process this directory. */ if (visit_dir (dir_stat.st_dev, dir_stat.st_ino)) - { - error (0, 0, _("%s: not listing already-listed directory"), - quotearg_colon (name)); - closedir (dirp); - return; - } + { + error (0, 0, _("%s: not listing already-listed directory"), + quotearg_colon (name)); + closedir (dirp); + return; + } DEV_INO_PUSH (dir_stat.st_dev, dir_stat.st_ino); } @@ -2459,12 +2459,12 @@ print_dir (char const *name, char const *realname, bool command_line_arg) if (recursive | print_dir_name) { if (!first) - DIRED_PUTCHAR ('\n'); + DIRED_PUTCHAR ('\n'); first = false; DIRED_INDENT (); PUSH_CURRENT_DIRED_POS (&subdired_obstack); dired_pos += quote_name (stdout, realname ? realname : name, - dirname_quoting_options, NULL); + dirname_quoting_options, NULL); PUSH_CURRENT_DIRED_POS (&subdired_obstack); DIRED_FPUTS_LITERAL (":\n", stdout); } @@ -2477,57 +2477,57 @@ print_dir (char const *name, char const *realname, bool command_line_arg) while (1) { /* Set errno to zero so we can distinguish between a readdir failure - and when readdir simply finds that there are no more entries. */ + and when readdir simply finds that there are no more entries. */ errno = 0; next = readdir (dirp); if (next) - { - if (! file_ignored (next->d_name)) - { - enum filetype type = unknown; + { + if (! file_ignored (next->d_name)) + { + enum filetype type = unknown; #if HAVE_STRUCT_DIRENT_D_TYPE - switch (next->d_type) - { - case DT_BLK: type = blockdev; break; - case DT_CHR: type = chardev; break; - case DT_DIR: type = directory; break; - case DT_FIFO: type = fifo; break; - case DT_LNK: type = symbolic_link; break; - case DT_REG: type = normal; break; - case DT_SOCK: type = sock; break; + switch (next->d_type) + { + case DT_BLK: type = blockdev; break; + case DT_CHR: type = chardev; break; + case DT_DIR: type = directory; break; + case DT_FIFO: type = fifo; break; + case DT_LNK: type = symbolic_link; break; + case DT_REG: type = normal; break; + case DT_SOCK: type = sock; break; # ifdef DT_WHT - case DT_WHT: type = whiteout; break; + case DT_WHT: type = whiteout; break; # endif - } + } #endif - total_blocks += gobble_file (next->d_name, type, D_INO (next), - false, name); - - /* In this narrow case, print out each name right away, so - ls uses constant memory while processing the entries of - this directory. Useful when there are many (millions) - of entries in a directory. */ - if (format == one_per_line && sort_type == sort_none - && !print_block_size && !recursive) - { - /* We must call sort_files in spite of - "sort_type == sort_none" for its initialization - of the sorted_file vector. */ - sort_files (); - print_current_files (); - clear_files (); - } - } - } + total_blocks += gobble_file (next->d_name, type, D_INO (next), + false, name); + + /* In this narrow case, print out each name right away, so + ls uses constant memory while processing the entries of + this directory. Useful when there are many (millions) + of entries in a directory. */ + if (format == one_per_line && sort_type == sort_none + && !print_block_size && !recursive) + { + /* We must call sort_files in spite of + "sort_type == sort_none" for its initialization + of the sorted_file vector. */ + sort_files (); + print_current_files (); + clear_files (); + } + } + } else if (errno != 0) - { - file_failure (command_line_arg, _("reading directory %s"), name); - if (errno != EOVERFLOW) - break; - } + { + file_failure (command_line_arg, _("reading directory %s"), name); + if (errno != EOVERFLOW) + break; + } else - break; + break; } if (closedir (dirp) != 0) @@ -2555,7 +2555,7 @@ print_dir (char const *name, char const *realname, bool command_line_arg) DIRED_FPUTS (p, stdout, strlen (p)); DIRED_PUTCHAR (' '); p = human_readable (total_blocks, buf, human_output_opts, - ST_NBLOCKSIZE, output_block_size); + ST_NBLOCKSIZE, output_block_size); DIRED_FPUTS (p, stdout, strlen (p)); DIRED_PUTCHAR ('\n'); } @@ -2597,11 +2597,11 @@ static bool file_ignored (char const *name) { return ((ignore_mode != IGNORE_MINIMAL - && name[0] == '.' - && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')])) - || (ignore_mode == IGNORE_DEFAULT - && patterns_match (hide_patterns, name)) - || patterns_match (ignore_patterns, name)); + && name[0] == '.' + && (ignore_mode == IGNORE_DEFAULT || ! name[1 + (name[1] == '.')])) + || (ignore_mode == IGNORE_DEFAULT + && patterns_match (hide_patterns, name)) + || patterns_match (ignore_patterns, name)); } /* POSIX requires that a file size be printed without a sign, even @@ -2629,7 +2629,7 @@ clear_files (void) free (f->name); free (f->linkname); if (f->scontext != UNKNOWN_SECURITY_CONTEXT) - freecon (f->scontext); + freecon (f->scontext); } cwd_n_used = 0; @@ -2652,7 +2652,7 @@ clear_files (void) static uintmax_t gobble_file (char const *name, enum filetype type, ino_t inode, - bool command_line_arg, char const *dirname) + bool command_line_arg, char const *dirname) { uintmax_t blocks = 0; struct fileinfo *f; @@ -2675,32 +2675,32 @@ gobble_file (char const *name, enum filetype type, ino_t inode, if (command_line_arg || format_needs_stat /* When coloring a directory (we may know the type from - direct.d_type), we have to stat it in order to indicate - sticky and/or other-writable attributes. */ + direct.d_type), we have to stat it in order to indicate + sticky and/or other-writable attributes. */ || (type == directory && print_with_color) /* When dereferencing symlinks, the inode and type must come from - stat, but readdir provides the inode and type of lstat. */ + stat, but readdir provides the inode and type of lstat. */ || ((print_inode || format_needs_type) - && (type == symbolic_link || type == unknown) - && (dereference == DEREF_ALWAYS - || (command_line_arg && dereference != DEREF_NEVER) - || color_symlink_as_referent || check_symlink_color)) + && (type == symbolic_link || type == unknown) + && (dereference == DEREF_ALWAYS + || (command_line_arg && dereference != DEREF_NEVER) + || color_symlink_as_referent || check_symlink_color)) /* Command line dereferences are already taken care of by the above - assertion that the inode number is not yet known. */ + assertion that the inode number is not yet known. */ || (print_inode && inode == NOT_AN_INODE_NUMBER) || (format_needs_type - && (type == unknown || command_line_arg - /* --indicator-style=classify (aka -F) - requires that we stat each regular file - to see if it's executable. */ - || (type == normal && (indicator_style == classify - /* This is so that --color ends up - highlighting files with the executable - bit set even when options like -F are - not specified. */ - || (print_with_color - && is_colored (C_EXEC)) - ))))) + && (type == unknown || command_line_arg + /* --indicator-style=classify (aka -F) + requires that we stat each regular file + to see if it's executable. */ + || (type == normal && (indicator_style == classify + /* This is so that --color ends up + highlighting files with the executable + bit set even when options like -F are + not specified. */ + || (print_with_color + && is_colored (C_EXEC)) + ))))) { /* Absolute name of this file. */ @@ -2709,241 +2709,241 @@ gobble_file (char const *name, enum filetype type, ino_t inode, int err; if (name[0] == '/' || dirname[0] == 0) - absolute_name = (char *) name; + absolute_name = (char *) name; else - { - absolute_name = alloca (strlen (name) + strlen (dirname) + 2); - attach (absolute_name, dirname, name); - } + { + absolute_name = alloca (strlen (name) + strlen (dirname) + 2); + attach (absolute_name, dirname, name); + } switch (dereference) - { - case DEREF_ALWAYS: - err = stat (absolute_name, &f->stat); - do_deref = true; - break; - - case DEREF_COMMAND_LINE_ARGUMENTS: - case DEREF_COMMAND_LINE_SYMLINK_TO_DIR: - if (command_line_arg) - { - bool need_lstat; - err = stat (absolute_name, &f->stat); - do_deref = true; - - if (dereference == DEREF_COMMAND_LINE_ARGUMENTS) - break; - - need_lstat = (err < 0 - ? errno == ENOENT - : ! S_ISDIR (f->stat.st_mode)); - if (!need_lstat) - break; - - /* stat failed because of ENOENT, maybe indicating a dangling - symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a - directory, and --dereference-command-line-symlink-to-dir is - in effect. Fall through so that we call lstat instead. */ - } - - default: /* DEREF_NEVER */ - err = lstat (absolute_name, &f->stat); - do_deref = false; - break; - } + { + case DEREF_ALWAYS: + err = stat (absolute_name, &f->stat); + do_deref = true; + break; + + case DEREF_COMMAND_LINE_ARGUMENTS: + case DEREF_COMMAND_LINE_SYMLINK_TO_DIR: + if (command_line_arg) + { + bool need_lstat; + err = stat (absolute_name, &f->stat); + do_deref = true; + + if (dereference == DEREF_COMMAND_LINE_ARGUMENTS) + break; + + need_lstat = (err < 0 + ? errno == ENOENT + : ! S_ISDIR (f->stat.st_mode)); + if (!need_lstat) + break; + + /* stat failed because of ENOENT, maybe indicating a dangling + symlink. Or stat succeeded, ABSOLUTE_NAME does not refer to a + directory, and --dereference-command-line-symlink-to-dir is + in effect. Fall through so that we call lstat instead. */ + } + + default: /* DEREF_NEVER */ + err = lstat (absolute_name, &f->stat); + do_deref = false; + break; + } if (err != 0) - { - /* Failure to stat a command line argument leads to - an exit status of 2. For other files, stat failure - provokes an exit status of 1. */ - file_failure (command_line_arg, - _("cannot access %s"), absolute_name); - if (command_line_arg) - return 0; + { + /* Failure to stat a command line argument leads to + an exit status of 2. For other files, stat failure + provokes an exit status of 1. */ + file_failure (command_line_arg, + _("cannot access %s"), absolute_name); + if (command_line_arg) + return 0; - f->name = xstrdup (name); - cwd_n_used++; + f->name = xstrdup (name); + cwd_n_used++; - return 0; - } + return 0; + } f->stat_ok = true; if (format == long_format || print_scontext) - { - bool have_selinux = false; - bool have_acl = false; - int attr_len = (do_deref - ? getfilecon (absolute_name, &f->scontext) - : lgetfilecon (absolute_name, &f->scontext)); - err = (attr_len < 0); - - /* Contrary to its documented API, getfilecon may return 0, - yet set f->scontext to NULL (on at least Debian's libselinux1 - 2.0.15-2+b1), so work around that bug. - FIXME: remove this work-around in 2011, or whenever affected - versions of libselinux are long gone. */ - if (attr_len == 0) - { - err = 0; - f->scontext = xstrdup ("unlabeled"); - } - - if (err == 0) - have_selinux = ! STREQ ("unlabeled", f->scontext); - else - { - f->scontext = UNKNOWN_SECURITY_CONTEXT; - - /* When requesting security context information, don't make - ls fail just because the file (even a command line argument) - isn't on the right type of file system. I.e., a getfilecon - failure isn't in the same class as a stat failure. */ - if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA) - err = 0; - } - - if (err == 0 && format == long_format) - { - int n = file_has_acl (absolute_name, &f->stat); - err = (n < 0); - have_acl = (0 < n); - } - - f->acl_type = (!have_selinux && !have_acl - ? ACL_T_NONE - : (have_selinux && !have_acl - ? ACL_T_SELINUX_ONLY - : ACL_T_YES)); - any_has_acl |= f->acl_type != ACL_T_NONE; - - if (err) - error (0, errno, "%s", quotearg_colon (absolute_name)); - } + { + bool have_selinux = false; + bool have_acl = false; + int attr_len = (do_deref + ? getfilecon (absolute_name, &f->scontext) + : lgetfilecon (absolute_name, &f->scontext)); + err = (attr_len < 0); + + /* Contrary to its documented API, getfilecon may return 0, + yet set f->scontext to NULL (on at least Debian's libselinux1 + 2.0.15-2+b1), so work around that bug. + FIXME: remove this work-around in 2011, or whenever affected + versions of libselinux are long gone. */ + if (attr_len == 0) + { + err = 0; + f->scontext = xstrdup ("unlabeled"); + } + + if (err == 0) + have_selinux = ! STREQ ("unlabeled", f->scontext); + else + { + f->scontext = UNKNOWN_SECURITY_CONTEXT; + + /* When requesting security context information, don't make + ls fail just because the file (even a command line argument) + isn't on the right type of file system. I.e., a getfilecon + failure isn't in the same class as a stat failure. */ + if (errno == ENOTSUP || errno == EOPNOTSUPP || errno == ENODATA) + err = 0; + } + + if (err == 0 && format == long_format) + { + int n = file_has_acl (absolute_name, &f->stat); + err = (n < 0); + have_acl = (0 < n); + } + + f->acl_type = (!have_selinux && !have_acl + ? ACL_T_NONE + : (have_selinux && !have_acl + ? ACL_T_SELINUX_ONLY + : ACL_T_YES)); + any_has_acl |= f->acl_type != ACL_T_NONE; + + if (err) + error (0, errno, "%s", quotearg_colon (absolute_name)); + } if (S_ISLNK (f->stat.st_mode) - && (format == long_format || check_symlink_color)) - { - char *linkname; - struct stat linkstats; - - get_link_name (absolute_name, f, command_line_arg); - linkname = make_link_name (absolute_name, f->linkname); - - /* Avoid following symbolic links when possible, ie, when - they won't be traced and when no indicator is needed. */ - if (linkname - && (file_type <= indicator_style || check_symlink_color) - && stat (linkname, &linkstats) == 0) - { - f->linkok = true; - - /* Symbolic links to directories that are mentioned on the - command line are automatically traced if not being - listed as files. */ - if (!command_line_arg || format == long_format - || !S_ISDIR (linkstats.st_mode)) - { - /* Get the linked-to file's mode for the filetype indicator - in long listings. */ - f->linkmode = linkstats.st_mode; - } - } - free (linkname); - } + && (format == long_format || check_symlink_color)) + { + char *linkname; + struct stat linkstats; + + get_link_name (absolute_name, f, command_line_arg); + linkname = make_link_name (absolute_name, f->linkname); + + /* Avoid following symbolic links when possible, ie, when + they won't be traced and when no indicator is needed. */ + if (linkname + && (file_type <= indicator_style || check_symlink_color) + && stat (linkname, &linkstats) == 0) + { + f->linkok = true; + + /* Symbolic links to directories that are mentioned on the + command line are automatically traced if not being + listed as files. */ + if (!command_line_arg || format == long_format + || !S_ISDIR (linkstats.st_mode)) + { + /* Get the linked-to file's mode for the filetype indicator + in long listings. */ + f->linkmode = linkstats.st_mode; + } + } + free (linkname); + } /* When not distinguishing types of symlinks, pretend we know that - it is stat'able, so that it will be colored as a regular symlink, - and not as an orphan. */ + it is stat'able, so that it will be colored as a regular symlink, + and not as an orphan. */ if (S_ISLNK (f->stat.st_mode) && !check_symlink_color) - f->linkok = true; + f->linkok = true; if (S_ISLNK (f->stat.st_mode)) - f->filetype = symbolic_link; + f->filetype = symbolic_link; else if (S_ISDIR (f->stat.st_mode)) - { - if (command_line_arg & !immediate_dirs) - f->filetype = arg_directory; - else - f->filetype = directory; - } + { + if (command_line_arg & !immediate_dirs) + f->filetype = arg_directory; + else + f->filetype = directory; + } else - f->filetype = normal; + f->filetype = normal; blocks = ST_NBLOCKS (f->stat); if (format == long_format || print_block_size) - { - char buf[LONGEST_HUMAN_READABLE + 1]; - int len = mbswidth (human_readable (blocks, buf, human_output_opts, - ST_NBLOCKSIZE, output_block_size), - 0); - if (block_size_width < len) - block_size_width = len; - } + { + char buf[LONGEST_HUMAN_READABLE + 1]; + int len = mbswidth (human_readable (blocks, buf, human_output_opts, + ST_NBLOCKSIZE, output_block_size), + 0); + if (block_size_width < len) + block_size_width = len; + } if (format == long_format) - { - if (print_owner) - { - int len = format_user_width (f->stat.st_uid); - if (owner_width < len) - owner_width = len; - } - - if (print_group) - { - int len = format_group_width (f->stat.st_gid); - if (group_width < len) - group_width = len; - } - - if (print_author) - { - int len = format_user_width (f->stat.st_author); - if (author_width < len) - author_width = len; - } - } + { + if (print_owner) + { + int len = format_user_width (f->stat.st_uid); + if (owner_width < len) + owner_width = len; + } + + if (print_group) + { + int len = format_group_width (f->stat.st_gid); + if (group_width < len) + group_width = len; + } + + if (print_author) + { + int len = format_user_width (f->stat.st_author); + if (author_width < len) + author_width = len; + } + } if (print_scontext) - { - int len = strlen (f->scontext); - if (scontext_width < len) - scontext_width = len; - } + { + int len = strlen (f->scontext); + if (scontext_width < len) + scontext_width = len; + } if (format == long_format) - { - char b[INT_BUFSIZE_BOUND (uintmax_t)]; - int b_len = strlen (umaxtostr (f->stat.st_nlink, b)); - if (nlink_width < b_len) - nlink_width = b_len; - - if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)) - { - char buf[INT_BUFSIZE_BOUND (uintmax_t)]; - int len = strlen (umaxtostr (major (f->stat.st_rdev), buf)); - if (major_device_number_width < len) - major_device_number_width = len; - len = strlen (umaxtostr (minor (f->stat.st_rdev), buf)); - if (minor_device_number_width < len) - minor_device_number_width = len; - len = major_device_number_width + 2 + minor_device_number_width; - if (file_size_width < len) - file_size_width = len; - } - else - { - char buf[LONGEST_HUMAN_READABLE + 1]; - uintmax_t size = unsigned_file_size (f->stat.st_size); - int len = mbswidth (human_readable (size, buf, human_output_opts, - 1, file_output_block_size), - 0); - if (file_size_width < len) - file_size_width = len; - } - } + { + char b[INT_BUFSIZE_BOUND (uintmax_t)]; + int b_len = strlen (umaxtostr (f->stat.st_nlink, b)); + if (nlink_width < b_len) + nlink_width = b_len; + + if (S_ISCHR (f->stat.st_mode) || S_ISBLK (f->stat.st_mode)) + { + char buf[INT_BUFSIZE_BOUND (uintmax_t)]; + int len = strlen (umaxtostr (major (f->stat.st_rdev), buf)); + if (major_device_number_width < len) + major_device_number_width = len; + len = strlen (umaxtostr (minor (f->stat.st_rdev), buf)); + if (minor_device_number_width < len) + minor_device_number_width = len; + len = major_device_number_width + 2 + minor_device_number_width; + if (file_size_width < len) + file_size_width = len; + } + else + { + char buf[LONGEST_HUMAN_READABLE + 1]; + uintmax_t size = unsigned_file_size (f->stat.st_size); + int len = mbswidth (human_readable (size, buf, human_output_opts, + 1, file_output_block_size), + 0); + if (file_size_width < len) + file_size_width = len; + } + } } if (print_inode) @@ -2951,7 +2951,7 @@ gobble_file (char const *name, enum filetype type, ino_t inode, char buf[INT_BUFSIZE_BOUND (uintmax_t)]; int len = strlen (umaxtostr (f->stat.st_ino, buf)); if (inode_number_width < len) - inode_number_width = len; + inode_number_width = len; } f->name = xstrdup (name); @@ -2977,7 +2977,7 @@ get_link_name (char const *filename, struct fileinfo *f, bool command_line_arg) f->linkname = areadlink_with_size (filename, f->stat.st_size); if (f->linkname == NULL) file_failure (command_line_arg, _("cannot read symbolic link %s"), - filename); + filename); } /* If `linkname' is a relative name and `name' contains one or more @@ -3038,8 +3038,8 @@ extract_dirs_from_files (char const *dirname, bool command_line_arg) if (dirname && LOOP_DETECT) { /* Insert a marker entry first. When we dequeue this marker entry, - we'll know that DIRNAME has been processed and may be removed - from the set of active directories. */ + we'll know that DIRNAME has been processed and may be removed + from the set of active directories. */ queue_directory (NULL, dirname, false); } @@ -3050,20 +3050,20 @@ extract_dirs_from_files (char const *dirname, bool command_line_arg) struct fileinfo *f = sorted_file[i]; if (is_directory (f) - && (! ignore_dot_and_dot_dot - || ! basename_is_dot_or_dotdot (f->name))) - { - if (!dirname || f->name[0] == '/') - queue_directory (f->name, f->linkname, command_line_arg); - else - { - char *name = file_name_concat (dirname, f->name, NULL); - queue_directory (name, f->linkname, command_line_arg); - free (name); - } - if (f->filetype == arg_directory) - free (f->name); - } + && (! ignore_dot_and_dot_dot + || ! basename_is_dot_or_dotdot (f->name))) + { + if (!dirname || f->name[0] == '/') + queue_directory (f->name, f->linkname, command_line_arg); + else + { + char *name = file_name_concat (dirname, f->name, NULL); + queue_directory (name, f->linkname, command_line_arg); + free (name); + } + if (f->filetype == arg_directory) + free (f->name); + } } /* Now delete the directories from the table, compacting all the remaining @@ -3092,7 +3092,7 @@ xstrcoll (char const *a, char const *b) if (errno) { error (0, errno, _("cannot compare file names %s and %s"), - quote_n (0, a), quote_n (1, b)); + quote_n (0, a), quote_n (1, b)); set_exit_status (false); longjmp (failed_strcoll, 1); } @@ -3113,9 +3113,9 @@ typedef int (*qsortFunc)(V a, V b); bool a_is_dir = is_directory ((struct fileinfo const *) a); \ bool b_is_dir = is_directory ((struct fileinfo const *) b); \ if (a_is_dir && !b_is_dir) \ - return -1; /* a goes before b */ \ + return -1; /* a goes before b */ \ if (!a_is_dir && b_is_dir) \ - return 1; /* b goes before a */ \ + return 1; /* b goes before a */ \ } \ while (0) @@ -3130,19 +3130,19 @@ typedef int (*qsortFunc)(V a, V b); { return key_cmp_func (a, b, xstrcoll); } \ static int strcmp_##key_name (V a, V b) \ { return key_cmp_func (a, b, strcmp); } \ - \ + \ /* reverse, non-dirfirst versions */ \ static int rev_xstrcoll_##key_name (V a, V b) \ { return key_cmp_func (b, a, xstrcoll); } \ static int rev_strcmp_##key_name (V a, V b) \ { return key_cmp_func (b, a, strcmp); } \ - \ + \ /* direct, dirfirst versions */ \ static int xstrcoll_df_##key_name (V a, V b) \ { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, xstrcoll); } \ static int strcmp_df_##key_name (V a, V b) \ { DIRFIRST_CHECK (a, b); return key_cmp_func (a, b, strcmp); } \ - \ + \ /* reverse, dirfirst versions */ \ static int rev_xstrcoll_df_##key_name (V a, V b) \ { DIRFIRST_CHECK (a, b); return key_cmp_func (b, a, xstrcoll); } \ @@ -3151,34 +3151,34 @@ typedef int (*qsortFunc)(V a, V b); static inline int cmp_ctime (struct fileinfo const *a, struct fileinfo const *b, - int (*cmp) (char const *, char const *)) + int (*cmp) (char const *, char const *)) { int diff = timespec_cmp (get_stat_ctime (&b->stat), - get_stat_ctime (&a->stat)); + get_stat_ctime (&a->stat)); return diff ? diff : cmp (a->name, b->name); } static inline int cmp_mtime (struct fileinfo const *a, struct fileinfo const *b, - int (*cmp) (char const *, char const *)) + int (*cmp) (char const *, char const *)) { int diff = timespec_cmp (get_stat_mtime (&b->stat), - get_stat_mtime (&a->stat)); + get_stat_mtime (&a->stat)); return diff ? diff : cmp (a->name, b->name); } static inline int cmp_atime (struct fileinfo const *a, struct fileinfo const *b, - int (*cmp) (char const *, char const *)) + int (*cmp) (char const *, char const *)) { int diff = timespec_cmp (get_stat_atime (&b->stat), - get_stat_atime (&a->stat)); + get_stat_atime (&a->stat)); return diff ? diff : cmp (a->name, b->name); } static inline int cmp_size (struct fileinfo const *a, struct fileinfo const *b, - int (*cmp) (char const *, char const *)) + int (*cmp) (char const *, char const *)) { int diff = longdiff (b->stat.st_size, a->stat.st_size); return diff ? diff : cmp (a->name, b->name); @@ -3186,7 +3186,7 @@ cmp_size (struct fileinfo const *a, struct fileinfo const *b, static inline int cmp_name (struct fileinfo const *a, struct fileinfo const *b, - int (*cmp) (char const *, char const *)) + int (*cmp) (char const *, char const *)) { return cmp (a->name, b->name); } @@ -3196,7 +3196,7 @@ cmp_name (struct fileinfo const *a, struct fileinfo const *b, static inline int cmp_extension (struct fileinfo const *a, struct fileinfo const *b, - int (*cmp) (char const *, char const *)) + int (*cmp) (char const *, char const *)) { char const *base1 = strrchr (a->name, '.'); char const *base2 = strrchr (b->name, '.'); @@ -3296,7 +3296,7 @@ static qsortFunc const sort_functions[][2][2][2] = This line verifies at compile-time that the array of sort functions has been initialized for all possible sortkeys. */ verify (ARRAY_CARDINALITY (sort_functions) - == sort_numtypes + time_numtypes - 1 ); + == sort_numtypes + time_numtypes - 1 ); /* Set up SORTED_FILE to point to the in-use entries in CWD_FILE, in order. */ @@ -3343,9 +3343,9 @@ sort_files (void) /* When sort_type == sort_time, use time_type as subindex. */ mpsort ((void const **) sorted_file, cwd_n_used, - sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)] - [use_strcmp][sort_reverse] - [directories_first]); + sort_functions[sort_type + (sort_type == sort_time ? time_type : 0)] + [use_strcmp][sort_reverse] + [directories_first]); } /* List all the files now in the table. */ @@ -3359,10 +3359,10 @@ print_current_files (void) { case one_per_line: for (i = 0; i < cwd_n_used; i++) - { - print_file_name_and_frills (sorted_file[i], 0); - putchar ('\n'); - } + { + print_file_name_and_frills (sorted_file[i], 0); + putchar ('\n'); + } break; case many_per_line: @@ -3379,10 +3379,10 @@ print_current_files (void) case long_format: for (i = 0; i < cwd_n_used; i++) - { - print_long_format (sorted_file[i]); - DIRED_PUTCHAR ('\n'); - } + { + print_long_format (sorted_file[i]); + DIRED_PUTCHAR ('\n'); + } break; } } @@ -3393,7 +3393,7 @@ print_current_files (void) static size_t align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm, - int __utc, int __ns) + int __utc, int __ns) { const char *nfmt = fmt; /* In the unlikely event that rpl_fmt below is not large enough, @@ -3403,14 +3403,14 @@ align_nstrftime (char *buf, size_t size, char const *fmt, struct tm const *tm, if (required_mon_width && (pb = strstr (fmt, "%b"))) { if (strlen (fmt) < (sizeof (rpl_fmt) - sizeof (abmon[0]) + 2)) - { - char *pfmt = rpl_fmt; - nfmt = rpl_fmt; - - pfmt = mempcpy (pfmt, fmt, pb - fmt); - pfmt = stpcpy (pfmt, abmon[tm->tm_mon]); - strcpy (pfmt, pb + 2); - } + { + char *pfmt = rpl_fmt; + nfmt = rpl_fmt; + + pfmt = mempcpy (pfmt, fmt, pb - fmt); + pfmt = stpcpy (pfmt, abmon[tm->tm_mon]); + strcpy (pfmt, pb + 2); + } } size_t ret = nstrftime (buf, size, nfmt, tm, __utc, __ns); return ret; @@ -3431,22 +3431,22 @@ long_time_expected_width (void) char buf[TIME_STAMP_LEN_MAXIMUM + 1]; /* In case you're wondering if localtime can fail with an input time_t - value of 0, let's just say it's very unlikely, but not inconceivable. - The TZ environment variable would have to specify a time zone that - is 2**31-1900 years or more ahead of UTC. This could happen only on - a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000. - However, this is not possible with Solaris 10 or glibc-2.3.5, since - their implementations limit the offset to 167:59 and 24:00, resp. */ + value of 0, let's just say it's very unlikely, but not inconceivable. + The TZ environment variable would have to specify a time zone that + is 2**31-1900 years or more ahead of UTC. This could happen only on + a 64-bit system that blindly accepts e.g., TZ=UTC+20000000000000. + However, this is not possible with Solaris 10 or glibc-2.3.5, since + their implementations limit the offset to 167:59 and 24:00, resp. */ if (tm) - { - size_t len = - align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0); - if (len != 0) - width = mbsnwidth (buf, len, 0); - } + { + size_t len = + align_nstrftime (buf, sizeof buf, long_time_format[0], tm, 0, 0); + if (len != 0) + width = mbsnwidth (buf, len, 0); + } if (width < 0) - width = 0; + width = 0; } return width; @@ -3468,7 +3468,7 @@ format_user_or_group (char const *name, unsigned long int id, int width) len = strlen (name) + pad; do - putchar (' '); + putchar (' '); while (pad--); } else @@ -3487,7 +3487,7 @@ static void format_user (uid_t u, int width, bool stat_ok) { format_user_or_group (! stat_ok ? "?" : - (numeric_ids ? NULL : getuser (u)), u, width); + (numeric_ids ? NULL : getuser (u)), u, width); } /* Likewise, for groups. */ @@ -3496,7 +3496,7 @@ static void format_group (gid_t g, int width, bool stat_ok) { format_user_or_group (! stat_ok ? "?" : - (numeric_ids ? NULL : getgroup (g)), g, width); + (numeric_ids ? NULL : getgroup (g)), g, width); } /* Return the number of columns that format_user_or_group will print. */ @@ -3592,11 +3592,11 @@ print_long_format (const struct fileinfo *f) { char hbuf[INT_BUFSIZE_BOUND (uintmax_t)]; sprintf (p, "%*s ", inode_number_width, - (f->stat.st_ino == NOT_AN_INODE_NUMBER - ? "?" - : umaxtostr (f->stat.st_ino, hbuf))); + (f->stat.st_ino == NOT_AN_INODE_NUMBER + ? "?" + : umaxtostr (f->stat.st_ino, hbuf))); /* Increment by strlen (p) here, rather than by inode_number_width + 1. - The latter is wrong when inode_number_width is zero. */ + The latter is wrong when inode_number_width is zero. */ p += strlen (p); } @@ -3604,15 +3604,15 @@ print_long_format (const struct fileinfo *f) { char hbuf[LONGEST_HUMAN_READABLE + 1]; char const *blocks = - (! f->stat_ok - ? "?" - : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts, - ST_NBLOCKSIZE, output_block_size)); + (! f->stat_ok + ? "?" + : human_readable (ST_NBLOCKS (f->stat), hbuf, human_output_opts, + ST_NBLOCKSIZE, output_block_size)); int pad; for (pad = block_size_width - mbswidth (blocks, 0); 0 < pad; pad--) - *p++ = ' '; + *p++ = ' '; while ((*p++ = *blocks++)) - continue; + continue; p[-1] = ' '; } @@ -3621,7 +3621,7 @@ print_long_format (const struct fileinfo *f) { char hbuf[INT_BUFSIZE_BOUND (uintmax_t)]; sprintf (p, "%s %*s ", modebuf, nlink_width, - ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf)); + ! f->stat_ok ? "?" : umaxtostr (f->stat.st_nlink, hbuf)); } /* Increment by strlen (p) here, rather than by, e.g., sizeof modebuf - 2 + any_has_acl + 1 + nlink_width + 1. @@ -3635,16 +3635,16 @@ print_long_format (const struct fileinfo *f) DIRED_FPUTS (buf, stdout, p - buf); if (print_owner) - format_user (f->stat.st_uid, owner_width, f->stat_ok); + format_user (f->stat.st_uid, owner_width, f->stat_ok); if (print_group) - format_group (f->stat.st_gid, group_width, f->stat_ok); + format_group (f->stat.st_gid, group_width, f->stat_ok); if (print_author) - format_user (f->stat.st_author, author_width, f->stat_ok); + format_user (f->stat.st_author, author_width, f->stat_ok); if (print_scontext) - format_user_or_group (f->scontext, 0, scontext_width); + format_user_or_group (f->scontext, 0, scontext_width); p = buf; } @@ -3655,28 +3655,28 @@ print_long_format (const struct fileinfo *f) char majorbuf[INT_BUFSIZE_BOUND (uintmax_t)]; char minorbuf[INT_BUFSIZE_BOUND (uintmax_t)]; int blanks_width = (file_size_width - - (major_device_number_width + 2 - + minor_device_number_width)); + - (major_device_number_width + 2 + + minor_device_number_width)); sprintf (p, "%*s, %*s ", - major_device_number_width + MAX (0, blanks_width), - umaxtostr (major (f->stat.st_rdev), majorbuf), - minor_device_number_width, - umaxtostr (minor (f->stat.st_rdev), minorbuf)); + major_device_number_width + MAX (0, blanks_width), + umaxtostr (major (f->stat.st_rdev), majorbuf), + minor_device_number_width, + umaxtostr (minor (f->stat.st_rdev), minorbuf)); p += file_size_width + 1; } else { char hbuf[LONGEST_HUMAN_READABLE + 1]; char const *size = - (! f->stat_ok - ? "?" - : human_readable (unsigned_file_size (f->stat.st_size), - hbuf, human_output_opts, 1, file_output_block_size)); + (! f->stat_ok + ? "?" + : human_readable (unsigned_file_size (f->stat.st_size), + hbuf, human_output_opts, 1, file_output_block_size)); int pad; for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--) - *p++ = ' '; + *p++ = ' '; while ((*p++ = *size++)) - continue; + continue; p[-1] = ' '; } @@ -3691,32 +3691,32 @@ print_long_format (const struct fileinfo *f) char const *fmt; /* If the file appears to be in the future, update the current - time, in case the file happens to have been modified since - the last time we checked the clock. */ + time, in case the file happens to have been modified since + the last time we checked the clock. */ if (timespec_cmp (current_time, when_timespec) < 0) - { - /* Note that gettime may call gettimeofday which, on some non- - compliant systems, clobbers the buffer used for localtime's result. - But it's ok here, because we use a gettimeofday wrapper that - saves and restores the buffer around the gettimeofday call. */ - gettime (¤t_time); - } + { + /* Note that gettime may call gettimeofday which, on some non- + compliant systems, clobbers the buffer used for localtime's result. + But it's ok here, because we use a gettimeofday wrapper that + saves and restores the buffer around the gettimeofday call. */ + gettime (¤t_time); + } /* Consider a time to be recent if it is within the past six - months. A Gregorian year has 365.2425 * 24 * 60 * 60 == - 31556952 seconds on the average. Write this value as an - integer constant to avoid floating point hassles. */ + months. A Gregorian year has 365.2425 * 24 * 60 * 60 == + 31556952 seconds on the average. Write this value as an + integer constant to avoid floating point hassles. */ six_months_ago.tv_sec = current_time.tv_sec - 31556952 / 2; six_months_ago.tv_nsec = current_time.tv_nsec; recent = (timespec_cmp (six_months_ago, when_timespec) < 0 - && (timespec_cmp (when_timespec, current_time) < 0)); + && (timespec_cmp (when_timespec, current_time) < 0)); fmt = long_time_format[recent]; /* We assume here that all time zones are offset from UTC by a - whole number of seconds. */ + whole number of seconds. */ s = align_nstrftime (p, TIME_STAMP_LEN_MAXIMUM + 1, fmt, - when_local, 0, when_timespec.tv_nsec); + when_local, 0, when_timespec.tv_nsec); } if (s || !*p) @@ -3730,32 +3730,32 @@ print_long_format (const struct fileinfo *f) else { /* The time cannot be converted using the desired format, so - print it as a huge integer number of seconds. */ + print it as a huge integer number of seconds. */ char hbuf[INT_BUFSIZE_BOUND (intmax_t)]; sprintf (p, "%*s ", long_time_expected_width (), - (! f->stat_ok - ? "?" - : timetostr (when_timespec.tv_sec, hbuf))); + (! f->stat_ok + ? "?" + : timetostr (when_timespec.tv_sec, hbuf))); /* FIXME: (maybe) We discarded when_timespec.tv_nsec. */ p += strlen (p); } DIRED_FPUTS (buf, stdout, p - buf); size_t w = print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), f->linkok, - f->stat_ok, f->filetype, &dired_obstack, - f->stat.st_nlink, p - buf); + f->stat_ok, f->filetype, &dired_obstack, + f->stat.st_nlink, p - buf); if (f->filetype == symbolic_link) { if (f->linkname) - { - DIRED_FPUTS_LITERAL (" -> ", stdout); - print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1, - f->stat_ok, f->filetype, NULL, - f->stat.st_nlink, (p - buf) + w + 4); - if (indicator_style != none) - print_type_indicator (true, f->linkmode, unknown); - } + { + DIRED_FPUTS_LITERAL (" -> ", stdout); + print_name_with_quoting (f->linkname, f->linkmode, f->linkok - 1, + f->stat_ok, f->filetype, NULL, + f->stat.st_nlink, (p - buf) + w + 4); + if (indicator_style != none) + print_type_indicator (true, f->linkmode, unknown); + } } else if (indicator_style != none) print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype); @@ -3769,7 +3769,7 @@ print_long_format (const struct fileinfo *f) static size_t quote_name (FILE *out, const char *name, struct quoting_options const *options, - size_t *width) + size_t *width) { char smallbuf[BUFSIZ]; size_t len = quotearg_buffer (smallbuf, sizeof smallbuf, name, -1, options); @@ -3787,137 +3787,137 @@ quote_name (FILE *out, const char *name, struct quoting_options const *options, if (qmark_funny_chars) { if (MB_CUR_MAX > 1) - { - char const *p = buf; - char const *plimit = buf + len; - char *q = buf; - displayed_width = 0; - - while (p < plimit) - switch (*p) - { - case ' ': case '!': case '"': case '#': case '%': - case '&': case '\'': case '(': case ')': case '*': - case '+': case ',': case '-': case '.': case '/': - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - case ':': case ';': case '<': case '=': case '>': - case '?': - case 'A': case 'B': case 'C': case 'D': case 'E': - case 'F': case 'G': case 'H': case 'I': case 'J': - case 'K': case 'L': case 'M': case 'N': case 'O': - case 'P': case 'Q': case 'R': case 'S': case 'T': - case 'U': case 'V': case 'W': case 'X': case 'Y': - case 'Z': - case '[': case '\\': case ']': case '^': case '_': - case 'a': case 'b': case 'c': case 'd': case 'e': - case 'f': case 'g': case 'h': case 'i': case 'j': - case 'k': case 'l': case 'm': case 'n': case 'o': - case 'p': case 'q': case 'r': case 's': case 't': - case 'u': case 'v': case 'w': case 'x': case 'y': - case 'z': case '{': case '|': case '}': case '~': - /* These characters are printable ASCII characters. */ - *q++ = *p++; - displayed_width += 1; - break; - default: - /* If we have a multibyte sequence, copy it until we - reach its end, replacing each non-printable multibyte - character with a single question mark. */ - { - DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate); - do - { - wchar_t wc; - size_t bytes; - int w; - - bytes = mbrtowc (&wc, p, plimit - p, &mbstate); - - if (bytes == (size_t) -1) - { - /* An invalid multibyte sequence was - encountered. Skip one input byte, and - put a question mark. */ - p++; - *q++ = '?'; - displayed_width += 1; - break; - } - - if (bytes == (size_t) -2) - { - /* An incomplete multibyte character - at the end. Replace it entirely with - a question mark. */ - p = plimit; - *q++ = '?'; - displayed_width += 1; - break; - } - - if (bytes == 0) - /* A null wide character was encountered. */ - bytes = 1; - - w = wcwidth (wc); - if (w >= 0) - { - /* A printable multibyte character. - Keep it. */ - for (; bytes > 0; --bytes) - *q++ = *p++; - displayed_width += w; - } - else - { - /* An unprintable multibyte character. - Replace it entirely with a question - mark. */ - p += bytes; - *q++ = '?'; - displayed_width += 1; - } - } - while (! mbsinit (&mbstate)); - } - break; - } - - /* The buffer may have shrunk. */ - len = q - buf; - } + { + char const *p = buf; + char const *plimit = buf + len; + char *q = buf; + displayed_width = 0; + + while (p < plimit) + switch (*p) + { + case ' ': case '!': case '"': case '#': case '%': + case '&': case '\'': case '(': case ')': case '*': + case '+': case ',': case '-': case '.': case '/': + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + case ':': case ';': case '<': case '=': case '>': + case '?': + case 'A': case 'B': case 'C': case 'D': case 'E': + case 'F': case 'G': case 'H': case 'I': case 'J': + case 'K': case 'L': case 'M': case 'N': case 'O': + case 'P': case 'Q': case 'R': case 'S': case 'T': + case 'U': case 'V': case 'W': case 'X': case 'Y': + case 'Z': + case '[': case '\\': case ']': case '^': case '_': + case 'a': case 'b': case 'c': case 'd': case 'e': + case 'f': case 'g': case 'h': case 'i': case 'j': + case 'k': case 'l': case 'm': case 'n': case 'o': + case 'p': case 'q': case 'r': case 's': case 't': + case 'u': case 'v': case 'w': case 'x': case 'y': + case 'z': case '{': case '|': case '}': case '~': + /* These characters are printable ASCII characters. */ + *q++ = *p++; + displayed_width += 1; + break; + default: + /* If we have a multibyte sequence, copy it until we + reach its end, replacing each non-printable multibyte + character with a single question mark. */ + { + DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate); + do + { + wchar_t wc; + size_t bytes; + int w; + + bytes = mbrtowc (&wc, p, plimit - p, &mbstate); + + if (bytes == (size_t) -1) + { + /* An invalid multibyte sequence was + encountered. Skip one input byte, and + put a question mark. */ + p++; + *q++ = '?'; + displayed_width += 1; + break; + } + + if (bytes == (size_t) -2) + { + /* An incomplete multibyte character + at the end. Replace it entirely with + a question mark. */ + p = plimit; + *q++ = '?'; + displayed_width += 1; + break; + } + + if (bytes == 0) + /* A null wide character was encountered. */ + bytes = 1; + + w = wcwidth (wc); + if (w >= 0) + { + /* A printable multibyte character. + Keep it. */ + for (; bytes > 0; --bytes) + *q++ = *p++; + displayed_width += w; + } + else + { + /* An unprintable multibyte character. + Replace it entirely with a question + mark. */ + p += bytes; + *q++ = '?'; + displayed_width += 1; + } + } + while (! mbsinit (&mbstate)); + } + break; + } + + /* The buffer may have shrunk. */ + len = q - buf; + } else - { - char *p = buf; - char const *plimit = buf + len; - - while (p < plimit) - { - if (! isprint (to_uchar (*p))) - *p = '?'; - p++; - } - displayed_width = len; - } + { + char *p = buf; + char const *plimit = buf + len; + + while (p < plimit) + { + if (! isprint (to_uchar (*p))) + *p = '?'; + p++; + } + displayed_width = len; + } } else if (width != NULL) { if (MB_CUR_MAX > 1) - displayed_width = mbsnwidth (buf, len, 0); + displayed_width = mbsnwidth (buf, len, 0); else - { - char const *p = buf; - char const *plimit = buf + len; - - displayed_width = 0; - while (p < plimit) - { - if (isprint (to_uchar (*p))) - displayed_width++; - p++; - } - } + { + char const *p = buf; + char const *plimit = buf + len; + + displayed_width = 0; + while (p < plimit) + { + if (isprint (to_uchar (*p))) + displayed_width++; + p++; + } + } } if (out != NULL) @@ -3929,9 +3929,9 @@ quote_name (FILE *out, const char *name, struct quoting_options const *options, static size_t print_name_with_quoting (const char *p, mode_t mode, int linkok, - bool stat_ok, enum filetype type, - struct obstack *stack, nlink_t nlink, - size_t start_col) + bool stat_ok, enum filetype type, + struct obstack *stack, nlink_t nlink, + size_t start_col) { bool used_color_this_time = (print_with_color @@ -3951,7 +3951,7 @@ print_name_with_quoting (const char *p, mode_t mode, int linkok, process_signals (); prep_non_filename_text (); if (start_col / line_length != (start_col + width - 1) / line_length) - put_indicator (&color_indicator[C_CLR_TO_EOL]); + put_indicator (&color_indicator[C_CLR_TO_EOL]); } return width; @@ -3981,19 +3981,19 @@ print_file_name_and_frills (const struct fileinfo *f, size_t start_col) if (print_inode) printf ("%*s ", format == with_commas ? 0 : inode_number_width, - umaxtostr (f->stat.st_ino, buf)); + umaxtostr (f->stat.st_ino, buf)); if (print_block_size) printf ("%*s ", format == with_commas ? 0 : block_size_width, - human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts, - ST_NBLOCKSIZE, output_block_size)); + human_readable (ST_NBLOCKS (f->stat), buf, human_output_opts, + ST_NBLOCKSIZE, output_block_size)); if (print_scontext) printf ("%*s ", format == with_commas ? 0 : scontext_width, f->scontext); size_t width = print_name_with_quoting (f->name, FILE_OR_LINK_MODE (f), - f->linkok, f->stat_ok, f->filetype, - NULL, f->stat.st_nlink, start_col); + f->linkok, f->stat_ok, f->filetype, + NULL, f->stat.st_nlink, start_col); if (indicator_style != none) width += print_type_indicator (f->stat_ok, f->stat.st_mode, f->filetype); @@ -4011,26 +4011,26 @@ get_type_indicator (bool stat_ok, mode_t mode, enum filetype type) if (stat_ok ? S_ISREG (mode) : type == normal) { if (stat_ok && indicator_style == classify && (mode & S_IXUGO)) - c = '*'; + c = '*'; else - c = 0; + c = 0; } else { if (stat_ok ? S_ISDIR (mode) : type == directory || type == arg_directory) - c = '/'; + c = '/'; else if (indicator_style == slash) - c = 0; + c = 0; else if (stat_ok ? S_ISLNK (mode) : type == symbolic_link) - c = '@'; + c = '@'; else if (stat_ok ? S_ISFIFO (mode) : type == fifo) - c = '|'; + c = '|'; else if (stat_ok ? S_ISSOCK (mode) : type == sock) - c = '='; + c = '='; else if (stat_ok && S_ISDOOR (mode)) - c = '>'; + c = '>'; else - c = 0; + c = 0; } return c; } @@ -4078,8 +4078,8 @@ has_capability (char const *name ATTRIBUTE_UNUSED) /* Returns whether any color sequence was printed. */ static bool print_color_indicator (const char *name, mode_t mode, int linkok, - bool stat_ok, enum filetype filetype, - nlink_t nlink) + bool stat_ok, enum filetype filetype, + nlink_t nlink) { int type; struct color_ext_type *ext; /* Color extension */ @@ -4097,48 +4097,48 @@ print_color_indicator (const char *name, mode_t mode, int linkok, else { if (S_ISREG (mode)) - { - type = C_FILE; - if ((mode & S_ISUID) != 0) - type = C_SETUID; - else if ((mode & S_ISGID) != 0) - type = C_SETGID; - else if (is_colored (C_CAP) && has_capability (name)) - type = C_CAP; - else if ((mode & S_IXUGO) != 0) - type = C_EXEC; - else if (is_colored (C_MULTIHARDLINK) && (1 < nlink)) - type = C_MULTIHARDLINK; - } + { + type = C_FILE; + if ((mode & S_ISUID) != 0) + type = C_SETUID; + else if ((mode & S_ISGID) != 0) + type = C_SETGID; + else if (is_colored (C_CAP) && has_capability (name)) + type = C_CAP; + else if ((mode & S_IXUGO) != 0) + type = C_EXEC; + else if (is_colored (C_MULTIHARDLINK) && (1 < nlink)) + type = C_MULTIHARDLINK; + } else if (S_ISDIR (mode)) - { - if ((mode & S_ISVTX) && (mode & S_IWOTH)) - type = C_STICKY_OTHER_WRITABLE; - else if ((mode & S_IWOTH) != 0) - type = C_OTHER_WRITABLE; - else if ((mode & S_ISVTX) != 0) - type = C_STICKY; - else - type = C_DIR; - } + { + if ((mode & S_ISVTX) && (mode & S_IWOTH)) + type = C_STICKY_OTHER_WRITABLE; + else if ((mode & S_IWOTH) != 0) + type = C_OTHER_WRITABLE; + else if ((mode & S_ISVTX) != 0) + type = C_STICKY; + else + type = C_DIR; + } else if (S_ISLNK (mode)) - type = ((!linkok && color_indicator[C_ORPHAN].string) - ? C_ORPHAN : C_LINK); + type = ((!linkok && color_indicator[C_ORPHAN].string) + ? C_ORPHAN : C_LINK); else if (S_ISFIFO (mode)) - type = C_FIFO; + type = C_FIFO; else if (S_ISSOCK (mode)) - type = C_SOCK; + type = C_SOCK; else if (S_ISBLK (mode)) - type = C_BLK; + type = C_BLK; else if (S_ISCHR (mode)) - type = C_CHR; + type = C_CHR; else if (S_ISDOOR (mode)) - type = C_DOOR; + type = C_DOOR; else - { - /* Classify a file of some other type as C_ORPHAN. */ - type = C_ORPHAN; - } + { + /* Classify a file of some other type as C_ORPHAN. */ + type = C_ORPHAN; + } } /* Check the file's suffix only if still classified as C_FILE. */ @@ -4150,12 +4150,12 @@ print_color_indicator (const char *name, mode_t mode, int linkok, len = strlen (name); name += len; /* Pointer to final \0. */ for (ext = color_ext_list; ext != NULL; ext = ext->next) - { - if (ext->ext.len <= len - && strncmp (name - ext->ext.len, ext->ext.string, - ext->ext.len) == 0) - break; - } + { + if (ext->ext.len <= len + && strncmp (name - ext->ext.len, ext->ext.string, + ext->ext.len) == 0) + break; + } } { @@ -4163,10 +4163,10 @@ print_color_indicator (const char *name, mode_t mode, int linkok, = ext ? &(ext->seq) : &color_indicator[type]; if (s->string != NULL) { - put_indicator (&color_indicator[C_LEFT]); - put_indicator (s); - put_indicator (&color_indicator[C_RIGHT]); - return true; + put_indicator (&color_indicator[C_LEFT]); + put_indicator (s); + put_indicator (&color_indicator[C_RIGHT]); + return true; } else return false; @@ -4195,15 +4195,15 @@ length_of_file_name_and_frills (const struct fileinfo *f) if (print_inode) len += 1 + (format == with_commas - ? strlen (umaxtostr (f->stat.st_ino, buf)) - : inode_number_width); + ? strlen (umaxtostr (f->stat.st_ino, buf)) + : inode_number_width); if (print_block_size) len += 1 + (format == with_commas - ? strlen (human_readable (ST_NBLOCKS (f->stat), buf, - human_output_opts, ST_NBLOCKSIZE, - output_block_size)) - : block_size_width); + ? strlen (human_readable (ST_NBLOCKS (f->stat), buf, + human_output_opts, ST_NBLOCKSIZE, + output_block_size)) + : block_size_width); if (print_scontext) len += 1 + (format == with_commas ? strlen (f->scontext) : scontext_width); @@ -4239,19 +4239,19 @@ print_many_per_line (void) /* Print the next row. */ while (1) - { - struct fileinfo const *f = sorted_file[filesno]; - size_t name_length = length_of_file_name_and_frills (f); - size_t max_name_length = line_fmt->col_arr[col++]; - print_file_name_and_frills (f, pos); - - filesno += rows; - if (filesno >= cwd_n_used) - break; - - indent (pos + name_length, pos + max_name_length); - pos += max_name_length; - } + { + struct fileinfo const *f = sorted_file[filesno]; + size_t name_length = length_of_file_name_and_frills (f); + size_t max_name_length = line_fmt->col_arr[col++]; + print_file_name_and_frills (f, pos); + + filesno += rows; + if (filesno >= cwd_n_used) + break; + + indent (pos + name_length, pos + max_name_length); + pos += max_name_length; + } putchar ('\n'); } } @@ -4276,15 +4276,15 @@ print_horizontal (void) size_t col = filesno % cols; if (col == 0) - { - putchar ('\n'); - pos = 0; - } + { + putchar ('\n'); + pos = 0; + } else - { - indent (pos + name_length, pos + max_name_length); - pos += max_name_length; - } + { + indent (pos + name_length, pos + max_name_length); + pos += max_name_length; + } f = sorted_file[filesno]; print_file_name_and_frills (f, pos); @@ -4307,23 +4307,23 @@ print_with_commas (void) size_t len = length_of_file_name_and_frills (f); if (filesno != 0) - { - char separator; - - if (pos + len + 2 < line_length) - { - pos += 2; - separator = ' '; - } - else - { - pos = 0; - separator = '\n'; - } - - putchar (','); - putchar (separator); - } + { + char separator; + + if (pos + len + 2 < line_length) + { + pos += 2; + separator = ' '; + } + else + { + pos = 0; + separator = '\n'; + } + + putchar (','); + putchar (separator); + } print_file_name_and_frills (f, pos); pos += len; @@ -4340,15 +4340,15 @@ indent (size_t from, size_t to) while (from < to) { if (tabsize != 0 && to / tabsize > (from + 1) / tabsize) - { - putchar ('\t'); - from += tabsize - from % tabsize; - } + { + putchar ('\t'); + from += tabsize - from % tabsize; + } else - { - putchar (' '); - from++; - } + { + putchar (' '); + from++; + } } } @@ -4365,10 +4365,10 @@ attach (char *dest, const char *dirname, const char *name) if (dirname[0] != '.' || dirname[1] != 0) { while (*dirnamep) - *dest++ = *dirnamep++; + *dest++ = *dirnamep++; /* Add '/' if `dirname' doesn't already end with it. */ if (dirnamep > dirname && dirnamep[-1] != '/') - *dest++ = '/'; + *dest++ = '/'; } while (*name) *dest++ = *name++; @@ -4394,41 +4394,41 @@ init_column_info (void) size_t *p; if (max_cols < max_idx / 2) - { - /* The number of columns is far less than the display width - allows. Grow the allocation, but only so that it's - double the current requirements. If the display is - extremely wide, this avoids allocating a lot of memory - that is never needed. */ - column_info = xnrealloc (column_info, max_cols, - 2 * sizeof *column_info); - new_column_info_alloc = 2 * max_cols; - } + { + /* The number of columns is far less than the display width + allows. Grow the allocation, but only so that it's + double the current requirements. If the display is + extremely wide, this avoids allocating a lot of memory + that is never needed. */ + column_info = xnrealloc (column_info, max_cols, + 2 * sizeof *column_info); + new_column_info_alloc = 2 * max_cols; + } else - { - column_info = xnrealloc (column_info, max_idx, sizeof *column_info); - new_column_info_alloc = max_idx; - } + { + column_info = xnrealloc (column_info, max_idx, sizeof *column_info); + new_column_info_alloc = max_idx; + } /* Allocate the new size_t objects by computing the triangle - formula n * (n + 1) / 2, except that we don't need to - allocate the part of the triangle that we've already - allocated. Check for address arithmetic overflow. */ + formula n * (n + 1) / 2, except that we don't need to + allocate the part of the triangle that we've already + allocated. Check for address arithmetic overflow. */ { - size_t column_info_growth = new_column_info_alloc - column_info_alloc; - size_t s = column_info_alloc + 1 + new_column_info_alloc; - size_t t = s * column_info_growth; - if (s < new_column_info_alloc || t / column_info_growth != s) - xalloc_die (); - p = xnmalloc (t / 2, sizeof *p); + size_t column_info_growth = new_column_info_alloc - column_info_alloc; + size_t s = column_info_alloc + 1 + new_column_info_alloc; + size_t t = s * column_info_growth; + if (s < new_column_info_alloc || t / column_info_growth != s) + xalloc_die (); + p = xnmalloc (t / 2, sizeof *p); } /* Grow the triangle by parceling out the cells just allocated. */ for (i = column_info_alloc; i < new_column_info_alloc; i++) - { - column_info[i].col_arr = p; - p += i + 1; - } + { + column_info[i].col_arr = p; + p += i + 1; + } column_info_alloc = new_column_info_alloc; } @@ -4440,7 +4440,7 @@ init_column_info (void) column_info[i].valid_len = true; column_info[i].line_len = (i + 1) * MIN_COLUMN_WIDTH; for (j = 0; j <= i; ++j) - column_info[i].col_arr[j] = MIN_COLUMN_WIDTH; + column_info[i].col_arr[j] = MIN_COLUMN_WIDTH; } } @@ -4468,31 +4468,31 @@ calculate_columns (bool by_columns) size_t i; for (i = 0; i < max_cols; ++i) - { - if (column_info[i].valid_len) - { - size_t idx = (by_columns - ? filesno / ((cwd_n_used + i) / (i + 1)) - : filesno % (i + 1)); - size_t real_length = name_length + (idx == i ? 0 : 2); - - if (column_info[i].col_arr[idx] < real_length) - { - column_info[i].line_len += (real_length - - column_info[i].col_arr[idx]); - column_info[i].col_arr[idx] = real_length; - column_info[i].valid_len = (column_info[i].line_len - < line_length); - } - } - } + { + if (column_info[i].valid_len) + { + size_t idx = (by_columns + ? filesno / ((cwd_n_used + i) / (i + 1)) + : filesno % (i + 1)); + size_t real_length = name_length + (idx == i ? 0 : 2); + + if (column_info[i].col_arr[idx] < real_length) + { + column_info[i].line_len += (real_length + - column_info[i].col_arr[idx]); + column_info[i].col_arr[idx] = real_length; + column_info[i].valid_len = (column_info[i].line_len + < line_length); + } + } + } } /* Find maximum allowed columns. */ for (cols = max_cols; 1 < cols; --cols) { if (column_info[cols - 1].valid_len) - break; + break; } return cols; @@ -4503,7 +4503,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name); diff --git a/src/md5sum.c b/src/md5sum.c index 1b1ae6aa0..c8e01efb8 100644 --- a/src/md5sum.c +++ b/src/md5sum.c @@ -147,7 +147,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -156,26 +156,26 @@ Print or check %s (%d-bit) checksums.\n\ With no FILE, or when FILE is -, read standard input.\n\ \n\ "), - program_name, - DIGEST_TYPE_STRING, - DIGEST_BITS); + program_name, + DIGEST_TYPE_STRING, + DIGEST_BITS); if (O_BINARY) - fputs (_("\ + fputs (_("\ -b, --binary read in binary mode (default unless reading tty stdin)\n\ "), stdout); else - fputs (_("\ + fputs (_("\ -b, --binary read in binary mode\n\ "), stdout); printf (_("\ -c, --check read %s sums from the FILEs and check them\n"), - DIGEST_TYPE_STRING); + DIGEST_TYPE_STRING); if (O_BINARY) - fputs (_("\ + fputs (_("\ -t, --text read in text mode (default if reading tty stdin)\n\ "), stdout); else - fputs (_("\ + fputs (_("\ -t, --text read in text mode (default)\n\ "), stdout); fputs (_("\ @@ -194,7 +194,7 @@ The sums are computed as described in %s. When checking, the input\n\ should be a former output of this program. The default mode is to print\n\ a line with checksum, a character indicating type (`*' for binary, ` ' for\n\ text), and name for each FILE.\n"), - DIGEST_REFERENCE); + DIGEST_REFERENCE); emit_bug_reporting_address (); } @@ -249,7 +249,7 @@ bsd_split_3 (char *s, size_t s_len, unsigned char **hex_digest, char **file_name static bool split_3 (char *s, size_t s_len, - unsigned char **hex_digest, int *binary, char **file_name) + unsigned char **hex_digest, int *binary, char **file_name) { size_t i; bool escaped_filename = false; @@ -264,12 +264,12 @@ split_3 (char *s, size_t s_len, if (strncmp (s + i, DIGEST_TYPE_STRING, algo_name_len) == 0) { if (strncmp (s + i + algo_name_len, " (", 2) == 0) - { - *binary = 0; - return bsd_split_3 (s + i + algo_name_len + 2, - s_len - (i + algo_name_len + 2), - hex_digest, file_name); - } + { + *binary = 0; + return bsd_split_3 (s + i + algo_name_len + 2, + s_len - (i + algo_name_len + 2), + hex_digest, file_name); + } } /* Ignore this line if it is too short. @@ -306,45 +306,45 @@ split_3 (char *s, size_t s_len, if (escaped_filename) { /* Translate each `\n' string in the file name to a NEWLINE, - and each `\\' string to a backslash. */ + and each `\\' string to a backslash. */ char *dst = &s[i]; while (i < s_len) - { - switch (s[i]) - { - case '\\': - if (i == s_len - 1) - { - /* A valid line does not end with a backslash. */ - return false; - } - ++i; - switch (s[i++]) - { - case 'n': - *dst++ = '\n'; - break; - case '\\': - *dst++ = '\\'; - break; - default: - /* Only `\' or `n' may follow a backslash. */ - return false; - } - break; - - case '\0': - /* The file name may not contain a NUL. */ - return false; - break; - - default: - *dst++ = s[i++]; - break; - } - } + { + switch (s[i]) + { + case '\\': + if (i == s_len - 1) + { + /* A valid line does not end with a backslash. */ + return false; + } + ++i; + switch (s[i++]) + { + case 'n': + *dst++ = '\n'; + break; + case '\\': + *dst++ = '\\'; + break; + default: + /* Only `\' or `n' may follow a backslash. */ + return false; + } + break; + + case '\0': + /* The file name may not contain a NUL. */ + return false; + break; + + default: + *dst++ = s[i++]; + break; + } + } *dst = '\0'; } return true; @@ -388,21 +388,21 @@ digest_file (const char *filename, int *binary, unsigned char *bin_result) have_read_stdin = true; fp = stdin; if (O_BINARY && *binary) - { - if (*binary < 0) - *binary = ! isatty (STDIN_FILENO); - if (*binary) - xfreopen (NULL, "rb", stdin); - } + { + if (*binary < 0) + *binary = ! isatty (STDIN_FILENO); + if (*binary) + xfreopen (NULL, "rb", stdin); + } } else { fp = fopen (filename, (O_BINARY && *binary ? "rb" : "r")); if (fp == NULL) - { - error (0, errno, "%s", filename); - return false; - } + { + error (0, errno, "%s", filename); + return false; + } } err = DIGEST_STREAM (fp, bin_result); @@ -410,7 +410,7 @@ digest_file (const char *filename, int *binary, unsigned char *bin_result) { error (0, errno, "%s", filename); if (fp != stdin) - fclose (fp); + fclose (fp); return false; } @@ -448,10 +448,10 @@ digest_check (const char *checkfile_name) { checkfile_stream = fopen (checkfile_name, "r"); if (checkfile_stream == NULL) - { - error (0, errno, "%s", checkfile_name); - return false; - } + { + error (0, errno, "%s", checkfile_name); + return false; + } } line_number = 0; @@ -466,82 +466,82 @@ digest_check (const char *checkfile_name) ++line_number; if (line_number == 0) - error (EXIT_FAILURE, 0, _("%s: too many checksum lines"), - checkfile_name); + error (EXIT_FAILURE, 0, _("%s: too many checksum lines"), + checkfile_name); line_length = getline (&line, &line_chars_allocated, checkfile_stream); if (line_length <= 0) - break; + break; /* Ignore comment lines, which begin with a '#' character. */ if (line[0] == '#') - continue; + continue; /* Remove any trailing newline. */ if (line[line_length - 1] == '\n') - line[--line_length] = '\0'; + line[--line_length] = '\0'; if (! (split_3 (line, line_length, &hex_digest, &binary, &filename) - && ! (is_stdin && STREQ (filename, "-")) - && hex_digits (hex_digest))) - { - if (warn) - { - error (0, 0, - _("%s: %" PRIuMAX - ": improperly formatted %s checksum line"), - checkfile_name, line_number, - DIGEST_TYPE_STRING); - } - } + && ! (is_stdin && STREQ (filename, "-")) + && hex_digits (hex_digest))) + { + if (warn) + { + error (0, 0, + _("%s: %" PRIuMAX + ": improperly formatted %s checksum line"), + checkfile_name, line_number, + DIGEST_TYPE_STRING); + } + } else - { - static const char bin2hex[] = { '0', '1', '2', '3', - '4', '5', '6', '7', - '8', '9', 'a', 'b', - 'c', 'd', 'e', 'f' }; - bool ok; - - ++n_properly_formatted_lines; - - ok = digest_file (filename, &binary, bin_buffer); - - if (!ok) - { - ++n_open_or_read_failures; - if (!status_only) - { - printf (_("%s: FAILED open or read\n"), filename); - fflush (stdout); - } - } - else - { - size_t digest_bin_bytes = digest_hex_bytes / 2; - size_t cnt; - /* Compare generated binary number with text representation - in check file. Ignore case of hex digits. */ - for (cnt = 0; cnt < digest_bin_bytes; ++cnt) - { - if (tolower (hex_digest[2 * cnt]) - != bin2hex[bin_buffer[cnt] >> 4] - || (tolower (hex_digest[2 * cnt + 1]) - != (bin2hex[bin_buffer[cnt] & 0xf]))) - break; - } - if (cnt != digest_bin_bytes) - ++n_mismatched_checksums; - - if (!status_only) - { - if (cnt != digest_bin_bytes) - printf ("%s: %s\n", filename, _("FAILED")); - else if (!quiet) - printf ("%s: %s\n", filename, _("OK")); - fflush (stdout); - } - } - } + { + static const char bin2hex[] = { '0', '1', '2', '3', + '4', '5', '6', '7', + '8', '9', 'a', 'b', + 'c', 'd', 'e', 'f' }; + bool ok; + + ++n_properly_formatted_lines; + + ok = digest_file (filename, &binary, bin_buffer); + + if (!ok) + { + ++n_open_or_read_failures; + if (!status_only) + { + printf (_("%s: FAILED open or read\n"), filename); + fflush (stdout); + } + } + else + { + size_t digest_bin_bytes = digest_hex_bytes / 2; + size_t cnt; + /* Compare generated binary number with text representation + in check file. Ignore case of hex digits. */ + for (cnt = 0; cnt < digest_bin_bytes; ++cnt) + { + if (tolower (hex_digest[2 * cnt]) + != bin2hex[bin_buffer[cnt] >> 4] + || (tolower (hex_digest[2 * cnt + 1]) + != (bin2hex[bin_buffer[cnt] & 0xf]))) + break; + } + if (cnt != digest_bin_bytes) + ++n_mismatched_checksums; + + if (!status_only) + { + if (cnt != digest_bin_bytes) + printf ("%s: %s\n", filename, _("FAILED")); + else if (!quiet) + printf ("%s: %s\n", filename, _("OK")); + fflush (stdout); + } + } + } } while (!feof (checkfile_stream) && !ferror (checkfile_stream)); @@ -563,39 +563,39 @@ digest_check (const char *checkfile_name) { /* Warn if no tests are found. */ error (0, 0, _("%s: no properly formatted %s checksum lines found"), - checkfile_name, DIGEST_TYPE_STRING); + checkfile_name, DIGEST_TYPE_STRING); } else { if (!status_only) - { - if (n_open_or_read_failures != 0) - error (0, 0, - ngettext ("WARNING: %" PRIuMAX " of %" PRIuMAX - " listed file could not be read", - "WARNING: %" PRIuMAX " of %" PRIuMAX - " listed files could not be read", - select_plural (n_properly_formatted_lines)), - n_open_or_read_failures, n_properly_formatted_lines); - - if (n_mismatched_checksums != 0) - { - uintmax_t n_computed_checksums = - (n_properly_formatted_lines - n_open_or_read_failures); - error (0, 0, - ngettext ("WARNING: %" PRIuMAX " of %" PRIuMAX - " computed checksum did NOT match", - "WARNING: %" PRIuMAX " of %" PRIuMAX - " computed checksums did NOT match", - select_plural (n_computed_checksums)), - n_mismatched_checksums, n_computed_checksums); - } - } + { + if (n_open_or_read_failures != 0) + error (0, 0, + ngettext ("WARNING: %" PRIuMAX " of %" PRIuMAX + " listed file could not be read", + "WARNING: %" PRIuMAX " of %" PRIuMAX + " listed files could not be read", + select_plural (n_properly_formatted_lines)), + n_open_or_read_failures, n_properly_formatted_lines); + + if (n_mismatched_checksums != 0) + { + uintmax_t n_computed_checksums = + (n_properly_formatted_lines - n_open_or_read_failures); + error (0, 0, + ngettext ("WARNING: %" PRIuMAX " of %" PRIuMAX + " computed checksum did NOT match", + "WARNING: %" PRIuMAX " of %" PRIuMAX + " computed checksums did NOT match", + select_plural (n_computed_checksums)), + n_mismatched_checksums, n_computed_checksums); + } + } } return (n_properly_formatted_lines != 0 - && n_mismatched_checksums == 0 - && n_open_or_read_failures == 0); + && n_mismatched_checksums == 0 + && n_open_or_read_failures == 0); } int @@ -622,33 +622,33 @@ main (int argc, char **argv) switch (opt) { case 'b': - binary = 1; - break; + binary = 1; + break; case 'c': - do_check = true; - break; + do_check = true; + break; case STATUS_OPTION: - status_only = true; - warn = false; - quiet = false; - break; + status_only = true; + warn = false; + quiet = false; + break; case 't': - binary = 0; - break; + binary = 0; + break; case 'w': - status_only = false; - warn = true; - quiet = false; - break; + status_only = false; + warn = true; + quiet = false; + break; case QUIET_OPTION: - status_only = false; - warn = false; - quiet = true; - break; + status_only = false; + warn = false; + quiet = true; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } min_digest_line_length = MIN_DIGEST_LINE_LENGTH; @@ -657,7 +657,7 @@ main (int argc, char **argv) if (0 <= binary && do_check) { error (0, 0, _("the --binary and --text options are meaningless when " - "verifying checksums")); + "verifying checksums")); usage (EXIT_FAILURE); } @@ -693,53 +693,53 @@ main (int argc, char **argv) char *file = argv[optind]; if (do_check) - ok &= digest_check (file); + ok &= digest_check (file); else - { - int file_is_binary = binary; - - if (! digest_file (file, &file_is_binary, bin_buffer)) - ok = false; - else - { - size_t i; - - /* Output a leading backslash if the file name contains - a newline or backslash. */ - if (strchr (file, '\n') || strchr (file, '\\')) - putchar ('\\'); - - for (i = 0; i < (digest_hex_bytes / 2); ++i) - printf ("%02x", bin_buffer[i]); - - putchar (' '); - if (file_is_binary) - putchar ('*'); - else - putchar (' '); - - /* Translate each NEWLINE byte to the string, "\\n", - and each backslash to "\\\\". */ - for (i = 0; i < strlen (file); ++i) - { - switch (file[i]) - { - case '\n': - fputs ("\\n", stdout); - break; - - case '\\': - fputs ("\\\\", stdout); - break; - - default: - putchar (file[i]); - break; - } - } - putchar ('\n'); - } - } + { + int file_is_binary = binary; + + if (! digest_file (file, &file_is_binary, bin_buffer)) + ok = false; + else + { + size_t i; + + /* Output a leading backslash if the file name contains + a newline or backslash. */ + if (strchr (file, '\n') || strchr (file, '\\')) + putchar ('\\'); + + for (i = 0; i < (digest_hex_bytes / 2); ++i) + printf ("%02x", bin_buffer[i]); + + putchar (' '); + if (file_is_binary) + putchar ('*'); + else + putchar (' '); + + /* Translate each NEWLINE byte to the string, "\\n", + and each backslash to "\\\\". */ + for (i = 0; i < strlen (file); ++i) + { + switch (file[i]) + { + case '\n': + fputs ("\\n", stdout); + break; + + case '\\': + fputs ("\\\\", stdout); + break; + + default: + putchar (file[i]); + break; + } + } + putchar ('\n'); + } + } } if (have_read_stdin && fclose (stdin) == EOF) diff --git a/src/mkdir.c b/src/mkdir.c index 17e1df5b8..4ae487593 100644 --- a/src/mkdir.c +++ b/src/mkdir.c @@ -51,7 +51,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... DIRECTORY...\n"), program_name); @@ -129,10 +129,10 @@ process_dir (char *dir, struct savewd *wd, void *options) { struct mkdir_options const *o = options; return (make_dir_parents (dir, wd, o->make_ancestor_function, options, - o->mode, announce_mkdir, - o->mode_bits, (uid_t) -1, (gid_t) -1, true) - ? EXIT_SUCCESS - : EXIT_FAILURE); + o->mode, announce_mkdir, + o->mode_bits, (uid_t) -1, (gid_t) -1, true) + ? EXIT_SUCCESS + : EXIT_FAILURE); } int @@ -159,24 +159,24 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "pm:vZ:", longopts, NULL)) != -1) { switch (optc) - { - case 'p': - options.make_ancestor_function = make_ancestor; - break; - case 'm': - specified_mode = optarg; - break; - case 'v': /* --verbose */ - options.created_directory_format = _("created directory %s"); - break; - case 'Z': - scontext = optarg; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'p': + options.make_ancestor_function = make_ancestor; + break; + case 'm': + specified_mode = optarg; + break; + case 'v': /* --verbose */ + options.created_directory_format = _("created directory %s"); + break; + case 'Z': + scontext = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (optind == argc) @@ -187,8 +187,8 @@ main (int argc, char **argv) if (scontext && setfscreatecon (scontext) < 0) error (EXIT_FAILURE, errno, - _("failed to set default file creation context to %s"), - quote (scontext)); + _("failed to set default file creation context to %s"), + quote (scontext)); if (options.make_ancestor_function || specified_mode) { @@ -197,19 +197,19 @@ main (int argc, char **argv) options.ancestor_mode = (S_IRWXUGO & ~umask_value) | (S_IWUSR | S_IXUSR); if (specified_mode) - { - struct mode_change *change = mode_compile (specified_mode); - if (!change) - error (EXIT_FAILURE, 0, _("invalid mode %s"), - quote (specified_mode)); - options.mode = mode_adjust (S_IRWXUGO, true, umask_value, change, - &options.mode_bits); - free (change); - } + { + struct mode_change *change = mode_compile (specified_mode); + if (!change) + error (EXIT_FAILURE, 0, _("invalid mode %s"), + quote (specified_mode)); + options.mode = mode_adjust (S_IRWXUGO, true, umask_value, change, + &options.mode_bits); + free (change); + } else - options.mode = S_IRWXUGO & ~umask_value; + options.mode = S_IRWXUGO & ~umask_value; } exit (savewd_process_files (argc - optind, argv + optind, - process_dir, &options)); + process_dir, &options)); } diff --git a/src/mkfifo.c b/src/mkfifo.c index 74210d435..5ea3e3b82 100644 --- a/src/mkfifo.c +++ b/src/mkfifo.c @@ -46,7 +46,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... NAME...\n"), program_name); @@ -90,18 +90,18 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "m:Z:", longopts, NULL)) != -1) { switch (optc) - { - case 'm': - specified_mode = optarg; - break; - case 'Z': - scontext = optarg; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'm': + specified_mode = optarg; + break; + case 'Z': + scontext = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (optind == argc) @@ -112,27 +112,27 @@ main (int argc, char **argv) if (scontext && setfscreatecon (scontext) < 0) error (EXIT_FAILURE, errno, - _("failed to set default file creation context to %s"), - quote (scontext)); + _("failed to set default file creation context to %s"), + quote (scontext)); newmode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (specified_mode) { struct mode_change *change = mode_compile (specified_mode); if (!change) - error (EXIT_FAILURE, 0, _("invalid mode")); + error (EXIT_FAILURE, 0, _("invalid mode")); newmode = mode_adjust (newmode, false, umask (0), change, NULL); free (change); if (newmode & ~S_IRWXUGO) - error (EXIT_FAILURE, 0, - _("mode must specify only file permission bits")); + error (EXIT_FAILURE, 0, + _("mode must specify only file permission bits")); } for (; optind < argc; ++optind) if (mkfifo (argv[optind], newmode) != 0) { - error (0, errno, _("cannot create fifo %s"), quote (argv[optind])); - exit_status = EXIT_FAILURE; + error (0, errno, _("cannot create fifo %s"), quote (argv[optind])); + exit_status = EXIT_FAILURE; } exit (exit_status); diff --git a/src/mknod.c b/src/mknod.c index 9422bdbd8..94e4471ef 100644 --- a/src/mknod.c +++ b/src/mknod.c @@ -47,11 +47,11 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... NAME TYPE [MAJOR MINOR]\n"), - program_name); + program_name); fputs (_("\ Create the special file NAME of the given TYPE.\n\ \n\ @@ -107,18 +107,18 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "m:Z:", longopts, NULL)) != -1) { switch (optc) - { - case 'm': - specified_mode = optarg; - break; - case 'Z': - scontext = optarg; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'm': + specified_mode = optarg; + break; + case 'Z': + scontext = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } newmode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); @@ -126,47 +126,47 @@ main (int argc, char **argv) { struct mode_change *change = mode_compile (specified_mode); if (!change) - error (EXIT_FAILURE, 0, _("invalid mode")); + error (EXIT_FAILURE, 0, _("invalid mode")); newmode = mode_adjust (newmode, false, umask (0), change, NULL); free (change); if (newmode & ~S_IRWXUGO) - error (EXIT_FAILURE, 0, - _("mode must specify only file permission bits")); + error (EXIT_FAILURE, 0, + _("mode must specify only file permission bits")); } /* If the number of arguments is 0 or 1, or (if it's 2 or more and the second one starts with `p'), then there must be exactly two operands. Otherwise, there must be four. */ expected_operands = (argc <= optind - || (optind + 1 < argc && argv[optind + 1][0] == 'p') - ? 2 : 4); + || (optind + 1 < argc && argv[optind + 1][0] == 'p') + ? 2 : 4); if (argc - optind < expected_operands) { if (argc <= optind) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); if (expected_operands == 4 && argc - optind == 2) - fprintf (stderr, "%s\n", - _("Special files require major and minor device numbers.")); + fprintf (stderr, "%s\n", + _("Special files require major and minor device numbers.")); usage (EXIT_FAILURE); } if (expected_operands < argc - optind) { error (0, 0, _("extra operand %s"), - quote (argv[optind + expected_operands])); + quote (argv[optind + expected_operands])); if (expected_operands == 2 && argc - optind == 4) - fprintf (stderr, "%s\n", - _("Fifos do not have major and minor device numbers.")); + fprintf (stderr, "%s\n", + _("Fifos do not have major and minor device numbers.")); usage (EXIT_FAILURE); } if (scontext && setfscreatecon (scontext) < 0) error (EXIT_FAILURE, errno, - _("failed to set default file creation context to %s"), - quote (scontext)); + _("failed to set default file creation context to %s"), + quote (scontext)); /* Only check the first character, to allow mnemonic usage like `mknod /dev/rst0 character 18 0'. */ @@ -192,35 +192,35 @@ main (int argc, char **argv) block_or_character: { - char const *s_major = argv[optind + 2]; - char const *s_minor = argv[optind + 3]; - uintmax_t i_major, i_minor; - dev_t device; - - if (xstrtoumax (s_major, NULL, 0, &i_major, NULL) != LONGINT_OK - || i_major != (major_t) i_major) - error (EXIT_FAILURE, 0, - _("invalid major device number %s"), quote (s_major)); - - if (xstrtoumax (s_minor, NULL, 0, &i_minor, NULL) != LONGINT_OK - || i_minor != (minor_t) i_minor) - error (EXIT_FAILURE, 0, - _("invalid minor device number %s"), quote (s_minor)); - - device = makedev (i_major, i_minor); + char const *s_major = argv[optind + 2]; + char const *s_minor = argv[optind + 3]; + uintmax_t i_major, i_minor; + dev_t device; + + if (xstrtoumax (s_major, NULL, 0, &i_major, NULL) != LONGINT_OK + || i_major != (major_t) i_major) + error (EXIT_FAILURE, 0, + _("invalid major device number %s"), quote (s_major)); + + if (xstrtoumax (s_minor, NULL, 0, &i_minor, NULL) != LONGINT_OK + || i_minor != (minor_t) i_minor) + error (EXIT_FAILURE, 0, + _("invalid minor device number %s"), quote (s_minor)); + + device = makedev (i_major, i_minor); #ifdef NODEV - if (device == NODEV) - error (EXIT_FAILURE, 0, _("invalid device %s %s"), s_major, s_minor); + if (device == NODEV) + error (EXIT_FAILURE, 0, _("invalid device %s %s"), s_major, s_minor); #endif - if (mknod (argv[optind], newmode | node_type, device) != 0) - error (EXIT_FAILURE, errno, "%s", quote (argv[optind])); + if (mknod (argv[optind], newmode | node_type, device) != 0) + error (EXIT_FAILURE, errno, "%s", quote (argv[optind])); } break; case 'p': /* `pipe' */ if (mkfifo (argv[optind], newmode) != 0) - error (EXIT_FAILURE, errno, "%s", quote (argv[optind])); + error (EXIT_FAILURE, errno, "%s", quote (argv[optind])); break; default: @@ -94,7 +94,7 @@ rm_option_init (struct rm_options *x) x->root_dev_ino = get_root_dev_ino (&dev_ino_buf); if (x->root_dev_ino == NULL) error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + quote ("/")); } } @@ -167,67 +167,67 @@ do_move (const char *source, const char *dest, const struct cp_options *x) { char const *dir_to_remove; if (copy_into_self) - { - /* In general, when copy returns with copy_into_self set, SOURCE is - the same as, or a parent of DEST. In this case we know it's a - parent. It doesn't make sense to move a directory into itself, and - besides in some situations doing so would give highly nonintuitive - results. Run this `mkdir b; touch a c; mv * b' in an empty - directory. Here's the result of running echo `find b -print`: - b b/a b/b b/b/a b/c. Notice that only file `a' was copied - into b/b. Handle this by giving a diagnostic, removing the - copied-into-self directory, DEST (`b/b' in the example), - and failing. */ - - dir_to_remove = NULL; - ok = false; - } + { + /* In general, when copy returns with copy_into_self set, SOURCE is + the same as, or a parent of DEST. In this case we know it's a + parent. It doesn't make sense to move a directory into itself, and + besides in some situations doing so would give highly nonintuitive + results. Run this `mkdir b; touch a c; mv * b' in an empty + directory. Here's the result of running echo `find b -print`: + b b/a b/b b/b/a b/c. Notice that only file `a' was copied + into b/b. Handle this by giving a diagnostic, removing the + copied-into-self directory, DEST (`b/b' in the example), + and failing. */ + + dir_to_remove = NULL; + ok = false; + } else if (rename_succeeded) - { - /* No need to remove anything. SOURCE was successfully - renamed to DEST. Or the user declined to rename a file. */ - dir_to_remove = NULL; - } + { + /* No need to remove anything. SOURCE was successfully + renamed to DEST. Or the user declined to rename a file. */ + dir_to_remove = NULL; + } else - { - /* This may mean SOURCE and DEST referred to different devices. - It may also conceivably mean that even though they referred - to the same device, rename wasn't implemented for that device. + { + /* This may mean SOURCE and DEST referred to different devices. + It may also conceivably mean that even though they referred + to the same device, rename wasn't implemented for that device. - E.g., (from Joel N. Weber), - [...] there might someday be cases where you can't rename - but you can copy where the device name is the same, especially - on Hurd. Consider an ftpfs with a primitive ftp server that - supports uploading, downloading and deleting, but not renaming. + E.g., (from Joel N. Weber), + [...] there might someday be cases where you can't rename + but you can copy where the device name is the same, especially + on Hurd. Consider an ftpfs with a primitive ftp server that + supports uploading, downloading and deleting, but not renaming. - Also, note that comparing device numbers is not a reliable - check for `can-rename'. Some systems can be set up so that - files from many different physical devices all have the same - st_dev field. This is a feature of some NFS mounting - configurations. + Also, note that comparing device numbers is not a reliable + check for `can-rename'. Some systems can be set up so that + files from many different physical devices all have the same + st_dev field. This is a feature of some NFS mounting + configurations. - We reach this point if SOURCE has been successfully copied - to DEST. Now we have to remove SOURCE. + We reach this point if SOURCE has been successfully copied + to DEST. Now we have to remove SOURCE. - This function used to resort to copying only when rename - failed and set errno to EXDEV. */ + This function used to resort to copying only when rename + failed and set errno to EXDEV. */ - dir_to_remove = source; - } + dir_to_remove = source; + } if (dir_to_remove != NULL) - { - struct rm_options rm_options; - enum RM_status status; - - rm_option_init (&rm_options); - rm_options.verbose = x->verbose; - - status = rm (1, &dir_to_remove, &rm_options); - assert (VALID_STATUS (status)); - if (status == RM_ERROR) - ok = false; - } + { + struct rm_options rm_options; + enum RM_status status; + + rm_option_init (&rm_options); + rm_options.verbose = x->verbose; + + status = rm (1, &dir_to_remove, &rm_options); + assert (VALID_STATUS (status)); + if (status == RM_ERROR) + ok = false; + } } return ok; @@ -239,7 +239,7 @@ do_move (const char *source, const char *dest, const struct cp_options *x) static bool movefile (char *source, char *dest, bool dest_is_dir, - const struct cp_options *x) + const struct cp_options *x) { bool ok; @@ -275,7 +275,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -283,7 +283,7 @@ Usage: %s [OPTION]... [-T] SOURCE DEST\n\ or: %s [OPTION]... SOURCE... DIRECTORY\n\ or: %s [OPTION]... -t DIRECTORY SOURCE...\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Rename SOURCE to DEST, or move SOURCE(s) to DIRECTORY.\n\ \n\ @@ -364,59 +364,59 @@ main (int argc, char **argv) backup_suffix_string = getenv ("SIMPLE_BACKUP_SUFFIX"); while ((c = getopt_long (argc, argv, "bfint:uvS:T", long_options, NULL)) - != -1) + != -1) { switch (c) - { - case 'b': - make_backups = true; - if (optarg) - version_control_string = optarg; - break; - case 'f': - x.interactive = I_ALWAYS_YES; - break; - case 'i': - x.interactive = I_ASK_USER; - break; - case 'n': - x.interactive = I_ALWAYS_NO; - break; - case STRIP_TRAILING_SLASHES_OPTION: - remove_trailing_slashes = true; - break; - case 't': - if (target_directory) - error (EXIT_FAILURE, 0, _("multiple target directories specified")); - else - { - struct stat st; - if (stat (optarg, &st) != 0) - error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); - if (! S_ISDIR (st.st_mode)) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (optarg)); - } - target_directory = optarg; - break; - case 'T': - no_target_directory = true; - break; - case 'u': - x.update = true; - break; - case 'v': - x.verbose = true; - break; - case 'S': - make_backups = true; - backup_suffix_string = optarg; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'b': + make_backups = true; + if (optarg) + version_control_string = optarg; + break; + case 'f': + x.interactive = I_ALWAYS_YES; + break; + case 'i': + x.interactive = I_ASK_USER; + break; + case 'n': + x.interactive = I_ALWAYS_NO; + break; + case STRIP_TRAILING_SLASHES_OPTION: + remove_trailing_slashes = true; + break; + case 't': + if (target_directory) + error (EXIT_FAILURE, 0, _("multiple target directories specified")); + else + { + struct stat st; + if (stat (optarg, &st) != 0) + error (EXIT_FAILURE, errno, _("accessing %s"), quote (optarg)); + if (! S_ISDIR (st.st_mode)) + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (optarg)); + } + target_directory = optarg; + break; + case 'T': + no_target_directory = true; + break; + case 'u': + x.update = true; + break; + case 'v': + x.verbose = true; + break; + case 'S': + make_backups = true; + backup_suffix_string = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } n_files = argc - optind; @@ -425,39 +425,39 @@ main (int argc, char **argv) if (n_files <= !target_directory) { if (n_files <= 0) - error (0, 0, _("missing file operand")); + error (0, 0, _("missing file operand")); else - error (0, 0, _("missing destination file operand after %s"), - quote (file[0])); + error (0, 0, _("missing destination file operand after %s"), + quote (file[0])); usage (EXIT_FAILURE); } if (no_target_directory) { if (target_directory) - error (EXIT_FAILURE, 0, - _("cannot combine --target-directory (-t) " - "and --no-target-directory (-T)")); + error (EXIT_FAILURE, 0, + _("cannot combine --target-directory (-t) " + "and --no-target-directory (-T)")); if (2 < n_files) - { - error (0, 0, _("extra operand %s"), quote (file[2])); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (file[2])); + usage (EXIT_FAILURE); + } } else if (!target_directory) { assert (2 <= n_files); if (target_directory_operand (file[n_files - 1])) - target_directory = file[--n_files]; + target_directory = file[--n_files]; else if (2 < n_files) - error (EXIT_FAILURE, 0, _("target %s is not a directory"), - quote (file[n_files - 1])); + error (EXIT_FAILURE, 0, _("target %s is not a directory"), + quote (file[n_files - 1])); } if (make_backups && x.interactive == I_ALWAYS_NO) { error (0, 0, - _("options --backup and --no-clobber are mutually exclusive")); + _("options --backup and --no-clobber are mutually exclusive")); usage (EXIT_FAILURE); } @@ -465,9 +465,9 @@ main (int argc, char **argv) simple_backup_suffix = xstrdup (backup_suffix_string); x.backup_type = (make_backups - ? xget_version (_("backup type"), - version_control_string) - : no_backups); + ? xget_version (_("backup type"), + version_control_string) + : no_backups); hash_init (); @@ -476,14 +476,14 @@ main (int argc, char **argv) int i; /* Initialize the hash table only if we'll need it. - The problem it is used to detect can arise only if there are - two or more files to move. */ + The problem it is used to detect can arise only if there are + two or more files to move. */ if (2 <= n_files) - dest_info_init (&x); + dest_info_init (&x); ok = true; for (i = 0; i < n_files; ++i) - ok &= movefile (file[i], target_directory, true, &x); + ok &= movefile (file[i], target_directory, true, &x); } else ok = movefile (file[0], file[1], false, &x); diff --git a/src/nice.c b/src/nice.c index d4432a37a..4a3c09212 100644 --- a/src/nice.c +++ b/src/nice.c @@ -66,7 +66,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION] [COMMAND [ARG]...]\n"), program_name); @@ -77,7 +77,7 @@ With no COMMAND, print the current niceness. Nicenesses range from\n\ \n\ -n, --adjustment=N add integer N to the niceness (default 10)\n\ "), - - NZERO, NZERO - 1); + - NZERO, NZERO - 1); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME); @@ -105,66 +105,66 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); for (i = 1; i < argc; /* empty */) { char const *s = argv[i]; if (s[0] == '-' && ISDIGIT (s[1 + (s[1] == '-' || s[1] == '+')])) - { - adjustment_given = s + 1; - ++i; - } + { + adjustment_given = s + 1; + ++i; + } else - { - int optc; - int fake_argc = argc - (i - 1); - char **fake_argv = argv + (i - 1); - - /* Ensure that any getopt diagnostics use the right name. */ - fake_argv[0] = argv[0]; - - /* Initialize getopt_long's internal state. */ - optind = 0; - - optc = getopt_long (fake_argc, fake_argv, "+n:", longopts, NULL); - i += optind - 1; - - if (optc == '?') - usage (EXIT_FAILURE); - else if (optc == 'n') - adjustment_given = optarg; - else /* optc == -1 */ - break; - } + { + int optc; + int fake_argc = argc - (i - 1); + char **fake_argv = argv + (i - 1); + + /* Ensure that any getopt diagnostics use the right name. */ + fake_argv[0] = argv[0]; + + /* Initialize getopt_long's internal state. */ + optind = 0; + + optc = getopt_long (fake_argc, fake_argv, "+n:", longopts, NULL); + i += optind - 1; + + if (optc == '?') + usage (EXIT_FAILURE); + else if (optc == 'n') + adjustment_given = optarg; + else /* optc == -1 */ + break; + } } if (adjustment_given) { /* If the requested adjustment is outside the valid range, - silently bring it to just within range; this mimics what - "setpriority" and "nice" do. */ + silently bring it to just within range; this mimics what + "setpriority" and "nice" do. */ enum { MIN_ADJUSTMENT = 1 - 2 * NZERO, MAX_ADJUSTMENT = 2 * NZERO - 1 }; long int tmp; if (LONGINT_OVERFLOW < xstrtol (adjustment_given, NULL, 10, &tmp, "")) - error (EXIT_FAILURE, 0, _("invalid adjustment %s"), - quote (adjustment_given)); + error (EXIT_FAILURE, 0, _("invalid adjustment %s"), + quote (adjustment_given)); adjustment = MAX (MIN_ADJUSTMENT, MIN (tmp, MAX_ADJUSTMENT)); } if (i == argc) { if (adjustment_given) - { - error (0, 0, _("a command must be given with an adjustment")); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("a command must be given with an adjustment")); + usage (EXIT_FAILURE); + } /* No command given; print the niceness. */ errno = 0; current_niceness = GET_NICENESS (); if (current_niceness == -1 && errno != 0) - error (EXIT_FAILURE, errno, _("cannot get niceness")); + error (EXIT_FAILURE, errno, _("cannot get niceness")); printf ("%d\n", current_niceness); exit (EXIT_SUCCESS); } @@ -176,13 +176,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Write each FILE to standard output, with line numbers added.\n\ With no FILE, or when FILE is -, read standard input.\n\ @@ -241,7 +241,7 @@ FORMAT is one of:\n\ static bool build_type_arg (char const **typep, - struct re_pattern_buffer *regexp, char *fastmap) + struct re_pattern_buffer *regexp, char *fastmap) { char const *errmsg; bool rval = true; @@ -260,10 +260,10 @@ build_type_arg (char const **typep, regexp->fastmap = fastmap; regexp->translate = NULL; re_syntax_options = - RE_SYNTAX_POSIX_BASIC & ~RE_CONTEXT_INVALID_DUP & ~RE_NO_EMPTY_RANGES; + RE_SYNTAX_POSIX_BASIC & ~RE_CONTEXT_INVALID_DUP & ~RE_NO_EMPTY_RANGES; errmsg = re_compile_pattern (optarg, strlen (optarg), regexp); if (errmsg) - error (EXIT_FAILURE, 0, "%s", errmsg); + error (EXIT_FAILURE, 0, "%s", errmsg); break; default: rval = false; @@ -330,42 +330,42 @@ proc_text (void) { case 'a': if (blank_join > 1) - { - if (1 < line_buf.length || ++blank_lines == blank_join) - { - print_lineno (); - blank_lines = 0; - } - else - fputs (print_no_line_fmt, stdout); - } + { + if (1 < line_buf.length || ++blank_lines == blank_join) + { + print_lineno (); + blank_lines = 0; + } + else + fputs (print_no_line_fmt, stdout); + } else - print_lineno (); + print_lineno (); break; case 't': if (1 < line_buf.length) - print_lineno (); + print_lineno (); else - fputs (print_no_line_fmt, stdout); + fputs (print_no_line_fmt, stdout); break; case 'n': fputs (print_no_line_fmt, stdout); break; case 'p': switch (re_search (current_regex, line_buf.buffer, line_buf.length - 1, - 0, line_buf.length - 1, NULL)) - { - case -2: - error (EXIT_FAILURE, errno, _("error in regular expression search")); - - case -1: - fputs (print_no_line_fmt, stdout); - break; - - default: - print_lineno (); - break; - } + 0, line_buf.length - 1, NULL)) + { + case -2: + error (EXIT_FAILURE, errno, _("error in regular expression search")); + + case -1: + fputs (print_no_line_fmt, stdout); + break; + + default: + print_lineno (); + break; + } } fwrite (line_buf.buffer, sizeof (char), line_buf.length, stdout); } @@ -399,20 +399,20 @@ process_file (FILE *fp) while (readlinebuffer (&line_buf, fp)) { switch (check_section ()) - { - case Header: - proc_header (); - break; - case Body: - proc_body (); - break; - case Footer: - proc_footer (); - break; - case Text: - proc_text (); - break; - } + { + case Header: + proc_header (); + break; + case Body: + proc_body (); + break; + case Footer: + proc_footer (); + break; + case Text: + proc_text (); + break; + } } } @@ -433,10 +433,10 @@ nl_file (char const *file) { stream = fopen (file, "r"); if (stream == NULL) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } } process_file (stream); @@ -474,110 +474,110 @@ main (int argc, char **argv) have_read_stdin = false; while ((c = getopt_long (argc, argv, "h:b:f:v:i:pl:s:w:n:d:", longopts, - NULL)) != -1) + NULL)) != -1) { switch (c) - { - case 'h': - if (! build_type_arg (&header_type, &header_regex, header_fastmap)) - { - error (0, 0, _("invalid header numbering style: %s"), - quote (optarg)); - ok = false; - } - break; - case 'b': - if (! build_type_arg (&body_type, &body_regex, body_fastmap)) - { - error (0, 0, _("invalid body numbering style: %s"), - quote (optarg)); - ok = false; - } - break; - case 'f': - if (! build_type_arg (&footer_type, &footer_regex, footer_fastmap)) - { - error (0, 0, _("invalid footer numbering style: %s"), - quote (optarg)); - ok = false; - } - break; - case 'v': - if (xstrtoimax (optarg, NULL, 10, &starting_line_number, "") - != LONGINT_OK) - { - error (0, 0, _("invalid starting line number: %s"), - quote (optarg)); - ok = false; - } - break; + { + case 'h': + if (! build_type_arg (&header_type, &header_regex, header_fastmap)) + { + error (0, 0, _("invalid header numbering style: %s"), + quote (optarg)); + ok = false; + } + break; + case 'b': + if (! build_type_arg (&body_type, &body_regex, body_fastmap)) + { + error (0, 0, _("invalid body numbering style: %s"), + quote (optarg)); + ok = false; + } + break; + case 'f': + if (! build_type_arg (&footer_type, &footer_regex, footer_fastmap)) + { + error (0, 0, _("invalid footer numbering style: %s"), + quote (optarg)); + ok = false; + } + break; + case 'v': + if (xstrtoimax (optarg, NULL, 10, &starting_line_number, "") + != LONGINT_OK) + { + error (0, 0, _("invalid starting line number: %s"), + quote (optarg)); + ok = false; + } + break; case PAGE_INCREMENT_OPTION_DEPRECATED: error (0, 0, _("WARNING: --page-increment is deprecated; " "use --line-increment instead")); /* fall through */ - case 'i': - if (! (xstrtoimax (optarg, NULL, 10, &page_incr, "") == LONGINT_OK - && 0 < page_incr)) - { - error (0, 0, _("invalid line number increment: %s"), - quote (optarg)); - ok = false; - } - break; - case 'p': - reset_numbers = false; - break; - case 'l': - if (! (xstrtoimax (optarg, NULL, 10, &blank_join, "") == LONGINT_OK - && 0 < blank_join)) - { - error (0, 0, _("invalid number of blank lines: %s"), - quote (optarg)); - ok = false; - } - break; - case 's': - separator_str = optarg; - break; - case 'w': - { - long int tmp_long; - if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long <= 0 || tmp_long > INT_MAX) - { - error (0, 0, _("invalid line number field width: %s"), - quote (optarg)); - ok = false; - } - else - { - lineno_width = tmp_long; - } - } - break; - case 'n': - if (STREQ (optarg, "ln")) - lineno_format = FORMAT_LEFT; - else if (STREQ (optarg, "rn")) - lineno_format = FORMAT_RIGHT_NOLZ; - else if (STREQ (optarg, "rz")) - lineno_format = FORMAT_RIGHT_LZ; - else - { - error (0, 0, _("invalid line numbering format: %s"), - quote (optarg)); - ok = false; - } - break; - case 'd': - section_del = optarg; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - ok = false; - break; - } + case 'i': + if (! (xstrtoimax (optarg, NULL, 10, &page_incr, "") == LONGINT_OK + && 0 < page_incr)) + { + error (0, 0, _("invalid line number increment: %s"), + quote (optarg)); + ok = false; + } + break; + case 'p': + reset_numbers = false; + break; + case 'l': + if (! (xstrtoimax (optarg, NULL, 10, &blank_join, "") == LONGINT_OK + && 0 < blank_join)) + { + error (0, 0, _("invalid number of blank lines: %s"), + quote (optarg)); + ok = false; + } + break; + case 's': + separator_str = optarg; + break; + case 'w': + { + long int tmp_long; + if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK + || tmp_long <= 0 || tmp_long > INT_MAX) + { + error (0, 0, _("invalid line number field width: %s"), + quote (optarg)); + ok = false; + } + else + { + lineno_width = tmp_long; + } + } + break; + case 'n': + if (STREQ (optarg, "ln")) + lineno_format = FORMAT_LEFT; + else if (STREQ (optarg, "rn")) + lineno_format = FORMAT_RIGHT_NOLZ; + else if (STREQ (optarg, "rz")) + lineno_format = FORMAT_RIGHT_LZ; + else + { + error (0, 0, _("invalid line numbering format: %s"), + quote (optarg)); + ok = false; + } + break; + case 'd': + section_del = optarg; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + ok = false; + break; + } } if (!ok) diff --git a/src/nohup.c b/src/nohup.c index 5ae6d1adc..f4b1b2342 100644 --- a/src/nohup.c +++ b/src/nohup.c @@ -48,14 +48,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s COMMAND [ARG]...\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Run COMMAND, ignoring hangup signals.\n\ @@ -69,7 +69,7 @@ If standard output is a terminal, append output to `nohup.out' if possible,\n\ `$HOME/nohup.out' otherwise.\n\ If standard error is a terminal, redirect it to standard output.\n\ To save output to FILE, use `%s COMMAND > FILE'.\n"), - program_name); + program_name); printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME); emit_bug_reporting_address (); } @@ -96,7 +96,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "+", NULL, NULL) != -1) usage (NOHUP_FAILURE); @@ -118,7 +118,7 @@ main (int argc, char **argv) { fd_reopen (STDIN_FILENO, "/dev/null", O_WRONLY, 0); if (!redirecting_stdout && !redirecting_stderr) - error (0, 0, _("ignoring input")); + error (0, 0, _("ignoring input")); } /* If standard output is a tty, redirect it (appending) to a file. @@ -133,38 +133,38 @@ main (int argc, char **argv) mode_t mode = S_IRUSR | S_IWUSR; mode_t umask_value = umask (~mode); out_fd = (redirecting_stdout - ? fd_reopen (STDOUT_FILENO, file, flags, mode) - : open (file, flags, mode)); + ? fd_reopen (STDOUT_FILENO, file, flags, mode) + : open (file, flags, mode)); if (out_fd < 0) - { - int saved_errno = errno; - char const *home = getenv ("HOME"); - if (home) - { - in_home = file_name_concat (home, file, NULL); - out_fd = (redirecting_stdout - ? fd_reopen (STDOUT_FILENO, in_home, flags, mode) - : open (in_home, flags, mode)); - } - if (out_fd < 0) - { - int saved_errno2 = errno; - error (0, saved_errno, _("failed to open %s"), quote (file)); - if (in_home) - error (0, saved_errno2, _("failed to open %s"), - quote (in_home)); - exit (NOHUP_FAILURE); - } - file = in_home; - } + { + int saved_errno = errno; + char const *home = getenv ("HOME"); + if (home) + { + in_home = file_name_concat (home, file, NULL); + out_fd = (redirecting_stdout + ? fd_reopen (STDOUT_FILENO, in_home, flags, mode) + : open (in_home, flags, mode)); + } + if (out_fd < 0) + { + int saved_errno2 = errno; + error (0, saved_errno, _("failed to open %s"), quote (file)); + if (in_home) + error (0, saved_errno2, _("failed to open %s"), + quote (in_home)); + exit (NOHUP_FAILURE); + } + file = in_home; + } umask (umask_value); error (0, 0, - _(ignoring_input - ? N_("ignoring input and appending output to %s") - : N_("appending output to %s")), - quote (file)); + _(ignoring_input + ? N_("ignoring input and appending output to %s") + : N_("appending output to %s")), + quote (file)); free (in_home); } @@ -172,27 +172,27 @@ main (int argc, char **argv) if (redirecting_stderr) { /* Save a copy of stderr before redirecting, so we can use the original - if execve fails. It's no big deal if this dup fails. It might - not change anything, and at worst, it'll lead to suppression of - the post-failed-execve diagnostic. */ + if execve fails. It's no big deal if this dup fails. It might + not change anything, and at worst, it'll lead to suppression of + the post-failed-execve diagnostic. */ saved_stderr_fd = dup (STDERR_FILENO); if (0 <= saved_stderr_fd - && set_cloexec_flag (saved_stderr_fd, true) != 0) - error (NOHUP_FAILURE, errno, - _("failed to set the copy of stderr to close on exec")); + && set_cloexec_flag (saved_stderr_fd, true) != 0) + error (NOHUP_FAILURE, errno, + _("failed to set the copy of stderr to close on exec")); if (!redirecting_stdout) - error (0, 0, - _(ignoring_input - ? N_("ignoring input and redirecting stderr to stdout") - : N_("redirecting stderr to stdout"))); + error (0, 0, + _(ignoring_input + ? N_("ignoring input and redirecting stderr to stdout") + : N_("redirecting stderr to stdout"))); if (dup2 (out_fd, STDERR_FILENO) < 0) - error (NOHUP_FAILURE, errno, _("failed to redirect standard error")); + error (NOHUP_FAILURE, errno, _("failed to redirect standard error")); if (stdout_is_closed) - close (out_fd); + close (out_fd); } signal (SIGHUP, SIG_IGN); @@ -209,7 +209,7 @@ main (int argc, char **argv) /* The execve failed. Output a diagnostic to stderr only if: - stderr was initially redirected to a non-tty, or - stderr was initially directed to a tty, and we - can dup2 it to point back to that same tty. + can dup2 it to point back to that same tty. In other words, output the diagnostic if possible, but only if it will go to the original stderr. */ if (dup2 (saved_stderr_fd, STDERR_FILENO) == STDERR_FILENO) @@ -93,12 +93,12 @@ enum { FMT_BYTES_ALLOCATED = MAX ((sizeof "%*.99" - 1 - + MAX (sizeof "ld", - MAX (sizeof PRIdMAX, - MAX (sizeof PRIoMAX, - MAX (sizeof PRIuMAX, - sizeof PRIxMAX))))), - sizeof "%*.99Le") + + MAX (sizeof "ld", + MAX (sizeof PRIdMAX, + MAX (sizeof PRIoMAX, + MAX (sizeof PRIuMAX, + sizeof PRIxMAX))))), + sizeof "%*.99Le") }; /* Ensure that our choice for FMT_BYTES_ALLOCATED is reasonable. */ @@ -116,7 +116,7 @@ struct tspec leading space, and PAD is total pad to divide among FIELDS. PAD is at least as large as FIELDS. */ void (*print_function) (size_t fields, size_t blank, void const *data, - char const *fmt, int width, int pad); + char const *fmt, int width, int pad); char fmt_string[FMT_BYTES_ALLOCATED]; /* Of the style "%*d". */ bool hexl_mode_trailer; int field_width; /* Minimum width of a field, excluding leading space. */ @@ -302,7 +302,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -310,7 +310,7 @@ Usage: %s [OPTION]... [FILE]...\n\ or: %s [-abcdfilosx]... [FILE] [[+]OFFSET[.][b]]\n\ or: %s --traditional [OPTION]... [FILE] [[+]OFFSET[.][b] [+][LABEL][.][b]]\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\n\ Write an unambiguous representation, octal bytes by default,\n\ of FILE to standard output. With more than one FILE argument,\n\ @@ -446,8 +446,8 @@ dump_hexl_mode_trailer (size_t n_bytes, const char *block) static void print_named_ascii (size_t fields, size_t blank, void const *block, - const char *unused_fmt_string ATTRIBUTE_UNUSED, - int width, int pad) + const char *unused_fmt_string ATTRIBUTE_UNUSED, + int width, int pad) { unsigned char const *p = block; size_t i; @@ -460,15 +460,15 @@ print_named_ascii (size_t fields, size_t blank, void const *block, char buf[2]; if (masked_c == 127) - s = "del"; + s = "del"; else if (masked_c <= 040) - s = charname[masked_c]; + s = charname[masked_c]; else - { - buf[0] = masked_c; - buf[1] = 0; - s = buf; - } + { + buf[0] = masked_c; + buf[1] = 0; + s = buf; + } xprintf ("%*s", pad_remaining - next_pad + width, s); pad_remaining = next_pad; @@ -477,8 +477,8 @@ print_named_ascii (size_t fields, size_t blank, void const *block, static void print_ascii (size_t fields, size_t blank, void const *block, - const char *unused_fmt_string ATTRIBUTE_UNUSED, int width, - int pad) + const char *unused_fmt_string ATTRIBUTE_UNUSED, int width, + int pad) { unsigned char const *p = block; size_t i; @@ -491,43 +491,43 @@ print_ascii (size_t fields, size_t blank, void const *block, char buf[4]; switch (c) - { - case '\0': - s = "\\0"; - break; + { + case '\0': + s = "\\0"; + break; - case '\a': - s = "\\a"; - break; + case '\a': + s = "\\a"; + break; - case '\b': - s = "\\b"; - break; + case '\b': + s = "\\b"; + break; - case '\f': - s = "\\f"; - break; + case '\f': + s = "\\f"; + break; - case '\n': - s = "\\n"; - break; + case '\n': + s = "\\n"; + break; - case '\r': - s = "\\r"; - break; + case '\r': + s = "\\r"; + break; - case '\t': - s = "\\t"; - break; + case '\t': + s = "\\t"; + break; - case '\v': - s = "\\v"; - break; + case '\v': + s = "\\v"; + break; - default: - sprintf (buf, (isprint (c) ? "%c" : "%03o"), c); - s = buf; - } + default: + sprintf (buf, (isprint (c) ? "%c" : "%03o"), c); + s = buf; + } xprintf ("%*s", pad_remaining - next_pad + width, s); pad_remaining = next_pad; @@ -552,7 +552,7 @@ simple_strtoul (const char *s, const char **p, unsigned long int *val) { int c = *s++ - '0'; if (sum > (ULONG_MAX - c) / 10) - return false; + return false; sum = sum * 10 + c; } *p = s; @@ -581,14 +581,14 @@ simple_strtoul (const char *s, const char **p, unsigned long int *val) static bool decode_one_format (const char *s_orig, const char *s, const char **next, - struct tspec *tspec) + struct tspec *tspec) { enum size_spec size_spec; unsigned long int size; enum output_format fmt; const char *pre_fmt_string; void (*print_function) (size_t, size_t, void const *, char const *, - int, int); + int, int); const char *p; char c; int field_width; @@ -605,51 +605,51 @@ decode_one_format (const char *s_orig, const char *s, const char **next, c = *s; ++s; switch (*s) - { - case 'C': - ++s; - size = sizeof (char); - break; - - case 'S': - ++s; - size = sizeof (short int); - break; - - case 'I': - ++s; - size = sizeof (int); - break; - - case 'L': - ++s; - size = sizeof (long int); - break; - - default: - if (! simple_strtoul (s, &p, &size)) - { - /* The integer at P in S would overflow an unsigned long int. - A digit string that long is sufficiently odd looking - that the following diagnostic is sufficient. */ - error (0, 0, _("invalid type string %s"), quote (s_orig)); - return false; - } - if (p == s) - size = sizeof (int); - else - { - if (MAX_INTEGRAL_TYPE_SIZE < size - || integral_type_size[size] == NO_SIZE) - { - error (0, 0, _("invalid type string %s;\n\ + { + case 'C': + ++s; + size = sizeof (char); + break; + + case 'S': + ++s; + size = sizeof (short int); + break; + + case 'I': + ++s; + size = sizeof (int); + break; + + case 'L': + ++s; + size = sizeof (long int); + break; + + default: + if (! simple_strtoul (s, &p, &size)) + { + /* The integer at P in S would overflow an unsigned long int. + A digit string that long is sufficiently odd looking + that the following diagnostic is sufficient. */ + error (0, 0, _("invalid type string %s"), quote (s_orig)); + return false; + } + if (p == s) + size = sizeof (int); + else + { + if (MAX_INTEGRAL_TYPE_SIZE < size + || integral_type_size[size] == NO_SIZE) + { + error (0, 0, _("invalid type string %s;\n\ this system doesn't provide a %lu-byte integral type"), quote (s_orig), size); - return false; - } - s = p; - } - break; - } + return false; + } + s = p; + } + break; + } #define ISPEC_TO_FORMAT(Spec, Min_format, Long_format, Max_format) \ ((Spec) == LONG_LONG ? (Max_format) \ @@ -659,143 +659,143 @@ this system doesn't provide a %lu-byte integral type"), quote (s_orig), size); size_spec = integral_type_size[size]; switch (c) - { - case 'd': - fmt = SIGNED_DECIMAL; - field_width = bytes_to_signed_dec_digits[size]; - sprintf (tspec->fmt_string, "%%*%s", - ISPEC_TO_FORMAT (size_spec, "d", "ld", PRIdMAX)); - break; - - case 'o': - fmt = OCTAL; - sprintf (tspec->fmt_string, "%%*.%d%s", - (field_width = bytes_to_oct_digits[size]), - ISPEC_TO_FORMAT (size_spec, "o", "lo", PRIoMAX)); - break; - - case 'u': - fmt = UNSIGNED_DECIMAL; - field_width = bytes_to_unsigned_dec_digits[size]; - sprintf (tspec->fmt_string, "%%*%s", - ISPEC_TO_FORMAT (size_spec, "u", "lu", PRIuMAX)); - break; - - case 'x': - fmt = HEXADECIMAL; - sprintf (tspec->fmt_string, "%%*.%d%s", - (field_width = bytes_to_hex_digits[size]), - ISPEC_TO_FORMAT (size_spec, "x", "lx", PRIxMAX)); - break; - - default: - abort (); - } + { + case 'd': + fmt = SIGNED_DECIMAL; + field_width = bytes_to_signed_dec_digits[size]; + sprintf (tspec->fmt_string, "%%*%s", + ISPEC_TO_FORMAT (size_spec, "d", "ld", PRIdMAX)); + break; + + case 'o': + fmt = OCTAL; + sprintf (tspec->fmt_string, "%%*.%d%s", + (field_width = bytes_to_oct_digits[size]), + ISPEC_TO_FORMAT (size_spec, "o", "lo", PRIoMAX)); + break; + + case 'u': + fmt = UNSIGNED_DECIMAL; + field_width = bytes_to_unsigned_dec_digits[size]; + sprintf (tspec->fmt_string, "%%*%s", + ISPEC_TO_FORMAT (size_spec, "u", "lu", PRIuMAX)); + break; + + case 'x': + fmt = HEXADECIMAL; + sprintf (tspec->fmt_string, "%%*.%d%s", + (field_width = bytes_to_hex_digits[size]), + ISPEC_TO_FORMAT (size_spec, "x", "lx", PRIxMAX)); + break; + + default: + abort (); + } assert (strlen (tspec->fmt_string) < FMT_BYTES_ALLOCATED); switch (size_spec) - { - case CHAR: - print_function = (fmt == SIGNED_DECIMAL - ? print_s_char - : print_char); - break; - - case SHORT: - print_function = (fmt == SIGNED_DECIMAL - ? print_s_short - : print_short); - break; - - case INT: - print_function = print_int; - break; - - case LONG: - print_function = print_long; - break; - - case LONG_LONG: - print_function = print_long_long; - break; - - default: - abort (); - } + { + case CHAR: + print_function = (fmt == SIGNED_DECIMAL + ? print_s_char + : print_char); + break; + + case SHORT: + print_function = (fmt == SIGNED_DECIMAL + ? print_s_short + : print_short); + break; + + case INT: + print_function = print_int; + break; + + case LONG: + print_function = print_long; + break; + + case LONG_LONG: + print_function = print_long_long; + break; + + default: + abort (); + } break; case 'f': fmt = FLOATING_POINT; ++s; switch (*s) - { - case 'F': - ++s; - size = sizeof (float); - break; - - case 'D': - ++s; - size = sizeof (double); - break; - - case 'L': - ++s; - size = sizeof (long double); - break; - - default: - if (! simple_strtoul (s, &p, &size)) - { - /* The integer at P in S would overflow an unsigned long int. - A digit string that long is sufficiently odd looking - that the following diagnostic is sufficient. */ - error (0, 0, _("invalid type string %s"), quote (s_orig)); - return false; - } - if (p == s) - size = sizeof (double); - else - { - if (size > MAX_FP_TYPE_SIZE - || fp_type_size[size] == NO_SIZE) - { - error (0, 0, _("invalid type string %s;\n\ + { + case 'F': + ++s; + size = sizeof (float); + break; + + case 'D': + ++s; + size = sizeof (double); + break; + + case 'L': + ++s; + size = sizeof (long double); + break; + + default: + if (! simple_strtoul (s, &p, &size)) + { + /* The integer at P in S would overflow an unsigned long int. + A digit string that long is sufficiently odd looking + that the following diagnostic is sufficient. */ + error (0, 0, _("invalid type string %s"), quote (s_orig)); + return false; + } + if (p == s) + size = sizeof (double); + else + { + if (size > MAX_FP_TYPE_SIZE + || fp_type_size[size] == NO_SIZE) + { + error (0, 0, _("invalid type string %s;\n\ this system doesn't provide a %lu-byte floating point type"), - quote (s_orig), size); - return false; - } - s = p; - } - break; - } + quote (s_orig), size); + return false; + } + s = p; + } + break; + } size_spec = fp_type_size[size]; switch (size_spec) - { - case FLOAT_SINGLE: - print_function = print_float; - /* FIXME - should we use %g instead of %e? */ - pre_fmt_string = "%%*.%de"; - precision = FLT_DIG; - break; - - case FLOAT_DOUBLE: - print_function = print_double; - pre_fmt_string = "%%*.%de"; - precision = DBL_DIG; - break; - - case FLOAT_LONG_DOUBLE: - print_function = print_long_double; - pre_fmt_string = "%%*.%dLe"; - precision = LDBL_DIG; - break; - - default: - abort (); - } + { + case FLOAT_SINGLE: + print_function = print_float; + /* FIXME - should we use %g instead of %e? */ + pre_fmt_string = "%%*.%de"; + precision = FLT_DIG; + break; + + case FLOAT_DOUBLE: + print_function = print_double; + pre_fmt_string = "%%*.%de"; + precision = DBL_DIG; + break; + + case FLOAT_LONG_DOUBLE: + print_function = print_long_double; + pre_fmt_string = "%%*.%dLe"; + precision = LDBL_DIG; + break; + + default: + abort (); + } field_width = precision + 8; sprintf (tspec->fmt_string, pre_fmt_string, precision); @@ -820,7 +820,7 @@ this system doesn't provide a %lu-byte floating point type"), default: error (0, 0, _("invalid character `%c' in type string %s"), - *s, quote (s_orig)); + *s, quote (s_orig)); return false; } @@ -855,26 +855,26 @@ open_next_file (void) { input_filename = *file_list; if (input_filename == NULL) - return ok; + return ok; ++file_list; if (STREQ (input_filename, "-")) - { - input_filename = _("standard input"); - in_stream = stdin; - have_read_stdin = true; - if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); - } + { + input_filename = _("standard input"); + in_stream = stdin; + have_read_stdin = true; + if (O_BINARY && ! isatty (STDIN_FILENO)) + xfreopen (NULL, "rb", stdin); + } else - { - in_stream = fopen (input_filename, (O_BINARY ? "rb" : "r")); - if (in_stream == NULL) - { - error (0, errno, "%s", input_filename); - ok = false; - } - } + { + in_stream = fopen (input_filename, (O_BINARY ? "rb" : "r")); + if (in_stream == NULL) + { + error (0, errno, "%s", input_filename); + ok = false; + } + } } while (in_stream == NULL); @@ -899,17 +899,17 @@ check_and_close (int in_errno) if (in_stream != NULL) { if (ferror (in_stream)) - { - error (0, in_errno, _("%s: read error"), input_filename); - if (! STREQ (file_list[-1], "-")) - fclose (in_stream); - ok = false; - } + { + error (0, in_errno, _("%s: read error"), input_filename); + if (! STREQ (file_list[-1], "-")) + fclose (in_stream); + ok = false; + } else if (! STREQ (file_list[-1], "-") && fclose (in_stream) != 0) - { - error (0, errno, "%s", input_filename); - ok = false; - } + { + error (0, errno, "%s", input_filename); + ok = false; + } in_stream = NULL; } @@ -938,10 +938,10 @@ decode_format_string (const char *s) const char *next; if (n_specs_allocated <= n_specs) - spec = X2NREALLOC (spec, &n_specs_allocated); + spec = X2NREALLOC (spec, &n_specs_allocated); if (! decode_one_format (s_orig, s, &next, &spec[n_specs])) - return false; + return false; assert (s != next); s = next; @@ -972,72 +972,72 @@ skip (uintmax_t n_skip) struct stat file_stats; /* First try seeking. For large offsets, this extra work is - worthwhile. If the offset is below some threshold it may be - more efficient to move the pointer by reading. There are two - issues when trying to seek: - - the file must be seekable. - - before seeking to the specified position, make sure - that the new position is in the current file. - Try to do that by getting file's size using fstat. - But that will work only for regular files. */ + worthwhile. If the offset is below some threshold it may be + more efficient to move the pointer by reading. There are two + issues when trying to seek: + - the file must be seekable. + - before seeking to the specified position, make sure + that the new position is in the current file. + Try to do that by getting file's size using fstat. + But that will work only for regular files. */ if (fstat (fileno (in_stream), &file_stats) == 0) - { - /* The st_size field is valid only for regular files - (and for symbolic links, which cannot occur here). - If the number of bytes left to skip is larger than - the size of the current file, we can decrement n_skip - and go on to the next file. Skip this optimization also - when st_size is 0, because some kernels report that - nonempty files in /proc have st_size == 0. */ - if (S_ISREG (file_stats.st_mode) && 0 < file_stats.st_size) - { - if ((uintmax_t) file_stats.st_size < n_skip) - n_skip -= file_stats.st_size; - else - { - if (fseeko (in_stream, n_skip, SEEK_CUR) != 0) - { - in_errno = errno; - ok = false; - } - n_skip = 0; - } - } - - /* If it's not a regular file with nonnegative size, - position the file pointer by reading. */ - - else - { - char buf[BUFSIZ]; - size_t n_bytes_read, n_bytes_to_read = BUFSIZ; - - while (0 < n_skip) - { - if (n_skip < n_bytes_to_read) - n_bytes_to_read = n_skip; - n_bytes_read = fread (buf, 1, n_bytes_to_read, in_stream); - n_skip -= n_bytes_read; - if (n_bytes_read != n_bytes_to_read) - { - in_errno = errno; - ok = false; - n_skip = 0; - break; - } - } - } - - if (n_skip == 0) - break; - } + { + /* The st_size field is valid only for regular files + (and for symbolic links, which cannot occur here). + If the number of bytes left to skip is larger than + the size of the current file, we can decrement n_skip + and go on to the next file. Skip this optimization also + when st_size is 0, because some kernels report that + nonempty files in /proc have st_size == 0. */ + if (S_ISREG (file_stats.st_mode) && 0 < file_stats.st_size) + { + if ((uintmax_t) file_stats.st_size < n_skip) + n_skip -= file_stats.st_size; + else + { + if (fseeko (in_stream, n_skip, SEEK_CUR) != 0) + { + in_errno = errno; + ok = false; + } + n_skip = 0; + } + } + + /* If it's not a regular file with nonnegative size, + position the file pointer by reading. */ + + else + { + char buf[BUFSIZ]; + size_t n_bytes_read, n_bytes_to_read = BUFSIZ; + + while (0 < n_skip) + { + if (n_skip < n_bytes_to_read) + n_bytes_to_read = n_skip; + n_bytes_read = fread (buf, 1, n_bytes_to_read, in_stream); + n_skip -= n_bytes_read; + if (n_bytes_read != n_bytes_to_read) + { + in_errno = errno; + ok = false; + n_skip = 0; + break; + } + } + } + + if (n_skip == 0) + break; + } else /* cannot fstat() file */ - { - error (0, errno, "%s", input_filename); - ok = false; - } + { + error (0, errno, "%s", input_filename); + ok = false; + } ok &= check_and_close (in_errno); @@ -1072,19 +1072,19 @@ format_address_std (uintmax_t address, char c) { case 8: do - *--p = '0' + (address & 7); + *--p = '0' + (address & 7); while ((address >>= 3) != 0); break; case 10: do - *--p = '0' + (address % 10); + *--p = '0' + (address % 10); while ((address /= 10) != 0); break; case 16: do - *--p = "0123456789abcdef"[address & 15]; + *--p = "0123456789abcdef"[address & 15]; while ((address >>= 4) != 0); break; } @@ -1123,7 +1123,7 @@ format_address_label (uintmax_t address, char c) static void write_block (uintmax_t current_offset, size_t n_bytes, - const char *prev_block, const char *curr_block) + const char *prev_block, const char *curr_block) { static bool first = true; static bool prev_pair_equal = false; @@ -1135,15 +1135,15 @@ write_block (uintmax_t current_offset, size_t n_bytes, && EQUAL_BLOCKS (prev_block, curr_block)) { if (prev_pair_equal) - { - /* The two preceding blocks were equal, and the current - block is the same as the last one, so print nothing. */ - } + { + /* The two preceding blocks were equal, and the current + block is the same as the last one, so print nothing. */ + } else - { - printf ("*\n"); - prev_pair_equal = true; - } + { + printf ("*\n"); + prev_pair_equal = true; + } } else { @@ -1151,28 +1151,28 @@ write_block (uintmax_t current_offset, size_t n_bytes, prev_pair_equal = false; for (i = 0; i < n_specs; i++) - { - int datum_width = width_bytes[spec[i].size]; - int fields_per_block = bytes_per_block / datum_width; - int blank_fields = (bytes_per_block - n_bytes) / datum_width; - if (i == 0) - format_address (current_offset, '\0'); - else - printf ("%*s", address_pad_len, ""); - (*spec[i].print_function) (fields_per_block, blank_fields, - curr_block, spec[i].fmt_string, - spec[i].field_width, spec[i].pad_width); - if (spec[i].hexl_mode_trailer) - { - /* space-pad out to full line width, then dump the trailer */ - int field_width = spec[i].field_width; - int pad_width = (spec[i].pad_width * blank_fields - / fields_per_block); - printf ("%*s", blank_fields * field_width + pad_width, ""); - dump_hexl_mode_trailer (n_bytes, curr_block); - } - putchar ('\n'); - } + { + int datum_width = width_bytes[spec[i].size]; + int fields_per_block = bytes_per_block / datum_width; + int blank_fields = (bytes_per_block - n_bytes) / datum_width; + if (i == 0) + format_address (current_offset, '\0'); + else + printf ("%*s", address_pad_len, ""); + (*spec[i].print_function) (fields_per_block, blank_fields, + curr_block, spec[i].fmt_string, + spec[i].field_width, spec[i].pad_width); + if (spec[i].hexl_mode_trailer) + { + /* space-pad out to full line width, then dump the trailer */ + int field_width = spec[i].field_width; + int pad_width = (spec[i].pad_width * blank_fields + / fields_per_block); + printf ("%*s", blank_fields * field_width + pad_width, ""); + dump_hexl_mode_trailer (n_bytes, curr_block); + } + putchar ('\n'); + } } first = false; } @@ -1200,7 +1200,7 @@ read_char (int *c) *c = fgetc (in_stream); if (*c != EOF) - break; + break; ok &= check_and_close (errno); @@ -1247,7 +1247,7 @@ read_block (size_t n, char *block, size_t *n_bytes_in_buffer) *n_bytes_in_buffer += n_read; if (n_read == n_needed) - break; + break; ok &= check_and_close (errno); @@ -1294,9 +1294,9 @@ parse_old_offset (const char *s, uintmax_t *offset) else { if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) - radix = 16; + radix = 16; else - radix = 8; + radix = 8; } return xstrtoumax (s, NULL, radix, offset, "Bb") == LONGINT_OK; @@ -1331,38 +1331,38 @@ dump (void) if (limit_bytes_to_format) { while (1) - { - size_t n_needed; - if (current_offset >= end_offset) - { - n_bytes_read = 0; - break; - } - n_needed = MIN (end_offset - current_offset, - (uintmax_t) bytes_per_block); - ok &= read_block (n_needed, block[idx], &n_bytes_read); - if (n_bytes_read < bytes_per_block) - break; - assert (n_bytes_read == bytes_per_block); - write_block (current_offset, n_bytes_read, - block[!idx], block[idx]); - current_offset += n_bytes_read; - idx = !idx; - } + { + size_t n_needed; + if (current_offset >= end_offset) + { + n_bytes_read = 0; + break; + } + n_needed = MIN (end_offset - current_offset, + (uintmax_t) bytes_per_block); + ok &= read_block (n_needed, block[idx], &n_bytes_read); + if (n_bytes_read < bytes_per_block) + break; + assert (n_bytes_read == bytes_per_block); + write_block (current_offset, n_bytes_read, + block[!idx], block[idx]); + current_offset += n_bytes_read; + idx = !idx; + } } else { while (1) - { - ok &= read_block (bytes_per_block, block[idx], &n_bytes_read); - if (n_bytes_read < bytes_per_block) - break; - assert (n_bytes_read == bytes_per_block); - write_block (current_offset, n_bytes_read, - block[!idx], block[idx]); - current_offset += n_bytes_read; - idx = !idx; - } + { + ok &= read_block (bytes_per_block, block[idx], &n_bytes_read); + if (n_bytes_read < bytes_per_block) + break; + assert (n_bytes_read == bytes_per_block); + write_block (current_offset, n_bytes_read, + block[!idx], block[idx]); + current_offset += n_bytes_read; + idx = !idx; + } } if (n_bytes_read > 0) @@ -1373,7 +1373,7 @@ dump (void) l_c_m = get_lcm (); /* Ensure zero-byte padding up to the smallest multiple of l_c_m that - is at least as large as n_bytes_read. */ + is at least as large as n_bytes_read. */ bytes_to_write = l_c_m * ((n_bytes_read + l_c_m - 1) / l_c_m); memset (block[idx] + n_bytes_read, 0, bytes_to_write - n_bytes_read); @@ -1414,87 +1414,87 @@ dump_strings (void) tryline: if (limit_bytes_to_format - && (end_offset < string_min || end_offset - string_min <= address)) - break; + && (end_offset < string_min || end_offset - string_min <= address)) + break; for (i = 0; i < string_min; i++) - { - ok &= read_char (&c); - address++; - if (c < 0) - { - free (buf); - return ok; - } - if (! isprint (c)) - /* Found a non-printing. Try again starting with next char. */ - goto tryline; - buf[i] = c; - } + { + ok &= read_char (&c); + address++; + if (c < 0) + { + free (buf); + return ok; + } + if (! isprint (c)) + /* Found a non-printing. Try again starting with next char. */ + goto tryline; + buf[i] = c; + } /* We found a run of `string_min' printable characters. - Now see if it is terminated with a null byte. */ + Now see if it is terminated with a null byte. */ while (!limit_bytes_to_format || address < end_offset) - { - if (i == bufsize) - { - buf = X2REALLOC (buf, &bufsize); - } - ok &= read_char (&c); - address++; - if (c < 0) - { - free (buf); - return ok; - } - if (c == '\0') - break; /* It is; print this string. */ - if (! isprint (c)) - goto tryline; /* It isn't; give up on this string. */ - buf[i++] = c; /* String continues; store it all. */ - } + { + if (i == bufsize) + { + buf = X2REALLOC (buf, &bufsize); + } + ok &= read_char (&c); + address++; + if (c < 0) + { + free (buf); + return ok; + } + if (c == '\0') + break; /* It is; print this string. */ + if (! isprint (c)) + goto tryline; /* It isn't; give up on this string. */ + buf[i++] = c; /* String continues; store it all. */ + } /* If we get here, the string is all printable and null-terminated, - so print it. It is all in `buf' and `i' is its length. */ + so print it. It is all in `buf' and `i' is its length. */ buf[i] = 0; format_address (address - i - 1, ' '); for (i = 0; (c = buf[i]); i++) - { - switch (c) - { - case '\a': - fputs ("\\a", stdout); - break; - - case '\b': - fputs ("\\b", stdout); - break; - - case '\f': - fputs ("\\f", stdout); - break; - - case '\n': - fputs ("\\n", stdout); - break; - - case '\r': - fputs ("\\r", stdout); - break; - - case '\t': - fputs ("\\t", stdout); - break; - - case '\v': - fputs ("\\v", stdout); - break; - - default: - putc (c, stdout); - } - } + { + switch (c) + { + case '\a': + fputs ("\\a", stdout); + break; + + case '\b': + fputs ("\\b", stdout); + break; + + case '\f': + fputs ("\\f", stdout); + break; + + case '\n': + fputs ("\\n", stdout); + break; + + case '\r': + fputs ("\\r", stdout); + break; + + case '\t': + fputs ("\\t", stdout); + break; + + case '\v': + fputs ("\\v", stdout); + break; + + default: + putc (c, stdout); + } + } putchar ('\n'); } @@ -1574,151 +1574,151 @@ main (int argc, char **argv) break; switch (c) - { - case 'A': - modern = true; - switch (optarg[0]) - { - case 'd': - format_address = format_address_std; - address_base = 10; - address_pad_len = 7; - break; - case 'o': - format_address = format_address_std; - address_base = 8; - address_pad_len = 7; - break; - case 'x': - format_address = format_address_std; - address_base = 16; - address_pad_len = 6; - break; - case 'n': - format_address = format_address_none; - address_pad_len = 0; - break; - default: - error (EXIT_FAILURE, 0, - _("invalid output address radix `%c'; \ + { + case 'A': + modern = true; + switch (optarg[0]) + { + case 'd': + format_address = format_address_std; + address_base = 10; + address_pad_len = 7; + break; + case 'o': + format_address = format_address_std; + address_base = 8; + address_pad_len = 7; + break; + case 'x': + format_address = format_address_std; + address_base = 16; + address_pad_len = 6; + break; + case 'n': + format_address = format_address_none; + address_pad_len = 0; + break; + default: + error (EXIT_FAILURE, 0, + _("invalid output address radix `%c'; \ it must be one character from [doxn]"), - optarg[0]); - break; - } - break; - - case 'j': - modern = true; - s_err = xstrtoumax (optarg, NULL, 0, &n_bytes_to_skip, multipliers); - if (s_err != LONGINT_OK) - xstrtol_fatal (s_err, oi, c, long_options, optarg); - break; - - case 'N': - modern = true; - limit_bytes_to_format = true; - - s_err = xstrtoumax (optarg, NULL, 0, &max_bytes_to_format, - multipliers); - if (s_err != LONGINT_OK) - xstrtol_fatal (s_err, oi, c, long_options, optarg); - break; - - case 'S': - modern = true; - if (optarg == NULL) - string_min = 3; - else - { - s_err = xstrtoumax (optarg, NULL, 0, &tmp, multipliers); - if (s_err != LONGINT_OK) - xstrtol_fatal (s_err, oi, c, long_options, optarg); - - /* The minimum string length may be no larger than SIZE_MAX, - since we may allocate a buffer of this size. */ - if (SIZE_MAX < tmp) - error (EXIT_FAILURE, 0, _("%s is too large"), optarg); - - string_min = tmp; - } - flag_dump_strings = true; - break; - - case 't': - modern = true; - ok &= decode_format_string (optarg); - break; - - case 'v': - modern = true; - abbreviate_duplicate_blocks = false; - break; - - case TRADITIONAL_OPTION: - traditional = true; - break; - - /* The next several cases map the traditional format - specification options to the corresponding modern format - specs. GNU od accepts any combination of old- and - new-style options. Format specification options accumulate. - The obsolescent and undocumented formats are compatible - with FreeBSD 4.10 od. */ + optarg[0]); + break; + } + break; + + case 'j': + modern = true; + s_err = xstrtoumax (optarg, NULL, 0, &n_bytes_to_skip, multipliers); + if (s_err != LONGINT_OK) + xstrtol_fatal (s_err, oi, c, long_options, optarg); + break; + + case 'N': + modern = true; + limit_bytes_to_format = true; + + s_err = xstrtoumax (optarg, NULL, 0, &max_bytes_to_format, + multipliers); + if (s_err != LONGINT_OK) + xstrtol_fatal (s_err, oi, c, long_options, optarg); + break; + + case 'S': + modern = true; + if (optarg == NULL) + string_min = 3; + else + { + s_err = xstrtoumax (optarg, NULL, 0, &tmp, multipliers); + if (s_err != LONGINT_OK) + xstrtol_fatal (s_err, oi, c, long_options, optarg); + + /* The minimum string length may be no larger than SIZE_MAX, + since we may allocate a buffer of this size. */ + if (SIZE_MAX < tmp) + error (EXIT_FAILURE, 0, _("%s is too large"), optarg); + + string_min = tmp; + } + flag_dump_strings = true; + break; + + case 't': + modern = true; + ok &= decode_format_string (optarg); + break; + + case 'v': + modern = true; + abbreviate_duplicate_blocks = false; + break; + + case TRADITIONAL_OPTION: + traditional = true; + break; + + /* The next several cases map the traditional format + specification options to the corresponding modern format + specs. GNU od accepts any combination of old- and + new-style options. Format specification options accumulate. + The obsolescent and undocumented formats are compatible + with FreeBSD 4.10 od. */ #define CASE_OLD_ARG(old_char,new_string) \ - case old_char: \ - ok &= decode_format_string (new_string); \ - break - - CASE_OLD_ARG ('a', "a"); - CASE_OLD_ARG ('b', "o1"); - CASE_OLD_ARG ('c', "c"); - CASE_OLD_ARG ('D', "u4"); /* obsolescent and undocumented */ - CASE_OLD_ARG ('d', "u2"); - case 'F': /* obsolescent and undocumented alias */ - CASE_OLD_ARG ('e', "fD"); /* obsolescent and undocumented */ - CASE_OLD_ARG ('f', "fF"); - case 'X': /* obsolescent and undocumented alias */ - CASE_OLD_ARG ('H', "x4"); /* obsolescent and undocumented */ - CASE_OLD_ARG ('i', "dI"); - case 'I': case 'L': /* obsolescent and undocumented aliases */ - CASE_OLD_ARG ('l', "dL"); - CASE_OLD_ARG ('O', "o4"); /* obsolesent and undocumented */ - case 'B': /* obsolescent and undocumented alias */ - CASE_OLD_ARG ('o', "o2"); - CASE_OLD_ARG ('s', "d2"); - case 'h': /* obsolescent and undocumented alias */ - CASE_OLD_ARG ('x', "x2"); + case old_char: \ + ok &= decode_format_string (new_string); \ + break + + CASE_OLD_ARG ('a', "a"); + CASE_OLD_ARG ('b', "o1"); + CASE_OLD_ARG ('c', "c"); + CASE_OLD_ARG ('D', "u4"); /* obsolescent and undocumented */ + CASE_OLD_ARG ('d', "u2"); + case 'F': /* obsolescent and undocumented alias */ + CASE_OLD_ARG ('e', "fD"); /* obsolescent and undocumented */ + CASE_OLD_ARG ('f', "fF"); + case 'X': /* obsolescent and undocumented alias */ + CASE_OLD_ARG ('H', "x4"); /* obsolescent and undocumented */ + CASE_OLD_ARG ('i', "dI"); + case 'I': case 'L': /* obsolescent and undocumented aliases */ + CASE_OLD_ARG ('l', "dL"); + CASE_OLD_ARG ('O', "o4"); /* obsolesent and undocumented */ + case 'B': /* obsolescent and undocumented alias */ + CASE_OLD_ARG ('o', "o2"); + CASE_OLD_ARG ('s', "d2"); + case 'h': /* obsolescent and undocumented alias */ + CASE_OLD_ARG ('x', "x2"); #undef CASE_OLD_ARG - case 'w': - modern = true; - width_specified = true; - if (optarg == NULL) - { - desired_width = 32; - } - else - { - uintmax_t w_tmp; - s_err = xstrtoumax (optarg, NULL, 10, &w_tmp, ""); - if (s_err != LONGINT_OK) - xstrtol_fatal (s_err, oi, c, long_options, optarg); - if (SIZE_MAX < w_tmp) - error (EXIT_FAILURE, 0, _("%s is too large"), optarg); - desired_width = w_tmp; - } - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - break; - } + case 'w': + modern = true; + width_specified = true; + if (optarg == NULL) + { + desired_width = 32; + } + else + { + uintmax_t w_tmp; + s_err = xstrtoumax (optarg, NULL, 10, &w_tmp, ""); + if (s_err != LONGINT_OK) + xstrtol_fatal (s_err, oi, c, long_options, optarg); + if (SIZE_MAX < w_tmp) + error (EXIT_FAILURE, 0, _("%s is too large"), optarg); + desired_width = w_tmp; + } + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + break; + } } if (!ok) @@ -1726,20 +1726,20 @@ it must be one character from [doxn]"), if (flag_dump_strings && n_specs > 0) error (EXIT_FAILURE, 0, - _("no type may be specified when dumping strings")); + _("no type may be specified when dumping strings")); n_files = argc - optind; /* If the --traditional option is used, there may be from 0 to 3 remaining command line arguments; handle each case separately. - od [file] [[+]offset[.][b] [[+]label[.][b]]] + od [file] [[+]offset[.][b] [[+]label[.][b]]] The offset and label have the same syntax. If --traditional is not given, and if no modern options are given, and if the offset begins with + or (if there are two operands) a digit, accept only this form, as per POSIX: - od [file] [[+]offset[.][b]] + od [file] [[+]offset[.][b]] */ if (!modern | traditional) @@ -1748,81 +1748,81 @@ it must be one character from [doxn]"), uintmax_t o2; switch (n_files) - { - case 1: - if ((traditional || argv[optind][0] == '+') - && parse_old_offset (argv[optind], &o1)) - { - n_bytes_to_skip = o1; - --n_files; - ++argv; - } - break; - - case 2: - if ((traditional || argv[optind + 1][0] == '+' - || ISDIGIT (argv[optind + 1][0])) - && parse_old_offset (argv[optind + 1], &o2)) - { - if (traditional && parse_old_offset (argv[optind], &o1)) - { - n_bytes_to_skip = o1; - flag_pseudo_start = true; - pseudo_start = o2; - argv += 2; - n_files -= 2; - } - else - { - n_bytes_to_skip = o2; - --n_files; - argv[optind + 1] = argv[optind]; - ++argv; - } - } - break; - - case 3: - if (traditional - && parse_old_offset (argv[optind + 1], &o1) - && parse_old_offset (argv[optind + 2], &o2)) - { - n_bytes_to_skip = o1; - flag_pseudo_start = true; - pseudo_start = o2; - argv[optind + 2] = argv[optind]; - argv += 2; - n_files -= 2; - } - break; - } + { + case 1: + if ((traditional || argv[optind][0] == '+') + && parse_old_offset (argv[optind], &o1)) + { + n_bytes_to_skip = o1; + --n_files; + ++argv; + } + break; + + case 2: + if ((traditional || argv[optind + 1][0] == '+' + || ISDIGIT (argv[optind + 1][0])) + && parse_old_offset (argv[optind + 1], &o2)) + { + if (traditional && parse_old_offset (argv[optind], &o1)) + { + n_bytes_to_skip = o1; + flag_pseudo_start = true; + pseudo_start = o2; + argv += 2; + n_files -= 2; + } + else + { + n_bytes_to_skip = o2; + --n_files; + argv[optind + 1] = argv[optind]; + ++argv; + } + } + break; + + case 3: + if (traditional + && parse_old_offset (argv[optind + 1], &o1) + && parse_old_offset (argv[optind + 2], &o2)) + { + n_bytes_to_skip = o1; + flag_pseudo_start = true; + pseudo_start = o2; + argv[optind + 2] = argv[optind]; + argv += 2; + n_files -= 2; + } + break; + } if (traditional && 1 < n_files) - { - error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); - error (0, 0, "%s\n", - _("compatibility mode supports at most one file")); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (argv[optind + 1])); + error (0, 0, "%s\n", + _("compatibility mode supports at most one file")); + usage (EXIT_FAILURE); + } } if (flag_pseudo_start) { if (format_address == format_address_none) - { - address_base = 8; - address_pad_len = 7; - format_address = format_address_paren; - } + { + address_base = 8; + address_pad_len = 7; + format_address = format_address_paren; + } else - format_address = format_address_label; + format_address = format_address_label; } if (limit_bytes_to_format) { end_offset = n_bytes_to_skip + max_bytes_to_format; if (end_offset < n_bytes_to_skip) - error (EXIT_FAILURE, 0, _("skip-bytes + read-bytes is too large")); + error (EXIT_FAILURE, 0, _("skip-bytes + read-bytes is too large")); } if (n_specs == 0) @@ -1831,15 +1831,15 @@ it must be one character from [doxn]"), if (n_files > 0) { /* Set the global pointer FILE_LIST so that it - references the first file-argument on the command-line. */ + references the first file-argument on the command-line. */ file_list = (char const *const *) &argv[optind]; } else { /* No files were listed on the command line. - Set the global pointer FILE_LIST so that it - references the null-terminated list of one name: "-". */ + Set the global pointer FILE_LIST so that it + references the null-terminated list of one name: "-". */ file_list = default_file_list; } @@ -1862,20 +1862,20 @@ it must be one character from [doxn]"), if (width_specified) { if (desired_width != 0 && desired_width % l_c_m == 0) - bytes_per_block = desired_width; + bytes_per_block = desired_width; else - { - error (0, 0, _("warning: invalid width %lu; using %d instead"), - (unsigned long int) desired_width, l_c_m); - bytes_per_block = l_c_m; - } + { + error (0, 0, _("warning: invalid width %lu; using %d instead"), + (unsigned long int) desired_width, l_c_m); + bytes_per_block = l_c_m; + } } else { if (l_c_m < DEFAULT_BYTES_PER_BLOCK) - bytes_per_block = l_c_m * (DEFAULT_BYTES_PER_BLOCK / l_c_m); + bytes_per_block = l_c_m * (DEFAULT_BYTES_PER_BLOCK / l_c_m); else - bytes_per_block = l_c_m; + bytes_per_block = l_c_m; } /* Compute padding necessary to align output block. */ @@ -1884,7 +1884,7 @@ it must be one character from [doxn]"), int fields_per_block = bytes_per_block / width_bytes[spec[i].size]; int block_width = (spec[i].field_width + 1) * fields_per_block; if (width_per_block < block_width) - width_per_block = block_width; + width_per_block = block_width; } for (i = 0; i < n_specs; i++) { @@ -1901,8 +1901,8 @@ it must be one character from [doxn]"), assert (bytes_per_block % width_bytes[spec[i].size] == 0); assert (1 <= spec[i].pad_width / fields_per_block); printf ("%d: fmt=\"%s\" in_width=%d out_width=%d pad=%d\n", - i, spec[i].fmt_string, width_bytes[spec[i].size], - spec[i].field_width, spec[i].pad_width); + i, spec[i].fmt_string, width_bytes[spec[i].size], + spec[i].field_width, spec[i].pad_width); } #endif diff --git a/src/paste.c b/src/paste.c index 9494f4217..730a28873 100644 --- a/src/paste.c +++ b/src/paste.c @@ -26,12 +26,12 @@ Options: --serial -s Paste one file at a time rather than - one line from each file. + one line from each file. --delimiters=delim-list -d delim-list Consecutively use the characters in - DELIM-LIST instead of tab to separate - merged lines. When DELIM-LIST is exhausted, - start again at its beginning. + DELIM-LIST instead of tab to separate + merged lines. When DELIM-LIST is exhausted, + start again at its beginning. A FILE of `-' means standard input. If no FILEs are given, standard input is used. */ @@ -95,53 +95,53 @@ collapse_escapes (char const *strptr) while (*strptr) { if (*strptr != '\\') /* Is it an escape character? */ - *strout++ = *strptr++; /* No, just transfer it. */ + *strout++ = *strptr++; /* No, just transfer it. */ else - { - switch (*++strptr) - { - case '0': - *strout++ = EMPTY_DELIM; - break; - - case 'b': - *strout++ = '\b'; - break; - - case 'f': - *strout++ = '\f'; - break; - - case 'n': - *strout++ = '\n'; - break; - - case 'r': - *strout++ = '\r'; - break; - - case 't': - *strout++ = '\t'; - break; - - case 'v': - *strout++ = '\v'; - break; - - case '\\': - *strout++ = '\\'; - break; - - case '\0': - backslash_at_end = true; - goto done; - - default: - *strout++ = *strptr; - break; - } - strptr++; - } + { + switch (*++strptr) + { + case '0': + *strout++ = EMPTY_DELIM; + break; + + case 'b': + *strout++ = '\b'; + break; + + case 'f': + *strout++ = '\f'; + break; + + case 'n': + *strout++ = '\n'; + break; + + case 'r': + *strout++ = '\r'; + break; + + case 't': + *strout++ = '\t'; + break; + + case 'v': + *strout++ = '\v'; + break; + + case '\\': + *strout++ = '\\'; + break; + + case '\0': + backslash_at_end = true; + goto done; + + default: + *strout++ = *strptr; + break; + } + strptr++; + } } done:; @@ -200,18 +200,18 @@ paste_parallel (size_t nfiles, char **fnamptr) for (files_open = 0; files_open < nfiles; ++files_open) { if (STREQ (fnamptr[files_open], "-")) - { - have_read_stdin = true; - fileptr[files_open] = stdin; - } + { + have_read_stdin = true; + fileptr[files_open] = stdin; + } else - { - fileptr[files_open] = fopen (fnamptr[files_open], "r"); - if (fileptr[files_open] == NULL) - error (EXIT_FAILURE, errno, "%s", fnamptr[files_open]); - else if (fileno (fileptr[files_open]) == STDIN_FILENO) - opened_stdin = true; - } + { + fileptr[files_open] = fopen (fnamptr[files_open], "r"); + if (fileptr[files_open] == NULL) + error (EXIT_FAILURE, errno, "%s", fnamptr[files_open]); + else if (fileno (fileptr[files_open]) == STDIN_FILENO) + opened_stdin = true; + } } if (opened_stdin && have_read_stdin) @@ -230,107 +230,107 @@ paste_parallel (size_t nfiles, char **fnamptr) size_t i; for (i = 0; i < nfiles && files_open; i++) - { - int chr IF_LINT (= 0); /* Input character. */ - int err IF_LINT (= 0); /* Input errno value. */ - size_t line_length = 0; /* Number of chars in line. */ - - if (fileptr[i]) - { - chr = getc (fileptr[i]); - err = errno; - if (chr != EOF && delims_saved) - { - if (fwrite (delbuf, 1, delims_saved, stdout) != delims_saved) - write_error (); - delims_saved = 0; - } - - while (chr != EOF) - { - line_length++; - if (chr == '\n') - break; - xputchar (chr); - chr = getc (fileptr[i]); - err = errno; - } - } - - if (line_length == 0) - { - /* EOF, read error, or closed file. - If an EOF or error, close the file. */ - if (fileptr[i]) - { - if (ferror (fileptr[i])) - { - error (0, err, "%s", fnamptr[i]); - ok = false; - } - if (fileptr[i] == stdin) - clearerr (fileptr[i]); /* Also clear EOF. */ - else if (fclose (fileptr[i]) == EOF) - { - error (0, errno, "%s", fnamptr[i]); - ok = false; - } - - fileptr[i] = NULL; - files_open--; - } - - if (i + 1 == nfiles) - { - /* End of this output line. - Is this the end of the whole thing? */ - if (somedone) - { - /* No. Some files were not closed for this line. */ - if (delims_saved) - { - if (fwrite (delbuf, 1, delims_saved, stdout) - != delims_saved) - write_error (); - delims_saved = 0; - } - xputchar ('\n'); - } - continue; /* Next read of files, or exit. */ - } - else - { - /* Closed file; add delimiter to `delbuf'. */ - if (*delimptr != EMPTY_DELIM) - delbuf[delims_saved++] = *delimptr; - if (++delimptr == delim_end) - delimptr = delims; - } - } - else - { - /* Some data read. */ - somedone = true; - - /* Except for last file, replace last newline with delim. */ - if (i + 1 != nfiles) - { - if (chr != '\n' && chr != EOF) - xputchar (chr); - if (*delimptr != EMPTY_DELIM) - xputchar (*delimptr); - if (++delimptr == delim_end) - delimptr = delims; - } - else - { - /* If the last line of the last file lacks a newline, - print one anyhow. POSIX requires this. */ - char c = (chr == EOF ? '\n' : chr); - xputchar (c); - } - } - } + { + int chr IF_LINT (= 0); /* Input character. */ + int err IF_LINT (= 0); /* Input errno value. */ + size_t line_length = 0; /* Number of chars in line. */ + + if (fileptr[i]) + { + chr = getc (fileptr[i]); + err = errno; + if (chr != EOF && delims_saved) + { + if (fwrite (delbuf, 1, delims_saved, stdout) != delims_saved) + write_error (); + delims_saved = 0; + } + + while (chr != EOF) + { + line_length++; + if (chr == '\n') + break; + xputchar (chr); + chr = getc (fileptr[i]); + err = errno; + } + } + + if (line_length == 0) + { + /* EOF, read error, or closed file. + If an EOF or error, close the file. */ + if (fileptr[i]) + { + if (ferror (fileptr[i])) + { + error (0, err, "%s", fnamptr[i]); + ok = false; + } + if (fileptr[i] == stdin) + clearerr (fileptr[i]); /* Also clear EOF. */ + else if (fclose (fileptr[i]) == EOF) + { + error (0, errno, "%s", fnamptr[i]); + ok = false; + } + + fileptr[i] = NULL; + files_open--; + } + + if (i + 1 == nfiles) + { + /* End of this output line. + Is this the end of the whole thing? */ + if (somedone) + { + /* No. Some files were not closed for this line. */ + if (delims_saved) + { + if (fwrite (delbuf, 1, delims_saved, stdout) + != delims_saved) + write_error (); + delims_saved = 0; + } + xputchar ('\n'); + } + continue; /* Next read of files, or exit. */ + } + else + { + /* Closed file; add delimiter to `delbuf'. */ + if (*delimptr != EMPTY_DELIM) + delbuf[delims_saved++] = *delimptr; + if (++delimptr == delim_end) + delimptr = delims; + } + } + else + { + /* Some data read. */ + somedone = true; + + /* Except for last file, replace last newline with delim. */ + if (i + 1 != nfiles) + { + if (chr != '\n' && chr != EOF) + xputchar (chr); + if (*delimptr != EMPTY_DELIM) + xputchar (*delimptr); + if (++delimptr == delim_end) + delimptr = delims; + } + else + { + /* If the last line of the last file lacks a newline, + print one anyhow. POSIX requires this. */ + char c = (chr == EOF ? '\n' : chr); + xputchar (c); + } + } + } } free (fileptr); free (delbuf); @@ -354,70 +354,70 @@ paste_serial (size_t nfiles, char **fnamptr) int saved_errno; bool is_stdin = STREQ (*fnamptr, "-"); if (is_stdin) - { - have_read_stdin = true; - fileptr = stdin; - } + { + have_read_stdin = true; + fileptr = stdin; + } else - { - fileptr = fopen (*fnamptr, "r"); - if (fileptr == NULL) - { - error (0, errno, "%s", *fnamptr); - ok = false; - continue; - } - } + { + fileptr = fopen (*fnamptr, "r"); + if (fileptr == NULL) + { + error (0, errno, "%s", *fnamptr); + ok = false; + continue; + } + } delimptr = delims; /* Set up for delimiter string. */ charold = getc (fileptr); saved_errno = errno; if (charold != EOF) - { - /* `charold' is set up. Hit it! - Keep reading characters, stashing them in `charnew'; - output `charold', converting to the appropriate delimiter - character if needed. After the EOF, output `charold' - if it's a newline; otherwise, output it and then a newline. */ - - while ((charnew = getc (fileptr)) != EOF) - { - /* Process the old character. */ - if (charold == '\n') - { - if (*delimptr != EMPTY_DELIM) - xputchar (*delimptr); - - if (++delimptr == delim_end) - delimptr = delims; - } - else - xputchar (charold); - - charold = charnew; - } - saved_errno = errno; - - /* Hit EOF. Process that last character. */ - xputchar (charold); - } + { + /* `charold' is set up. Hit it! + Keep reading characters, stashing them in `charnew'; + output `charold', converting to the appropriate delimiter + character if needed. After the EOF, output `charold' + if it's a newline; otherwise, output it and then a newline. */ + + while ((charnew = getc (fileptr)) != EOF) + { + /* Process the old character. */ + if (charold == '\n') + { + if (*delimptr != EMPTY_DELIM) + xputchar (*delimptr); + + if (++delimptr == delim_end) + delimptr = delims; + } + else + xputchar (charold); + + charold = charnew; + } + saved_errno = errno; + + /* Hit EOF. Process that last character. */ + xputchar (charold); + } if (charold != '\n') - xputchar ('\n'); + xputchar ('\n'); if (ferror (fileptr)) - { - error (0, saved_errno, "%s", *fnamptr); - ok = false; - } + { + error (0, saved_errno, "%s", *fnamptr); + ok = false; + } if (is_stdin) - clearerr (fileptr); /* Also clear EOF. */ + clearerr (fileptr); /* Also clear EOF. */ else if (fclose (fileptr) == EOF) - { - error (0, errno, "%s", *fnamptr); - ok = false; - } + { + error (0, errno, "%s", *fnamptr); + ok = false; + } } return ok; } @@ -427,13 +427,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Write lines consisting of the sequentially corresponding lines from\n\ each FILE, separated by TABs, to standard output.\n\ @@ -476,23 +476,23 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "d:s", longopts, NULL)) != -1) { switch (optc) - { - case 'd': - /* Delimiter character(s). */ - delim_arg = (optarg[0] == '\0' ? "\\0" : optarg); - break; + { + case 'd': + /* Delimiter character(s). */ + delim_arg = (optarg[0] == '\0' ? "\\0" : optarg); + break; - case 's': - serial_merge = true; - break; + case 's': + serial_merge = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (optind == argc) @@ -501,11 +501,11 @@ main (int argc, char **argv) if (collapse_escapes (delim_arg)) { /* Don't use the default quoting style, because that would double the - number of displayed backslashes, making the diagnostic look bogus. */ + number of displayed backslashes, making the diagnostic look bogus. */ set_quoting_style (NULL, escape_quoting_style); error (EXIT_FAILURE, 0, - _("delimiter list ends with an unescaped backslash: %s"), - quotearg_colon (delim_arg)); + _("delimiter list ends with an unescaped backslash: %s"), + quotearg_colon (delim_arg)); } if (!serial_merge) diff --git a/src/pathchk.c b/src/pathchk.c index 526134507..04b70a389 100644 --- a/src/pathchk.c +++ b/src/pathchk.c @@ -91,7 +91,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... NAME...\n"), program_name); @@ -128,27 +128,27 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "+pP", longopts, NULL)) != -1) { switch (optc) - { - case PORTABILITY_OPTION: - check_basic_portability = true; - check_extra_portability = true; - break; + { + case PORTABILITY_OPTION: + check_basic_portability = true; + check_extra_portability = true; + break; - case 'p': - check_basic_portability = true; - break; + case 'p': + check_basic_portability = true; + break; - case 'P': - check_extra_portability = true; - break; + case 'P': + check_extra_portability = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (optind == argc) @@ -159,7 +159,7 @@ main (int argc, char **argv) for (; optind < argc; ++optind) ok &= validate_file_name (argv[optind], - check_basic_portability, check_extra_portability); + check_basic_portability, check_extra_portability); exit (ok ? EXIT_SUCCESS : EXIT_FAILURE); } @@ -175,9 +175,9 @@ no_leading_hyphen (char const *file) for (p = file; (p = strchr (p, '-')); p++) if (p == file || p[-1] == '/') { - error (0, 0, _("leading `-' in a component of file name %s"), - quote (file)); - return false; + error (0, 0, _("leading `-' in a component of file name %s"), + quote (file)); + return false; } return true; @@ -190,10 +190,10 @@ static bool portable_chars_only (char const *file, size_t filelen) { size_t validlen = strspn (file, - ("/" - "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789._-")); + ("/" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789._-")); char const *invalid = file + validlen; if (*invalid) @@ -201,10 +201,10 @@ portable_chars_only (char const *file, size_t filelen) DECLARE_ZEROED_AGGREGATE (mbstate_t, mbstate); size_t charlen = mbrlen (invalid, filelen - validlen, &mbstate); error (0, 0, - _("nonportable character %s in file name %s"), - quotearg_n_style_mem (1, locale_quoting_style, invalid, - (charlen <= MB_LEN_MAX ? charlen : 1)), - quote_n (0, file)); + _("nonportable character %s in file name %s"), + quotearg_n_style_mem (1, locale_quoting_style, invalid, + (charlen <= MB_LEN_MAX ? charlen : 1)), + quote_n (0, file)); return false; } @@ -254,7 +254,7 @@ component_len (char const *f) static bool validate_file_name (char *file, bool check_basic_portability, - bool check_extra_portability) + bool check_extra_portability) { size_t filelen = strlen (file); @@ -274,9 +274,9 @@ validate_file_name (char *file, bool check_basic_portability, && filelen == 0) { /* Fail, since empty names are not portable. As of - 2005-01-06 POSIX does not address whether "pathchk -p ''" - should (or is allowed to) fail, so this is not a - conformance violation. */ + 2005-01-06 POSIX does not address whether "pathchk -p ''" + should (or is allowed to) fail, so this is not a + conformance violation. */ error (0, 0, _("empty file name")); return false; } @@ -284,23 +284,23 @@ validate_file_name (char *file, bool check_basic_portability, if (check_basic_portability) { if (! portable_chars_only (file, filelen)) - return false; + return false; } else { /* Check whether a file name component is in a directory that - is not searchable, or has some other serious problem. - POSIX does not allow "" as a file name, but some non-POSIX - hosts do (as an alias for "."), so allow "" if lstat does. */ + is not searchable, or has some other serious problem. + POSIX does not allow "" as a file name, but some non-POSIX + hosts do (as an alias for "."), so allow "" if lstat does. */ struct stat st; if (lstat (file, &st) == 0) - file_exists = true; + file_exists = true; else if (errno != ENOENT || filelen == 0) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } } if (check_basic_portability @@ -309,31 +309,31 @@ validate_file_name (char *file, bool check_basic_portability, size_t maxsize; if (check_basic_portability) - maxsize = _POSIX_PATH_MAX; + maxsize = _POSIX_PATH_MAX; else - { - long int size; - char const *dir = (*file == '/' ? "/" : "."); - errno = 0; - size = pathconf (dir, _PC_PATH_MAX); - if (size < 0 && errno != 0) - { - error (0, errno, - _("%s: unable to determine maximum file name length"), - dir); - return false; - } - maxsize = MIN (size, SSIZE_MAX); - } + { + long int size; + char const *dir = (*file == '/' ? "/" : "."); + errno = 0; + size = pathconf (dir, _PC_PATH_MAX); + if (size < 0 && errno != 0) + { + error (0, errno, + _("%s: unable to determine maximum file name length"), + dir); + return false; + } + maxsize = MIN (size, SSIZE_MAX); + } if (maxsize <= filelen) - { - unsigned long int len = filelen; - unsigned long int maxlen = maxsize - 1; - error (0, 0, _("limit %lu exceeded by length %lu of file name %s"), - maxlen, len, quote (file)); - return false; - } + { + unsigned long int len = filelen; + unsigned long int maxlen = maxsize - 1; + error (0, 0, _("limit %lu exceeded by length %lu of file name %s"), + maxlen, len, quote (file)); + return false; + } } /* Check whether pathconf (..., _PC_NAME_MAX) can be avoided, i.e., @@ -345,17 +345,17 @@ validate_file_name (char *file, bool check_basic_portability, if (! check_component_lengths && ! file_exists) { for (start = file; *(start = component_start (start)); ) - { - size_t length = component_len (start); + { + size_t length = component_len (start); - if (NAME_MAX_MINIMUM < length) - { - check_component_lengths = true; - break; - } + if (NAME_MAX_MINIMUM < length) + { + check_component_lengths = true; + break; + } - start += length; - } + start += length; + } } if (check_component_lengths) @@ -370,61 +370,61 @@ validate_file_name (char *file, bool check_basic_portability, size_t known_name_max = (check_basic_portability ? _POSIX_NAME_MAX : 0); for (start = file; *(start = component_start (start)); ) - { - size_t length; - - if (known_name_max) - name_max = known_name_max; - else - { - long int len; - char const *dir = (start == file ? "." : file); - char c = *start; - errno = 0; - *start = '\0'; - len = pathconf (dir, _PC_NAME_MAX); - *start = c; - if (0 <= len) - name_max = MIN (len, SSIZE_MAX); - else - switch (errno) - { - case 0: - /* There is no limit. */ - name_max = SIZE_MAX; - break; - - case ENOENT: - /* DIR does not exist; use its parent's maximum. */ - known_name_max = name_max; - break; - - default: - *start = '\0'; - error (0, errno, "%s", dir); - *start = c; - return false; - } - } - - length = component_len (start); - - if (name_max < length) - { - unsigned long int len = length; - unsigned long int maxlen = name_max; - char c = start[len]; - start[len] = '\0'; - error (0, 0, - _("limit %lu exceeded by length %lu " - "of file name component %s"), - maxlen, len, quote (start)); - start[len] = c; - return false; - } - - start += length; - } + { + size_t length; + + if (known_name_max) + name_max = known_name_max; + else + { + long int len; + char const *dir = (start == file ? "." : file); + char c = *start; + errno = 0; + *start = '\0'; + len = pathconf (dir, _PC_NAME_MAX); + *start = c; + if (0 <= len) + name_max = MIN (len, SSIZE_MAX); + else + switch (errno) + { + case 0: + /* There is no limit. */ + name_max = SIZE_MAX; + break; + + case ENOENT: + /* DIR does not exist; use its parent's maximum. */ + known_name_max = name_max; + break; + + default: + *start = '\0'; + error (0, errno, "%s", dir); + *start = c; + return false; + } + } + + length = component_len (start); + + if (name_max < length) + { + unsigned long int len = length; + unsigned long int maxlen = name_max; + char c = start[len]; + start[len] = '\0'; + error (0, 0, + _("limit %lu exceeded by length %lu " + "of file name component %s"), + maxlen, len, quote (start)); + start[len] = c; + return false; + } + + start += length; + } } return true; diff --git a/src/pinky.c b/src/pinky.c index 8ddd218fa..f75002e1f 100644 --- a/src/pinky.c +++ b/src/pinky.c @@ -92,7 +92,7 @@ count_ampersands (const char *str) do { if (*str == '&') - count++; + count++; } while (*str++); return count; } @@ -117,7 +117,7 @@ create_fullname (const char *gecos_name, const char *user_name) size_t product = ampersands * ulen; rsize += product - ampersands; if (xalloc_oversized (ulen, ampersands) || rsize < product) - xalloc_die (); + xalloc_die (); } r = result = xmalloc (rsize); @@ -125,17 +125,17 @@ create_fullname (const char *gecos_name, const char *user_name) while (*gecos_name) { if (*gecos_name == '&') - { - const char *uname = user_name; - if (islower (to_uchar (*uname))) - *r++ = toupper (to_uchar (*uname++)); - while (*uname) - *r++ = *uname++; - } + { + const char *uname = user_name; + if (islower (to_uchar (*uname))) + *r++ = toupper (to_uchar (*uname++)); + while (*uname) + *r++ = *uname++; + } else - { - *r++ = *gecos_name; - } + { + *r++ = *gecos_name; + } gecos_name++; } @@ -249,32 +249,32 @@ print_entry (const STRUCT_UTMP *utmp_ent) name[UT_USER_SIZE] = '\0'; pw = getpwnam (name); if (pw == NULL) - /* TRANSLATORS: Real name is unknown; at most 19 characters. */ - printf (" %19s", _(" ???")); + /* TRANSLATORS: Real name is unknown; at most 19 characters. */ + printf (" %19s", _(" ???")); else - { - char *const comma = strchr (pw->pw_gecos, ','); - char *result; + { + char *const comma = strchr (pw->pw_gecos, ','); + char *result; - if (comma) - *comma = '\0'; + if (comma) + *comma = '\0'; - result = create_fullname (pw->pw_gecos, pw->pw_name); - printf (" %-19.19s", result); - free (result); - } + result = create_fullname (pw->pw_gecos, pw->pw_name); + printf (" %-19.19s", result); + free (result); + } } printf (" %c%-8.*s", - mesg, (int) sizeof (utmp_ent->ut_line), utmp_ent->ut_line); + mesg, (int) sizeof (utmp_ent->ut_line), utmp_ent->ut_line); if (include_idle) { if (last_change) - printf (" %-6s", idle_string (last_change)); + printf (" %-6s", idle_string (last_change)); else - /* TRANSLATORS: Idle time is unknown; at most 5 characters. */ - printf (" %-6s", _("?????")); + /* TRANSLATORS: Idle time is unknown; at most 5 characters. */ + printf (" %-6s", _("?????")); } printf (" %s", time_string (utmp_ent)); @@ -293,21 +293,21 @@ print_entry (const STRUCT_UTMP *utmp_ent) /* Look for an X display. */ display = strchr (ut_host, ':'); if (display) - *display++ = '\0'; + *display++ = '\0'; if (*ut_host) - /* See if we can canonicalize it. */ - host = canon_host (ut_host); + /* See if we can canonicalize it. */ + host = canon_host (ut_host); if ( ! host) - host = ut_host; + host = ut_host; if (display) - printf (" %s:%s", host, display); + printf (" %s:%s", host, display); else - printf (" %s", host); + printf (" %s", host); if (host != ut_host) - free (host); + free (host); } #endif @@ -339,7 +339,7 @@ print_long_entry (const char name[]) char *result; if (comma) - *comma = '\0'; + *comma = '\0'; result = create_fullname (pw->pw_gecos, pw->pw_name); printf (" %s", result); @@ -368,15 +368,15 @@ print_long_entry (const char name[]) stream = fopen (project, "r"); if (stream) - { - size_t bytes; + { + size_t bytes; - printf (_("Project: ")); + printf (_("Project: ")); - while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0) - fwrite (buf, 1, bytes, stdout); - fclose (stream); - } + while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0) + fwrite (buf, 1, bytes, stdout); + fclose (stream); + } free (project); } @@ -392,15 +392,15 @@ print_long_entry (const char name[]) stream = fopen (plan, "r"); if (stream) - { - size_t bytes; + { + size_t bytes; - printf (_("Plan:\n")); + printf (_("Plan:\n")); - while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0) - fwrite (buf, 1, bytes, stdout); - fclose (stream); - } + while ((bytes = fread (buf, 1, sizeof (buf), stream)) > 0) + fwrite (buf, 1, bytes, stdout); + fclose (stream); + } free (plan); } @@ -432,7 +432,7 @@ print_heading (void) static void scan_entries (size_t n, const STRUCT_UTMP *utmp_buf, - const int argc_names, char *const argv_names[]) + const int argc_names, char *const argv_names[]) { if (hard_locale (LC_TIME)) { @@ -451,22 +451,22 @@ scan_entries (size_t n, const STRUCT_UTMP *utmp_buf, while (n--) { if (IS_USER_PROCESS (utmp_buf)) - { - if (argc_names) - { - int i; - - for (i = 0; i < argc_names; i++) - if (strncmp (UT_USER (utmp_buf), argv_names[i], UT_USER_SIZE) - == 0) - { - print_entry (utmp_buf); - break; - } - } - else - print_entry (utmp_buf); - } + { + if (argc_names) + { + int i; + + for (i = 0; i < argc_names; i++) + if (strncmp (UT_USER (utmp_buf), argv_names[i], UT_USER_SIZE) + == 0) + { + print_entry (utmp_buf); + break; + } + } + else + print_entry (utmp_buf); + } utmp_buf++; } } @@ -475,7 +475,7 @@ scan_entries (size_t n, const STRUCT_UTMP *utmp_buf, static void short_pinky (const char *filename, - const int argc_names, char *const argv_names[]) + const int argc_names, char *const argv_names[]) { size_t n_users; STRUCT_UTMP *utmp_buf; @@ -500,7 +500,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [USER]...\n"), program_name); @@ -548,57 +548,57 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "sfwiqbhlp", longopts, NULL)) != -1) { switch (optc) - { - case 's': - do_short_format = true; - break; + { + case 's': + do_short_format = true; + break; - case 'l': - do_short_format = false; - break; + case 'l': + do_short_format = false; + break; - case 'f': - include_heading = false; - break; + case 'f': + include_heading = false; + break; - case 'w': - include_fullname = false; - break; + case 'w': + include_fullname = false; + break; - case 'i': - include_fullname = false; + case 'i': + include_fullname = false; #ifdef HAVE_UT_HOST - include_where = false; + include_where = false; #endif - break; + break; - case 'q': - include_fullname = false; + case 'q': + include_fullname = false; #ifdef HAVE_UT_HOST - include_where = false; + include_where = false; #endif - include_idle = false; - break; + include_idle = false; + break; - case 'h': - include_project = false; - break; + case 'h': + include_project = false; + break; - case 'p': - include_plan = false; - break; + case 'p': + include_plan = false; + break; - case 'b': - include_home_and_shell = false; - break; + case 'b': + include_home_and_shell = false; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } n_users = argc - optind; @@ -112,198 +112,198 @@ form feeds produce empty pages. +FIRST_PAGE[:LAST_PAGE], --pages=FIRST_PAGE[:LAST_PAGE] - begin [stop] printing with page FIRST_[LAST_]PAGE + begin [stop] printing with page FIRST_[LAST_]PAGE -COLUMN, --columns=COLUMN - Produce output that is COLUMN columns wide and - print columns down, unless -a is used. Balance number of - lines in the columns on each page. + Produce output that is COLUMN columns wide and + print columns down, unless -a is used. Balance number of + lines in the columns on each page. -a, --across Print columns across rather than down, used - together with -COLUMN. The input - one - two - three - four - will be printed with `-a -3' as - one two three - four + together with -COLUMN. The input + one + two + three + four + will be printed with `-a -3' as + one two three + four -b Balance columns on the last page. - -b is no longer an independent option. It's always used - together with -COLUMN (unless -a is used) to get a - consistent formulation with "FF set by hand" in input - files. Each formfeed found terminates the number of lines - to be read with the actual page. The situation for - printing columns down is equivalent to that on the last - page. So we need a balancing. - - Keeping -b as an underground option guarantees some - downward compatibility. Utilities using pr with -b - (a most frequently used form) still work as usual. + -b is no longer an independent option. It's always used + together with -COLUMN (unless -a is used) to get a + consistent formulation with "FF set by hand" in input + files. Each formfeed found terminates the number of lines + to be read with the actual page. The situation for + printing columns down is equivalent to that on the last + page. So we need a balancing. + + Keeping -b as an underground option guarantees some + downward compatibility. Utilities using pr with -b + (a most frequently used form) still work as usual. -c, --show-control-chars - Print unprintable characters as control prefixes. - Control-g is printed as ^G (use hat notation) and - octal backslash notation. + Print unprintable characters as control prefixes. + Control-g is printed as ^G (use hat notation) and + octal backslash notation. -d, --double-space Double space the output. -D FORMAT, --date-format=FORMAT Use FORMAT for the header date. -e[CHAR[WIDTH]], --expand-tabs[=CHAR[WIDTH]] - Expand tabs to spaces on input. Optional argument CHAR - is the input TAB character. (Default is TAB). Optional - argument WIDTH is the input TAB character's width. - (Default is 8.) + Expand tabs to spaces on input. Optional argument CHAR + is the input TAB character. (Default is TAB). Optional + argument WIDTH is the input TAB character's width. + (Default is 8.) -F, -f, --form-feed Use formfeeds instead of newlines to separate - pages. A three line HEADER is used, no TRAILER with -F, - without -F both HEADER and TRAILER are made of five lines. + pages. A three line HEADER is used, no TRAILER with -F, + without -F both HEADER and TRAILER are made of five lines. -h HEADER, --header=HEADER - Replace the filename in the header with the string HEADER. - A centered header is used. + Replace the filename in the header with the string HEADER. + A centered header is used. -i[CHAR[WIDTH]], --output-tabs[=CHAR[WIDTH]] - Replace spaces with tabs on output. Optional argument - CHAR is the output TAB character. (Default is TAB). - Optional argument WIDTH is the output TAB character's - width. (Default is 8) + Replace spaces with tabs on output. Optional argument + CHAR is the output TAB character. (Default is TAB). + Optional argument WIDTH is the output TAB character's + width. (Default is 8) -J, --join-lines Merge lines of full length, turns off -W/-w - line truncation, no column alignment, --sep-string[=STRING] - sets separators, works with all column options - (-COLUMN | -a -COLUMN | -m). - -J has been introduced (together with -W and --sep-string) to - disentangle the old (POSIX compliant) options -w, -s - along with the 3 column options. + line truncation, no column alignment, --sep-string[=STRING] + sets separators, works with all column options + (-COLUMN | -a -COLUMN | -m). + -J has been introduced (together with -W and --sep-string) to + disentangle the old (POSIX compliant) options -w, -s + along with the 3 column options. -l PAGE_LENGTH, --length=PAGE_LENGTH - Set the page length to PAGE_LENGTH lines. Default is 66, - including 5 lines of HEADER and 5 lines of TRAILER - without -F, but only 3 lines of HEADER and no TRAILER - with -F (i.e the number of text lines defaults to 56 or - 63 respectively). + Set the page length to PAGE_LENGTH lines. Default is 66, + including 5 lines of HEADER and 5 lines of TRAILER + without -F, but only 3 lines of HEADER and no TRAILER + with -F (i.e the number of text lines defaults to 56 or + 63 respectively). -m, --merge Print files in parallel; pad_across_to align - columns; truncate lines and print separator strings; - Do it also with empty columns to get a continuous line - numbering and column marking by separators throughout - the whole merged file. + columns; truncate lines and print separator strings; + Do it also with empty columns to get a continuous line + numbering and column marking by separators throughout + the whole merged file. - Empty pages in some input files produce empty columns - [marked by separators] in the merged pages. Completely - empty merged pages show no column separators at all. + Empty pages in some input files produce empty columns + [marked by separators] in the merged pages. Completely + empty merged pages show no column separators at all. - The layout of a merged page is ruled by the largest form - feed distance of the single pages at that page. Shorter - columns will be filled up with empty lines. + The layout of a merged page is ruled by the largest form + feed distance of the single pages at that page. Shorter + columns will be filled up with empty lines. - Together with -J option join lines of full length and - set separators when -S option is used. + Together with -J option join lines of full length and + set separators when -S option is used. -n[SEP[DIGITS]], --number-lines[=SEP[DIGITS]] - Provide DIGITS digit line numbering (default for DIGITS - is 5). With multicolumn output the number occupies the - first DIGITS column positions of each text column or only - each line of -m output. - With single column output the number precedes each line - just as -m output. - Optional argument SEP is the character appended to the - line number to separate it from the text followed. - The default separator is a TAB. In a strict sense a TAB - is always printed with single column output only. The - TAB-width varies with the TAB-position, e.g. with the - left margin specified by -o option. - With multicolumn output priority is given to `equal width - of output columns' (a POSIX specification). The TAB-width - is fixed to the value of the 1st column and does not - change with different values of left margin. That means a - fixed number of spaces is always printed in the place of - a TAB. The tabification depends upon the output - position. - - Default counting of the line numbers starts with 1st - line of the input file (not the 1st line printed, - compare the --page option and -N option). + Provide DIGITS digit line numbering (default for DIGITS + is 5). With multicolumn output the number occupies the + first DIGITS column positions of each text column or only + each line of -m output. + With single column output the number precedes each line + just as -m output. + Optional argument SEP is the character appended to the + line number to separate it from the text followed. + The default separator is a TAB. In a strict sense a TAB + is always printed with single column output only. The + TAB-width varies with the TAB-position, e.g. with the + left margin specified by -o option. + With multicolumn output priority is given to `equal width + of output columns' (a POSIX specification). The TAB-width + is fixed to the value of the 1st column and does not + change with different values of left margin. That means a + fixed number of spaces is always printed in the place of + a TAB. The tabification depends upon the output + position. + + Default counting of the line numbers starts with 1st + line of the input file (not the 1st line printed, + compare the --page option and -N option). -N NUMBER, --first-line-number=NUMBER - Start line counting with the number NUMBER at the 1st - line of first page printed (mostly not the 1st line of - the input file). + Start line counting with the number NUMBER at the 1st + line of first page printed (mostly not the 1st line of + the input file). -o MARGIN, --indent=MARGIN - Offset each line with a margin MARGIN spaces wide. - Total page width is the size of the margin plus the - PAGE_WIDTH set with -W/-w option. + Offset each line with a margin MARGIN spaces wide. + Total page width is the size of the margin plus the + PAGE_WIDTH set with -W/-w option. -r, --no-file-warnings - Omit warning when a file cannot be opened. + Omit warning when a file cannot be opened. -s[CHAR], --separator[=CHAR] - Separate columns by a single character CHAR, default for - CHAR is the TAB character without -w and 'no char' with -w. - Without `-s' default separator `space' is set. - -s[CHAR] turns off line truncation of all 3 column options - (-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX - compliant formulation. The source code translates -s into - the new options -S and -J, also -W if required. + Separate columns by a single character CHAR, default for + CHAR is the TAB character without -w and 'no char' with -w. + Without `-s' default separator `space' is set. + -s[CHAR] turns off line truncation of all 3 column options + (-COLUMN|-a -COLUMN|-m) except -w is set. That is a POSIX + compliant formulation. The source code translates -s into + the new options -S and -J, also -W if required. -S STRING, --sep-string[=STRING] - Separate columns by any string STRING. The -S option - doesn't react upon the -W/-w option (unlike -s option - does). It defines a separator nothing else. - Without -S: Default separator TAB is used with -J and - `space' otherwise (same as -S" "). - With -S "": No separator is used. - Quotes should be used with blanks and some shell active - characters. - -S is problematic because in its obsolete form you - cannot use -S "STRING", but in its standard form you - must use -S "STRING" if STRING is empty. Use - --sep-string to avoid the ambiguity. + Separate columns by any string STRING. The -S option + doesn't react upon the -W/-w option (unlike -s option + does). It defines a separator nothing else. + Without -S: Default separator TAB is used with -J and + `space' otherwise (same as -S" "). + With -S "": No separator is used. + Quotes should be used with blanks and some shell active + characters. + -S is problematic because in its obsolete form you + cannot use -S "STRING", but in its standard form you + must use -S "STRING" if STRING is empty. Use + --sep-string to avoid the ambiguity. -t, --omit-header Do not print headers or footers but retain form - feeds set in the input files. + feeds set in the input files. -T, --omit-pagination - Do not print headers or footers, eliminate any pagination - by form feeds set in the input files. + Do not print headers or footers, eliminate any pagination + by form feeds set in the input files. -v, --show-nonprinting - Print unprintable characters as escape sequences. Use - octal backslash notation. Control-G becomes \007. + Print unprintable characters as escape sequences. Use + octal backslash notation. Control-G becomes \007. -w PAGE_WIDTH, --width=PAGE_WIDTH - Set page width to PAGE_WIDTH characters for multiple - text-column output only (default for PAGE_WIDTH is 72). - -s[CHAR] turns off the default page width and any line - truncation. Lines of full length will be merged, - regardless of the column options set. A POSIX compliant - formulation. + Set page width to PAGE_WIDTH characters for multiple + text-column output only (default for PAGE_WIDTH is 72). + -s[CHAR] turns off the default page width and any line + truncation. Lines of full length will be merged, + regardless of the column options set. A POSIX compliant + formulation. -W PAGE_WIDTH, --page-width=PAGE_WIDTH - Set the page width to PAGE_WIDTH characters. That's valid - with and without a column option. Text lines will be - truncated, unless -J is used. Together with one of the - column options (-COLUMN| -a -COLUMN| -m) column alignment - is always used. - Default is 72 characters. - Without -W PAGE_WIDTH - - but with one of the column options default truncation of - 72 characters is used (to keep downward compatibility - and to simplify most frequently met column tasks). - Column alignment and column separators are used. - - and without any of the column options NO line truncation - is used (to keep downward compatibility and to meet most - frequent tasks). That's equivalent to -W 72 -J . - - With/without -W PAGE_WIDTH the header line is always - truncated to avoid line overflow. - - (In pr versions newer than 1.14 -S option does no longer - affect -W option.) + Set the page width to PAGE_WIDTH characters. That's valid + with and without a column option. Text lines will be + truncated, unless -J is used. Together with one of the + column options (-COLUMN| -a -COLUMN| -m) column alignment + is always used. + Default is 72 characters. + Without -W PAGE_WIDTH + - but with one of the column options default truncation of + 72 characters is used (to keep downward compatibility + and to simplify most frequently met column tasks). + Column alignment and column separators are used. + - and without any of the column options NO line truncation + is used (to keep downward compatibility and to meet most + frequent tasks). That's equivalent to -W 72 -J . + + With/without -W PAGE_WIDTH the header line is always + truncated to avoid line overflow. + + (In pr versions newer than 1.14 -S option does no longer + affect -W option.) */ @@ -348,27 +348,27 @@ fit the same printing loop. print_func Function used to print lines in this column. - If we're storing this column it will be - print_stored(), Otherwise it will be read_line(). + If we're storing this column it will be + print_stored(), Otherwise it will be read_line(). char_func Function used to process characters in this column. - If we're storing this column it will be store_char(), - otherwise it will be print_char(). + If we're storing this column it will be store_char(), + otherwise it will be print_char(). current_line Index of the current entry in line_vector, which - contains the index of the first character of the - current line in buff[]. + contains the index of the first character of the + current line in buff[]. lines_stored Number of lines in this column which are stored in - buff. + buff. lines_to_print If we're storing this column, lines_to_print is - the number of stored_lines which remain to be - printed. Otherwise it is the number of lines - we can print without exceeding lines_per_body. + the number of stored_lines which remain to be + printed. Otherwise it is the number of lines + we can print without exceeding lines_per_body. start_position The horizontal position we want to be in before we - print the first character in this column. + print the first character in this column. numbered True means precede this column with a line number. */ @@ -384,11 +384,11 @@ struct COLUMN char const *name; /* File name. */ enum { - OPEN, - FF_FOUND, /* used with -b option, set with \f, changed - to ON_HOLD after print_header */ - ON_HOLD, /* Hit a form feed. */ - CLOSED + OPEN, + FF_FOUND, /* used with -b option, set with \f, changed + to ON_HOLD after print_header */ + ON_HOLD, /* Hit a form feed. */ + CLOSED } status; /* Status of the file pointer. */ @@ -423,7 +423,7 @@ static void print_header (void); static void pad_across_to (int position); static void add_line_number (COLUMN *p); static void getoptarg (char *arg, char switch_char, char *character, - int *number); + int *number); void usage (int status); static void print_files (int number_of_files, char **av); static void init_parameters (int number_of_files); @@ -781,8 +781,8 @@ cols_ready_to_print (void) n = 0; for (q = column_vector, i = 0; i < columns; ++q, ++i) if (q->status == OPEN || - q->status == FF_FOUND || /* With -b: To print a header only */ - (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0)) + q->status == FF_FOUND || /* With -b: To print a header only */ + (storing_columns && q->lines_stored > 0 && q->lines_to_print > 0)) ++n; return n; } @@ -808,9 +808,9 @@ first_last_page (int oi, char c, char const *pages) char const *p1 = p + 1; err = xstrtoumax (p1, &p, 10, &last, ""); if (err != LONGINT_OK) - xstrtol_fatal (err, oi, c, long_options, pages); + xstrtol_fatal (err, oi, c, long_options, pages); if (p1 == p || last < first) - return false; + return false; } if (*p) @@ -832,7 +832,7 @@ parse_column_count (char const *s) if (xstrtol (s, NULL, 10, &tmp_long, "") != LONGINT_OK || !(1 <= tmp_long && tmp_long <= INT_MAX)) error (EXIT_FAILURE, 0, - _("invalid number of columns: %s"), quote (s)); + _("invalid number of columns: %s"), quote (s)); columns = tmp_long; explicit_columns = true; @@ -872,211 +872,211 @@ main (int argc, char **argv) n_files = 0; file_names = (argc > 1 - ? xmalloc ((argc - 1) * sizeof (char *)) - : NULL); + ? xmalloc ((argc - 1) * sizeof (char *)) + : NULL); for (;;) { int oi = -1; int c = getopt_long (argc, argv, short_options, long_options, &oi); if (c == -1) - break; + break; if (ISDIGIT (c)) - { - /* Accumulate column-count digits specified via old-style options. */ - if (n_digits + 1 >= n_alloc) - column_count_string - = X2REALLOC (column_count_string, &n_alloc); - column_count_string[n_digits++] = c; - column_count_string[n_digits] = '\0'; - continue; - } + { + /* Accumulate column-count digits specified via old-style options. */ + if (n_digits + 1 >= n_alloc) + column_count_string + = X2REALLOC (column_count_string, &n_alloc); + column_count_string[n_digits++] = c; + column_count_string[n_digits] = '\0'; + continue; + } n_digits = 0; switch (c) - { - case 1: /* Non-option argument. */ - /* long option --page dominates old `+FIRST_PAGE ...'. */ - if (! (first_page_number == 0 - && *optarg == '+' && first_last_page (-2, '+', optarg + 1))) - file_names[n_files++] = optarg; - break; - - case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */ - { /* dominates old opt +... */ - if (! optarg) - error (EXIT_FAILURE, 0, - _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument")); - else if (! first_last_page (oi, 0, optarg)) - error (EXIT_FAILURE, 0, _("invalid page range %s"), - quote (optarg)); - break; - } - - case COLUMNS_OPTION: /* --columns=COLUMN */ - { - parse_column_count (optarg); - - /* If there was a prior column count specified via the - short-named option syntax, e.g., -9, ensure that this - long-name-specified value overrides it. */ - free (column_count_string); - column_count_string = NULL; - n_alloc = 0; - break; - } - - case 'a': - print_across_flag = true; - storing_columns = false; - break; - case 'b': - balance_columns = true; - break; - case 'c': - use_cntrl_prefix = true; - break; - case 'd': - double_space = true; - break; - case 'D': - date_format = optarg; - break; - case 'e': - if (optarg) - getoptarg (optarg, 'e', &input_tab_char, - &chars_per_input_tab); - /* Could check tab width > 0. */ - untabify_input = true; - break; - case 'f': - case 'F': - use_form_feed = true; - break; - case 'h': - custom_header = optarg; - break; - case 'i': - if (optarg) - getoptarg (optarg, 'i', &output_tab_char, - &chars_per_output_tab); - /* Could check tab width > 0. */ - tabify_output = true; - break; - case 'J': - join_lines = true; - break; - case 'l': - { - long int tmp_long; - if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long <= 0 || tmp_long > INT_MAX) - { - error (EXIT_FAILURE, 0, - _("`-l PAGE_LENGTH' invalid number of lines: %s"), - quote (optarg)); - } - lines_per_page = tmp_long; - break; - } - case 'm': - parallel_files = true; - storing_columns = false; - break; - case 'n': - numbered_lines = true; - if (optarg) - getoptarg (optarg, 'n', &number_separator, - &chars_per_number); - break; - case 'N': - skip_count = false; - { - long int tmp_long; - if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long > INT_MAX) - { - error (EXIT_FAILURE, 0, - _("`-N NUMBER' invalid starting line number: %s"), - quote (optarg)); - } - start_line_num = tmp_long; - break; - } - case 'o': - { - long int tmp_long; - if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long < 0 || tmp_long > INT_MAX) - error (EXIT_FAILURE, 0, - _("`-o MARGIN' invalid line offset: %s"), quote (optarg)); - chars_per_margin = tmp_long; - break; - } - case 'r': - ignore_failed_opens = true; - break; - case 's': - old_options = true; - old_s = true; - if (!use_col_separator && optarg) - separator_string (optarg); - break; - case 'S': - old_s = false; - /* Reset an additional input of -s, -S dominates -s */ - col_sep_string = bad_cast (""); - col_sep_length = 0; - use_col_separator = true; - if (optarg) - separator_string (optarg); - break; - case 't': - extremities = false; - keep_FF = true; - break; - case 'T': - extremities = false; - keep_FF = false; - break; - case 'v': - use_esc_sequence = true; - break; - case 'w': - old_options = true; - old_w = true; - { - long int tmp_long; - if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long <= 0 || tmp_long > INT_MAX) - error (EXIT_FAILURE, 0, - _("`-w PAGE_WIDTH' invalid number of characters: %s"), - quote (optarg)); - if (!truncate_lines) - chars_per_line = tmp_long; - break; - } - case 'W': - old_w = false; /* dominates -w */ - truncate_lines = true; - { - long int tmp_long; - if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long <= 0 || tmp_long > INT_MAX) - error (EXIT_FAILURE, 0, - _("`-W PAGE_WIDTH' invalid number of characters: %s"), - quote (optarg)); - chars_per_line = tmp_long; - break; - } - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - break; - } + { + case 1: /* Non-option argument. */ + /* long option --page dominates old `+FIRST_PAGE ...'. */ + if (! (first_page_number == 0 + && *optarg == '+' && first_last_page (-2, '+', optarg + 1))) + file_names[n_files++] = optarg; + break; + + case PAGES_OPTION: /* --pages=FIRST_PAGE[:LAST_PAGE] */ + { /* dominates old opt +... */ + if (! optarg) + error (EXIT_FAILURE, 0, + _("`--pages=FIRST_PAGE[:LAST_PAGE]' missing argument")); + else if (! first_last_page (oi, 0, optarg)) + error (EXIT_FAILURE, 0, _("invalid page range %s"), + quote (optarg)); + break; + } + + case COLUMNS_OPTION: /* --columns=COLUMN */ + { + parse_column_count (optarg); + + /* If there was a prior column count specified via the + short-named option syntax, e.g., -9, ensure that this + long-name-specified value overrides it. */ + free (column_count_string); + column_count_string = NULL; + n_alloc = 0; + break; + } + + case 'a': + print_across_flag = true; + storing_columns = false; + break; + case 'b': + balance_columns = true; + break; + case 'c': + use_cntrl_prefix = true; + break; + case 'd': + double_space = true; + break; + case 'D': + date_format = optarg; + break; + case 'e': + if (optarg) + getoptarg (optarg, 'e', &input_tab_char, + &chars_per_input_tab); + /* Could check tab width > 0. */ + untabify_input = true; + break; + case 'f': + case 'F': + use_form_feed = true; + break; + case 'h': + custom_header = optarg; + break; + case 'i': + if (optarg) + getoptarg (optarg, 'i', &output_tab_char, + &chars_per_output_tab); + /* Could check tab width > 0. */ + tabify_output = true; + break; + case 'J': + join_lines = true; + break; + case 'l': + { + long int tmp_long; + if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK + || tmp_long <= 0 || tmp_long > INT_MAX) + { + error (EXIT_FAILURE, 0, + _("`-l PAGE_LENGTH' invalid number of lines: %s"), + quote (optarg)); + } + lines_per_page = tmp_long; + break; + } + case 'm': + parallel_files = true; + storing_columns = false; + break; + case 'n': + numbered_lines = true; + if (optarg) + getoptarg (optarg, 'n', &number_separator, + &chars_per_number); + break; + case 'N': + skip_count = false; + { + long int tmp_long; + if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK + || tmp_long > INT_MAX) + { + error (EXIT_FAILURE, 0, + _("`-N NUMBER' invalid starting line number: %s"), + quote (optarg)); + } + start_line_num = tmp_long; + break; + } + case 'o': + { + long int tmp_long; + if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK + || tmp_long < 0 || tmp_long > INT_MAX) + error (EXIT_FAILURE, 0, + _("`-o MARGIN' invalid line offset: %s"), quote (optarg)); + chars_per_margin = tmp_long; + break; + } + case 'r': + ignore_failed_opens = true; + break; + case 's': + old_options = true; + old_s = true; + if (!use_col_separator && optarg) + separator_string (optarg); + break; + case 'S': + old_s = false; + /* Reset an additional input of -s, -S dominates -s */ + col_sep_string = bad_cast (""); + col_sep_length = 0; + use_col_separator = true; + if (optarg) + separator_string (optarg); + break; + case 't': + extremities = false; + keep_FF = true; + break; + case 'T': + extremities = false; + keep_FF = false; + break; + case 'v': + use_esc_sequence = true; + break; + case 'w': + old_options = true; + old_w = true; + { + long int tmp_long; + if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK + || tmp_long <= 0 || tmp_long > INT_MAX) + error (EXIT_FAILURE, 0, + _("`-w PAGE_WIDTH' invalid number of characters: %s"), + quote (optarg)); + if (!truncate_lines) + chars_per_line = tmp_long; + break; + } + case 'W': + old_w = false; /* dominates -w */ + truncate_lines = true; + { + long int tmp_long; + if (xstrtol (optarg, NULL, 10, &tmp_long, "") != LONGINT_OK + || tmp_long <= 0 || tmp_long > INT_MAX) + error (EXIT_FAILURE, 0, + _("`-W PAGE_WIDTH' invalid number of characters: %s"), + quote (optarg)); + chars_per_line = tmp_long; + break; + } + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + break; + } } if (column_count_string) @@ -1087,8 +1087,8 @@ main (int argc, char **argv) if (! date_format) date_format = (getenv ("POSIXLY_CORRECT") && !hard_locale (LC_TIME) - ? "%b %e %H:%M %Y" - : "%Y-%m-%d %H:%M"); + ? "%b %e %H:%M %Y" + : "%Y-%m-%d %H:%M"); /* Now we can set a reasonable initial value: */ if (first_page_number == 0) @@ -1096,7 +1096,7 @@ main (int argc, char **argv) if (parallel_files & explicit_columns) error (EXIT_FAILURE, 0, - _("cannot specify number of columns when printing in parallel")); + _("cannot specify number of columns when printing in parallel")); if (parallel_files & print_across_flag) error (EXIT_FAILURE, 0, @@ -1111,40 +1111,40 @@ main (int argc, char **argv) if (old_w) { if (parallel_files | explicit_columns) - { - /* activate -W */ - truncate_lines = true; - if (old_s) - /* adapt HP-UX and SunOS: -s = no separator; - activate -S */ - use_col_separator = true; - } - else - /* old -w sets width with columns only - activate -J */ - join_lines = true; - } + { + /* activate -W */ + truncate_lines = true; + if (old_s) + /* adapt HP-UX and SunOS: -s = no separator; + activate -S */ + use_col_separator = true; + } + else + /* old -w sets width with columns only + activate -J */ + join_lines = true; + } else if (!use_col_separator) { - /* No -S option read */ + /* No -S option read */ if (old_s & (parallel_files | explicit_columns)) - { - if (!truncate_lines) - { - /* old -s (without -w and -W) annuls column alignment, - uses fields, activate -J */ - join_lines = true; - if (col_sep_length > 0) - /* activate -S */ - use_col_separator = true; - } - else - /* with -W */ - /* adapt HP-UX and SunOS: -s = no separator; - activate -S */ - use_col_separator = true; - } - } + { + if (!truncate_lines) + { + /* old -s (without -w and -W) annuls column alignment, + uses fields, activate -J */ + join_lines = true; + if (col_sep_length > 0) + /* activate -S */ + use_col_separator = true; + } + else + /* with -W */ + /* adapt HP-UX and SunOS: -s = no separator; + activate -S */ + use_col_separator = true; + } + } } for (; optind < argc; optind++) @@ -1160,13 +1160,13 @@ main (int argc, char **argv) else { if (parallel_files) - print_files (n_files, file_names); + print_files (n_files, file_names); else - { - int i; - for (i = 0; i < n_files; i++) - print_files (1, &file_names[i]); - } + { + int i; + for (i = 0; i < n_files; i++) + print_files (1, &file_names[i]); + } } cleanup (); @@ -1193,13 +1193,13 @@ getoptarg (char *arg, char switch_char, char *character, int *number) { long int tmp_long; if (xstrtol (arg, NULL, 10, &tmp_long, "") != LONGINT_OK - || tmp_long <= 0 || tmp_long > INT_MAX) - { - error (0, 0, - _("`-%c' extra characters or invalid number in the argument: %s"), - switch_char, quote (arg)); - usage (EXIT_FAILURE); - } + || tmp_long <= 0 || tmp_long > INT_MAX) + { + error (0, 0, + _("`-%c' extra characters or invalid number in the argument: %s"), + switch_char, quote (arg)); + usage (EXIT_FAILURE); + } *number = tmp_long; } } @@ -1240,16 +1240,16 @@ init_parameters (int number_of_files) if (columns > 1) { if (!use_col_separator) - { - /* Use default separator */ - if (join_lines) - col_sep_string = line_separator; - else - col_sep_string = column_separator; - - col_sep_length = 1; - use_col_separator = true; - } + { + /* Use default separator */ + if (join_lines) + col_sep_string = line_separator; + else + col_sep_string = column_separator; + + col_sep_length = 1; + use_col_separator = true; + } /* It's rather pointless to define a TAB separator with column alignment */ else if (!join_lines && *col_sep_string == '\t') @@ -1273,21 +1273,21 @@ init_parameters (int number_of_files) line_count = start_line_num; /* To allow input tab-expansion (-e sensitive) use: - if (number_separator == input_tab_char) - number_width = chars_per_number + - TAB_WIDTH (chars_per_input_tab, chars_per_number); */ + if (number_separator == input_tab_char) + number_width = chars_per_number + + TAB_WIDTH (chars_per_input_tab, chars_per_number); */ /* Estimate chars_per_text without any margin and keep it constant. */ if (number_separator == '\t') - number_width = chars_per_number + - TAB_WIDTH (chars_per_default_tab, chars_per_number); + number_width = chars_per_number + + TAB_WIDTH (chars_per_default_tab, chars_per_number); else - number_width = chars_per_number + 1; + number_width = chars_per_number + 1; /* The number is part of the column width unless we are - printing files in parallel. */ + printing files in parallel. */ if (parallel_files) - chars_used_by_number = number_width; + chars_used_by_number = number_width; /* We use power_10 to cut off the higher-order digits of the line_number in function add_line_number */ @@ -1297,7 +1297,7 @@ init_parameters (int number_of_files) } chars_per_column = (chars_per_line - chars_used_by_number - - (columns - 1) * col_sep_length) / columns; + (columns - 1) * col_sep_length) / columns; if (chars_per_column < 1) error (EXIT_FAILURE, 0, _("page width too narrow")); @@ -1345,49 +1345,49 @@ init_fps (int number_of_files, char **av) { files_left = number_of_files; for (p = column_vector; files_left--; ++p, ++av) - { - if (! open_file (*av, p)) - { - --p; - --columns; - } - } + { + if (! open_file (*av, p)) + { + --p; + --columns; + } + } if (columns == 0) - return false; + return false; init_header ("", -1); } else { p = column_vector; if (number_of_files > 0) - { - if (! open_file (*av, p)) - return false; - init_header (*av, fileno (p->fp)); - p->lines_stored = 0; - } + { + if (! open_file (*av, p)) + return false; + init_header (*av, fileno (p->fp)); + p->lines_stored = 0; + } else - { - p->name = _("standard input"); - p->fp = stdin; - have_read_stdin = true; - p->status = OPEN; - p->full_page_printed = false; - ++total_files; - init_header ("", -1); - p->lines_stored = 0; - } + { + p->name = _("standard input"); + p->fp = stdin; + have_read_stdin = true; + p->status = OPEN; + p->full_page_printed = false; + ++total_files; + init_header ("", -1); + p->lines_stored = 0; + } firstname = p->name; firstfp = p->fp; for (i = columns - 1, ++p; i; --i, ++p) - { - p->name = firstname; - p->fp = firstfp; - p->status = OPEN; - p->full_page_printed = false; - p->lines_stored = 0; - } + { + p->name = firstname; + p->fp = firstfp; + p->status = OPEN; + p->full_page_printed = false; + p->lines_stored = 0; + } } files_ready_to_read = total_files; return true; @@ -1415,9 +1415,9 @@ init_funcs (void) first column to accomodate the number. Looks better than the Sys V approach. */ if (parallel_files & numbered_lines) - h_next = h + chars_per_column + number_width; + h_next = h + chars_per_column + number_width; else - h_next = h + chars_per_column; + h_next = h + chars_per_column; } /* Enlarge p->start_position of first column to use the same form of @@ -1429,16 +1429,16 @@ init_funcs (void) for (p = column_vector, i = 1; i < columns; ++p, ++i) { if (storing_columns) /* One file, multi columns down. */ - { - p->char_func = store_char; - p->print_func = print_stored; - } + { + p->char_func = store_char; + p->print_func = print_stored; + } else - /* One file, multi columns across; or parallel files. */ - { - p->char_func = print_char; - p->print_func = read_line; - } + /* One file, multi columns across; or parallel files. */ + { + p->char_func = print_char; + p->print_func = read_line; + } /* Number only the first column when printing files in parallel. */ @@ -1450,15 +1450,15 @@ init_funcs (void) using a margin. */ if (!truncate_lines) - { - h = ANYWHERE; - h_next = ANYWHERE; - } + { + h = ANYWHERE; + h_next = ANYWHERE; + } else - { - h = h_next + col_sep_length; - h_next = h + chars_per_column; - } + { + h = h_next + col_sep_length; + h_next = h + chars_per_column; + } } /* The rightmost column. @@ -1503,7 +1503,7 @@ open_file (char *name, COLUMN *p) { failed_opens = true; if (!ignore_failed_opens) - error (0, errno, "%s", name); + error (0, errno, "%s", name); return false; } p->status = OPEN; @@ -1533,13 +1533,13 @@ close_file (COLUMN *p) if (!parallel_files) { for (q = column_vector, i = columns; i; ++q, --i) - { - q->status = CLOSED; - if (q->lines_stored == 0) - { - q->lines_to_print = 0; - } - } + { + q->status = CLOSED; + if (q->lines_stored == 0) + { + q->lines_to_print = 0; + } + } } else { @@ -1565,10 +1565,10 @@ hold_file (COLUMN *p) if (!parallel_files) for (q = column_vector, i = columns; i; ++q, --i) { - if (storing_columns) - q->status = FF_FOUND; - else - q->status = ON_HOLD; + if (storing_columns) + q->status = FF_FOUND; + else + q->status = ON_HOLD; } else p->status = ON_HOLD; @@ -1589,8 +1589,8 @@ reset_status (void) for (p = column_vector; i; --i, ++p) if (p->status == ON_HOLD) { - p->status = OPEN; - files_ready_to_read++; + p->status = OPEN; + files_ready_to_read++; } if (storing_columns) @@ -1624,9 +1624,9 @@ print_files (int number_of_files, char **av) if (first_page_number > 1) { if (!skip_to_page (first_page_number)) - return; + return; else - page_number = first_page_number; + page_number = first_page_number; } else page_number = 1; @@ -1660,7 +1660,7 @@ init_header (char const *filename, int desc) { static struct timespec timespec; if (! timespec.tv_sec) - gettime (×pec); + gettime (×pec); t = timespec; } @@ -1669,7 +1669,7 @@ init_header (char const *filename, int desc) if (tm == NULL) { buf = xmalloc (INT_BUFSIZE_BOUND (long int) - + MAX (10, INT_BUFSIZE_BOUND (int))); + + MAX (10, INT_BUFSIZE_BOUND (int))); sprintf (buf, "%ld.%09d", (long int) t.tv_sec, ns); } else @@ -1683,8 +1683,8 @@ init_header (char const *filename, int desc) date_text = buf; file_text = custom_header ? custom_header : desc < 0 ? "" : filename; header_width_available = (chars_per_line - - mbswidth (date_text, 0) - - mbswidth (file_text, 0)); + - mbswidth (date_text, 0) + - mbswidth (file_text, 0)); } /* Set things up for printing a page @@ -1707,35 +1707,35 @@ init_page (void) { store_columns (); for (j = columns - 1, p = column_vector; j; --j, ++p) - { - p->lines_to_print = p->lines_stored; - } + { + p->lines_to_print = p->lines_stored; + } /* Last column. */ if (balance_columns) - { - p->lines_to_print = p->lines_stored; - } + { + p->lines_to_print = p->lines_stored; + } /* Since we're not balancing columns, we don't need to store the rightmost column. Read it straight from the file. */ else - { - if (p->status == OPEN) - { - p->lines_to_print = lines_per_body; - } - else - p->lines_to_print = 0; - } + { + if (p->status == OPEN) + { + p->lines_to_print = lines_per_body; + } + else + p->lines_to_print = 0; + } } else for (j = columns, p = column_vector; j; --j, ++p) if (p->status == OPEN) - { - p->lines_to_print = lines_per_body; - } + { + p->lines_to_print = lines_per_body; + } else - p->lines_to_print = 0; + p->lines_to_print = 0; } /* Align empty columns and print separators. @@ -1812,67 +1812,67 @@ print_page (void) empty_line = true; for (j = 1, p = column_vector; j <= columns; ++j, ++p) - { - input_position = 0; - if (p->lines_to_print > 0 || p->status == FF_FOUND) - { - FF_only = false; - padding_not_printed = p->start_position; - if (!(p->print_func) (p)) - read_rest_of_line (p); - pv |= pad_vertically; - - --p->lines_to_print; - if (p->lines_to_print <= 0) - { - if (cols_ready_to_print () <= 0) - break; - } - - /* File p changed its status to ON_HOLD or CLOSED */ - if (parallel_files && p->status != OPEN) - { - if (empty_line) - align_empty_cols = true; - else if (p->status == CLOSED || - (p->status == ON_HOLD && FF_only)) - align_column (p); - } - } - else if (parallel_files) - { - /* File status ON_HOLD or CLOSED */ - if (empty_line) - align_empty_cols = true; - else - align_column (p); - } - - /* We need it also with an empty column */ - if (use_col_separator) - ++separators_not_printed; - } + { + input_position = 0; + if (p->lines_to_print > 0 || p->status == FF_FOUND) + { + FF_only = false; + padding_not_printed = p->start_position; + if (!(p->print_func) (p)) + read_rest_of_line (p); + pv |= pad_vertically; + + --p->lines_to_print; + if (p->lines_to_print <= 0) + { + if (cols_ready_to_print () <= 0) + break; + } + + /* File p changed its status to ON_HOLD or CLOSED */ + if (parallel_files && p->status != OPEN) + { + if (empty_line) + align_empty_cols = true; + else if (p->status == CLOSED || + (p->status == ON_HOLD && FF_only)) + align_column (p); + } + } + else if (parallel_files) + { + /* File status ON_HOLD or CLOSED */ + if (empty_line) + align_empty_cols = true; + else + align_column (p); + } + + /* We need it also with an empty column */ + if (use_col_separator) + ++separators_not_printed; + } if (pad_vertically) - { - putchar ('\n'); - --lines_left_on_page; - } + { + putchar ('\n'); + --lines_left_on_page; + } if (cols_ready_to_print () <= 0 && !extremities) - break; + break; if (double_space & pv) - { - putchar ('\n'); - --lines_left_on_page; - } + { + putchar ('\n'); + --lines_left_on_page; + } } if (lines_left_on_page == 0) for (j = 1, p = column_vector; j <= columns; ++j, ++p) if (p->status == OPEN) - p->full_page_printed = true; + p->full_page_printed = true; pad_vertically = pv; @@ -1921,8 +1921,8 @@ init_store_cols (void) free (buff); buff_allocated = (use_col_separator - ? 2 * chars_if_truncate - : chars_if_truncate); /* Tune this. */ + ? 2 * chars_if_truncate + : chars_if_truncate); /* Tune this. */ buff = xmalloc (buff_allocated); } @@ -1964,22 +1964,22 @@ store_columns (void) p->current_line = line; for (j = lines_per_body; j && files_ready_to_read; --j) - if (p->status == OPEN) /* Redundant. Clean up. */ - { - input_position = 0; - - if (!read_line (p)) - read_rest_of_line (p); - - if (p->status == OPEN - || buff_start != buff_current) - { - ++p->lines_stored; - line_vector[line] = buff_start; - end_vector[line++] = input_position; - buff_start = buff_current; - } - } + if (p->status == OPEN) /* Redundant. Clean up. */ + { + input_position = 0; + + if (!read_line (p)) + read_rest_of_line (p); + + if (p->status == OPEN + || buff_start != buff_current) + { + ++p->lines_stored; + line_vector[line] = buff_start; + end_vector[line++] = input_position; + buff_start = buff_current; + } + } } /* Keep track of the location of the last char in buff. */ @@ -2000,7 +2000,7 @@ balance (int total_stored) { lines = total_stored / columns; if (i <= total_stored % columns) - ++lines; + ++lines; p->lines_stored = lines; p->current_line = first_line; @@ -2046,13 +2046,13 @@ add_line_number (COLUMN *p) if (columns > 1) { /* Tabification is assumed for multiple columns, also for n-separators, - but `default n-separator = TAB' hasn't been given priority over - equal column_width also specified by POSIX. */ + but `default n-separator = TAB' hasn't been given priority over + equal column_width also specified by POSIX. */ if (number_separator == '\t') { i = number_width - chars_per_number; while (i-- > 0) - (p->char_func) (' '); + (p->char_func) (' '); } else (p->char_func) (number_separator); @@ -2065,7 +2065,7 @@ add_line_number (COLUMN *p) (p->char_func) (number_separator); if (number_separator == '\t') output_position = POS_AFTER_TAB (chars_per_output_tab, - output_position); + output_position); } if (truncate_lines & !parallel_files) @@ -2085,7 +2085,7 @@ pad_across_to (int position) else { while (++h <= position) - putchar (' '); + putchar (' '); output_position = position; } } @@ -2122,19 +2122,19 @@ read_rest_of_line (COLUMN *p) while ((c = getc (f)) != '\n') { if (c == '\f') - { - if ((c = getc (f)) != '\n') - ungetc (c, f); - if (keep_FF) - print_a_FF = true; - hold_file (p); - break; - } + { + if ((c = getc (f)) != '\n') + ungetc (c, f); + if (keep_FF) + print_a_FF = true; + hold_file (p); + break; + } else if (c == EOF) - { - close_file (p); - break; - } + { + close_file (p); + break; + } } } @@ -2178,28 +2178,28 @@ skip_read (COLUMN *p, int column_number) while (c != '\n') { if (c == '\f') - { - /* No FF-coincidence possible, - no catching up of a FF-coincidence with next page */ - if (last_line) - { - if (!parallel_files) - for (q = column_vector, i = columns; i; ++q, --i) - q->full_page_printed = false; - else - p->full_page_printed = false; - } - - if ((c = getc (f)) != '\n') - ungetc (c, f); - hold_file (p); - break; - } + { + /* No FF-coincidence possible, + no catching up of a FF-coincidence with next page */ + if (last_line) + { + if (!parallel_files) + for (q = column_vector, i = columns; i; ++q, --i) + q->full_page_printed = false; + else + p->full_page_printed = false; + } + + if ((c = getc (f)) != '\n') + ungetc (c, f); + hold_file (p); + break; + } else if (c == EOF) - { - close_file (p); - break; - } + { + close_file (p); + break; + } c = getc (f); } @@ -2222,7 +2222,7 @@ print_white_space (void) int goal = h_old + spaces_not_printed; while (goal - h_old > 1 - && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal) + && (h_new = POS_AFTER_TAB (chars_per_output_tab, h_old)) <= goal) { putchar (output_tab_char); h_old = h_new; @@ -2251,35 +2251,35 @@ print_sep_string (void) { /* We'll be starting a line with chars_per_margin, anything else? */ if (spaces_not_printed > 0) - print_white_space (); + print_white_space (); } else { for (; separators_not_printed > 0; --separators_not_printed) - { - while (l-- > 0) - { - /* 3 types of sep_strings: spaces only, spaces and chars, - chars only */ - if (*s == ' ') - { - /* We're tabifying output; consecutive spaces in - sep_string may have to be converted to tabs */ - s++; - ++spaces_not_printed; - } - else - { - if (spaces_not_printed > 0) - print_white_space (); - putchar (*s++); - ++output_position; - } - } + { + while (l-- > 0) + { + /* 3 types of sep_strings: spaces only, spaces and chars, + chars only */ + if (*s == ' ') + { + /* We're tabifying output; consecutive spaces in + sep_string may have to be converted to tabs */ + s++; + ++spaces_not_printed; + } + else + { + if (spaces_not_printed > 0) + print_white_space (); + putchar (*s++); + ++output_position; + } + } /* sep_string ends with some spaces */ - if (spaces_not_printed > 0) - print_white_space (); - } + if (spaces_not_printed > 0) + print_white_space (); + } } } @@ -2308,21 +2308,21 @@ print_char (char c) if (tabify_output) { if (c == ' ') - { - ++spaces_not_printed; - return; - } + { + ++spaces_not_printed; + return; + } else if (spaces_not_printed > 0) - print_white_space (); + print_white_space (); /* Nonprintables are assumed to have width 0, except '\b'. */ if (! isprint (to_uchar (c))) - { - if (c == '\b') - --output_position; - } + { + if (c == '\b') + --output_position; + } else - ++output_position; + ++output_position; } putchar (c); } @@ -2341,34 +2341,34 @@ skip_to_page (uintmax_t page) for (n = 1; n < page; ++n) { for (i = 1; i < lines_per_body; ++i) - { - for (j = 1, p = column_vector; j <= columns; ++j, ++p) - if (p->status == OPEN) - skip_read (p, j); - } + { + for (j = 1, p = column_vector; j <= columns; ++j, ++p) + if (p->status == OPEN) + skip_read (p, j); + } last_line = true; for (j = 1, p = column_vector; j <= columns; ++j, ++p) - if (p->status == OPEN) - skip_read (p, j); + if (p->status == OPEN) + skip_read (p, j); if (storing_columns) /* change FF_FOUND to ON_HOLD */ - for (j = 1, p = column_vector; j <= columns; ++j, ++p) - if (p->status != CLOSED) - p->status = ON_HOLD; + for (j = 1, p = column_vector; j <= columns; ++j, ++p) + if (p->status != CLOSED) + p->status = ON_HOLD; reset_status (); last_line = false; if (files_ready_to_read < 1) { - /* It's very helpful, normally the total number of pages is - not known in advance. */ - error (0, 0, - _("starting page number %"PRIuMAX - " exceeds page count %"PRIuMAX), - page, n); + /* It's very helpful, normally the total number of pages is + not known in advance. */ + error (0, 0, + _("starting page number %"PRIuMAX + " exceeds page count %"PRIuMAX), + page, n); break; - } + } } return files_ready_to_read > 0; } @@ -2455,15 +2455,15 @@ read_line (COLUMN *p) { case '\f': if ((c = getc (p->fp)) != '\n') - ungetc (c, p->fp); + ungetc (c, p->fp); FF_only = true; if (print_a_header & !storing_columns) - { - pad_vertically = true; - print_header (); - } + { + pad_vertically = true; + print_header (); + } else if (keep_FF) - print_a_FF = true; + print_a_FF = true; hold_file (p); return true; case EOF: @@ -2486,34 +2486,34 @@ read_line (COLUMN *p) pad_vertically = true; if (print_a_header & !storing_columns) - print_header (); + print_header (); if (parallel_files & align_empty_cols) - { - /* We have to align empty columns at the beginning of a line. */ - k = separators_not_printed; - separators_not_printed = 0; - for (j = 1, q = column_vector; j <= k; ++j, ++q) - { - align_column (q); - separators_not_printed += 1; - } - padding_not_printed = p->start_position; - if (truncate_lines) - spaces_not_printed = chars_per_column; - else - spaces_not_printed = 0; - align_empty_cols = false; - } + { + /* We have to align empty columns at the beginning of a line. */ + k = separators_not_printed; + separators_not_printed = 0; + for (j = 1, q = column_vector; j <= k; ++j, ++q) + { + align_column (q); + separators_not_printed += 1; + } + padding_not_printed = p->start_position; + if (truncate_lines) + spaces_not_printed = chars_per_column; + else + spaces_not_printed = 0; + align_empty_cols = false; + } if (padding_not_printed - col_sep_length > 0) - { - pad_across_to (padding_not_printed - col_sep_length); - padding_not_printed = ANYWHERE; - } + { + pad_across_to (padding_not_printed - col_sep_length); + padding_not_printed = ANYWHERE; + } if (use_col_separator) - print_sep_string (); + print_sep_string (); } if (p->numbered) @@ -2530,28 +2530,28 @@ read_line (COLUMN *p) c = getc (p->fp); switch (c) - { - case '\n': - return true; - case '\f': - if ((c = getc (p->fp)) != '\n') - ungetc (c, p->fp); - if (keep_FF) - print_a_FF = true; - hold_file (p); - return true; - case EOF: - close_file (p); - return true; - } + { + case '\n': + return true; + case '\f': + if ((c = getc (p->fp)) != '\n') + ungetc (c, p->fp); + if (keep_FF) + print_a_FF = true; + hold_file (p); + return true; + case EOF: + close_file (p); + return true; + } last_input_position = input_position; chars = char_to_clump (c); if (truncate_lines && input_position > chars_per_column) - { - input_position = last_input_position; - return false; - } + { + input_position = last_input_position; + return false; + } print_clump (p, chars, clump_buff); } @@ -2600,13 +2600,13 @@ print_stored (COLUMN *p) if (p->status == FF_FOUND) { for (i = 1, q = column_vector; i <= columns; ++i, ++q) - q->status = ON_HOLD; + q->status = ON_HOLD; if (column_vector->lines_to_print <= 0) - { - if (!extremities) - pad_vertically = false; - return true; /* print a header only */ - } + { + if (!extremities) + pad_vertically = false; + return true; /* print a header only */ + } } if (padding_not_printed - col_sep_length > 0) @@ -2625,7 +2625,7 @@ print_stored (COLUMN *p) { output_position = p->start_position + end_vector[line]; if (p->start_position - col_sep_length == chars_per_margin) - output_position -= col_sep_length; + output_position -= col_sep_length; } return true; @@ -2662,60 +2662,60 @@ char_to_clump (char c) width = TAB_WIDTH (chars_per_c, input_position); if (untabify_input) - { - for (i = width; i; --i) - *s++ = ' '; - chars = width; - } + { + for (i = width; i; --i) + *s++ = ' '; + chars = width; + } else - { - *s = c; - chars = 1; - } + { + *s = c; + chars = 1; + } } else if (! isprint (uc)) { if (use_esc_sequence) - { - width = 4; - chars = 4; - *s++ = '\\'; - sprintf (esc_buff, "%03o", uc); - for (i = 0; i <= 2; ++i) - *s++ = esc_buff[i]; - } + { + width = 4; + chars = 4; + *s++ = '\\'; + sprintf (esc_buff, "%03o", uc); + for (i = 0; i <= 2; ++i) + *s++ = esc_buff[i]; + } else if (use_cntrl_prefix) - { - if (uc < 0200) - { - width = 2; - chars = 2; - *s++ = '^'; - *s++ = c ^ 0100; - } - else - { - width = 4; - chars = 4; - *s++ = '\\'; - sprintf (esc_buff, "%03o", uc); - for (i = 0; i <= 2; ++i) - *s++ = esc_buff[i]; - } - } + { + if (uc < 0200) + { + width = 2; + chars = 2; + *s++ = '^'; + *s++ = c ^ 0100; + } + else + { + width = 4; + chars = 4; + *s++ = '\\'; + sprintf (esc_buff, "%03o", uc); + for (i = 0; i <= 2; ++i) + *s++ = esc_buff[i]; + } + } else if (c == '\b') - { - width = -1; - chars = 1; - *s = c; - } + { + width = -1; + chars = 1; + *s = c; + } else - { - width = 0; - chars = 1; - *s = c; - } + { + width = 0; + chars = 1; + *s = c; + } } else { @@ -2761,13 +2761,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Paginate or columnate FILE(s) for printing.\n\ diff --git a/src/printenv.c b/src/printenv.c index 7c9b54441..69e2a6639 100644 --- a/src/printenv.c +++ b/src/printenv.c @@ -52,7 +52,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -62,7 +62,7 @@ Print the values of the specified environment VARIABLE(s).\n\ If no VARIABLE is specified, print name and value pairs for them all.\n\ \n\ "), - program_name, program_name); + program_name, program_name); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME); @@ -89,14 +89,14 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "+", NULL, NULL) != -1) usage (PRINTENV_FAILURE); if (optind >= argc) { for (env = environ; *env != NULL; ++env) - puts (*env); + puts (*env); ok = true; } else @@ -104,26 +104,26 @@ main (int argc, char **argv) int matches = 0; for (i = optind; i < argc; ++i) - { - bool matched = false; - - for (env = environ; *env; ++env) - { - ep = *env; - ap = argv[i]; - while (*ep != '\0' && *ap != '\0' && *ep++ == *ap++) - { - if (*ep == '=' && *ap == '\0') - { - puts (ep + 1); - matched = true; - break; - } - } - } - - matches += matched; - } + { + bool matched = false; + + for (env = environ; *env; ++env) + { + ep = *env; + ap = argv[i]; + while (*ep != '\0' && *ap != '\0' && *ep++ == *ap++) + { + if (*ep == '=' && *ap == '\0') + { + puts (ep + 1); + matched = true; + break; + } + } + } + + matches += matched; + } ok = (matches == argc - optind); } diff --git a/src/printf.c b/src/printf.c index 89fa45628..5fa25dee8 100644 --- a/src/printf.c +++ b/src/printf.c @@ -63,7 +63,7 @@ #define isodigit(c) ((c) >= '0' && (c) <= '7') #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \ - (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0') + (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0') #define octtobin(c) ((c) - '0') /* The value to return to the calling program. */ @@ -82,14 +82,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s FORMAT [ARGUMENT]...\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Print ARGUMENT(s) according to FORMAT, or execute according to OPTION:\n\ \n\ @@ -146,9 +146,9 @@ verify_numeric (const char *s, const char *end) else if (*end) { if (s == end) - error (0, 0, _("%s: expected a numeric value"), s); + error (0, 0, _("%s: expected a numeric value"), s); else - error (0, 0, _("%s: value not completely converted"), s); + error (0, 0, _("%s: value not completely converted"), s); exit_status = EXIT_FAILURE; } } @@ -159,17 +159,17 @@ FUNC_NAME (char const *s) \ { \ char *end; \ TYPE val; \ - \ + \ if (*s == '\"' || *s == '\'') \ { \ unsigned char ch = *++s; \ val = ch; \ /* If POSIXLY_CORRECT is not set, then give a warning that there \ - are characters following the character constant and that GNU \ - printf is ignoring those characters. If POSIXLY_CORRECT *is* \ - set, then don't give the warning. */ \ + are characters following the character constant and that GNU \ + printf is ignoring those characters. If POSIXLY_CORRECT *is* \ + set, then don't give the warning. */ \ if (*++s != 0 && !posixly_correct) \ - error (0, 0, _(cfcc_msg), s); \ + error (0, 0, _(cfcc_msg), s); \ } \ else \ { \ @@ -238,11 +238,11 @@ print_esc (const char *escstart, bool octal_0) { /* A hexadecimal \xhh escape sequence must have 1 or 2 hex. digits. */ for (esc_length = 0, ++p; - esc_length < 2 && isxdigit (to_uchar (*p)); - ++esc_length, ++p) - esc_value = esc_value * 16 + hextobin (*p); + esc_length < 2 && isxdigit (to_uchar (*p)); + ++esc_length, ++p) + esc_value = esc_value * 16 + hextobin (*p); if (esc_length == 0) - error (EXIT_FAILURE, 0, _("missing hexadecimal number in escape")); + error (EXIT_FAILURE, 0, _("missing hexadecimal number in escape")); putchar (esc_value); } else if (isodigit (*p)) @@ -251,9 +251,9 @@ print_esc (const char *escstart, bool octal_0) Allow \ooo if octal_0 && *p != '0'; this is an undocumented extension to POSIX that is compatible with Bash 2.05b. */ for (esc_length = 0, p += octal_0 && *p == '0'; - esc_length < 3 && isodigit (*p); - ++esc_length, ++p) - esc_value = esc_value * 8 + octtobin (*p); + esc_length < 3 && isodigit (*p); + ++esc_length, ++p) + esc_value = esc_value * 8 + octtobin (*p); putchar (esc_value); } else if (*p && strchr ("\"\\abcfnrtv", *p)) @@ -265,24 +265,24 @@ print_esc (const char *escstart, bool octal_0) uni_value = 0; for (esc_length = (esc_char == 'u' ? 4 : 8), ++p; - esc_length > 0; - --esc_length, ++p) - { - if (! isxdigit (to_uchar (*p))) - error (EXIT_FAILURE, 0, _("missing hexadecimal number in escape")); - uni_value = uni_value * 16 + hextobin (*p); - } + esc_length > 0; + --esc_length, ++p) + { + if (! isxdigit (to_uchar (*p))) + error (EXIT_FAILURE, 0, _("missing hexadecimal number in escape")); + uni_value = uni_value * 16 + hextobin (*p); + } /* A universal character name shall not specify a character short - identifier in the range 00000000 through 00000020, 0000007F through - 0000009F, or 0000D800 through 0000DFFF inclusive. A universal - character name shall not designate a character in the required - character set. */ + identifier in the range 00000000 through 00000020, 0000007F through + 0000009F, or 0000D800 through 0000DFFF inclusive. A universal + character name shall not designate a character in the required + character set. */ if ((uni_value <= 0x9f - && uni_value != 0x24 && uni_value != 0x40 && uni_value != 0x60) - || (uni_value >= 0xd800 && uni_value <= 0xdfff)) - error (EXIT_FAILURE, 0, _("invalid universal character name \\%c%0*x"), - esc_char, (esc_char == 'u' ? 4 : 8), uni_value); + && uni_value != 0x24 && uni_value != 0x40 && uni_value != 0x60) + || (uni_value >= 0xd800 && uni_value <= 0xdfff)) + error (EXIT_FAILURE, 0, _("invalid universal character name \\%c%0*x"), + esc_char, (esc_char == 'u' ? 4 : 8), uni_value); print_unicode_char (stdout, uni_value, 0); } @@ -290,10 +290,10 @@ print_esc (const char *escstart, bool octal_0) { putchar ('\\'); if (*p) - { - putchar (*p); - p++; - } + { + putchar (*p); + p++; + } } return p - escstart - 1; } @@ -320,9 +320,9 @@ print_esc_string (const char *str) static void print_direc (const char *start, size_t length, char conversion, - bool have_field_width, int field_width, - bool have_precision, int precision, - char const *argument) + bool have_field_width, int field_width, + bool have_precision, int precision, + char const *argument) { char *p; /* Null-terminated copy of % directive. */ @@ -337,20 +337,20 @@ print_direc (const char *start, size_t length, char conversion, switch (conversion) { case 'd': case 'i': case 'o': case 'u': case 'x': case 'X': - length_modifier = PRIdMAX; - length_modifier_len = sizeof PRIdMAX - 2; - break; + length_modifier = PRIdMAX; + length_modifier_len = sizeof PRIdMAX - 2; + break; case 'a': case 'e': case 'f': case 'g': case 'A': case 'E': case 'F': case 'G': - length_modifier = "L"; - length_modifier_len = 1; - break; + length_modifier = "L"; + length_modifier_len = 1; + break; default: - length_modifier = start; /* Any valid pointer will do. */ - length_modifier_len = 0; - break; + length_modifier = start; /* Any valid pointer will do. */ + length_modifier_len = 0; + break; } p = xmalloc (length + length_modifier_len + 2); @@ -365,21 +365,21 @@ print_direc (const char *start, size_t length, char conversion, case 'd': case 'i': { - intmax_t arg = vstrtoimax (argument); - if (!have_field_width) - { - if (!have_precision) - xprintf (p, arg); - else - xprintf (p, precision, arg); - } - else - { - if (!have_precision) - xprintf (p, field_width, arg); - else - xprintf (p, field_width, precision, arg); - } + intmax_t arg = vstrtoimax (argument); + if (!have_field_width) + { + if (!have_precision) + xprintf (p, arg); + else + xprintf (p, precision, arg); + } + else + { + if (!have_precision) + xprintf (p, field_width, arg); + else + xprintf (p, field_width, precision, arg); + } } break; @@ -388,21 +388,21 @@ print_direc (const char *start, size_t length, char conversion, case 'x': case 'X': { - uintmax_t arg = vstrtoumax (argument); - if (!have_field_width) - { - if (!have_precision) - xprintf (p, arg); - else - xprintf (p, precision, arg); - } - else - { - if (!have_precision) - xprintf (p, field_width, arg); - else - xprintf (p, field_width, precision, arg); - } + uintmax_t arg = vstrtoumax (argument); + if (!have_field_width) + { + if (!have_precision) + xprintf (p, arg); + else + xprintf (p, precision, arg); + } + else + { + if (!have_precision) + xprintf (p, field_width, arg); + else + xprintf (p, field_width, precision, arg); + } } break; @@ -415,46 +415,46 @@ print_direc (const char *start, size_t length, char conversion, case 'g': case 'G': { - long double arg = vstrtold (argument); - if (!have_field_width) - { - if (!have_precision) - xprintf (p, arg); - else - xprintf (p, precision, arg); - } - else - { - if (!have_precision) - xprintf (p, field_width, arg); - else - xprintf (p, field_width, precision, arg); - } + long double arg = vstrtold (argument); + if (!have_field_width) + { + if (!have_precision) + xprintf (p, arg); + else + xprintf (p, precision, arg); + } + else + { + if (!have_precision) + xprintf (p, field_width, arg); + else + xprintf (p, field_width, precision, arg); + } } break; case 'c': if (!have_field_width) - xprintf (p, *argument); + xprintf (p, *argument); else - xprintf (p, field_width, *argument); + xprintf (p, field_width, *argument); break; case 's': if (!have_field_width) - { - if (!have_precision) - xprintf (p, argument); - else - xprintf (p, precision, argument); - } + { + if (!have_precision) + xprintf (p, argument); + else + xprintf (p, precision, argument); + } else - { - if (!have_precision) - xprintf (p, field_width, argument); - else - xprintf (p, field_width, precision, argument); - } + { + if (!have_precision) + xprintf (p, field_width, argument); + else + xprintf (p, field_width, precision, argument); + } break; } @@ -481,146 +481,146 @@ print_formatted (const char *format, int argc, char **argv) for (f = format; *f; ++f) { switch (*f) - { - case '%': - direc_start = f++; - direc_length = 1; - have_field_width = have_precision = false; - if (*f == '%') - { - putchar ('%'); - break; - } - if (*f == 'b') - { - /* FIXME: Field width and precision are not supported - for %b, even though POSIX requires it. */ - if (argc > 0) - { - print_esc_string (*argv); - ++argv; - --argc; - } - break; - } - - memset (ok, 0, sizeof ok); - ok['a'] = ok['A'] = ok['c'] = ok['d'] = ok['e'] = ok['E'] = - ok['f'] = ok['F'] = ok['g'] = ok['G'] = ok['i'] = ok['o'] = - ok['s'] = ok['u'] = ok['x'] = ok['X'] = 1; - - for (;; f++, direc_length++) - switch (*f) - { + { + case '%': + direc_start = f++; + direc_length = 1; + have_field_width = have_precision = false; + if (*f == '%') + { + putchar ('%'); + break; + } + if (*f == 'b') + { + /* FIXME: Field width and precision are not supported + for %b, even though POSIX requires it. */ + if (argc > 0) + { + print_esc_string (*argv); + ++argv; + --argc; + } + break; + } + + memset (ok, 0, sizeof ok); + ok['a'] = ok['A'] = ok['c'] = ok['d'] = ok['e'] = ok['E'] = + ok['f'] = ok['F'] = ok['g'] = ok['G'] = ok['i'] = ok['o'] = + ok['s'] = ok['u'] = ok['x'] = ok['X'] = 1; + + for (;; f++, direc_length++) + switch (*f) + { #if (__GLIBC__ == 2 && 2 <= __GLIBC_MINOR__) || 3 <= __GLIBC__ - case 'I': + case 'I': #endif - case '\'': - ok['a'] = ok['A'] = ok['c'] = ok['e'] = ok['E'] = - ok['o'] = ok['s'] = ok['x'] = ok['X'] = 0; - break; - case '-': case '+': case ' ': - break; - case '#': - ok['c'] = ok['d'] = ok['i'] = ok['s'] = ok['u'] = 0; - break; - case '0': - ok['c'] = ok['s'] = 0; - break; - default: - goto no_more_flag_characters; - } - no_more_flag_characters:; - - if (*f == '*') - { - ++f; - ++direc_length; - if (argc > 0) - { - intmax_t width = vstrtoimax (*argv); - if (INT_MIN <= width && width <= INT_MAX) - field_width = width; - else - error (EXIT_FAILURE, 0, _("invalid field width: %s"), - *argv); - ++argv; - --argc; - } - else - field_width = 0; - have_field_width = true; - } - else - while (ISDIGIT (*f)) - { - ++f; - ++direc_length; - } - if (*f == '.') - { - ++f; - ++direc_length; - ok['c'] = 0; - if (*f == '*') - { - ++f; - ++direc_length; - if (argc > 0) - { - intmax_t prec = vstrtoimax (*argv); - if (prec < 0) - { - /* A negative precision is taken as if the - precision were omitted, so -1 is safe - here even if prec < INT_MIN. */ - precision = -1; - } - else if (INT_MAX < prec) - error (EXIT_FAILURE, 0, _("invalid precision: %s"), - *argv); - else - precision = prec; - ++argv; - --argc; - } - else - precision = 0; - have_precision = true; - } - else - while (ISDIGIT (*f)) - { - ++f; - ++direc_length; - } - } - - while (*f == 'l' || *f == 'L' || *f == 'h' - || *f == 'j' || *f == 't' || *f == 'z') - ++f; - - { - unsigned char conversion = *f; - if (! ok[conversion]) - error (EXIT_FAILURE, 0, - _("%.*s: invalid conversion specification"), - (int) (f + 1 - direc_start), direc_start); - } - - print_direc (direc_start, direc_length, *f, - have_field_width, field_width, - have_precision, precision, - (argc <= 0 ? "" : (argc--, *argv++))); - break; - - case '\\': - f += print_esc (f, false); - break; - - default: - putchar (*f); - } + case '\'': + ok['a'] = ok['A'] = ok['c'] = ok['e'] = ok['E'] = + ok['o'] = ok['s'] = ok['x'] = ok['X'] = 0; + break; + case '-': case '+': case ' ': + break; + case '#': + ok['c'] = ok['d'] = ok['i'] = ok['s'] = ok['u'] = 0; + break; + case '0': + ok['c'] = ok['s'] = 0; + break; + default: + goto no_more_flag_characters; + } + no_more_flag_characters:; + + if (*f == '*') + { + ++f; + ++direc_length; + if (argc > 0) + { + intmax_t width = vstrtoimax (*argv); + if (INT_MIN <= width && width <= INT_MAX) + field_width = width; + else + error (EXIT_FAILURE, 0, _("invalid field width: %s"), + *argv); + ++argv; + --argc; + } + else + field_width = 0; + have_field_width = true; + } + else + while (ISDIGIT (*f)) + { + ++f; + ++direc_length; + } + if (*f == '.') + { + ++f; + ++direc_length; + ok['c'] = 0; + if (*f == '*') + { + ++f; + ++direc_length; + if (argc > 0) + { + intmax_t prec = vstrtoimax (*argv); + if (prec < 0) + { + /* A negative precision is taken as if the + precision were omitted, so -1 is safe + here even if prec < INT_MIN. */ + precision = -1; + } + else if (INT_MAX < prec) + error (EXIT_FAILURE, 0, _("invalid precision: %s"), + *argv); + else + precision = prec; + ++argv; + --argc; + } + else + precision = 0; + have_precision = true; + } + else + while (ISDIGIT (*f)) + { + ++f; + ++direc_length; + } + } + + while (*f == 'l' || *f == 'L' || *f == 'h' + || *f == 'j' || *f == 't' || *f == 'z') + ++f; + + { + unsigned char conversion = *f; + if (! ok[conversion]) + error (EXIT_FAILURE, 0, + _("%.*s: invalid conversion specification"), + (int) (f + 1 - direc_start), direc_start); + } + + print_direc (direc_start, direc_length, *f, + have_field_width, field_width, + have_precision, precision, + (argc <= 0 ? "" : (argc--, *argv++))); + break; + + case '\\': + f += print_esc (f, false); + break; + + default: + putchar (*f); + } } return save_argc - argc; @@ -649,14 +649,14 @@ main (int argc, char **argv) if (argc == 2) { if (STREQ (argv[1], "--help")) - usage (EXIT_SUCCESS); + usage (EXIT_SUCCESS); if (STREQ (argv[1], "--version")) - { - version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, - (char *) NULL); - exit (EXIT_SUCCESS); - } + { + version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, + (char *) NULL); + exit (EXIT_SUCCESS); + } } /* The above handles --help and --version. @@ -687,8 +687,8 @@ main (int argc, char **argv) if (argc > 0) error (0, 0, - _("warning: ignoring excess arguments, starting with %s"), - quote (argv[0])); + _("warning: ignoring excess arguments, starting with %s"), + quote (argv[0])); exit (exit_status); } @@ -44,7 +44,7 @@ #define ISODIGIT(C) ((C) >= '0' && (C) <= '7') #define HEXTOBIN(C) ((C) >= 'a' && (C) <= 'f' ? (C)-'a'+10 \ - : (C) >= 'A' && (C) <= 'F' ? (C)-'A'+10 : (C)-'0') + : (C) >= 'A' && (C) <= 'F' ? (C)-'A'+10 : (C)-'0') #define OCTTOBIN(C) ((C) - '0') /* Debugging the memory allocator. */ @@ -82,10 +82,10 @@ static bool right_reference = false; /* output refs after right context */ static int line_width = 72; /* output line width in characters */ static int gap_size = 3; /* number of spaces between output fields */ static const char *truncation_string = "/"; - /* string used to mark line truncations */ + /* string used to mark line truncations */ static const char *macro_name = "xx"; /* macro name for roff or TeX output */ static enum Format output_format = UNKNOWN_FORMAT; - /* output format */ + /* output format */ static bool ignore_case = false; /* fold lower to upper for sorting */ static const char *break_file = NULL; /* name of the `Break characters' file */ @@ -306,94 +306,94 @@ copy_unescaped_string (const char *string) while (*string) { if (*string == '\\') - { - string++; - switch (*string) - { - case 'x': /* \xhhh escape, 3 chars maximum */ - value = 0; - for (length = 0, string++; - length < 3 && isxdigit (to_uchar (*string)); - length++, string++) - value = value * 16 + HEXTOBIN (*string); - if (length == 0) - { - *cursor++ = '\\'; - *cursor++ = 'x'; - } - else - *cursor++ = value; - break; - - case '0': /* \0ooo escape, 3 chars maximum */ - value = 0; - for (length = 0, string++; - length < 3 && ISODIGIT (*string); - length++, string++) - value = value * 8 + OCTTOBIN (*string); - *cursor++ = value; - break; - - case 'a': /* alert */ + { + string++; + switch (*string) + { + case 'x': /* \xhhh escape, 3 chars maximum */ + value = 0; + for (length = 0, string++; + length < 3 && isxdigit (to_uchar (*string)); + length++, string++) + value = value * 16 + HEXTOBIN (*string); + if (length == 0) + { + *cursor++ = '\\'; + *cursor++ = 'x'; + } + else + *cursor++ = value; + break; + + case '0': /* \0ooo escape, 3 chars maximum */ + value = 0; + for (length = 0, string++; + length < 3 && ISODIGIT (*string); + length++, string++) + value = value * 8 + OCTTOBIN (*string); + *cursor++ = value; + break; + + case 'a': /* alert */ #if __STDC__ - *cursor++ = '\a'; + *cursor++ = '\a'; #else - *cursor++ = 7; + *cursor++ = 7; #endif - string++; - break; - - case 'b': /* backspace */ - *cursor++ = '\b'; - string++; - break; - - case 'c': /* cancel the rest of the output */ - while (*string) - string++; - break; - - case 'f': /* form feed */ - *cursor++ = '\f'; - string++; - break; - - case 'n': /* new line */ - *cursor++ = '\n'; - string++; - break; - - case 'r': /* carriage return */ - *cursor++ = '\r'; - string++; - break; - - case 't': /* horizontal tab */ - *cursor++ = '\t'; - string++; - break; - - case 'v': /* vertical tab */ + string++; + break; + + case 'b': /* backspace */ + *cursor++ = '\b'; + string++; + break; + + case 'c': /* cancel the rest of the output */ + while (*string) + string++; + break; + + case 'f': /* form feed */ + *cursor++ = '\f'; + string++; + break; + + case 'n': /* new line */ + *cursor++ = '\n'; + string++; + break; + + case 'r': /* carriage return */ + *cursor++ = '\r'; + string++; + break; + + case 't': /* horizontal tab */ + *cursor++ = '\t'; + string++; + break; + + case 'v': /* vertical tab */ #if __STDC__ - *cursor++ = '\v'; + *cursor++ = '\v'; #else - *cursor++ = 11; + *cursor++ = 11; #endif - string++; - break; - - case '\0': /* lone backslash at end of string */ - /* ignore it */ - break; - - default: - *cursor++ = '\\'; - *cursor++ = *string++; - break; - } - } + string++; + break; + + case '\0': /* lone backslash at end of string */ + /* ignore it */ + break; + + default: + *cursor++ = '\\'; + *cursor++ = *string++; + break; + } + } else - *cursor++ = *string++; + *cursor++ = *string++; } *cursor = '\0'; @@ -453,7 +453,7 @@ initialize_regex (void) if (context_regex.string) { if (!*context_regex.string) - context_regex.string = NULL; + context_regex.string = NULL; } else if (gnu_extensions & !input_reference) context_regex.string = "[.?!][]\"')}]*\\($\\|\t\\| \\)[ \t\n]*"; @@ -476,23 +476,23 @@ initialize_regex (void) else if (!break_file) { if (gnu_extensions) - { + { - /* Simulate \w+. */ + /* Simulate \w+. */ - for (character = 0; character < CHAR_SET_SIZE; character++) - word_fastmap[character] = !! isalpha (character); - } + for (character = 0; character < CHAR_SET_SIZE; character++) + word_fastmap[character] = !! isalpha (character); + } else - { + { - /* Simulate [^ \t\n]+. */ + /* Simulate [^ \t\n]+. */ - memset (word_fastmap, 1, CHAR_SET_SIZE); - word_fastmap[' '] = 0; - word_fastmap['\t'] = 0; - word_fastmap['\n'] = 0; - } + memset (word_fastmap, 1, CHAR_SET_SIZE); + word_fastmap[' '] = 0; + word_fastmap['\t'] = 0; + word_fastmap['\n'] = 0; + } } } @@ -541,23 +541,23 @@ swallow_file_in_memory (const char *file_name, BLOCK *block) block->start = xmalloc ((size_t) stat_block.st_size); if ((in_memory_size = read (file_handle, - block->start, (size_t) stat_block.st_size)) - != stat_block.st_size) - { + block->start, (size_t) stat_block.st_size)) + != stat_block.st_size) + { #if MSDOS - /* On MSDOS, in memory size may be smaller than the file - size, because of end of line conversions. But it can - never be smaller than half the file size, because the - minimum is when all lines are empty and terminated by - CR+LF. */ - if (in_memory_size != (size_t)-1 - && in_memory_size >= stat_block.st_size / 2) - block->start = xrealloc (block->start, in_memory_size); - else + /* On MSDOS, in memory size may be smaller than the file + size, because of end of line conversions. But it can + never be smaller than half the file size, because the + minimum is when all lines are empty and terminated by + CR+LF. */ + if (in_memory_size != (size_t)-1 + && in_memory_size >= stat_block.st_size / 2) + block->start = xrealloc (block->start, in_memory_size); + else #endif /* not MSDOS */ - error (EXIT_FAILURE, errno, "%s", file_name); - } + error (EXIT_FAILURE, errno, "%s", file_name); + } block->end = block->start + in_memory_size; } else @@ -567,21 +567,21 @@ swallow_file_in_memory (const char *file_name, BLOCK *block) allocated_length = (1 << SWALLOW_REALLOC_LOG); while (read_length = read (file_handle, - block->start + used_length, - allocated_length - used_length), - read_length > 0) - { - used_length += read_length; - if (used_length == allocated_length) - { - allocated_length += (1 << SWALLOW_REALLOC_LOG); - block->start - = xrealloc (block->start, allocated_length); - } - } + block->start + used_length, + allocated_length - used_length), + read_length > 0) + { + used_length += read_length; + if (used_length == allocated_length) + { + allocated_length += (1 << SWALLOW_REALLOC_LOG); + block->start + = xrealloc (block->start, allocated_length); + } + } if (read_length < 0) - error (EXIT_FAILURE, errno, "%s", file_name); + error (EXIT_FAILURE, errno, "%s", file_name); block->end = block->start + used_length; } @@ -616,22 +616,22 @@ compare_words (const void *void_first, const void *void_second) if (ignore_case) { for (counter = 0; counter < length; counter++) - { - value = (folded_chars [to_uchar (first->start[counter])] - - folded_chars [to_uchar (second->start[counter])]); - if (value != 0) - return value; - } + { + value = (folded_chars [to_uchar (first->start[counter])] + - folded_chars [to_uchar (second->start[counter])]); + if (value != 0) + return value; + } } else { for (counter = 0; counter < length; counter++) - { - value = (to_uchar (first->start[counter]) - - to_uchar (second->start[counter])); - if (value != 0) - return value; - } + { + value = (to_uchar (first->start[counter]) + - to_uchar (second->start[counter])); + if (value != 0) + return value; + } } return first->size - second->size; @@ -677,11 +677,11 @@ search_table (WORD *word, WORD_TABLE *table) middle = (lowest + highest) / 2; value = compare_words (word, table->start + middle); if (value < 0) - highest = middle - 1; + highest = middle - 1; else if (value > 0) - lowest = middle + 1; + lowest = middle + 1; else - return 1; + return 1; } return 0; } @@ -699,7 +699,7 @@ sort_found_occurs (void) /* Only one language for the time being. */ qsort (occurs_table[0], number_of_occurs[0], sizeof **occurs_table, - compare_occurs); + compare_occurs); } /* Parameter files reading routines. */ @@ -728,10 +728,10 @@ digest_break_file (const char *file_name) { /* If GNU extensions are enabled, the only way to avoid newline as - a break character is to write all the break characters in the - file with no newline at all, not even at the end of the file. - If disabled, spaces, tabs and newlines are always considered as - break characters even if not included in the break file. */ + a break character is to write all the break characters in the + file with no newline at all, not even at the end of the file. + If disabled, spaces, tabs and newlines are always considered as + break characters even if not included in the break file. */ word_fastmap[' '] = 0; word_fastmap['\t'] = 0; @@ -773,30 +773,30 @@ digest_word_file (const char *file_name, WORD_TABLE *table) word_start = cursor; while (cursor < file_contents.end && *cursor != '\n') - cursor++; + cursor++; /* Record the word in table if it is not empty. */ if (cursor > word_start) - { - if (table->length == table->alloc) - { - if ((SIZE_MAX / sizeof *table->start - 1) / 2 < table->alloc) - xalloc_die (); - table->alloc = table->alloc * 2 + 1; - table->start = xrealloc (table->start, - table->alloc * sizeof *table->start); - } - - table->start[table->length].start = word_start; - table->start[table->length].size = cursor - word_start; - table->length++; - } + { + if (table->length == table->alloc) + { + if ((SIZE_MAX / sizeof *table->start - 1) / 2 < table->alloc) + xalloc_die (); + table->alloc = table->alloc * 2 + 1; + table->start = xrealloc (table->start, + table->alloc * sizeof *table->start); + } + + table->start[table->length].start = word_start; + table->start[table->length].size = cursor - word_start; + table->length++; + } /* This test allows for an incomplete line at end of file. */ if (cursor < file_contents.end) - cursor++; + cursor++; } /* Finally, sort all the words read. */ @@ -859,223 +859,223 @@ find_occurs_in_text (void) { /* `context_start' gets initialized before the processing of each - line, or once for the whole buffer if no end of line or sentence - sequence separator. */ + line, or once for the whole buffer if no end of line or sentence + sequence separator. */ context_start = cursor; /* If a end of line or end of sentence sequence is defined and - non-empty, `next_context_start' will be recomputed to be the end of - each line or sentence, before each one is processed. If no such - sequence, then `next_context_start' is set at the end of the whole - buffer, which is then considered to be a single line or sentence. - This test also accounts for the case of an incomplete line or - sentence at the end of the buffer. */ + non-empty, `next_context_start' will be recomputed to be the end of + each line or sentence, before each one is processed. If no such + sequence, then `next_context_start' is set at the end of the whole + buffer, which is then considered to be a single line or sentence. + This test also accounts for the case of an incomplete line or + sentence at the end of the buffer. */ next_context_start = text_buffer.end; if (context_regex.string) - switch (re_search (&context_regex.pattern, cursor, - text_buffer.end - cursor, - 0, text_buffer.end - cursor, &context_regs)) - { - case -2: - matcher_error (); + switch (re_search (&context_regex.pattern, cursor, + text_buffer.end - cursor, + 0, text_buffer.end - cursor, &context_regs)) + { + case -2: + matcher_error (); - case -1: - break; + case -1: + break; - default: - next_context_start = cursor + context_regs.end[0]; - break; - } + default: + next_context_start = cursor + context_regs.end[0]; + break; + } /* Include the separator into the right context, but not any suffix - white space in this separator; this insures it will be seen in - output and will not take more space than necessary. */ + white space in this separator; this insures it will be seen in + output and will not take more space than necessary. */ context_end = next_context_start; SKIP_WHITE_BACKWARDS (context_end, context_start); /* Read and process a single input line or sentence, one word at a - time. */ + time. */ while (1) - { - if (word_regex.string) - - /* If a word regexp has been compiled, use it to skip at the - beginning of the next word. If there is no such word, exit - the loop. */ - - { - regoff_t r = re_search (&word_regex.pattern, cursor, - context_end - cursor, - 0, context_end - cursor, &word_regs); - if (r == -2) - matcher_error (); - if (r == -1) - break; - word_start = cursor + word_regs.start[0]; - word_end = cursor + word_regs.end[0]; - } - else - - /* Avoid re_search and use the fastmap to skip to the - beginning of the next word. If there is no more word in - the buffer, exit the loop. */ - - { - scan = cursor; - while (scan < context_end - && !word_fastmap[to_uchar (*scan)]) - scan++; - - if (scan == context_end) - break; - - word_start = scan; - - while (scan < context_end - && word_fastmap[to_uchar (*scan)]) - scan++; - - word_end = scan; - } - - /* Skip right to the beginning of the found word. */ - - cursor = word_start; - - /* Skip any zero length word. Just advance a single position, - then go fetch the next word. */ - - if (word_end == word_start) - { - cursor++; - continue; - } - - /* This is a genuine, non empty word, so save it as a possible - key. Then skip over it. Also, maintain the maximum length of - all words read so far. It is mandatory to take the maximum - length of all words in the file, without considering if they - are actually kept or rejected, because backward jumps at output - generation time may fall in *any* word. */ - - possible_key.start = cursor; - possible_key.size = word_end - word_start; - cursor += possible_key.size; - - if (possible_key.size > maximum_word_length) - maximum_word_length = possible_key.size; - - /* In input reference mode, update `line_start' from its previous - value. Count the lines just in case auto reference mode is - also selected. If it happens that the word just matched is - indeed part of a reference; just ignore it. */ - - if (input_reference) - { - while (line_scan < possible_key.start) - if (*line_scan == '\n') - { - total_line_count++; - line_scan++; - line_start = line_scan; - SKIP_NON_WHITE (line_scan, text_buffer.end); - reference_length = line_scan - line_start; - } - else - line_scan++; - if (line_scan > possible_key.start) - continue; - } - - /* Ignore the word if an `Ignore words' table exists and if it is - part of it. Also ignore the word if an `Only words' table and - if it is *not* part of it. - - It is allowed that both tables be used at once, even if this - may look strange for now. Just ignore a word that would appear - in both. If regexps are eventually implemented for these - tables, the Ignore table could then reject words that would - have been previously accepted by the Only table. */ - - if (ignore_file && search_table (&possible_key, &ignore_table)) - continue; - if (only_file && !search_table (&possible_key, &only_table)) - continue; - - /* A non-empty word has been found. First of all, insure - proper allocation of the next OCCURS, and make a pointer to - where it will be constructed. */ - - if (number_of_occurs[0] == occurs_alloc[0]) - { - if ((SIZE_MAX / sizeof *occurs_table[0] - 1) / 2 - < occurs_alloc[0]) - xalloc_die (); - occurs_alloc[0] = occurs_alloc[0] * 2 + 1; - occurs_table[0] = xrealloc (occurs_table[0], - occurs_alloc[0] * sizeof *occurs_table[0]); - } - - occurs_cursor = occurs_table[0] + number_of_occurs[0]; - - /* Define the refence field, if any. */ - - if (auto_reference) - { - - /* While auto referencing, update `line_start' from its - previous value, counting lines as we go. If input - referencing at the same time, `line_start' has been - advanced earlier, and the following loop is never really - executed. */ - - while (line_scan < possible_key.start) - if (*line_scan == '\n') - { - total_line_count++; - line_scan++; - line_start = line_scan; - SKIP_NON_WHITE (line_scan, text_buffer.end); - } - else - line_scan++; - - occurs_cursor->reference = total_line_count; - } - else if (input_reference) - { - - /* If only input referencing, `line_start' has been computed - earlier to detect the case the word matched would be part - of the reference. The reference position is simply the - value of `line_start'. */ - - occurs_cursor->reference - = (DELTA) (line_start - possible_key.start); - if (reference_length > reference_max_width) - reference_max_width = reference_length; - } - - /* Exclude the reference from the context in simple cases. */ - - if (input_reference && line_start == context_start) - { - SKIP_NON_WHITE (context_start, context_end); - SKIP_WHITE (context_start, context_end); - } - - /* Completes the OCCURS structure. */ - - occurs_cursor->key = possible_key; - occurs_cursor->left = context_start - possible_key.start; - occurs_cursor->right = context_end - possible_key.start; - - number_of_occurs[0]++; - } + { + if (word_regex.string) + + /* If a word regexp has been compiled, use it to skip at the + beginning of the next word. If there is no such word, exit + the loop. */ + + { + regoff_t r = re_search (&word_regex.pattern, cursor, + context_end - cursor, + 0, context_end - cursor, &word_regs); + if (r == -2) + matcher_error (); + if (r == -1) + break; + word_start = cursor + word_regs.start[0]; + word_end = cursor + word_regs.end[0]; + } + else + + /* Avoid re_search and use the fastmap to skip to the + beginning of the next word. If there is no more word in + the buffer, exit the loop. */ + + { + scan = cursor; + while (scan < context_end + && !word_fastmap[to_uchar (*scan)]) + scan++; + + if (scan == context_end) + break; + + word_start = scan; + + while (scan < context_end + && word_fastmap[to_uchar (*scan)]) + scan++; + + word_end = scan; + } + + /* Skip right to the beginning of the found word. */ + + cursor = word_start; + + /* Skip any zero length word. Just advance a single position, + then go fetch the next word. */ + + if (word_end == word_start) + { + cursor++; + continue; + } + + /* This is a genuine, non empty word, so save it as a possible + key. Then skip over it. Also, maintain the maximum length of + all words read so far. It is mandatory to take the maximum + length of all words in the file, without considering if they + are actually kept or rejected, because backward jumps at output + generation time may fall in *any* word. */ + + possible_key.start = cursor; + possible_key.size = word_end - word_start; + cursor += possible_key.size; + + if (possible_key.size > maximum_word_length) + maximum_word_length = possible_key.size; + + /* In input reference mode, update `line_start' from its previous + value. Count the lines just in case auto reference mode is + also selected. If it happens that the word just matched is + indeed part of a reference; just ignore it. */ + + if (input_reference) + { + while (line_scan < possible_key.start) + if (*line_scan == '\n') + { + total_line_count++; + line_scan++; + line_start = line_scan; + SKIP_NON_WHITE (line_scan, text_buffer.end); + reference_length = line_scan - line_start; + } + else + line_scan++; + if (line_scan > possible_key.start) + continue; + } + + /* Ignore the word if an `Ignore words' table exists and if it is + part of it. Also ignore the word if an `Only words' table and + if it is *not* part of it. + + It is allowed that both tables be used at once, even if this + may look strange for now. Just ignore a word that would appear + in both. If regexps are eventually implemented for these + tables, the Ignore table could then reject words that would + have been previously accepted by the Only table. */ + + if (ignore_file && search_table (&possible_key, &ignore_table)) + continue; + if (only_file && !search_table (&possible_key, &only_table)) + continue; + + /* A non-empty word has been found. First of all, insure + proper allocation of the next OCCURS, and make a pointer to + where it will be constructed. */ + + if (number_of_occurs[0] == occurs_alloc[0]) + { + if ((SIZE_MAX / sizeof *occurs_table[0] - 1) / 2 + < occurs_alloc[0]) + xalloc_die (); + occurs_alloc[0] = occurs_alloc[0] * 2 + 1; + occurs_table[0] = xrealloc (occurs_table[0], + occurs_alloc[0] * sizeof *occurs_table[0]); + } + + occurs_cursor = occurs_table[0] + number_of_occurs[0]; + + /* Define the refence field, if any. */ + + if (auto_reference) + { + + /* While auto referencing, update `line_start' from its + previous value, counting lines as we go. If input + referencing at the same time, `line_start' has been + advanced earlier, and the following loop is never really + executed. */ + + while (line_scan < possible_key.start) + if (*line_scan == '\n') + { + total_line_count++; + line_scan++; + line_start = line_scan; + SKIP_NON_WHITE (line_scan, text_buffer.end); + } + else + line_scan++; + + occurs_cursor->reference = total_line_count; + } + else if (input_reference) + { + + /* If only input referencing, `line_start' has been computed + earlier to detect the case the word matched would be part + of the reference. The reference position is simply the + value of `line_start'. */ + + occurs_cursor->reference + = (DELTA) (line_start - possible_key.start); + if (reference_length > reference_max_width) + reference_max_width = reference_length; + } + + /* Exclude the reference from the context in simple cases. */ + + if (input_reference && line_start == context_start) + { + SKIP_NON_WHITE (context_start, context_end); + SKIP_WHITE (context_start, context_end); + } + + /* Completes the OCCURS structure. */ + + occurs_cursor->key = possible_key; + occurs_cursor->left = context_start - possible_key.start; + occurs_cursor->right = context_end - possible_key.start; + + number_of_occurs[0]++; + } } } @@ -1112,144 +1112,144 @@ print_field (BLOCK field) { unsigned char character = *cursor; if (edited_flag[character]) - { - - /* First check if this is a diacriticized character. - - This works only for TeX. I do not know how diacriticized - letters work with `roff'. Please someone explain it to me! */ - - diacritic = todiac (character); - if (diacritic != 0 && output_format == TEX_FORMAT) - { - base = tobase (character); - switch (diacritic) - { - - case 1: /* Latin diphthongs */ - switch (base) - { - case 'o': - fputs ("\\oe{}", stdout); - break; - - case 'O': - fputs ("\\OE{}", stdout); - break; - - case 'a': - fputs ("\\ae{}", stdout); - break; - - case 'A': - fputs ("\\AE{}", stdout); - break; - - default: - putchar (' '); - } - break; - - case 2: /* Acute accent */ - printf ("\\'%s%c", (base == 'i' ? "\\" : ""), base); - break; - - case 3: /* Grave accent */ - printf ("\\`%s%c", (base == 'i' ? "\\" : ""), base); - break; - - case 4: /* Circumflex accent */ - printf ("\\^%s%c", (base == 'i' ? "\\" : ""), base); - break; - - case 5: /* Diaeresis */ - printf ("\\\"%s%c", (base == 'i' ? "\\" : ""), base); - break; - - case 6: /* Tilde accent */ - printf ("\\~%s%c", (base == 'i' ? "\\" : ""), base); - break; - - case 7: /* Cedilla */ - printf ("\\c{%c}", base); - break; - - case 8: /* Small circle beneath */ - switch (base) - { - case 'a': - fputs ("\\aa{}", stdout); - break; - - case 'A': - fputs ("\\AA{}", stdout); - break; - - default: - putchar (' '); - } - break; - - case 9: /* Strike through */ - switch (base) - { - case 'o': - fputs ("\\o{}", stdout); - break; - - case 'O': - fputs ("\\O{}", stdout); - break; - - default: - putchar (' '); - } - break; - } - } - else - - /* This is not a diacritic character, so handle cases which are - really specific to `roff' or TeX. All white space processing - is done as the default case of this switch. */ - - switch (character) - { - case '"': - /* In roff output format, double any quote. */ - putchar ('"'); - putchar ('"'); - break; - - case '$': - case '%': - case '&': - case '#': - case '_': - /* In TeX output format, precede these with a backslash. */ - putchar ('\\'); - putchar (character); - break; - - case '{': - case '}': - /* In TeX output format, precede these with a backslash and - force mathematical mode. */ - printf ("$\\%c$", character); - break; - - case '\\': - /* In TeX output mode, request production of a backslash. */ - fputs ("\\backslash{}", stdout); - break; - - default: - /* Any other flagged character produces a single space. */ - putchar (' '); - } - } + { + + /* First check if this is a diacriticized character. + + This works only for TeX. I do not know how diacriticized + letters work with `roff'. Please someone explain it to me! */ + + diacritic = todiac (character); + if (diacritic != 0 && output_format == TEX_FORMAT) + { + base = tobase (character); + switch (diacritic) + { + + case 1: /* Latin diphthongs */ + switch (base) + { + case 'o': + fputs ("\\oe{}", stdout); + break; + + case 'O': + fputs ("\\OE{}", stdout); + break; + + case 'a': + fputs ("\\ae{}", stdout); + break; + + case 'A': + fputs ("\\AE{}", stdout); + break; + + default: + putchar (' '); + } + break; + + case 2: /* Acute accent */ + printf ("\\'%s%c", (base == 'i' ? "\\" : ""), base); + break; + + case 3: /* Grave accent */ + printf ("\\`%s%c", (base == 'i' ? "\\" : ""), base); + break; + + case 4: /* Circumflex accent */ + printf ("\\^%s%c", (base == 'i' ? "\\" : ""), base); + break; + + case 5: /* Diaeresis */ + printf ("\\\"%s%c", (base == 'i' ? "\\" : ""), base); + break; + + case 6: /* Tilde accent */ + printf ("\\~%s%c", (base == 'i' ? "\\" : ""), base); + break; + + case 7: /* Cedilla */ + printf ("\\c{%c}", base); + break; + + case 8: /* Small circle beneath */ + switch (base) + { + case 'a': + fputs ("\\aa{}", stdout); + break; + + case 'A': + fputs ("\\AA{}", stdout); + break; + + default: + putchar (' '); + } + break; + + case 9: /* Strike through */ + switch (base) + { + case 'o': + fputs ("\\o{}", stdout); + break; + + case 'O': + fputs ("\\O{}", stdout); + break; + + default: + putchar (' '); + } + break; + } + } + else + + /* This is not a diacritic character, so handle cases which are + really specific to `roff' or TeX. All white space processing + is done as the default case of this switch. */ + + switch (character) + { + case '"': + /* In roff output format, double any quote. */ + putchar ('"'); + putchar ('"'); + break; + + case '$': + case '%': + case '&': + case '#': + case '_': + /* In TeX output format, precede these with a backslash. */ + putchar ('\\'); + putchar (character); + break; + + case '{': + case '}': + /* In TeX output format, precede these with a backslash and + force mathematical mode. */ + printf ("$\\%c$", character); + break; + + case '\\': + /* In TeX output mode, request production of a backslash. */ + fputs ("\\backslash{}", stdout); + break; + + default: + /* Any other flagged character produces a single space. */ + putchar (' '); + } + } else - putchar (*cursor); + putchar (*cursor); } } @@ -1278,17 +1278,17 @@ fix_output_parameters (void) { reference_max_width = 0; for (file_index = 0; file_index < number_input_files; file_index++) - { - line_ordinal = file_line_count[file_index] + 1; - if (file_index > 0) - line_ordinal -= file_line_count[file_index - 1]; - sprintf (ordinal_string, "%d", line_ordinal); - reference_width = strlen (ordinal_string); - if (input_file_name[file_index]) - reference_width += strlen (input_file_name[file_index]); - if (reference_width > reference_max_width) - reference_max_width = reference_width; - } + { + line_ordinal = file_line_count[file_index] + 1; + if (file_index > 0) + line_ordinal -= file_line_count[file_index - 1]; + sprintf (ordinal_string, "%d", line_ordinal); + reference_width = strlen (ordinal_string); + if (input_file_name[file_index]) + reference_width += strlen (input_file_name[file_index]); + if (reference_width > reference_max_width) + reference_max_width = reference_width; + } reference_max_width++; reference.start = xmalloc ((size_t) reference_max_width + 1); } @@ -1328,40 +1328,40 @@ fix_output_parameters (void) { /* When flagging truncation at the left of the keyword, the - truncation mark goes at the beginning of the before field, - unless there is a head field, in which case the mark goes at the - left of the head field. When flagging truncation at the right - of the keyword, the mark goes at the end of the keyafter field, - unless there is a tail field, in which case the mark goes at the - end of the tail field. Only eight combination cases could arise - for truncation marks: - - . None. - . One beginning the before field. - . One beginning the head field. - . One ending the keyafter field. - . One ending the tail field. - . One beginning the before field, another ending the keyafter field. - . One ending the tail field, another beginning the before field. - . One ending the keyafter field, another beginning the head field. - - So, there is at most two truncation marks, which could appear both - on the left side of the center of the output line, both on the - right side, or one on either side. */ + truncation mark goes at the beginning of the before field, + unless there is a head field, in which case the mark goes at the + left of the head field. When flagging truncation at the right + of the keyword, the mark goes at the end of the keyafter field, + unless there is a tail field, in which case the mark goes at the + end of the tail field. Only eight combination cases could arise + for truncation marks: + + . None. + . One beginning the before field. + . One beginning the head field. + . One ending the keyafter field. + . One ending the tail field. + . One beginning the before field, another ending the keyafter field. + . One ending the tail field, another beginning the before field. + . One ending the keyafter field, another beginning the head field. + + So, there is at most two truncation marks, which could appear both + on the left side of the center of the output line, both on the + right side, or one on either side. */ before_max_width -= 2 * truncation_string_length; if (before_max_width < 0) - before_max_width = 0; + before_max_width = 0; keyafter_max_width -= 2 * truncation_string_length; } else { /* I never figured out exactly how UNIX' ptx plans the output width - of its various fields. If GNU extensions are disabled, do not - try computing the field widths correctly; instead, use the - following formula, which does not completely imitate UNIX' ptx, - but almost. */ + of its various fields. If GNU extensions are disabled, do not + try computing the field widths correctly; instead, use the + following formula, which does not completely imitate UNIX' ptx, + but almost. */ keyafter_max_width -= 2 * truncation_string_length + 1; } @@ -1397,13 +1397,13 @@ fix_output_parameters (void) /* Various characters need special processing. */ for (cursor = "$%&#_{}\\"; *cursor; cursor++) - edited_flag[to_uchar (*cursor)] = 1; + edited_flag[to_uchar (*cursor)] = 1; /* Any character with 8th bit set will print to a single space, unless - it is diacriticized. */ + it is diacriticized. */ for (character = 0200; character < CHAR_SET_SIZE; character++) - edited_flag[character] = todiac (character) != 0; + edited_flag[character] = todiac (character) != 0; break; } } @@ -1439,7 +1439,7 @@ define_all_fields (OCCURS *occurs) cursor = keyafter.end; while (cursor < right_context_end - && cursor <= keyafter.start + keyafter_max_width) + && cursor <= keyafter.start + keyafter_max_width) { keyafter.end = cursor; SKIP_SOMETHING (cursor, right_context_end); @@ -1466,7 +1466,7 @@ define_all_fields (OCCURS *occurs) if (-occurs->left > half_line_width + maximum_word_length) { left_field_start - = keyafter.start - (half_line_width + maximum_word_length); + = keyafter.start - (half_line_width + maximum_word_length); SKIP_SOMETHING (left_field_start, keyafter.start); } else @@ -1514,22 +1514,22 @@ define_all_fields (OCCURS *occurs) tail.end = tail.start; cursor = tail.end; while (cursor < right_context_end - && cursor < tail.start + tail_max_width) - { - tail.end = cursor; - SKIP_SOMETHING (cursor, right_context_end); - } + && cursor < tail.start + tail_max_width) + { + tail.end = cursor; + SKIP_SOMETHING (cursor, right_context_end); + } if (cursor < tail.start + tail_max_width) - tail.end = cursor; + tail.end = cursor; if (tail.end > tail.start) - { - keyafter_truncation = 0; - tail_truncation = truncation_string && tail.end < right_context_end; - } + { + keyafter_truncation = 0; + tail_truncation = truncation_string && tail.end < right_context_end; + } else - tail_truncation = 0; + tail_truncation = 0; SKIP_WHITE_BACKWARDS (tail.end, tail.start); } @@ -1559,16 +1559,16 @@ define_all_fields (OCCURS *occurs) head.start = left_field_start; while (head.start + head_max_width < head.end) - SKIP_SOMETHING (head.start, head.end); + SKIP_SOMETHING (head.start, head.end); if (head.end > head.start) - { - before_truncation = 0; - head_truncation = (truncation_string - && head.start > left_context_start); - } + { + before_truncation = 0; + head_truncation = (truncation_string + && head.start > left_context_start); + } else - head_truncation = 0; + head_truncation = 0; SKIP_WHITE (head.start, head.end); } @@ -1586,21 +1586,21 @@ define_all_fields (OCCURS *occurs) { /* Construct the reference text in preallocated space from the file - name and the line number. Find out in which file the reference - occurred. Standard input yields an empty file name. Insure line - numbers are one based, even if they are computed zero based. */ + name and the line number. Find out in which file the reference + occurred. Standard input yields an empty file name. Insure line + numbers are one based, even if they are computed zero based. */ file_index = 0; while (file_line_count[file_index] < occurs->reference) - file_index++; + file_index++; file_name = input_file_name[file_index]; if (!file_name) - file_name = ""; + file_name = ""; line_ordinal = occurs->reference + 1; if (file_index > 0) - line_ordinal -= file_line_count[file_index - 1]; + line_ordinal -= file_line_count[file_index - 1]; sprintf (reference.start, "%s:%d", file_name, line_ordinal); reference.end = reference.start + strlen (reference.start); @@ -1609,7 +1609,7 @@ define_all_fields (OCCURS *occurs) { /* Reference starts at saved position for reference and extends right - until some white space is met. */ + until some white space is met. */ reference.start = keyafter.start + (DELTA) occurs->reference; reference.end = reference.start; @@ -1718,29 +1718,29 @@ output_one_dumb_line (void) if (!right_reference) { if (auto_reference) - { - - /* Output the `reference' field, in such a way that GNU emacs - next-error will handle it. The ending colon is taken from the - gap which follows. */ - - print_field (reference); - putchar (':'); - print_spaces (reference_max_width - + gap_size - - (reference.end - reference.start) - - 1); - } + { + + /* Output the `reference' field, in such a way that GNU emacs + next-error will handle it. The ending colon is taken from the + gap which follows. */ + + print_field (reference); + putchar (':'); + print_spaces (reference_max_width + + gap_size + - (reference.end - reference.start) + - 1); + } else - { + { - /* Output the `reference' field and its following gap. */ + /* Output the `reference' field and its following gap. */ - print_field (reference); - print_spaces (reference_max_width - + gap_size - - (reference.end - reference.start)); - } + print_field (reference); + print_spaces (reference_max_width + + gap_size + - (reference.end - reference.start)); + } } if (tail.start < tail.end) @@ -1749,18 +1749,18 @@ output_one_dumb_line (void) print_field (tail); if (tail_truncation) - fputs (truncation_string, stdout); + fputs (truncation_string, stdout); print_spaces (half_line_width - gap_size - - (before.end - before.start) - - (before_truncation ? truncation_string_length : 0) - - (tail.end - tail.start) - - (tail_truncation ? truncation_string_length : 0)); + - (before.end - before.start) + - (before_truncation ? truncation_string_length : 0) + - (tail.end - tail.start) + - (tail_truncation ? truncation_string_length : 0)); } else print_spaces (half_line_width - gap_size - - (before.end - before.start) - - (before_truncation ? truncation_string_length : 0)); + - (before.end - before.start) + - (before_truncation ? truncation_string_length : 0)); /* Output the `before' field. */ @@ -1781,20 +1781,20 @@ output_one_dumb_line (void) /* Output the `head' field. */ print_spaces (half_line_width - - (keyafter.end - keyafter.start) - - (keyafter_truncation ? truncation_string_length : 0) - - (head.end - head.start) - - (head_truncation ? truncation_string_length : 0)); + - (keyafter.end - keyafter.start) + - (keyafter_truncation ? truncation_string_length : 0) + - (head.end - head.start) + - (head_truncation ? truncation_string_length : 0)); if (head_truncation) - fputs (truncation_string, stdout); + fputs (truncation_string, stdout); print_field (head); } else if ((auto_reference | input_reference) & right_reference) print_spaces (half_line_width - - (keyafter.end - keyafter.start) - - (keyafter_truncation ? truncation_string_length : 0)); + - (keyafter.end - keyafter.start) + - (keyafter_truncation ? truncation_string_length : 0)); if ((auto_reference | input_reference) & right_reference) { @@ -1837,29 +1837,29 @@ generate_all_output (void) for (occurs_index = 0; occurs_index < number_of_occurs[0]; occurs_index++) { /* Compute the exact size of every field and whenever truncation flags - are present or not. */ + are present or not. */ define_all_fields (occurs_cursor); /* Produce one output line according to selected format. */ switch (output_format) - { - case UNKNOWN_FORMAT: - /* Should never happen. */ + { + case UNKNOWN_FORMAT: + /* Should never happen. */ - case DUMB_FORMAT: - output_one_dumb_line (); - break; + case DUMB_FORMAT: + output_one_dumb_line (); + break; - case ROFF_FORMAT: - output_one_roff_line (); - break; + case ROFF_FORMAT: + output_one_roff_line (); + break; - case TEX_FORMAT: - output_one_tex_line (); - break; - } + case TEX_FORMAT: + output_one_tex_line (); + break; + } /* Advance the cursor into the occurs table. */ @@ -1878,13 +1878,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [INPUT]... (without -G)\n\ or: %s -G [OPTION]... [INPUT [OUTPUT]]\n"), - program_name, program_name); + program_name, program_name); fputs (_("\ Output a permuted index, including context, of the words in the input files.\n\ \n\ @@ -1988,105 +1988,105 @@ main (int argc, char **argv) #endif while (optchar = getopt_long (argc, argv, "AF:GM:ORS:TW:b:i:fg:o:trw:", - long_options, NULL), - optchar != EOF) + long_options, NULL), + optchar != EOF) { switch (optchar) - { - default: - usage (EXIT_FAILURE); - - case 'G': - gnu_extensions = false; - break; - - case 'b': - break_file = optarg; - break; - - case 'f': - ignore_case = true; - break; - - case 'g': - { - unsigned long int tmp_ulong; - if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK - || ! (0 < tmp_ulong && tmp_ulong <= INT_MAX)) - error (EXIT_FAILURE, 0, _("invalid gap width: %s"), - quotearg (optarg)); - gap_size = tmp_ulong; - break; - } - - case 'i': - ignore_file = optarg; - break; - - case 'o': - only_file = optarg; - break; - - case 'r': - input_reference = true; - break; - - case 't': - /* Yet to understand... */ - break; - - case 'w': - { - unsigned long int tmp_ulong; - if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK - || ! (0 < tmp_ulong && tmp_ulong <= INT_MAX)) - error (EXIT_FAILURE, 0, _("invalid line width: %s"), - quotearg (optarg)); - line_width = tmp_ulong; - break; - } - - case 'A': - auto_reference = true; - break; - - case 'F': - truncation_string = copy_unescaped_string (optarg); - break; - - case 'M': - macro_name = optarg; - break; - - case 'O': - output_format = ROFF_FORMAT; - break; - - case 'R': - right_reference = true; - break; - - case 'S': - context_regex.string = copy_unescaped_string (optarg); - break; - - case 'T': - output_format = TEX_FORMAT; - break; - - case 'W': - word_regex.string = copy_unescaped_string (optarg); - if (!*word_regex.string) - word_regex.string = NULL; - break; - - case 10: - output_format = XARGMATCH ("--format", optarg, - format_args, format_vals); - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - } + { + default: + usage (EXIT_FAILURE); + + case 'G': + gnu_extensions = false; + break; + + case 'b': + break_file = optarg; + break; + + case 'f': + ignore_case = true; + break; + + case 'g': + { + unsigned long int tmp_ulong; + if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK + || ! (0 < tmp_ulong && tmp_ulong <= INT_MAX)) + error (EXIT_FAILURE, 0, _("invalid gap width: %s"), + quotearg (optarg)); + gap_size = tmp_ulong; + break; + } + + case 'i': + ignore_file = optarg; + break; + + case 'o': + only_file = optarg; + break; + + case 'r': + input_reference = true; + break; + + case 't': + /* Yet to understand... */ + break; + + case 'w': + { + unsigned long int tmp_ulong; + if (xstrtoul (optarg, NULL, 0, &tmp_ulong, NULL) != LONGINT_OK + || ! (0 < tmp_ulong && tmp_ulong <= INT_MAX)) + error (EXIT_FAILURE, 0, _("invalid line width: %s"), + quotearg (optarg)); + line_width = tmp_ulong; + break; + } + + case 'A': + auto_reference = true; + break; + + case 'F': + truncation_string = copy_unescaped_string (optarg); + break; + + case 'M': + macro_name = optarg; + break; + + case 'O': + output_format = ROFF_FORMAT; + break; + + case 'R': + right_reference = true; + break; + + case 'S': + context_regex.string = copy_unescaped_string (optarg); + break; + + case 'T': + output_format = TEX_FORMAT; + break; + + case 'W': + word_regex.string = copy_unescaped_string (optarg); + if (!*word_regex.string) + word_regex.string = NULL; + break; + + case 10: + output_format = XARGMATCH ("--format", optarg, + format_args, format_vals); + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + } } /* Process remaining arguments. If GNU extensions are enabled, process @@ -2110,13 +2110,13 @@ main (int argc, char **argv) file_line_count = xmalloc (number_input_files * sizeof *file_line_count); for (file_index = 0; file_index < number_input_files; file_index++) - { - if (!*argv[optind] || STREQ (argv[optind], "-")) - input_file_name[file_index] = NULL; - else - input_file_name[file_index] = argv[optind]; - optind++; - } + { + if (!*argv[optind] || STREQ (argv[optind], "-")) + input_file_name[file_index] = NULL; + else + input_file_name[file_index] = argv[optind]; + optind++; + } } else { @@ -2127,27 +2127,27 @@ main (int argc, char **argv) input_file_name = xmalloc (sizeof *input_file_name); file_line_count = xmalloc (sizeof *file_line_count); if (!*argv[optind] || STREQ (argv[optind], "-")) - input_file_name[0] = NULL; + input_file_name[0] = NULL; else - input_file_name[0] = argv[optind]; + input_file_name[0] = argv[optind]; optind++; /* Redirect standard output, only if requested. */ if (optind < argc) - { - if (! freopen (argv[optind], "w", stdout)) - error (EXIT_FAILURE, errno, "%s", argv[optind]); - optind++; - } + { + if (! freopen (argv[optind], "w", stdout)) + error (EXIT_FAILURE, errno, "%s", argv[optind]); + optind++; + } /* Diagnose any other argument as an error. */ if (optind < argc) - { - error (0, 0, _("extra operand %s"), quote (argv[optind])); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (argv[optind])); + usage (EXIT_FAILURE); + } } /* If the output format has not been explicitly selected, choose dumb @@ -2173,14 +2173,14 @@ main (int argc, char **argv) { digest_word_file (ignore_file, &ignore_table); if (ignore_table.length == 0) - ignore_file = NULL; + ignore_file = NULL; } if (only_file) { digest_word_file (only_file, &only_table); if (only_table.length == 0) - only_file = NULL; + only_file = NULL; } /* Prepare to study all the input files. */ @@ -2199,8 +2199,8 @@ main (int argc, char **argv) find_occurs_in_text (); /* Maintain for each file how many lines has been read so far when its - end is reached. Incrementing the count first is a simple kludge to - handle a possible incomplete line at end of file. */ + end is reached. Incrementing the count first is a simple kludge to + handle a possible incomplete line at end of file. */ total_line_count++; file_line_count[file_index] = total_line_count; @@ -51,7 +51,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]...\n"), program_name); @@ -102,9 +102,9 @@ file_name_prepend (struct file_name *p, char const *s, size_t s_len) { size_t half = p->n_alloc + 1 + s_len; /* Use xnmalloc+free rather than xnrealloc, since with the latter - we'd end up copying the data twice: once via realloc, then again - to align it with the end of the new buffer. With xnmalloc, we - copy it only once. */ + we'd end up copying the data twice: once via realloc, then again + to align it with the end of the new buffer. With xnmalloc, we + copy it only once. */ char *q = xnmalloc (2, half); size_t n_used = p->n_alloc - n_free; p->start = q + 2 * half - n_used; @@ -149,7 +149,7 @@ nth_parent (size_t n) static void find_dir_entry (struct stat *dot_sb, struct file_name *file_name, - size_t parent_height) + size_t parent_height) { DIR *dirp; int fd; @@ -160,16 +160,16 @@ find_dir_entry (struct stat *dot_sb, struct file_name *file_name, dirp = opendir (".."); if (dirp == NULL) error (EXIT_FAILURE, errno, _("cannot open directory %s"), - quote (nth_parent (parent_height))); + quote (nth_parent (parent_height))); fd = dirfd (dirp); if ((0 <= fd ? fchdir (fd) : chdir ("..")) < 0) error (EXIT_FAILURE, errno, _("failed to chdir to %s"), - quote (nth_parent (parent_height))); + quote (nth_parent (parent_height))); if ((0 <= fd ? fstat (fd, &parent_sb) : stat (".", &parent_sb)) < 0) error (EXIT_FAILURE, errno, _("failed to stat %s"), - quote (nth_parent (parent_height))); + quote (nth_parent (parent_height))); /* If parent and child directory are on different devices, then we can't rely on d_ino for useful i-node numbers; use lstat instead. */ @@ -184,57 +184,57 @@ find_dir_entry (struct stat *dot_sb, struct file_name *file_name, errno = 0; if ((dp = readdir_ignoring_dot_and_dotdot (dirp)) == NULL) - { - if (errno) - { - /* Save/restore errno across closedir call. */ - int e = errno; - closedir (dirp); - errno = e; - - /* Arrange to give a diagnostic after exiting this loop. */ - dirp = NULL; - } - break; - } + { + if (errno) + { + /* Save/restore errno across closedir call. */ + int e = errno; + closedir (dirp); + errno = e; + + /* Arrange to give a diagnostic after exiting this loop. */ + dirp = NULL; + } + break; + } ino = D_INO (dp); if (ino == NOT_AN_INODE_NUMBER || use_lstat) - { - if (lstat (dp->d_name, &ent_sb) < 0) - { - /* Skip any entry we can't stat. */ - continue; - } - ino = ent_sb.st_ino; - } + { + if (lstat (dp->d_name, &ent_sb) < 0) + { + /* Skip any entry we can't stat. */ + continue; + } + ino = ent_sb.st_ino; + } if (ino != dot_sb->st_ino) - continue; + continue; /* If we're not crossing a device boundary, then a simple i-node - match is enough. */ + match is enough. */ if ( ! use_lstat || ent_sb.st_dev == dot_sb->st_dev) - { - file_name_prepend (file_name, dp->d_name, _D_EXACT_NAMLEN (dp)); - found = true; - break; - } + { + file_name_prepend (file_name, dp->d_name, _D_EXACT_NAMLEN (dp)); + found = true; + break; + } } if (dirp == NULL || closedir (dirp) != 0) { /* Note that this diagnostic serves for both readdir - and closedir failures. */ + and closedir failures. */ error (EXIT_FAILURE, errno, _("reading directory %s"), - quote (nth_parent (parent_height))); + quote (nth_parent (parent_height))); } if ( ! found) error (EXIT_FAILURE, 0, - _("couldn't find directory entry in %s with matching i-node"), - quote (nth_parent (parent_height))); + _("couldn't find directory entry in %s with matching i-node"), + quote (nth_parent (parent_height))); *dot_sb = parent_sb; } @@ -272,7 +272,7 @@ robust_getcwd (struct file_name *file_name) if (root_dev_ino == NULL) error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + quote ("/")); if (stat (".", &dot_sb) < 0) error (EXIT_FAILURE, errno, _("failed to stat %s"), quote (".")); @@ -281,7 +281,7 @@ robust_getcwd (struct file_name *file_name) { /* If we've reached the root, we're done. */ if (SAME_INODE (dot_sb, *root_dev_ino)) - break; + break; find_dir_entry (&dot_sb, file_name, height++); } @@ -309,8 +309,8 @@ logical_getcwd (void) while ((p = strstr (p, "/."))) { if (!p[2] || p[2] == '/' - || (p[2] == '.' && (!p[3] || p[3] == '/'))) - return NULL; + || (p[2] == '.' && (!p[3] || p[3] == '/'))) + return NULL; p++; } @@ -340,23 +340,23 @@ main (int argc, char **argv) { int c = getopt_long (argc, argv, "LP", longopts, NULL); if (c == -1) - break; + break; switch (c) - { - case 'L': - logical = true; - break; - case 'P': - logical = false; - break; + { + case 'L': + logical = true; + break; + case 'P': + logical = false; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (optind < argc) @@ -366,10 +366,10 @@ main (int argc, char **argv) { wd = logical_getcwd (); if (wd) - { - puts (wd); - exit (EXIT_SUCCESS); - } + { + puts (wd); + exit (EXIT_SUCCESS); + } } wd = xgetcwd (); diff --git a/src/readlink.c b/src/readlink.c index 444a02a01..a6f42f5c0 100644 --- a/src/readlink.c +++ b/src/readlink.c @@ -57,12 +57,12 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... FILE\n"), program_name); fputs (_("Print value of a symbolic link or canonical file name\n\n"), - stdout); + stdout); fputs (_("\ -f, --canonicalize canonicalize by following every symlink in\n\ every component of the given name recursively;\n\ @@ -112,31 +112,31 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "efmnqsv", longopts, NULL)) != -1) { switch (optc) - { - case 'e': - can_mode = CAN_EXISTING; - break; - case 'f': - can_mode = CAN_ALL_BUT_LAST; - break; - case 'm': - can_mode = CAN_MISSING; - break; - case 'n': - no_newline = true; - break; - case 'q': - case 's': - verbose = false; - break; - case 'v': - verbose = true; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'e': + can_mode = CAN_EXISTING; + break; + case 'f': + can_mode = CAN_ALL_BUT_LAST; + break; + case 'm': + can_mode = CAN_MISSING; + break; + case 'n': + no_newline = true; + break; + case 'q': + case 's': + verbose = false; + break; + case 'v': + verbose = true; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (optind >= argc) @@ -154,8 +154,8 @@ main (int argc, char **argv) } value = (can_mode != -1 - ? canonicalize_filename_mode (fname, can_mode) - : areadlink_with_size (fname, 63)); + ? canonicalize_filename_mode (fname, can_mode) + : areadlink_with_size (fname, 63)); if (value) { printf ("%s%s", value, (no_newline ? "" : "\n")); diff --git a/src/remove.c b/src/remove.c index d48541603..6c8613bfa 100644 --- a/src/remove.c +++ b/src/remove.c @@ -306,7 +306,7 @@ pop_dir (Dirstack_state *ds) static size_t right_justify (char *dst, size_t dst_len, const char *src, size_t src_len, - char **result, bool *truncated) + char **result, bool *truncated) { const char *sp; char *dp; @@ -345,7 +345,7 @@ full_filename0 (Dirstack_state const *ds, const char *filename) { char *new_buf = realloc (g_buf, n_bytes_needed); if (new_buf == NULL) - return NULL; + return NULL; g_buf = new_buf; g_n_allocated = n_bytes_needed; @@ -354,15 +354,15 @@ full_filename0 (Dirstack_state const *ds, const char *filename) if (STREQ (filename, ".") && dir_len) { /* FILENAME is just `.' and dir_len is nonzero. - Copy the directory part, omitting the trailing slash, - and append a trailing zero byte. */ + Copy the directory part, omitting the trailing slash, + and append a trailing zero byte. */ char *p = mempcpy (g_buf, dir_name, dir_len - 1); *p = 0; } else { /* Copy the directory part, including trailing slash, and then - append the filename part, including a trailing zero byte. */ + append the filename part, including a trailing zero byte. */ memcpy (mempcpy (g_buf, dir_name, dir_len), filename, filename_len + 1); assert (strlen (g_buf) + 1 == n_bytes_needed); } @@ -414,14 +414,14 @@ full_filename_ (Dirstack_state const *ds, const char *filename) free (g_buf); n_bytes_remaining = right_justify (static_buf, SBUF_SIZE, filename, - strlen (filename) + 1, &p, - &file_truncated); + strlen (filename) + 1, &p, + &file_truncated); right_justify (static_buf, n_bytes_remaining, dir_name, dir_len, - &p, &dir_truncated); + &p, &dir_truncated); if (file_truncated || dir_truncated) { - memcpy (static_buf, ELLIPSES_PREFIX, - sizeof (ELLIPSES_PREFIX) - 1); + memcpy (static_buf, ELLIPSES_PREFIX, + sizeof (ELLIPSES_PREFIX) - 1); } errno = saved_errno; return p; @@ -556,7 +556,7 @@ AD_pop_and_chdir (DIR *dirp, int *fdp, Dirstack_state *ds) of a directory that this rm process would encounter, which would result in a false-positive cycle indication. */ CYCLE_CHECK_REFLECT_CHDIR_UP (&ds->cycle_check_state, - top->dev_ino, leaf_dev_ino); + top->dev_ino, leaf_dev_ino); /* Propagate any failure to parent. */ UPDATE_STATUS (top->status, old_status); @@ -568,55 +568,55 @@ AD_pop_and_chdir (DIR *dirp, int *fdp, Dirstack_state *ds) struct stat sb; int fd = openat (dirfd (dirp), "..", O_RDONLY); if (closedir (dirp) != 0) - { - error (0, errno, _("FATAL: failed to close directory %s"), - quote (full_filename (prev_dir))); - goto next_cmdline_arg; - } + { + error (0, errno, _("FATAL: failed to close directory %s"), + quote (full_filename (prev_dir))); + goto next_cmdline_arg; + } /* The above fails with EACCES when DIRP is readable but not - searchable, when using Solaris' openat. Without this openat - call, tests/rm2 would fail to remove directories a/2 and a/3. */ + searchable, when using Solaris' openat. Without this openat + call, tests/rm2 would fail to remove directories a/2 and a/3. */ if (fd < 0) - fd = openat (AT_FDCWD, xfull_filename (ds, "."), O_RDONLY); + fd = openat (AT_FDCWD, xfull_filename (ds, "."), O_RDONLY); if (fd < 0) - { - error (0, errno, _("FATAL: cannot open .. from %s"), - quote (full_filename (prev_dir))); - goto next_cmdline_arg; - } + { + error (0, errno, _("FATAL: cannot open .. from %s"), + quote (full_filename (prev_dir))); + goto next_cmdline_arg; + } if (fstat (fd, &sb)) - { - error (0, errno, - _("FATAL: cannot ensure %s (returned to via ..) is safe"), - quote (full_filename ("."))); - goto close_and_next; - } + { + error (0, errno, + _("FATAL: cannot ensure %s (returned to via ..) is safe"), + quote (full_filename ("."))); + goto close_and_next; + } /* Ensure that post-chdir dev/ino match the stored ones. */ if ( ! SAME_INODE (sb, top->dev_ino)) - { - error (0, 0, _("FATAL: directory %s changed dev/ino"), - quote (full_filename ("."))); - close_and_next:; - close (fd); - - next_cmdline_arg:; - free (prev_dir); - longjmp (ds->current_arg_jumpbuf, 1); - } + { + error (0, 0, _("FATAL: directory %s changed dev/ino"), + quote (full_filename ("."))); + close_and_next:; + close (fd); + + next_cmdline_arg:; + free (prev_dir); + longjmp (ds->current_arg_jumpbuf, 1); + } *fdp = fd; } else { if (closedir (dirp) != 0) - { - error (0, errno, _("FATAL: failed to close directory %s"), - quote (full_filename (prev_dir))); - goto next_cmdline_arg; - } + { + error (0, errno, _("FATAL: failed to close directory %s"), + quote (full_filename (prev_dir))); + goto next_cmdline_arg; + } *fdp = AT_FDCWD; } @@ -630,9 +630,9 @@ AD_ensure_initialized (Hash_table **ht) if (*ht == NULL) { *ht = hash_initialize (HT_UNREMOVABLE_INITIAL_CAPACITY, NULL, hash_pjw, - hash_compare_strings, hash_freer); + hash_compare_strings, hash_freer); if (*ht == NULL) - xalloc_die (); + xalloc_die (); } return *ht; @@ -649,7 +649,7 @@ AD_mark_helper (Hash_table **ht, char *filename) else { if (ent != filename) - free (filename); + free (filename); } } @@ -706,7 +706,7 @@ AD_push_initial (Dirstack_state *ds) replaced DIR with e.g., a symlink to some other directory. */ static void AD_push (int fd_cwd, Dirstack_state *ds, char const *dir, - struct stat const *dir_sb_from_parent) + struct stat const *dir_sb_from_parent) { struct AD_ent *top; @@ -718,19 +718,19 @@ AD_push (int fd_cwd, Dirstack_state *ds, char const *dir, { struct stat sb; if (fstat (fd_cwd, &sb) != 0) - { - error (0, errno, _("FATAL: cannot enter directory %s"), - quote (full_filename ("."))); - longjmp (ds->current_arg_jumpbuf, 1); - } + { + error (0, errno, _("FATAL: cannot enter directory %s"), + quote (full_filename ("."))); + longjmp (ds->current_arg_jumpbuf, 1); + } if ( ! SAME_INODE (sb, *dir_sb_from_parent)) - { - error (0, 0, - _("FATAL: just-changed-to directory %s changed dev/ino"), - quote (full_filename ("."))); - longjmp (ds->current_arg_jumpbuf, 1); - } + { + error (0, 0, + _("FATAL: just-changed-to directory %s changed dev/ino"), + quote (full_filename ("."))); + longjmp (ds->current_arg_jumpbuf, 1); + } } if (cycle_check (&ds->cycle_check_state, dir_sb_from_parent)) @@ -740,7 +740,7 @@ WARNING: Circular directory structure.\n\ This almost certainly means that you have a corrupted file system.\n\ NOTIFY YOUR SYSTEM MANAGER.\n\ The following directory is part of the cycle:\n %s\n"), - quote (full_filename ("."))); + quote (full_filename ("."))); longjmp (ds->current_arg_jumpbuf, 1); } @@ -749,7 +749,7 @@ The following directory is part of the cycle:\n %s\n"), /* The active directory stack must be one larger than the length stack. */ assert (AD_stack_height (ds) == - 1 + obstack_object_size (&ds->len_stack) / sizeof (size_t)); + 1 + obstack_object_size (&ds->len_stack) / sizeof (size_t)); /* Fill in the new values. */ top = AD_stack_top (ds); @@ -772,9 +772,9 @@ AD_is_removable (Dirstack_state const *ds, char const *file) This is to avoid calling euidaccess when FILE is a symlink. */ static int write_protected_non_symlink (int fd_cwd, - char const *file, - Dirstack_state const *ds, - struct stat *buf) + char const *file, + Dirstack_state const *ds, + struct stat *buf) { if (can_write_any_file ()) return 0; @@ -793,42 +793,42 @@ write_protected_non_symlink (int fd_cwd, /* In the absence of a native eaccessat function, here are some of the implementation choices [#4 and #5 were suggested by Paul Eggert]: 1) call openat with O_WRONLY|O_NOCTTY - Disadvantage: may create the file and doesn't work for directory, - may mistakenly report `unwritable' for EROFS or ACLs even though - perm bits say the file is writable. + Disadvantage: may create the file and doesn't work for directory, + may mistakenly report `unwritable' for EROFS or ACLs even though + perm bits say the file is writable. 2) fake eaccessat (save_cwd, fchdir, call euidaccess, restore_cwd) - Disadvantage: changes working directory (not reentrant) and can't - work if save_cwd fails. + Disadvantage: changes working directory (not reentrant) and can't + work if save_cwd fails. 3) if (euidaccess (xfull_filename (file), W_OK) == 0) - Disadvantage: doesn't work if xfull_filename is too long. - Inefficient for very deep trees (O(Depth^2)). + Disadvantage: doesn't work if xfull_filename is too long. + Inefficient for very deep trees (O(Depth^2)). 4) If the full pathname is sufficiently short (say, less than - PATH_MAX or 8192 bytes, whichever is shorter): - use method (3) (i.e., euidaccess (xfull_filename (file), W_OK)); - Otherwise: vfork, fchdir in the child, run euidaccess in the - child, then the child exits with a status that tells the parent - whether euidaccess succeeded. - - This avoids the O(N**2) algorithm of method (3), and it also avoids - the failure-due-to-too-long-file-names of method (3), but it's fast - in the normal shallow case. It also avoids the lack-of-reentrancy - and the save_cwd problems. - Disadvantage; it uses a process slot for very-long file names, - and would be very slow for hierarchies with many such files. + PATH_MAX or 8192 bytes, whichever is shorter): + use method (3) (i.e., euidaccess (xfull_filename (file), W_OK)); + Otherwise: vfork, fchdir in the child, run euidaccess in the + child, then the child exits with a status that tells the parent + whether euidaccess succeeded. + + This avoids the O(N**2) algorithm of method (3), and it also avoids + the failure-due-to-too-long-file-names of method (3), but it's fast + in the normal shallow case. It also avoids the lack-of-reentrancy + and the save_cwd problems. + Disadvantage; it uses a process slot for very-long file names, + and would be very slow for hierarchies with many such files. 5) If the full file name is sufficiently short (say, less than - PATH_MAX or 8192 bytes, whichever is shorter): - use method (3) (i.e., euidaccess (xfull_filename (file), W_OK)); - Otherwise: look just at the file bits. Perhaps issue a warning - the first time this occurs. + PATH_MAX or 8192 bytes, whichever is shorter): + use method (3) (i.e., euidaccess (xfull_filename (file), W_OK)); + Otherwise: look just at the file bits. Perhaps issue a warning + the first time this occurs. - This is like (4), except for the "Otherwise" case where it isn't as - "perfect" as (4) but is considerably faster. It conforms to current - POSIX, and is uniformly better than what Solaris and FreeBSD do (they - mess up with long file names). */ + This is like (4), except for the "Otherwise" case where it isn't as + "perfect" as (4) but is considerably faster. It conforms to current + POSIX, and is uniformly better than what Solaris and FreeBSD do (they + mess up with long file names). */ { /* This implements #5: */ @@ -841,8 +841,8 @@ write_protected_non_symlink (int fd_cwd, return 0; if (errno == EACCES) { - errno = 0; - return 1; + errno = 0; + return 1; } /* Perhaps some other process has removed the file, or perhaps this @@ -867,9 +867,9 @@ write_protected_non_symlink (int fd_cwd, Don't even try to set *IS_EMPTY when MODE == PA_REMOVE_DIR. */ static enum RM_status prompt (int fd_cwd, Dirstack_state const *ds, char const *filename, - int *pdirent_type, struct stat *sbuf, - struct rm_options const *x, enum Prompt_action mode, - Ternary *is_empty) + int *pdirent_type, struct stat *sbuf, + struct rm_options const *x, enum Prompt_action mode, + Ternary *is_empty) { int write_protected = 0; int dirent_type = *pdirent_type; @@ -892,84 +892,84 @@ prompt (int fd_cwd, Dirstack_state const *ds, char const *filename, if (write_protected || x->interactive == RMI_ALWAYS) { if (0 <= write_protected && dirent_type == DT_UNKNOWN) - { - if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) == 0) - { - if (S_ISLNK (sbuf->st_mode)) - dirent_type = DT_LNK; - else if (S_ISDIR (sbuf->st_mode)) - dirent_type = DT_DIR; - /* Otherwise it doesn't matter, so leave it DT_UNKNOWN. */ - *pdirent_type = dirent_type; - } - else - { - /* This happens, e.g., with `rm '''. */ - write_protected = -1; - wp_errno = errno; - } - } + { + if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) == 0) + { + if (S_ISLNK (sbuf->st_mode)) + dirent_type = DT_LNK; + else if (S_ISDIR (sbuf->st_mode)) + dirent_type = DT_DIR; + /* Otherwise it doesn't matter, so leave it DT_UNKNOWN. */ + *pdirent_type = dirent_type; + } + else + { + /* This happens, e.g., with `rm '''. */ + write_protected = -1; + wp_errno = errno; + } + } if (0 <= write_protected) - switch (dirent_type) - { - case DT_LNK: - /* Using permissions doesn't make sense for symlinks. */ - if (x->interactive != RMI_ALWAYS) - return RM_OK; - break; - - case DT_DIR: - if (!x->recursive) - { - write_protected = -1; - wp_errno = EISDIR; - } - break; - } + switch (dirent_type) + { + case DT_LNK: + /* Using permissions doesn't make sense for symlinks. */ + if (x->interactive != RMI_ALWAYS) + return RM_OK; + break; + + case DT_DIR: + if (!x->recursive) + { + write_protected = -1; + wp_errno = EISDIR; + } + break; + } char const *quoted_name = quote (full_filename (filename)); if (write_protected < 0) - { - error (0, wp_errno, _("cannot remove %s"), quoted_name); - return RM_ERROR; - } + { + error (0, wp_errno, _("cannot remove %s"), quoted_name); + return RM_ERROR; + } /* Issue the prompt. */ /* FIXME: use a variant of error (instead of fprintf) that doesn't - append a newline. Then we won't have to declare program_name in - this file. */ + append a newline. Then we won't have to declare program_name in + this file. */ if (dirent_type == DT_DIR - && mode == PA_DESCEND_INTO_DIR - && ((*is_empty = (is_empty_dir (fd_cwd, filename) ? T_YES : T_NO)) - == T_NO)) - fprintf (stderr, - (write_protected - ? _("%s: descend into write-protected directory %s? ") - : _("%s: descend into directory %s? ")), - program_name, quoted_name); + && mode == PA_DESCEND_INTO_DIR + && ((*is_empty = (is_empty_dir (fd_cwd, filename) ? T_YES : T_NO)) + == T_NO)) + fprintf (stderr, + (write_protected + ? _("%s: descend into write-protected directory %s? ") + : _("%s: descend into directory %s? ")), + program_name, quoted_name); else - { - if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) != 0) - { - error (0, errno, _("cannot remove %s"), quoted_name); - return RM_ERROR; - } - - fprintf (stderr, - (write_protected - /* TRANSLATORS: You may find it more convenient to - translate "%s: remove %s (write-protected) %s? " - instead. It should avoid grammatical problems - with the output of file_type. */ - ? _("%s: remove write-protected %s %s? ") - : _("%s: remove %s %s? ")), - program_name, file_type (sbuf), quoted_name); - } + { + if (cache_fstatat (fd_cwd, filename, sbuf, AT_SYMLINK_NOFOLLOW) != 0) + { + error (0, errno, _("cannot remove %s"), quoted_name); + return RM_ERROR; + } + + fprintf (stderr, + (write_protected + /* TRANSLATORS: You may find it more convenient to + translate "%s: remove %s (write-protected) %s? " + instead. It should avoid grammatical problems + with the output of file_type. */ + ? _("%s: remove write-protected %s %s? ") + : _("%s: remove %s %s? ")), + program_name, file_type (sbuf), quoted_name); + } if (!yesno ()) - return RM_USER_DECLINED; + return RM_USER_DECLINED; } return RM_OK; } @@ -1008,14 +1008,14 @@ is_nondir_lstat (int fd_cwd, char const *filename, struct stat *st) do \ { \ if (unlinkat (Fd_cwd, Filename, 0) == 0) \ - { \ - if ((X)->verbose) \ - printf (_("removed %s\n"), quote (full_filename (Filename))); \ - return RM_OK; \ - } \ - \ + { \ + if ((X)->verbose) \ + printf (_("removed %s\n"), quote (full_filename (Filename))); \ + return RM_OK; \ + } \ + \ if (ignorable_missing (X, errno)) \ - return RM_OK; \ + return RM_OK; \ } \ while (0) @@ -1023,18 +1023,18 @@ is_nondir_lstat (int fd_cwd, char const *filename, struct stat *st) do \ { \ if (unlinkat (Fd_cwd, Filename, AT_REMOVEDIR) == 0) /* rmdir */ \ - { \ - if ((X)->verbose) \ - printf (_("removed directory: %s\n"), \ - quote (full_filename (Filename))); \ - return RM_OK; \ - } \ - \ + { \ + if ((X)->verbose) \ + printf (_("removed directory: %s\n"), \ + quote (full_filename (Filename))); \ + return RM_OK; \ + } \ + \ if (ignorable_missing (X, errno)) \ - return RM_OK; \ - \ + return RM_OK; \ + \ if (errno == ENOTEMPTY || errno == EEXIST) \ - return RM_NONEMPTY_DIR; \ + return RM_NONEMPTY_DIR; \ } \ while (0) @@ -1073,13 +1073,13 @@ ignorable_missing (struct rm_options const *x, int errnum) static enum RM_status remove_entry (int fd_cwd, Dirstack_state const *ds, char const *filename, - int dirent_type_arg, struct stat *st, - struct rm_options const *x) + int dirent_type_arg, struct stat *st, + struct rm_options const *x) { Ternary is_empty_directory; enum RM_status s = prompt (fd_cwd, ds, filename, &dirent_type_arg, st, x, - PA_DESCEND_INTO_DIR, - &is_empty_directory); + PA_DESCEND_INTO_DIR, + &is_empty_directory); int dirent_type = dirent_type_arg; if (s != RM_OK) return s; @@ -1101,101 +1101,101 @@ remove_entry (int fd_cwd, Dirstack_state const *ds, char const *filename, if (cannot_unlink_dir ()) { if (dirent_type == DT_DIR && ! x->recursive) - { - error (0, EISDIR, _("cannot remove %s"), - quote (full_filename (filename))); - return RM_ERROR; - } + { + error (0, EISDIR, _("cannot remove %s"), + quote (full_filename (filename))); + return RM_ERROR; + } /* is_empty_directory is set iff it's ok to use rmdir. - Note that it's set only in interactive mode -- in which case it's - an optimization that arranges so that the user is asked just - once whether to remove the directory. */ + Note that it's set only in interactive mode -- in which case it's + an optimization that arranges so that the user is asked just + once whether to remove the directory. */ if (is_empty_directory == T_YES) - DO_RMDIR (fd_cwd, filename, x); + DO_RMDIR (fd_cwd, filename, x); /* If we happen to know that FILENAME is a directory, return now - and let the caller remove it -- this saves the overhead of a failed - unlink call. If FILENAME is a command-line argument, then - DIRENT_TYPE is DT_UNKNOWN so we'll first try to unlink it. - Using unlink here is ok, because it cannot remove a - directory. */ + and let the caller remove it -- this saves the overhead of a failed + unlink call. If FILENAME is a command-line argument, then + DIRENT_TYPE is DT_UNKNOWN so we'll first try to unlink it. + Using unlink here is ok, because it cannot remove a + directory. */ if (dirent_type == DT_DIR) - return RM_NONEMPTY_DIR; + return RM_NONEMPTY_DIR; DO_UNLINK (fd_cwd, filename, x); /* Upon a failed attempt to unlink a directory, most non GNU/Linux - systems set errno to the POSIX-required value EPERM. In that case, - change errno to EISDIR so that we emit a better diagnostic. */ + systems set errno to the POSIX-required value EPERM. In that case, + change errno to EISDIR so that we emit a better diagnostic. */ if (! x->recursive && errno == EPERM && is_dir_lstat (fd_cwd, - filename, st)) - errno = EISDIR; + filename, st)) + errno = EISDIR; if (! x->recursive - || (cache_stat_ok (st) && !S_ISDIR (st->st_mode)) - || ((errno == EACCES || errno == EPERM) - && is_nondir_lstat (fd_cwd, filename, st)) - ) - { - if (ignorable_missing (x, errno)) - return RM_OK; - - /* Either --recursive is not in effect, or the file cannot be a - directory. Report the unlink problem and fail. */ - error (0, errno, _("cannot remove %s"), - quote (full_filename (filename))); - return RM_ERROR; - } + || (cache_stat_ok (st) && !S_ISDIR (st->st_mode)) + || ((errno == EACCES || errno == EPERM) + && is_nondir_lstat (fd_cwd, filename, st)) + ) + { + if (ignorable_missing (x, errno)) + return RM_OK; + + /* Either --recursive is not in effect, or the file cannot be a + directory. Report the unlink problem and fail. */ + error (0, errno, _("cannot remove %s"), + quote (full_filename (filename))); + return RM_ERROR; + } assert (!cache_stat_ok (st) || S_ISDIR (st->st_mode)); } else { /* If we don't already know whether FILENAME is a directory, - find out now. Then, if it's a non-directory, we can use - unlink on it. */ + find out now. Then, if it's a non-directory, we can use + unlink on it. */ if (dirent_type == DT_UNKNOWN) - { - if (fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW)) - { - if (ignorable_missing (x, errno)) - return RM_OK; + { + if (fstatat (fd_cwd, filename, st, AT_SYMLINK_NOFOLLOW)) + { + if (ignorable_missing (x, errno)) + return RM_OK; - error (0, errno, _("cannot remove %s"), - quote (full_filename (filename))); - return RM_ERROR; - } + error (0, errno, _("cannot remove %s"), + quote (full_filename (filename))); + return RM_ERROR; + } - if (S_ISDIR (st->st_mode)) - dirent_type = DT_DIR; - } + if (S_ISDIR (st->st_mode)) + dirent_type = DT_DIR; + } if (dirent_type != DT_DIR) - { - /* At this point, barring race conditions, FILENAME is known - to be a non-directory, so it's ok to try to unlink it. */ - DO_UNLINK (fd_cwd, filename, x); + { + /* At this point, barring race conditions, FILENAME is known + to be a non-directory, so it's ok to try to unlink it. */ + DO_UNLINK (fd_cwd, filename, x); - /* unlink failed with some other error code. report it. */ - error (0, errno, _("cannot remove %s"), - quote (full_filename (filename))); - return RM_ERROR; - } + /* unlink failed with some other error code. report it. */ + error (0, errno, _("cannot remove %s"), + quote (full_filename (filename))); + return RM_ERROR; + } if (! x->recursive) - { - error (0, EISDIR, _("cannot remove %s"), - quote (full_filename (filename))); - return RM_ERROR; - } + { + error (0, EISDIR, _("cannot remove %s"), + quote (full_filename (filename))); + return RM_ERROR; + } if (is_empty_directory == T_YES) - { - DO_RMDIR (fd_cwd, filename, x); - /* Don't diagnose any failure here. - It'll be detected when the caller tries another way. */ - } + { + DO_RMDIR (fd_cwd, filename, x); + /* Don't diagnose any failure here. + It'll be detected when the caller tries another way. */ + } } return RM_NONEMPTY_DIR; @@ -1218,9 +1218,9 @@ remove_entry (int fd_cwd, Dirstack_state const *ds, char const *filename, isn't restored. */ static DIR * fd_to_subdirp (int fd_cwd, char const *f, - int prev_errno, - struct stat *subdir_sb, - int *cwd_errno ATTRIBUTE_UNUSED) + int prev_errno, + struct stat *subdir_sb, + int *cwd_errno ATTRIBUTE_UNUSED) { int open_flags = O_RDONLY | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK; int fd_sub = openat_permissive (fd_cwd, f, open_flags, 0, cwd_errno); @@ -1237,7 +1237,7 @@ fd_to_subdirp (int fd_cwd, char const *f, { DIR *subdir_dirp = fdopendir (fd_sub); if (subdir_dirp) - return subdir_dirp; + return subdir_dirp; saved_errno = errno; } else @@ -1262,7 +1262,7 @@ compare_ino (void const *av, void const *bv) struct readdir_data const *const *a = av; struct readdir_data const *const *b = bv; return (a[0]->ino < b[0]->ino ? -1 - : b[0]->ino < a[0]->ino ? 1 : 0); + : b[0]->ino < a[0]->ino ? 1 : 0); } /* Return an approximation of the maximum number of dirent entries @@ -1303,7 +1303,7 @@ dirent_inode_sort_may_be_useful (int dir_fd) case S_MAGIC_TMPFS: case S_MAGIC_NFS: /* On a file system of any of these types, sorting - is unnecessary, and hence wasteful. */ + is unnecessary, and hence wasteful. */ return false; default: @@ -1349,18 +1349,18 @@ preprocess_dir (DIR **dirp, struct rm_options const *x) || x->verbose /* - privileged users can unlink nonempty directories. - Otherwise, there'd be a race condition between the readdir - call (in which we learn dirent.d_type) and the unlink, by - which time the non-directory may be replaced with a directory. */ + Otherwise, there'd be a race condition between the readdir + call (in which we learn dirent.d_type) and the unlink, by + which time the non-directory may be replaced with a directory. */ || ! cannot_unlink_dir () /* - we can't fstat the file descriptor */ || fstat (dir_fd, &st) != 0 /* - the directory is smaller than some threshold. - Estimate the number of inodes with a heuristic. + Estimate the number of inodes with a heuristic. There's no significant benefit to sorting if there are - too few inodes. */ + too few inodes. */ || dirent_count (&st) < INODE_SORT_DIR_ENTRIES_THRESHOLD /* Sort only if it might help. */ @@ -1381,9 +1381,9 @@ preprocess_dir (DIR **dirp, struct rm_options const *x) obstack_init_minimal (&o_p); obstack_specify_allocation_with_arg (&o_readdir_data, 0, 0, - rm_malloc, rm_free, &readdir_jumpbuf); + rm_malloc, rm_free, &readdir_jumpbuf); obstack_specify_allocation_with_arg (&o_p, 0, 0, - rm_malloc, rm_free, &readdir_jumpbuf); + rm_malloc, rm_free, &readdir_jumpbuf); /* Read all entries, storing <d_ino, d_name> for each non-dir one. Maintain a parallel list of pointers into the primary buffer. */ @@ -1393,11 +1393,11 @@ preprocess_dir (DIR **dirp, struct rm_options const *x) dp = readdir_ignoring_dot_and_dotdot (*dirp); /* no need to distinguish EOF from failure */ if (dp == NULL) - break; + break; /* Skip known-directory and type-unknown entries. */ if (D_TYPE (dp) == DT_UNKNOWN || D_TYPE (dp) == DT_DIR) - break; + break; size_t name_len = strlen (dp->d_name); size_t ent_len = offsetof (struct readdir_data, name) + name_len + 1; @@ -1442,8 +1442,8 @@ preprocess_dir (DIR **dirp, struct rm_options const *x) possible, continuing even if we fail to remove some entries. */ static enum RM_status remove_cwd_entries (DIR **dirp, - Dirstack_state *ds, char **subdir, struct stat *subdir_sb, - struct rm_options const *x) + Dirstack_state *ds, char **subdir, struct stat *subdir_sb, + struct rm_options const *x) { struct AD_ent *top = AD_stack_top (ds); enum RM_status status = top->status; @@ -1463,105 +1463,105 @@ remove_cwd_entries (DIR **dirp, const char *f; /* Set errno to zero so we can distinguish between a readdir failure - and when readdir simply finds that there are no more entries. */ + and when readdir simply finds that there are no more entries. */ errno = 0; dp = readdir_ignoring_dot_and_dotdot (*dirp); if (dp == NULL) - { - if (errno) - { - /* fall through */ - } - else if (NEED_REWIND (n_unlinked_since_opendir_or_last_rewind)) - { - /* Call rewinddir if we've called unlink or rmdir so many times - (since the opendir or the previous rewinddir) that this - NULL-return may be the symptom of a buggy readdir. */ - rewinddir (*dirp); - n_unlinked_since_opendir_or_last_rewind = 0; - continue; - } - break; - } + { + if (errno) + { + /* fall through */ + } + else if (NEED_REWIND (n_unlinked_since_opendir_or_last_rewind)) + { + /* Call rewinddir if we've called unlink or rmdir so many times + (since the opendir or the previous rewinddir) that this + NULL-return may be the symptom of a buggy readdir. */ + rewinddir (*dirp); + n_unlinked_since_opendir_or_last_rewind = 0; + continue; + } + break; + } f = dp->d_name; /* Skip files we've already tried/failed to remove. */ if ( ! AD_is_removable (ds, f)) - continue; + continue; /* Pass dp->d_type info to remove_entry so the non-glibc - case can decide whether to use unlink or chdir. - Systems without the d_type member will have to endure - the performance hit of first calling lstat F. */ + case can decide whether to use unlink or chdir. + Systems without the d_type member will have to endure + the performance hit of first calling lstat F. */ cache_stat_init (subdir_sb); tmp_status = remove_entry (dirfd (*dirp), ds, f, - D_TYPE (dp), subdir_sb, x); + D_TYPE (dp), subdir_sb, x); switch (tmp_status) - { - case RM_OK: - /* Count how many files we've unlinked since the initial - opendir or the last rewinddir. On buggy systems, if you - remove too many, readdir returns NULL even though there - remain unprocessed directory entries. */ - ++n_unlinked_since_opendir_or_last_rewind; - break; - - case RM_ERROR: - case RM_USER_DECLINED: - AD_mark_as_unremovable (ds, f); - UPDATE_STATUS (status, tmp_status); - break; - - case RM_NONEMPTY_DIR: - { - DIR *subdir_dirp = fd_to_subdirp (dirfd (*dirp), f, - errno, subdir_sb, NULL); - if (subdir_dirp == NULL) - { - status = RM_ERROR; - - /* CAUTION: this test and diagnostic are identical to - those following the other use of fd_to_subdirp. */ - if (ignorable_missing (x, errno)) - { - /* With -f, don't report "file not found". */ - } - else - { - /* Upon fd_to_subdirp failure, try to remove F directly, - in case it's just an empty directory. */ - int saved_errno = errno; - if (unlinkat (dirfd (*dirp), f, AT_REMOVEDIR) == 0) - status = RM_OK; - else - error (0, saved_errno, - _("cannot remove %s"), quote (full_filename (f))); - } - - if (status == RM_ERROR) - AD_mark_as_unremovable (ds, f); - break; - } - - *subdir = xstrdup (f); - if (closedir (*dirp) != 0) - { - error (0, 0, _("failed to close directory %s"), - quote (full_filename ("."))); - status = RM_ERROR; - } - *dirp = subdir_dirp; - - break; - } - } + { + case RM_OK: + /* Count how many files we've unlinked since the initial + opendir or the last rewinddir. On buggy systems, if you + remove too many, readdir returns NULL even though there + remain unprocessed directory entries. */ + ++n_unlinked_since_opendir_or_last_rewind; + break; + + case RM_ERROR: + case RM_USER_DECLINED: + AD_mark_as_unremovable (ds, f); + UPDATE_STATUS (status, tmp_status); + break; + + case RM_NONEMPTY_DIR: + { + DIR *subdir_dirp = fd_to_subdirp (dirfd (*dirp), f, + errno, subdir_sb, NULL); + if (subdir_dirp == NULL) + { + status = RM_ERROR; + + /* CAUTION: this test and diagnostic are identical to + those following the other use of fd_to_subdirp. */ + if (ignorable_missing (x, errno)) + { + /* With -f, don't report "file not found". */ + } + else + { + /* Upon fd_to_subdirp failure, try to remove F directly, + in case it's just an empty directory. */ + int saved_errno = errno; + if (unlinkat (dirfd (*dirp), f, AT_REMOVEDIR) == 0) + status = RM_OK; + else + error (0, saved_errno, + _("cannot remove %s"), quote (full_filename (f))); + } + + if (status == RM_ERROR) + AD_mark_as_unremovable (ds, f); + break; + } + + *subdir = xstrdup (f); + if (closedir (*dirp) != 0) + { + error (0, 0, _("failed to close directory %s"), + quote (full_filename ("."))); + status = RM_ERROR; + } + *dirp = subdir_dirp; + + break; + } + } /* Record status for this directory. */ UPDATE_STATUS (top->status, status); if (*subdir) - break; + break; } /* Ensure that *dirp is not NULL and that its file descriptor is valid. */ @@ -1590,8 +1590,8 @@ remove_cwd_entries (DIR **dirp, static enum RM_status remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir, - struct stat *dir_st, - struct rm_options const *x, int *cwd_errno) + struct stat *dir_st, + struct rm_options const *x, int *cwd_errno) { enum RM_status status; dev_t current_dev = dir_st->st_dev; @@ -1609,22 +1609,22 @@ remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir, if (dirp == NULL) { /* CAUTION: this test and diagnostic are identical to - those following the other use of fd_to_subdirp. */ + those following the other use of fd_to_subdirp. */ if (ignorable_missing (x, errno)) - { - /* With -f, don't report "file not found". */ - } + { + /* With -f, don't report "file not found". */ + } else - { - /* Upon fd_to_subdirp failure, try to remove DIR directly, - in case it's just an empty directory. */ - int saved_errno = errno; - if (unlinkat (fd_cwd, dir, AT_REMOVEDIR) == 0) - return RM_OK; + { + /* Upon fd_to_subdirp failure, try to remove DIR directly, + in case it's just an empty directory. */ + int saved_errno = errno; + if (unlinkat (fd_cwd, dir, AT_REMOVEDIR) == 0) + return RM_OK; - error (0, saved_errno, - _("cannot remove %s"), quote (full_filename (dir))); - } + error (0, saved_errno, + _("cannot remove %s"), quote (full_filename (dir))); + } return RM_ERROR; } @@ -1650,93 +1650,93 @@ remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir, tmp_status = remove_cwd_entries (&dirp, ds, &subdir, &subdir_sb, x); if (tmp_status != RM_OK) - { - UPDATE_STATUS (status, tmp_status); - AD_mark_current_as_unremovable (ds); - } + { + UPDATE_STATUS (status, tmp_status); + AD_mark_current_as_unremovable (ds); + } if (subdir) - { - if ( ! x->one_file_system - || subdir_sb.st_dev == current_dev) - { - AD_push (dirfd (dirp), ds, subdir, &subdir_sb); - AD_INIT_OTHER_MEMBERS (); - free (subdir); - continue; - } - - /* Here, --one-file-system is in effect, and with remove_cwd_entries' - traversal into the current directory, (known as SUBDIR, from ..), - DIRP's device number is different from CURRENT_DEV. Arrange not - to do anything more with this hierarchy. */ - error (0, 0, _("skipping %s, since it's on a different device"), - quote (full_filename (subdir))); - free (subdir); - AD_mark_current_as_unremovable (ds); - tmp_status = RM_ERROR; - UPDATE_STATUS (status, tmp_status); - } + { + if ( ! x->one_file_system + || subdir_sb.st_dev == current_dev) + { + AD_push (dirfd (dirp), ds, subdir, &subdir_sb); + AD_INIT_OTHER_MEMBERS (); + free (subdir); + continue; + } + + /* Here, --one-file-system is in effect, and with remove_cwd_entries' + traversal into the current directory, (known as SUBDIR, from ..), + DIRP's device number is different from CURRENT_DEV. Arrange not + to do anything more with this hierarchy. */ + error (0, 0, _("skipping %s, since it's on a different device"), + quote (full_filename (subdir))); + free (subdir); + AD_mark_current_as_unremovable (ds); + tmp_status = RM_ERROR; + UPDATE_STATUS (status, tmp_status); + } /* Execution reaches this point when we've removed the last - removable entry from the current directory -- or, with - --one-file-system, when the current directory is on a - different file system. */ + removable entry from the current directory -- or, with + --one-file-system, when the current directory is on a + different file system. */ { - int fd; - /* The name of the directory that we have just processed, - nominally removing all of its contents. */ - char *empty_dir = AD_pop_and_chdir (dirp, &fd, ds); - dirp = NULL; - assert (fd != AT_FDCWD || AD_stack_height (ds) == 1); - - /* Try to remove EMPTY_DIR only if remove_cwd_entries succeeded. */ - if (tmp_status == RM_OK) - { - struct stat empty_st; - Ternary is_empty; - int dirent_type = DT_DIR; - enum RM_status s = prompt (fd, ds, empty_dir, &dirent_type, - cache_stat_init (&empty_st), x, - PA_REMOVE_DIR, &is_empty); - - if (s != RM_OK) - { - free (empty_dir); - status = s; - if (fd != AT_FDCWD) - close (fd); - goto closedir_and_return; - } - - if (unlinkat (fd, empty_dir, AT_REMOVEDIR) == 0) - { - if (x->verbose) - printf (_("removed directory: %s\n"), - quote (full_filename (empty_dir))); - } - else - { - error (0, errno, _("cannot remove directory %s"), - quote (full_filename (empty_dir))); - AD_mark_as_unremovable (ds, empty_dir); - status = RM_ERROR; - UPDATE_STATUS (AD_stack_top(ds)->status, status); - } - } - - free (empty_dir); - - if (fd == AT_FDCWD) - break; - - dirp = fdopendir (fd); - if (dirp == NULL) - { - error (0, errno, _("FATAL: cannot return to .. from %s"), - quote (full_filename ("."))); - close (fd); - longjmp (ds->current_arg_jumpbuf, 1); - } + int fd; + /* The name of the directory that we have just processed, + nominally removing all of its contents. */ + char *empty_dir = AD_pop_and_chdir (dirp, &fd, ds); + dirp = NULL; + assert (fd != AT_FDCWD || AD_stack_height (ds) == 1); + + /* Try to remove EMPTY_DIR only if remove_cwd_entries succeeded. */ + if (tmp_status == RM_OK) + { + struct stat empty_st; + Ternary is_empty; + int dirent_type = DT_DIR; + enum RM_status s = prompt (fd, ds, empty_dir, &dirent_type, + cache_stat_init (&empty_st), x, + PA_REMOVE_DIR, &is_empty); + + if (s != RM_OK) + { + free (empty_dir); + status = s; + if (fd != AT_FDCWD) + close (fd); + goto closedir_and_return; + } + + if (unlinkat (fd, empty_dir, AT_REMOVEDIR) == 0) + { + if (x->verbose) + printf (_("removed directory: %s\n"), + quote (full_filename (empty_dir))); + } + else + { + error (0, errno, _("cannot remove directory %s"), + quote (full_filename (empty_dir))); + AD_mark_as_unremovable (ds, empty_dir); + status = RM_ERROR; + UPDATE_STATUS (AD_stack_top(ds)->status, status); + } + } + + free (empty_dir); + + if (fd == AT_FDCWD) + break; + + dirp = fdopendir (fd); + if (dirp == NULL) + { + error (0, errno, _("FATAL: cannot return to .. from %s"), + quote (full_filename ("."))); + close (fd); + longjmp (ds->current_arg_jumpbuf, 1); + } } } @@ -1748,7 +1748,7 @@ remove_dir (int fd_cwd, Dirstack_state *ds, char const *dir, if (dirp != NULL && closedir (dirp) != 0) { error (0, 0, _("failed to close directory %s"), - quote (full_filename ("."))); + quote (full_filename ("."))); status = RM_ERROR; } @@ -1766,9 +1766,9 @@ rm_1 (Dirstack_state *ds, char const *filename, if (dot_or_dotdot (base)) { error (0, 0, _(base == filename - ? N_("cannot remove directory %s") - : N_("cannot remove %s directory %s")), - quote_n (0, base), quote_n (1, filename)); + ? N_("cannot remove directory %s") + : N_("cannot remove %s directory %s")), + quote_n (0, base), quote_n (1, filename)); return RM_ERROR; } @@ -1778,33 +1778,33 @@ rm_1 (Dirstack_state *ds, char const *filename, if (x->root_dev_ino) { if (cache_fstatat (AT_FDCWD, filename, &st, AT_SYMLINK_NOFOLLOW) != 0) - { - if (ignorable_missing (x, errno)) - return RM_OK; - error (0, errno, _("cannot remove %s"), quote (filename)); - return RM_ERROR; - } + { + if (ignorable_missing (x, errno)) + return RM_OK; + error (0, errno, _("cannot remove %s"), quote (filename)); + return RM_ERROR; + } if (SAME_INODE (st, *(x->root_dev_ino))) - { - error (0, 0, _("cannot remove root directory %s"), quote (filename)); - return RM_ERROR; - } + { + error (0, 0, _("cannot remove root directory %s"), quote (filename)); + return RM_ERROR; + } } AD_push_initial (ds); AD_INIT_OTHER_MEMBERS (); enum RM_status status = remove_entry (AT_FDCWD, ds, filename, - DT_UNKNOWN, &st, x); + DT_UNKNOWN, &st, x); if (status == RM_NONEMPTY_DIR) { /* In the event that remove_dir->remove_cwd_entries detects - a directory cycle, arrange to fail, give up on this FILE, but - continue on with any other arguments. */ + a directory cycle, arrange to fail, give up on this FILE, but + continue on with any other arguments. */ if (setjmp (ds->current_arg_jumpbuf)) - status = RM_ERROR; + status = RM_ERROR; else - status = remove_dir (AT_FDCWD, ds, filename, &st, x, cwd_errno); + status = remove_dir (AT_FDCWD, ds, filename, &st, x, cwd_errno); AD_stack_clear (ds); } @@ -1835,22 +1835,22 @@ rm (size_t n_files, char const *const *file, struct rm_options const *x) for (i = 0; i < n_files; i++) { if (cwd_errno && IS_RELATIVE_FILE_NAME (file[i])) - { - error (0, 0, _("cannot remove relative-named %s"), quote (file[i])); - status = RM_ERROR; - } + { + error (0, 0, _("cannot remove relative-named %s"), quote (file[i])); + status = RM_ERROR; + } else - { - enum RM_status s = rm_1 (&ds, file[i], x, &cwd_errno); - assert (VALID_STATUS (s)); - UPDATE_STATUS (status, s); - } + { + enum RM_status s = rm_1 (&ds, file[i], x, &cwd_errno); + assert (VALID_STATUS (s)); + UPDATE_STATUS (status, s); + } } if (x->require_restore_cwd && cwd_errno) { error (0, cwd_errno, - _("cannot restore current working directory")); + _("cannot restore current working directory")); status = RM_ERROR; } diff --git a/src/remove.h b/src/remove.h index 8d5fd4994..ed1a0214e 100644 --- a/src/remove.h +++ b/src/remove.h @@ -83,12 +83,12 @@ enum RM_status do \ { \ if ((New_value) == RM_ERROR \ - || ((New_value) == RM_USER_DECLINED && (S) == RM_OK)) \ - (S) = (New_value); \ + || ((New_value) == RM_USER_DECLINED && (S) == RM_OK)) \ + (S) = (New_value); \ } \ while (0) enum RM_status rm (size_t n_files, char const *const *file, - struct rm_options const *x); + struct rm_options const *x); #endif @@ -137,14 +137,14 @@ diagnose_leading_hyphen (int argc, char **argv) struct stat st; if (arg[0] == '-' && arg[1] && lstat (arg, &st) == 0) - { - fprintf (stderr, - _("Try `%s ./%s' to remove the file %s.\n"), - argv[0], - quotearg_n_style (1, shell_quoting_style, arg), - quote (arg)); - break; - } + { + fprintf (stderr, + _("Try `%s ./%s' to remove the file %s.\n"), + argv[0], + quotearg_n_style (1, shell_quoting_style, arg), + quote (arg)); + break; + } } } @@ -153,7 +153,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... FILE...\n"), program_name); @@ -196,7 +196,7 @@ use one of these commands:\n\ \n\ %s ./-foo\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ \n\ Note that if you use rm to remove a file, it is usually possible to recover\n\ @@ -248,104 +248,104 @@ main (int argc, char **argv) while ((c = getopt_long (argc, argv, "dfirvIR", long_opts, NULL)) != -1) { switch (c) - { - case 'd': - /* Ignore this option, for backward compatibility with - coreutils 5.92. FIXME: Some time after 2005, change this - to report an error (or perhaps behave like FreeBSD does) - instead of ignoring the option. */ - break; - - case 'f': - x.interactive = RMI_NEVER; - x.ignore_missing_files = true; - prompt_once = false; - break; - - case 'i': - x.interactive = RMI_ALWAYS; - x.ignore_missing_files = false; - prompt_once = false; - break; - - case 'I': - x.interactive = RMI_NEVER; - x.ignore_missing_files = false; - prompt_once = true; - break; - - case 'r': - case 'R': - x.recursive = true; - break; - - case INTERACTIVE_OPTION: - { - int i; - if (optarg) - i = XARGMATCH ("--interactive", optarg, interactive_args, - interactive_types); - else - i = interactive_always; - switch (i) - { - case interactive_never: - x.interactive = RMI_NEVER; - prompt_once = false; - break; - - case interactive_once: - x.interactive = RMI_SOMETIMES; - x.ignore_missing_files = false; - prompt_once = true; - break; - - case interactive_always: - x.interactive = RMI_ALWAYS; - x.ignore_missing_files = false; - prompt_once = false; - break; - } - break; - } - - case ONE_FILE_SYSTEM: - x.one_file_system = true; - break; - - case NO_PRESERVE_ROOT: - preserve_root = false; - break; - - case PRESERVE_ROOT: - preserve_root = true; - break; - - case PRESUME_INPUT_TTY_OPTION: - x.stdin_tty = true; - break; - - case 'v': - x.verbose = true; - break; - - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - diagnose_leading_hyphen (argc, argv); - usage (EXIT_FAILURE); - } + { + case 'd': + /* Ignore this option, for backward compatibility with + coreutils 5.92. FIXME: Some time after 2005, change this + to report an error (or perhaps behave like FreeBSD does) + instead of ignoring the option. */ + break; + + case 'f': + x.interactive = RMI_NEVER; + x.ignore_missing_files = true; + prompt_once = false; + break; + + case 'i': + x.interactive = RMI_ALWAYS; + x.ignore_missing_files = false; + prompt_once = false; + break; + + case 'I': + x.interactive = RMI_NEVER; + x.ignore_missing_files = false; + prompt_once = true; + break; + + case 'r': + case 'R': + x.recursive = true; + break; + + case INTERACTIVE_OPTION: + { + int i; + if (optarg) + i = XARGMATCH ("--interactive", optarg, interactive_args, + interactive_types); + else + i = interactive_always; + switch (i) + { + case interactive_never: + x.interactive = RMI_NEVER; + prompt_once = false; + break; + + case interactive_once: + x.interactive = RMI_SOMETIMES; + x.ignore_missing_files = false; + prompt_once = true; + break; + + case interactive_always: + x.interactive = RMI_ALWAYS; + x.ignore_missing_files = false; + prompt_once = false; + break; + } + break; + } + + case ONE_FILE_SYSTEM: + x.one_file_system = true; + break; + + case NO_PRESERVE_ROOT: + preserve_root = false; + break; + + case PRESERVE_ROOT: + preserve_root = true; + break; + + case PRESUME_INPUT_TTY_OPTION: + x.stdin_tty = true; + break; + + case 'v': + x.verbose = true; + break; + + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + diagnose_leading_hyphen (argc, argv); + usage (EXIT_FAILURE); + } } if (argc <= optind) { if (x.ignore_missing_files) - exit (EXIT_SUCCESS); + exit (EXIT_SUCCESS); else - { - error (0, 0, _("missing operand")); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("missing operand")); + usage (EXIT_FAILURE); + } } if (x.recursive & preserve_root) @@ -353,8 +353,8 @@ main (int argc, char **argv) static struct dev_ino dev_ino_buf; x.root_dev_ino = get_root_dev_ino (&dev_ino_buf); if (x.root_dev_ino == NULL) - error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), - quote ("/")); + error (EXIT_FAILURE, errno, _("failed to get attributes of %s"), + quote ("/")); } size_t n_files = argc - optind; @@ -363,12 +363,12 @@ main (int argc, char **argv) if (prompt_once && (x.recursive || 3 < n_files)) { fprintf (stderr, - (x.recursive - ? _("%s: remove all arguments recursively? ") - : _("%s: remove all arguments? ")), - program_name); + (x.recursive + ? _("%s: remove all arguments recursively? ") + : _("%s: remove all arguments? ")), + program_name); if (!yesno ()) - exit (EXIT_SUCCESS); + exit (EXIT_SUCCESS); } enum RM_status status = rm (n_files, file, &x); assert (VALID_STATUS (status)); diff --git a/src/rmdir.c b/src/rmdir.c index a319b1fda..3bfff22d4 100644 --- a/src/rmdir.c +++ b/src/rmdir.c @@ -17,8 +17,8 @@ /* Options: -p, --parent Remove any parent dirs that are explicitly mentioned - in an argument, if they become empty after the - argument file is removed. + in an argument, if they become empty after the + argument file is removed. David MacKenzie <djm@ai.mit.edu> */ @@ -101,9 +101,9 @@ static bool ignorable_failure (int error_number, char const *dir) { return (ignore_fail_on_non_empty - && (errno_rmdir_non_empty (error_number) - || (errno_may_be_empty (error_number) - && is_empty_dir (AT_FDCWD, dir)))); + && (errno_rmdir_non_empty (error_number) + || (errno_may_be_empty (error_number) + && is_empty_dir (AT_FDCWD, dir)))); } /* Remove any empty parent directories of DIR. @@ -122,34 +122,34 @@ remove_parents (char *dir) { slash = strrchr (dir, '/'); if (slash == NULL) - break; + break; /* Remove any characters after the slash, skipping any extra - slashes in a row. */ + slashes in a row. */ while (slash > dir && *slash == '/') - --slash; + --slash; slash[1] = 0; /* Give a diagnostic for each attempted removal if --verbose. */ if (verbose) - prog_fprintf (stdout, _("removing directory, %s"), quote (dir)); + prog_fprintf (stdout, _("removing directory, %s"), quote (dir)); ok = (rmdir (dir) == 0); if (!ok) - { - /* Stop quietly if --ignore-fail-on-non-empty. */ - if (ignorable_failure (errno, dir)) - { - ok = true; - } - else - { - /* Barring race conditions, DIR is expected to be a directory. */ - error (0, errno, _("failed to remove directory %s"), - quote (dir)); - } - break; - } + { + /* Stop quietly if --ignore-fail-on-non-empty. */ + if (ignorable_failure (errno, dir)) + { + ok = true; + } + else + { + /* Barring race conditions, DIR is expected to be a directory. */ + error (0, errno, _("failed to remove directory %s"), + quote (dir)); + } + break; + } } return ok; } @@ -159,7 +159,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... DIRECTORY...\n"), program_name); @@ -201,21 +201,21 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "pv", longopts, NULL)) != -1) { switch (optc) - { - case 'p': - remove_empty_parents = true; - break; - case IGNORE_FAIL_ON_NON_EMPTY_OPTION: - ignore_fail_on_non_empty = true; - break; - case 'v': - verbose = true; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'p': + remove_empty_parents = true; + break; + case IGNORE_FAIL_ON_NON_EMPTY_OPTION: + ignore_fail_on_non_empty = true; + break; + case 'v': + verbose = true; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (optind == argc) @@ -230,22 +230,22 @@ main (int argc, char **argv) /* Give a diagnostic for each attempted removal if --verbose. */ if (verbose) - prog_fprintf (stdout, _("removing directory, %s"), quote (dir)); + prog_fprintf (stdout, _("removing directory, %s"), quote (dir)); if (rmdir (dir) != 0) - { - if (ignorable_failure (errno, dir)) - continue; - - /* Here, the diagnostic is less precise, since we have no idea - whether DIR is a directory. */ - error (0, errno, _("failed to remove %s"), quote (dir)); - ok = false; - } + { + if (ignorable_failure (errno, dir)) + continue; + + /* Here, the diagnostic is less precise, since we have no idea + whether DIR is a directory. */ + error (0, errno, _("failed to remove %s"), quote (dir)); + ok = false; + } else if (remove_empty_parents) - { - ok &= remove_parents (dir); - } + { + ok &= remove_parents (dir); + } } exit (ok ? EXIT_SUCCESS : EXIT_FAILURE); diff --git a/src/runcon.c b/src/runcon.c index 2331f938b..7bf256821 100644 --- a/src/runcon.c +++ b/src/runcon.c @@ -78,7 +78,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -131,47 +131,47 @@ main (int argc, char **argv) { int option_index = 0; int c = getopt_long (argc, argv, "+r:t:u:l:c", long_options, - &option_index); + &option_index); if (c == -1) - break; + break; switch (c) - { - case 'r': - if (role) - error (EXIT_FAILURE, 0, _("multiple roles")); - role = optarg; - break; - case 't': - if (type) - error (EXIT_FAILURE, 0, _("multiple types")); - type = optarg; - break; - case 'u': - if (user) - error (EXIT_FAILURE, 0, _("multiple users")); - user = optarg; - break; - case 'l': - if (range) - error (EXIT_FAILURE, 0, _("multiple levelranges")); - range = optarg; - break; - case 'c': - compute_trans = true; - break; + { + case 'r': + if (role) + error (EXIT_FAILURE, 0, _("multiple roles")); + role = optarg; + break; + case 't': + if (type) + error (EXIT_FAILURE, 0, _("multiple types")); + type = optarg; + break; + case 'u': + if (user) + error (EXIT_FAILURE, 0, _("multiple users")); + user = optarg; + break; + case 'l': + if (range) + error (EXIT_FAILURE, 0, _("multiple levelranges")); + range = optarg; + break; + case 'c': + compute_trans = true; + break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - break; - } + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + break; + } } if (argc - optind == 0) { if (getcon (&cur_context) < 0) - error (EXIT_FAILURE, errno, _("failed to get current context")); + error (EXIT_FAILURE, errno, _("failed to get current context")); fputs (cur_context, stdout); fputc ('\n', stdout); exit (EXIT_SUCCESS); @@ -180,10 +180,10 @@ main (int argc, char **argv) if (!(user || role || type || range || compute_trans)) { if (optind >= argc) - { - error (0, 0, _("you must specify -c, -t, -u, -l, -r, or context")); - usage (1); - } + { + error (0, 0, _("you must specify -c, -t, -u, -l, -r, or context")); + usage (1); + } context = argv[optind++]; } @@ -195,62 +195,62 @@ main (int argc, char **argv) if (is_selinux_enabled () != 1) error (EXIT_FAILURE, 0, - _("runcon may be used only on a SELinux kernel")); + _("runcon may be used only on a SELinux kernel")); if (context) { con = context_new (context); if (!con) - error (EXIT_FAILURE, errno, _("failed to create security context: %s"), - quotearg_colon (context)); + error (EXIT_FAILURE, errno, _("failed to create security context: %s"), + quotearg_colon (context)); } else { if (getcon (&cur_context) < 0) - error (EXIT_FAILURE, errno, _("failed to get current context")); + error (EXIT_FAILURE, errno, _("failed to get current context")); /* We will generate context based on process transition */ if (compute_trans) - { - /* Get context of file to be executed */ - if (getfilecon (argv[optind], &file_context) == -1) - error (EXIT_FAILURE, errno, - _("failed to get security context of %s"), - quote (argv[optind])); - /* compute result of process transition */ - if (security_compute_create (cur_context, file_context, - SECCLASS_PROCESS, &new_context) != 0) - error (EXIT_FAILURE, errno, - _("failed to compute a new context")); - /* free contexts */ - freecon (file_context); - freecon (cur_context); + { + /* Get context of file to be executed */ + if (getfilecon (argv[optind], &file_context) == -1) + error (EXIT_FAILURE, errno, + _("failed to get security context of %s"), + quote (argv[optind])); + /* compute result of process transition */ + if (security_compute_create (cur_context, file_context, + SECCLASS_PROCESS, &new_context) != 0) + error (EXIT_FAILURE, errno, + _("failed to compute a new context")); + /* free contexts */ + freecon (file_context); + freecon (cur_context); - /* set cur_context equal to new_context */ - cur_context = new_context; - } + /* set cur_context equal to new_context */ + cur_context = new_context; + } con = context_new (cur_context); if (!con) - error (EXIT_FAILURE, errno, _("failed to create security context: %s"), - quotearg_colon (cur_context)); + error (EXIT_FAILURE, errno, _("failed to create security context: %s"), + quotearg_colon (cur_context)); if (user && context_user_set (con, user)) - error (EXIT_FAILURE, errno, _("failed to set new user %s"), user); + error (EXIT_FAILURE, errno, _("failed to set new user %s"), user); if (type && context_type_set (con, type)) - error (EXIT_FAILURE, errno, _("failed to set new type %s"), type); + error (EXIT_FAILURE, errno, _("failed to set new type %s"), type); if (range && context_range_set (con, range)) - error (EXIT_FAILURE, errno, _("failed to set new range %s"), range); + error (EXIT_FAILURE, errno, _("failed to set new range %s"), range); if (role && context_role_set (con, role)) - error (EXIT_FAILURE, errno, _("failed to set new role %s"), role); + error (EXIT_FAILURE, errno, _("failed to set new role %s"), role); } if (security_check_context (context_str (con)) < 0) error (EXIT_FAILURE, errno, _("invalid context: %s"), - quotearg_colon (context_str (con))); + quotearg_colon (context_str (con))); if (setexeccon (context_str (con)) != 0) error (EXIT_FAILURE, errno, _("unable to set security context %s"), - quote (context_str (con))); + quote (context_str (con))); if (cur_context != NULL) freecon (cur_context); @@ -64,7 +64,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -150,25 +150,25 @@ scan_arg (const char *arg) { char const *decimal_point = strchr (arg, '.'); if (! decimal_point) - ret.precision = 0; + ret.precision = 0; else - { - size_t fraction_len = strcspn (decimal_point + 1, "eE"); - if (fraction_len <= INT_MAX) - ret.precision = fraction_len; - ret.width += (fraction_len == 0 /* #. -> # */ - ? -1 - : (decimal_point == arg /* .# -> 0.# */ - || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */ - } + { + size_t fraction_len = strcspn (decimal_point + 1, "eE"); + if (fraction_len <= INT_MAX) + ret.precision = fraction_len; + ret.width += (fraction_len == 0 /* #. -> # */ + ? -1 + : (decimal_point == arg /* .# -> 0.# */ + || ! ISDIGIT (decimal_point[-1]))); /* -.# -> 0.# */ + } char const *e = strchr (arg, 'e'); if (! e) - e = strchr (arg, 'E'); + e = strchr (arg, 'E'); if (e) - { - long exponent = strtol (e + 1, NULL, 10); - ret.precision += exponent < 0 ? -exponent : 0; - } + { + long exponent = strtol (e + 1, NULL, 10); + ret.precision += exponent < 0 ? -exponent : 0; + } } return ret; @@ -191,8 +191,8 @@ long_double_format (char const *fmt, struct layout *layout) for (i = 0; ! (fmt[i] == '%' && fmt[i + 1] != '%'); i += (fmt[i] == '%') + 1) { if (!fmt[i]) - error (EXIT_FAILURE, 0, - _("format %s has no %% directive"), quote (fmt)); + error (EXIT_FAILURE, 0, + _("format %s has no %% directive"), quote (fmt)); prefix_len++; } @@ -212,25 +212,25 @@ long_double_format (char const *fmt, struct layout *layout) error (EXIT_FAILURE, 0, _("format %s ends in %%"), quote (fmt)); if (! strchr ("efgaEFGA", fmt[i])) error (EXIT_FAILURE, 0, - _("format %s has unknown %%%c directive"), quote (fmt), fmt[i]); + _("format %s has unknown %%%c directive"), quote (fmt), fmt[i]); for (i++; ; i += (fmt[i] == '%') + 1) if (fmt[i] == '%' && fmt[i + 1] != '%') error (EXIT_FAILURE, 0, _("format %s has too many %% directives"), - quote (fmt)); + quote (fmt)); else if (fmt[i]) suffix_len++; else { - size_t format_size = i + 1; - char *ldfmt = xmalloc (format_size + 1); - memcpy (ldfmt, fmt, length_modifier_offset); - ldfmt[length_modifier_offset] = 'L'; - strcpy (ldfmt + length_modifier_offset + 1, - fmt + length_modifier_offset + has_L); - layout->prefix_len = prefix_len; - layout->suffix_len = suffix_len; - return ldfmt; + size_t format_size = i + 1; + char *ldfmt = xmalloc (format_size + 1); + memcpy (ldfmt, fmt, length_modifier_offset); + ldfmt[length_modifier_offset] = 'L'; + strcpy (ldfmt + length_modifier_offset + 1, + fmt + length_modifier_offset + has_L); + layout->prefix_len = prefix_len; + layout->suffix_len = suffix_len; + return ldfmt; } } @@ -239,7 +239,7 @@ long_double_format (char const *fmt, struct layout *layout) static void print_numbers (char const *fmt, struct layout layout, - long double first, long double step, long double last) + long double first, long double step, long double last) { bool out_of_range = (step < 0 ? first < last : last < first); @@ -249,51 +249,51 @@ print_numbers (char const *fmt, struct layout layout, long double i; for (i = 1; ; i++) - { - long double x0 = x; - printf (fmt, x); - if (out_of_range) - break; - x = first + i * step; - out_of_range = (step < 0 ? x < last : last < x); - - if (out_of_range) - { - /* If the number just past LAST prints as a value equal - to LAST, and prints differently from the previous - number, then print the number. This avoids problems - with rounding. For example, with the x86 it causes - "seq 0 0.000001 0.000003" to print 0.000003 instead - of stopping at 0.000002. */ - - bool print_extra_number = false; - long double x_val; - char *x_str; - int x_strlen; - setlocale (LC_NUMERIC, "C"); - x_strlen = asprintf (&x_str, fmt, x); - setlocale (LC_NUMERIC, ""); - if (x_strlen < 0) - xalloc_die (); - x_str[x_strlen - layout.suffix_len] = '\0'; - - if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold) - && x_val == last) - { - char *x0_str = NULL; - if (asprintf (&x0_str, fmt, x0) < 0) - xalloc_die (); - print_extra_number = !STREQ (x0_str, x_str); - free (x0_str); - } - - free (x_str); - if (! print_extra_number) - break; - } - - fputs (separator, stdout); - } + { + long double x0 = x; + printf (fmt, x); + if (out_of_range) + break; + x = first + i * step; + out_of_range = (step < 0 ? x < last : last < x); + + if (out_of_range) + { + /* If the number just past LAST prints as a value equal + to LAST, and prints differently from the previous + number, then print the number. This avoids problems + with rounding. For example, with the x86 it causes + "seq 0 0.000001 0.000003" to print 0.000003 instead + of stopping at 0.000002. */ + + bool print_extra_number = false; + long double x_val; + char *x_str; + int x_strlen; + setlocale (LC_NUMERIC, "C"); + x_strlen = asprintf (&x_str, fmt, x); + setlocale (LC_NUMERIC, ""); + if (x_strlen < 0) + xalloc_die (); + x_str[x_strlen - layout.suffix_len] = '\0'; + + if (xstrtold (x_str + layout.prefix_len, NULL, &x_val, c_strtold) + && x_val == last) + { + char *x0_str = NULL; + if (asprintf (&x0_str, fmt, x0) < 0) + xalloc_die (); + print_extra_number = !STREQ (x0_str, x_str); + free (x0_str); + } + + free (x_str); + if (! print_extra_number) + break; + } + + fputs (separator, stdout); + } fputs (terminator, stdout); } @@ -310,28 +310,28 @@ get_default_format (operand first, operand step, operand last) if (prec != INT_MAX && last.precision != INT_MAX) { if (equal_width) - { - /* increase first_width by any increased precision in step */ - size_t first_width = first.width + (prec - first.precision); - /* adjust last_width to use precision from first/step */ - size_t last_width = last.width + (prec - last.precision); - if (last.precision && prec == 0) - last_width--; /* don't include space for '.' */ - if (last.precision == 0 && prec) - last_width++; /* include space for '.' */ - size_t width = MAX (first_width, last_width); - if (width <= INT_MAX) - { - int w = width; - sprintf (format_buf, "%%0%d.%dLf", w, prec); - return format_buf; - } - } + { + /* increase first_width by any increased precision in step */ + size_t first_width = first.width + (prec - first.precision); + /* adjust last_width to use precision from first/step */ + size_t last_width = last.width + (prec - last.precision); + if (last.precision && prec == 0) + last_width--; /* don't include space for '.' */ + if (last.precision == 0 && prec) + last_width++; /* include space for '.' */ + size_t width = MAX (first_width, last_width); + if (width <= INT_MAX) + { + int w = width; + sprintf (format_buf, "%%0%d.%dLf", w, prec); + return format_buf; + } + } else - { - sprintf (format_buf, "%%.%dLf", prec); - return format_buf; - } + { + sprintf (format_buf, "%%.%dLf", prec); + return format_buf; + } } return "%Lg"; @@ -366,37 +366,37 @@ main (int argc, char **argv) while (optind < argc) { if (argv[optind][0] == '-' - && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc))) - { - /* means negative number */ - break; - } + && ((optc = argv[optind][1]) == '.' || ISDIGIT (optc))) + { + /* means negative number */ + break; + } optc = getopt_long (argc, argv, "+f:s:w", long_options, NULL); if (optc == -1) - break; + break; switch (optc) - { - case 'f': - format_str = optarg; - break; + { + case 'f': + format_str = optarg; + break; - case 's': - separator = optarg; - break; + case 's': + separator = optarg; + break; - case 'w': - equal_width = true; - break; + case 'w': + equal_width = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (argc - optind < 1) @@ -422,10 +422,10 @@ main (int argc, char **argv) last = scan_arg (argv[optind++]); if (optind < argc) - { - step = last; - last = scan_arg (argv[optind++]); - } + { + step = last; + last = scan_arg (argv[optind++]); + } } if (format_str != NULL && equal_width) diff --git a/src/shred.c b/src/shred.c index cf40bdc4c..43b6d64f5 100644 --- a/src/shred.c +++ b/src/shred.c @@ -152,7 +152,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... FILE...\n"), program_name); @@ -282,9 +282,9 @@ static bool ignorable_sync_errno (int errno_val) { return (errno_val == EINVAL - || errno_val == EBADF - /* HP-UX does this */ - || errno_val == EISDIR); + || errno_val == EBADF + /* HP-UX does this */ + || errno_val == EISDIR); } /* Request that all data for FD be transferred to the corresponding @@ -333,13 +333,13 @@ direct_mode (int fd, bool enable) { int fd_flags = fcntl (fd, F_GETFL); if (0 < fd_flags) - { - int new_flags = (enable - ? (fd_flags | O_DIRECT) - : (fd_flags & ~O_DIRECT)); - if (new_flags != fd_flags) - fcntl (fd, F_SETFL, new_flags); - } + { + int new_flags = (enable + ? (fd_flags | O_DIRECT) + : (fd_flags & ~O_DIRECT)); + if (new_flags != fd_flags) + fcntl (fd, F_SETFL, new_flags); + } } #if HAVE_DIRECTIO && defined DIRECTIO_ON && defined DIRECTIO_OFF @@ -361,7 +361,7 @@ direct_mode (int fd, bool enable) */ static int dopass (int fd, char const *qname, off_t *sizep, int type, - struct randread_source *s, unsigned long int k, unsigned long int n) + struct randread_source *s, unsigned long int k, unsigned long int n) { off_t size = *sizep; off_t offset; /* Current file posiiton */ @@ -422,144 +422,144 @@ dopass (int fd, char const *qname, off_t *sizep, int type, /* How much to write this time? */ lim = sizeof r; if (0 <= size && size - offset < sizeof_r) - { - if (size < offset) - break; - lim = size - offset; - if (!lim) - break; - } + { + if (size < offset) + break; + lim = size - offset; + if (!lim) + break; + } if (type < 0) - randread (s, &r, lim); + randread (s, &r, lim); /* Loop to retry partial writes. */ for (soff = 0; soff < lim; soff += ssize, first_write = false) - { - ssize = write (fd, r.c + soff, lim - soff); - if (ssize <= 0) - { - if (size < 0 && (ssize == 0 || errno == ENOSPC)) - { - /* Ah, we have found the end of the file */ - *sizep = size = offset + soff; - break; - } - else - { - int errnum = errno; - char buf[INT_BUFSIZE_BOUND (uintmax_t)]; - - /* If the first write of the first pass for a given file - has just failed with EINVAL, turn off direct mode I/O - and try again. This works around a bug in Linux kernel - 2.4 whereby opening with O_DIRECT would succeed for some - file system types (e.g., ext3), but any attempt to - access a file through the resulting descriptor would - fail with EINVAL. */ - if (k == 1 && first_write && errno == EINVAL) - { - direct_mode (fd, false); - ssize = 0; - continue; - } - error (0, errnum, _("%s: error writing at offset %s"), - qname, umaxtostr (offset + soff, buf)); - - /* 'shred' is often used on bad media, before throwing it - out. Thus, it shouldn't give up on bad blocks. This - code works because lim is always a multiple of - SECTOR_SIZE, except at the end. */ - verify (sizeof r % SECTOR_SIZE == 0); - if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim) - { - size_t soff1 = (soff | SECTOR_MASK) + 1; - if (lseek (fd, offset + soff1, SEEK_SET) != -1) - { - /* Arrange to skip this block. */ - ssize = soff1 - soff; - write_error = true; - continue; - } - error (0, errno, _("%s: lseek failed"), qname); - } - return -1; - } - } - } + { + ssize = write (fd, r.c + soff, lim - soff); + if (ssize <= 0) + { + if (size < 0 && (ssize == 0 || errno == ENOSPC)) + { + /* Ah, we have found the end of the file */ + *sizep = size = offset + soff; + break; + } + else + { + int errnum = errno; + char buf[INT_BUFSIZE_BOUND (uintmax_t)]; + + /* If the first write of the first pass for a given file + has just failed with EINVAL, turn off direct mode I/O + and try again. This works around a bug in Linux kernel + 2.4 whereby opening with O_DIRECT would succeed for some + file system types (e.g., ext3), but any attempt to + access a file through the resulting descriptor would + fail with EINVAL. */ + if (k == 1 && first_write && errno == EINVAL) + { + direct_mode (fd, false); + ssize = 0; + continue; + } + error (0, errnum, _("%s: error writing at offset %s"), + qname, umaxtostr (offset + soff, buf)); + + /* 'shred' is often used on bad media, before throwing it + out. Thus, it shouldn't give up on bad blocks. This + code works because lim is always a multiple of + SECTOR_SIZE, except at the end. */ + verify (sizeof r % SECTOR_SIZE == 0); + if (errnum == EIO && 0 <= size && (soff | SECTOR_MASK) < lim) + { + size_t soff1 = (soff | SECTOR_MASK) + 1; + if (lseek (fd, offset + soff1, SEEK_SET) != -1) + { + /* Arrange to skip this block. */ + ssize = soff1 - soff; + write_error = true; + continue; + } + error (0, errno, _("%s: lseek failed"), qname); + } + return -1; + } + } + } /* Okay, we have written "soff" bytes. */ if (offset > OFF_T_MAX - (off_t) soff) - { - error (0, 0, _("%s: file too large"), qname); - return -1; - } + { + error (0, 0, _("%s: file too large"), qname); + return -1; + } offset += soff; /* Time to print progress? */ if (n - && ((offset == size && *previous_human_offset) - || thresh <= (now = time (NULL)))) - { - char offset_buf[LONGEST_HUMAN_READABLE + 1]; - char size_buf[LONGEST_HUMAN_READABLE + 1]; - int human_progress_opts = (human_autoscale | human_SI - | human_base_1024 | human_B); - char const *human_offset - = human_readable (offset, offset_buf, - human_floor | human_progress_opts, 1, 1); - - if (offset == size - || !STREQ (previous_human_offset, human_offset)) - { - if (size < 0) - error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), - qname, k, n, pass_string, human_offset); - else - { - uintmax_t off = offset; - int percent = (size == 0 - ? 100 - : (off <= TYPE_MAXIMUM (uintmax_t) / 100 - ? off * 100 / size - : off / (size / 100))); - char const *human_size - = human_readable (size, size_buf, - human_ceiling | human_progress_opts, - 1, 1); - if (offset == size) - human_offset = human_size; - error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"), - qname, k, n, pass_string, human_offset, human_size, - percent); - } - - strcpy (previous_offset_buf, human_offset); - previous_human_offset = previous_offset_buf; - thresh = now + VERBOSE_UPDATE; - - /* - * Force periodic syncs to keep displayed progress accurate - * FIXME: Should these be present even if -v is not enabled, - * to keep the buffer cache from filling with dirty pages? - * It's a common problem with programs that do lots of writes, - * like mkfs. - */ - if (dosync (fd, qname) != 0) - { - if (errno != EIO) - return -1; - write_error = true; - } - } - } + && ((offset == size && *previous_human_offset) + || thresh <= (now = time (NULL)))) + { + char offset_buf[LONGEST_HUMAN_READABLE + 1]; + char size_buf[LONGEST_HUMAN_READABLE + 1]; + int human_progress_opts = (human_autoscale | human_SI + | human_base_1024 | human_B); + char const *human_offset + = human_readable (offset, offset_buf, + human_floor | human_progress_opts, 1, 1); + + if (offset == size + || !STREQ (previous_human_offset, human_offset)) + { + if (size < 0) + error (0, 0, _("%s: pass %lu/%lu (%s)...%s"), + qname, k, n, pass_string, human_offset); + else + { + uintmax_t off = offset; + int percent = (size == 0 + ? 100 + : (off <= TYPE_MAXIMUM (uintmax_t) / 100 + ? off * 100 / size + : off / (size / 100))); + char const *human_size + = human_readable (size, size_buf, + human_ceiling | human_progress_opts, + 1, 1); + if (offset == size) + human_offset = human_size; + error (0, 0, _("%s: pass %lu/%lu (%s)...%s/%s %d%%"), + qname, k, n, pass_string, human_offset, human_size, + percent); + } + + strcpy (previous_offset_buf, human_offset); + previous_human_offset = previous_offset_buf; + thresh = now + VERBOSE_UPDATE; + + /* + * Force periodic syncs to keep displayed progress accurate + * FIXME: Should these be present even if -v is not enabled, + * to keep the buffer cache from filling with dirty pages? + * It's a common problem with programs that do lots of writes, + * like mkfs. + */ + if (dosync (fd, qname) != 0) + { + if (errno != EIO) + return -1; + write_error = true; + } + } + } } /* Force what we just wrote to hit the media. */ if (dosync (fd, qname) != 0) { if (errno != EIO) - return -1; + return -1; write_error = true; } @@ -631,7 +631,7 @@ static int const 12, 0x111, 0x222, 0x333, 0x444, 0x666, 0x777, 0x888, 0x999, 0xBBB, 0xCCC, 0xDDD, 0xEEE, /* 4-bit */ -1, /* 1 random pass */ - /* The following patterns have the frst bit per block flipped */ + /* The following patterns have the frst bit per block flipped */ 8, 0x1000, 0x1249, 0x1492, 0x16DB, 0x1924, 0x1B6D, 0x1DB6, 0x1FFF, 14, 0x1111, 0x1222, 0x1333, 0x1444, 0x1555, 0x1666, 0x1777, 0x1888, 0x1999, 0x1AAA, 0x1BBB, 0x1CCC, 0x1DDD, 0x1EEE, @@ -668,47 +668,47 @@ genpattern (int *dest, size_t num, struct randint_source *s) { k = *p++; /* Block descriptor word */ if (!k) - { /* Loop back to the beginning */ - p = patterns; - } + { /* Loop back to the beginning */ + p = patterns; + } else if (k < 0) - { /* -k random passes */ - k = -k; - if ((size_t) k >= n) - { - randpasses += n; - n = 0; - break; - } - randpasses += k; - n -= k; - } + { /* -k random passes */ + k = -k; + if ((size_t) k >= n) + { + randpasses += n; + n = 0; + break; + } + randpasses += k; + n -= k; + } else if ((size_t) k <= n) - { /* Full block of patterns */ - memcpy (d, p, k * sizeof (int)); - p += k; - d += k; - n -= k; - } + { /* Full block of patterns */ + memcpy (d, p, k * sizeof (int)); + p += k; + d += k; + n -= k; + } else if (n < 2 || 3 * n < (size_t) k) - { /* Finish with random */ - randpasses += n; - break; - } + { /* Finish with random */ + randpasses += n; + break; + } else - { /* Pad out with k of the n available */ - do - { - if (n == (size_t) k || randint_choose (s, k) < n) - { - *d++ = *p; - n--; - } - p++; - } - while (n); - break; - } + { /* Pad out with k of the n available */ + do + { + if (n == (size_t) k || randint_choose (s, k) < n) + { + *d++ = *p; + n--; + } + p++; + } + while (n); + break; + } } top = num - randpasses; /* Top of initialized data */ /* assert (d == dest+top); */ @@ -738,18 +738,18 @@ genpattern (int *dest, size_t num, struct randint_source *s) for (n = 0; n < num; n++) { if (accum <= randpasses) - { - accum += num - 1; - dest[top++] = dest[n]; - dest[n] = -1; - } + { + accum += num - 1; + dest[top++] = dest[n]; + dest[n] = -1; + } else - { - swap = n + randint_choose (s, top - n); - k = dest[n]; - dest[n] = dest[swap]; - dest[swap] = k; - } + { + swap = n + randint_choose (s, top - n); + k = dest[n]; + dest[n] = dest[swap]; + dest[swap] = k; + } accum -= randpasses; } /* assert (top == num); */ @@ -761,7 +761,7 @@ genpattern (int *dest, size_t num, struct randint_source *s) */ static bool do_wipefd (int fd, char const *qname, struct randint_source *s, - struct Options const *flags) + struct Options const *flags) { size_t i; struct stat st; @@ -801,36 +801,36 @@ do_wipefd (int fd, char const *qname, struct randint_source *s, if (size == -1) { /* Accept a length of zero only if it's a regular file. - For any other type of file, try to get the size another way. */ + For any other type of file, try to get the size another way. */ if (S_ISREG (st.st_mode)) - { - size = st.st_size; - if (size < 0) - { - error (0, 0, _("%s: file has negative size"), qname); - return false; - } - } + { + size = st.st_size; + if (size < 0) + { + error (0, 0, _("%s: file has negative size"), qname); + return false; + } + } else - { - size = lseek (fd, 0, SEEK_END); - if (size <= 0) - { - /* We are unable to determine the length, up front. - Let dopass do that as part of its first iteration. */ - size = -1; - } - } + { + size = lseek (fd, 0, SEEK_END); + if (size <= 0) + { + /* We are unable to determine the length, up front. + Let dopass do that as part of its first iteration. */ + size = -1; + } + } /* Allow `rounding up' only for regular files. */ if (0 <= size && !(flags->exact) && S_ISREG (st.st_mode)) - { - size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st); + { + size += ST_BLKSIZE (st) - 1 - (size - 1) % ST_BLKSIZE (st); - /* If in rounding up, we've just overflowed, use the maximum. */ - if (size < 0) - size = TYPE_MAXIMUM (off_t); - } + /* If in rounding up, we've just overflowed, use the maximum. */ + if (size < 0) + size = TYPE_MAXIMUM (off_t); + } } /* Schedule the passes in random order. */ @@ -843,15 +843,15 @@ do_wipefd (int fd, char const *qname, struct randint_source *s, { int err = dopass (fd, qname, &size, passarray[i], rs, i + 1, n); if (err) - { - if (err < 0) - { - memset (passarray, 0, flags->n_iterations * sizeof (int)); - free (passarray); - return false; - } - ok = false; - } + { + if (err < 0) + { + memset (passarray, 0, flags->n_iterations * sizeof (int)); + free (passarray); + return false; + } + ok = false; + } } memset (passarray, 0, flags->n_iterations * sizeof (int)); @@ -861,11 +861,11 @@ do_wipefd (int fd, char const *qname, struct randint_source *s, { int err = dopass (fd, qname, &size, 0, rs, flags->n_iterations + 1, n); if (err) - { - if (err < 0) - return false; - ok = false; - } + { + if (err < 0) + return false; + ok = false; + } } /* Okay, now deallocate the data. The effect of ftruncate on @@ -884,7 +884,7 @@ do_wipefd (int fd, char const *qname, struct randint_source *s, /* A wrapper with a little more checking for fds on the command line */ static bool wipefd (int fd, char const *qname, struct randint_source *s, - struct Options const *flags) + struct Options const *flags) { int fd_flags = fcntl (fd, F_GETFL); @@ -921,10 +921,10 @@ incname (char *name, size_t len) /* If this character has a successor, use it. */ if (p[1]) - { - name[len] = p[1]; - return true; - } + { + name[len] = p[1]; + return true; + } /* Otherwise, set this digit to 0 and increment the prefix. */ name[len] = nameset[0]; @@ -980,40 +980,40 @@ wipename (char *oldname, char const *qoldname, struct Options const *flags) memset (base, nameset[0], len); base[len] = 0; do - { - struct stat st; - if (lstat (newname, &st) < 0) - { - if (rename (oldname, newname) == 0) - { - if (0 <= dir_fd && dosync (dir_fd, qdir) != 0) - ok = false; - if (flags->verbose) - { - /* - * People seem to understand this better than talking - * about renaming oldname. newname doesn't need - * quoting because we picked it. oldname needs to - * be quoted only the first time. - */ - char const *old = (first ? qoldname : oldname); - error (0, 0, _("%s: renamed to %s"), old, newname); - first = false; - } - memcpy (oldname + (base - newname), base, len + 1); - break; - } - else - { - /* The rename failed: give up on this length. */ - break; - } - } - else - { - /* newname exists, so increment BASE so we use another */ - } - } + { + struct stat st; + if (lstat (newname, &st) < 0) + { + if (rename (oldname, newname) == 0) + { + if (0 <= dir_fd && dosync (dir_fd, qdir) != 0) + ok = false; + if (flags->verbose) + { + /* + * People seem to understand this better than talking + * about renaming oldname. newname doesn't need + * quoting because we picked it. oldname needs to + * be quoted only the first time. + */ + char const *old = (first ? qoldname : oldname); + error (0, 0, _("%s: renamed to %s"), old, newname); + first = false; + } + memcpy (oldname + (base - newname), base, len + 1); + break; + } + else + { + /* The rename failed: give up on this length. */ + break; + } + } + else + { + /* newname exists, so increment BASE so we use another */ + } + } while (incname (base, len)); len--; } @@ -1027,12 +1027,12 @@ wipename (char *oldname, char const *qoldname, struct Options const *flags) if (0 <= dir_fd) { if (dosync (dir_fd, qdir) != 0) - ok = false; + ok = false; if (close (dir_fd) != 0) - { - error (0, errno, _("%s: failed to close"), qdir); - ok = false; - } + { + error (0, errno, _("%s: failed to close"), qdir); + ok = false; + } } free (newname); free (dir); @@ -1054,7 +1054,7 @@ wipename (char *oldname, char const *qoldname, struct Options const *flags) */ static bool wipefile (char *name, char const *qname, - struct randint_source *s, struct Options const *flags) + struct randint_source *s, struct Options const *flags) { bool ok; int fd; @@ -1120,66 +1120,66 @@ main (int argc, char **argv) while ((c = getopt_long (argc, argv, "fn:s:uvxz", long_opts, NULL)) != -1) { switch (c) - { - case 'f': - flags.force = true; - break; - - case 'n': - { - uintmax_t tmp; - if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK - || MIN (UINT32_MAX, SIZE_MAX / sizeof (int)) < tmp) - { - error (EXIT_FAILURE, 0, _("%s: invalid number of passes"), - quotearg_colon (optarg)); - } - flags.n_iterations = tmp; - } - break; - - case RANDOM_SOURCE_OPTION: - if (random_source && !STREQ (random_source, optarg)) - error (EXIT_FAILURE, 0, _("multiple random sources specified")); - random_source = optarg; - break; - - case 'u': - flags.remove_file = true; - break; - - case 's': - { - uintmax_t tmp; - if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0") - != LONGINT_OK) - { - error (EXIT_FAILURE, 0, _("%s: invalid file size"), - quotearg_colon (optarg)); - } - flags.size = tmp; - } - break; - - case 'v': - flags.verbose = true; - break; - - case 'x': - flags.exact = true; - break; - - case 'z': - flags.zero_fill = true; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'f': + flags.force = true; + break; + + case 'n': + { + uintmax_t tmp; + if (xstrtoumax (optarg, NULL, 10, &tmp, NULL) != LONGINT_OK + || MIN (UINT32_MAX, SIZE_MAX / sizeof (int)) < tmp) + { + error (EXIT_FAILURE, 0, _("%s: invalid number of passes"), + quotearg_colon (optarg)); + } + flags.n_iterations = tmp; + } + break; + + case RANDOM_SOURCE_OPTION: + if (random_source && !STREQ (random_source, optarg)) + error (EXIT_FAILURE, 0, _("multiple random sources specified")); + random_source = optarg; + break; + + case 'u': + flags.remove_file = true; + break; + + case 's': + { + uintmax_t tmp; + if (xstrtoumax (optarg, NULL, 0, &tmp, "cbBkKMGTPEZY0") + != LONGINT_OK) + { + error (EXIT_FAILURE, 0, _("%s: invalid file size"), + quotearg_colon (optarg)); + } + flags.size = tmp; + } + break; + + case 'v': + flags.verbose = true; + break; + + case 'x': + flags.exact = true; + break; + + case 'z': + flags.zero_fill = true; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } file = argv + optind; @@ -1200,14 +1200,14 @@ main (int argc, char **argv) { char *qname = xstrdup (quotearg_colon (file[i])); if (STREQ (file[i], "-")) - { - ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags); - } + { + ok &= wipefd (STDOUT_FILENO, qname, randint_source, &flags); + } else - { - /* Plain filename - Note that this overwrites *argv! */ - ok &= wipefile (file[i], qname, randint_source, &flags); - } + { + /* Plain filename - Note that this overwrites *argv! */ + ok &= wipefile (file[i], qname, randint_source, &flags); + } free (qname); } diff --git a/src/shuf.c b/src/shuf.c index 8cacf8b10..0e61e32dd 100644 --- a/src/shuf.c +++ b/src/shuf.c @@ -41,7 +41,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -49,7 +49,7 @@ Usage: %s [OPTION]... [FILE]\n\ or: %s -e [OPTION]... [ARG]...\n\ or: %s -i LO-HI [OPTION]...\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Write a random permutation of the input lines to standard output.\n\ \n\ @@ -163,27 +163,27 @@ read_input (FILE *in, char eolbyte, char ***pline) off_t file_size = instat.st_size; off_t current_offset = ftello (in); if (0 <= current_offset) - { - off_t remaining_size = - (current_offset < file_size ? file_size - current_offset : 0); - if (SIZE_MAX - 2 < remaining_size) - xalloc_die (); - next_alloc = remaining_size + 2; - } + { + off_t remaining_size = + (current_offset < file_size ? file_size - current_offset : 0); + if (SIZE_MAX - 2 < remaining_size) + xalloc_die (); + next_alloc = remaining_size + 2; + } } do { if (alloc <= used + 1) - { - if (alloc == SIZE_MAX) - xalloc_die (); - alloc = next_alloc; - next_alloc = alloc * 2; - if (next_alloc < alloc) - next_alloc = SIZE_MAX; - buf = xrealloc (buf, alloc); - } + { + if (alloc == SIZE_MAX) + xalloc_die (); + alloc = next_alloc; + next_alloc = alloc * 2; + if (next_alloc < alloc) + next_alloc = SIZE_MAX; + buf = xrealloc (buf, alloc); + } bytes_to_read = alloc - used - 1; nread = fread (buf + used, sizeof (char), bytes_to_read, in); @@ -214,24 +214,24 @@ read_input (FILE *in, char eolbyte, char ***pline) static int write_permuted_output (size_t n_lines, char * const *line, size_t lo_input, - size_t const *permutation, char eolbyte) + size_t const *permutation, char eolbyte) { size_t i; if (line) for (i = 0; i < n_lines; i++) { - char * const *p = line + permutation[i]; - size_t len = p[1] - p[0]; - if (fwrite (p[0], sizeof *p[0], len, stdout) != len) - return -1; + char * const *p = line + permutation[i]; + size_t len = p[1] - p[0]; + if (fwrite (p[0], sizeof *p[0], len, stdout) != len) + return -1; } else for (i = 0; i < n_lines; i++) { - unsigned long int n = lo_input + permutation[i]; - if (printf ("%lu%c", n, eolbyte) < 0) - return -1; + unsigned long int n = lo_input + permutation[i]; + if (printf ("%lu%c", n, eolbyte) < 0) + return -1; } return 0; @@ -269,75 +269,75 @@ main (int argc, char **argv) switch (optc) { case 'e': - echo = true; - break; + echo = true; + break; case 'i': - { - unsigned long int argval = 0; - char *p = strchr (optarg, '-'); - char const *hi_optarg = optarg; - bool invalid = !p; - - if (input_numbers_option_used (lo_input, hi_input)) - error (EXIT_FAILURE, 0, _("multiple -i options specified")); - - if (p) - { - *p = '\0'; - invalid = ((xstrtoul (optarg, NULL, 10, &argval, NULL) - != LONGINT_OK) - || SIZE_MAX < argval); - *p = '-'; - lo_input = argval; - hi_optarg = p + 1; - } - - invalid |= ((xstrtoul (hi_optarg, NULL, 10, &argval, NULL) - != LONGINT_OK) - || SIZE_MAX < argval); - hi_input = argval; - n_lines = hi_input - lo_input + 1; - invalid |= ((lo_input <= hi_input) == (n_lines == 0)); - if (invalid) - error (EXIT_FAILURE, 0, _("invalid input range %s"), - quote (optarg)); - } - break; + { + unsigned long int argval = 0; + char *p = strchr (optarg, '-'); + char const *hi_optarg = optarg; + bool invalid = !p; + + if (input_numbers_option_used (lo_input, hi_input)) + error (EXIT_FAILURE, 0, _("multiple -i options specified")); + + if (p) + { + *p = '\0'; + invalid = ((xstrtoul (optarg, NULL, 10, &argval, NULL) + != LONGINT_OK) + || SIZE_MAX < argval); + *p = '-'; + lo_input = argval; + hi_optarg = p + 1; + } + + invalid |= ((xstrtoul (hi_optarg, NULL, 10, &argval, NULL) + != LONGINT_OK) + || SIZE_MAX < argval); + hi_input = argval; + n_lines = hi_input - lo_input + 1; + invalid |= ((lo_input <= hi_input) == (n_lines == 0)); + if (invalid) + error (EXIT_FAILURE, 0, _("invalid input range %s"), + quote (optarg)); + } + break; case 'n': - { - unsigned long int argval; - strtol_error e = xstrtoul (optarg, NULL, 10, &argval, NULL); - - if (e == LONGINT_OK) - head_lines = MIN (head_lines, argval); - else if (e != LONGINT_OVERFLOW) - error (EXIT_FAILURE, 0, _("invalid line count %s"), - quote (optarg)); - } - break; + { + unsigned long int argval; + strtol_error e = xstrtoul (optarg, NULL, 10, &argval, NULL); + + if (e == LONGINT_OK) + head_lines = MIN (head_lines, argval); + else if (e != LONGINT_OVERFLOW) + error (EXIT_FAILURE, 0, _("invalid line count %s"), + quote (optarg)); + } + break; case 'o': - if (outfile && !STREQ (outfile, optarg)) - error (EXIT_FAILURE, 0, _("multiple output files specified")); - outfile = optarg; - break; + if (outfile && !STREQ (outfile, optarg)) + error (EXIT_FAILURE, 0, _("multiple output files specified")); + outfile = optarg; + break; case RANDOM_SOURCE_OPTION: - if (random_source && !STREQ (random_source, optarg)) - error (EXIT_FAILURE, 0, _("multiple random sources specified")); - random_source = optarg; - break; + if (random_source && !STREQ (random_source, optarg)) + error (EXIT_FAILURE, 0, _("multiple random sources specified")); + random_source = optarg; + break; case 'z': - eolbyte = '\0'; - break; + eolbyte = '\0'; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } n_operands = argc - optind; @@ -346,7 +346,7 @@ main (int argc, char **argv) if (echo) { if (input_numbers_option_used (lo_input, hi_input)) - error (EXIT_FAILURE, 0, _("cannot combine -e and -i options")); + error (EXIT_FAILURE, 0, _("cannot combine -e and -i options")); input_from_argv (operand, n_operands, eolbyte); n_lines = n_operands; line = operand; @@ -354,29 +354,29 @@ main (int argc, char **argv) else if (input_numbers_option_used (lo_input, hi_input)) { if (n_operands) - { - error (0, 0, _("extra operand %s\n"), quote (operand[0])); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s\n"), quote (operand[0])); + usage (EXIT_FAILURE); + } n_lines = hi_input - lo_input + 1; line = NULL; } else { switch (n_operands) - { - case 0: - break; + { + case 0: + break; - case 1: - if (! (STREQ (operand[0], "-") || freopen (operand[0], "r", stdin))) - error (EXIT_FAILURE, errno, "%s", operand[0]); - break; + case 1: + if (! (STREQ (operand[0], "-") || freopen (operand[0], "r", stdin))) + error (EXIT_FAILURE, errno, "%s", operand[0]); + break; - default: - error (0, 0, _("extra operand %s"), quote (operand[1])); - usage (EXIT_FAILURE); - } + default: + error (0, 0, _("extra operand %s"), quote (operand[1])); + usage (EXIT_FAILURE); + } n_lines = read_input (stdin, eolbyte, &input_lines); line = input_lines; @@ -385,7 +385,7 @@ main (int argc, char **argv) head_lines = MIN (head_lines, n_lines); randint_source = randint_all_new (random_source, - randperm_bound (head_lines, n_lines)); + randperm_bound (head_lines, n_lines)); if (! randint_source) error (EXIT_FAILURE, errno, "%s", quotearg_colon (random_source)); diff --git a/src/sleep.c b/src/sleep.c index 42a7cf904..4c203e621 100644 --- a/src/sleep.c +++ b/src/sleep.c @@ -40,7 +40,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -53,7 +53,7 @@ point number. Given two or more arguments, pause for the amount of time\n\ specified by the sum of their values.\n\ \n\ "), - program_name, program_name); + program_name, program_name); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); emit_bug_reporting_address (); @@ -112,7 +112,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -127,16 +127,16 @@ main (int argc, char **argv) double s; const char *p; if (! xstrtod (argv[i], &p, &s, c_strtod) - /* Nonnegative interval. */ - || ! (0 <= s) - /* No extra chars after the number and an optional s,m,h,d char. */ - || (*p && *(p+1)) - /* Check any suffix char and update S based on the suffix. */ - || ! apply_suffix (&s, *p)) - { - error (0, 0, _("invalid time interval %s"), quote (argv[i])); - ok = false; - } + /* Nonnegative interval. */ + || ! (0 <= s) + /* No extra chars after the number and an optional s,m,h,d char. */ + || (*p && *(p+1)) + /* Check any suffix char and update S based on the suffix. */ + || ! apply_suffix (&s, *p)) + { + error (0, 0, _("invalid time interval %s"), quote (argv[i])); + ok = false; + } seconds += s; } diff --git a/src/sort.c b/src/sort.c index 832be5a39..b9ae19883 100644 --- a/src/sort.c +++ b/src/sort.c @@ -148,10 +148,10 @@ struct line struct buffer { char *buf; /* Dynamically allocated buffer, - partitioned into 3 regions: - - input data; - - unused area; - - an array of lines, in reverse order. */ + partitioned into 3 regions: + - input data; + - unused area; + - an array of lines, in reverse order. */ size_t used; /* Number of bytes used for input data. */ size_t nlines; /* Number of lines in the line array. */ size_t alloc; /* Number of bytes allocated. */ @@ -171,13 +171,13 @@ struct keyfield bool skipsblanks; /* Skip leading blanks when finding start. */ bool skipeblanks; /* Skip leading blanks when finding end. */ bool numeric; /* Flag for numeric comparison. Handle - strings of digits with optional decimal - point, but no exponential notation. */ + strings of digits with optional decimal + point, but no exponential notation. */ bool random; /* Sort by random hash of key. */ bool general_numeric; /* Flag for general, numeric comparison. - Handle numbers in exponential notation. */ + Handle numbers in exponential notation. */ bool human_numeric; /* Flag for sorting by human readable - units with either SI xor IEC prefixes. */ + units with either SI xor IEC prefixes. */ int si_present; /* Flag for checking for mixed SI and IEC. */ bool month; /* Flag for comparison by month name. */ bool reverse; /* Reverse the sense of comparison. */ @@ -310,14 +310,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ or: %s [OPTION]... --files0-from=F\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Write sorted concatenation of all FILE(s) to standard output.\n\ \n\ @@ -611,8 +611,8 @@ reap (pid_t pid) else if (0 < cpid) { if (! WIFEXITED (status) || WEXITSTATUS (status)) - error (SORT_FAILURE, 0, _("%s [-d] terminated abnormally"), - compress_program); + error (SORT_FAILURE, 0, _("%s [-d] terminated abnormally"), + compress_program); --nprocs; } @@ -631,11 +631,11 @@ register_proc (pid_t pid) if (! proctab) { proctab = hash_initialize (INIT_PROCTAB_SIZE, NULL, - proctab_hasher, - proctab_comparator, - free); + proctab_hasher, + proctab_comparator, + free); if (! proctab) - xalloc_die (); + xalloc_die (); } test.pid = pid; @@ -731,7 +731,7 @@ exit_cleanup (void) if (temphead) { /* Clean up any remaining temporary files in a critical section so - that a signal handler does not try to clean them too. */ + that a signal handler does not try to clean them too. */ struct cs_status cs = cs_enter (); cleanup (); cs_leave (cs); @@ -782,8 +782,8 @@ create_temp_file (int *pfd, bool survive_fd_exhaustion) if (fd < 0) { if (! (survive_fd_exhaustion && errno == EMFILE)) - error (SORT_FAILURE, errno, _("cannot create temporary file in %s"), - quote (temp_dir)); + error (SORT_FAILURE, errno, _("cannot create temporary file in %s"), + quote (temp_dir)); free (node); node = NULL; } @@ -833,18 +833,18 @@ xfclose (FILE *fp, char const *file) case STDIN_FILENO: /* Allow reading stdin from tty more than once. */ if (feof (fp)) - clearerr (fp); + clearerr (fp); break; case STDOUT_FILENO: /* Don't close stdout just yet. close_stdout does that. */ if (fflush (fp) != 0) - die (_("fflush failed"), file); + die (_("fflush failed"), file); break; default: if (fclose (fp) != 0) - die (_("close failed"), file); + die (_("close failed"), file); break; } } @@ -877,7 +877,7 @@ pipe_fork (int pipefds[2], size_t tries) while (tries--) { /* This is so the child process won't delete our temp files - if it receives a signal before exec-ing. */ + if it receives a signal before exec-ing. */ cs = cs_enter (); saved_temphead = temphead; temphead = NULL; @@ -885,19 +885,19 @@ pipe_fork (int pipefds[2], size_t tries) pid = fork (); saved_errno = errno; if (pid) - temphead = saved_temphead; + temphead = saved_temphead; cs_leave (cs); errno = saved_errno; if (0 <= pid || errno != EAGAIN) - break; + break; else - { - sleep (wait_retry); - wait_retry *= 2; - reap_some (); - } + { + sleep (wait_retry); + wait_retry *= 2; + reap_some (); + } } if (pid < 0) @@ -946,27 +946,27 @@ maybe_create_temp (FILE **pfp, pid_t *ppid, bool survive_fd_exhaustion) node->pid = pipe_fork (pipefds, MAX_FORK_TRIES_COMPRESS); if (0 < node->pid) - { - close (tempfd); - close (pipefds[0]); - tempfd = pipefds[1]; + { + close (tempfd); + close (pipefds[0]); + tempfd = pipefds[1]; - register_proc (node->pid); - } + register_proc (node->pid); + } else if (node->pid == 0) - { - close (pipefds[1]); - dup2_or_die (tempfd, STDOUT_FILENO); - close (tempfd); - dup2_or_die (pipefds[0], STDIN_FILENO); - close (pipefds[0]); - - if (execlp (compress_program, compress_program, (char *) NULL) < 0) - error (SORT_FAILURE, errno, _("couldn't execute %s"), - compress_program); - } + { + close (pipefds[1]); + dup2_or_die (tempfd, STDOUT_FILENO); + close (tempfd); + dup2_or_die (pipefds[0], STDIN_FILENO); + close (pipefds[0]); + + if (execlp (compress_program, compress_program, (char *) NULL) < 0) + error (SORT_FAILURE, errno, _("couldn't execute %s"), + compress_program); + } else - node->pid = 0; + node->pid = 0; } *pfp = fdopen (tempfd, "w"); @@ -1011,8 +1011,8 @@ open_temp (const char *name, pid_t pid) { case -1: if (errno != EMFILE) - error (SORT_FAILURE, errno, _("couldn't create process for %s -d"), - compress_program); + error (SORT_FAILURE, errno, _("couldn't create process for %s -d"), + compress_program); close (tempfd); errno = EMFILE; break; @@ -1026,7 +1026,7 @@ open_temp (const char *name, pid_t pid) execlp (compress_program, compress_program, "-d", (char *) NULL); error (SORT_FAILURE, errno, _("couldn't execute %s -d"), - compress_program); + compress_program); default: close (tempfd); @@ -1034,11 +1034,11 @@ open_temp (const char *name, pid_t pid) fp = fdopen (pipefds[0], "r"); if (! fp) - { - int saved_errno = errno; - close (pipefds[0]); - errno = saved_errno; - } + { + int saved_errno = errno; + close (pipefds[0]); + errno = saved_errno; + } break; } @@ -1124,23 +1124,23 @@ inittables (void) if (hard_LC_TIME) { for (i = 0; i < MONTHS_PER_YEAR; i++) - { - char const *s; - size_t s_len; - size_t j; - char *name; - - s = (char *) nl_langinfo (ABMON_1 + i); - s_len = strlen (s); - monthtab[i].name = name = xmalloc (s_len + 1); - monthtab[i].val = i + 1; - - for (j = 0; j < s_len; j++) - name[j] = fold_toupper[to_uchar (s[j])]; - name[j] = '\0'; - } + { + char const *s; + size_t s_len; + size_t j; + char *name; + + s = (char *) nl_langinfo (ABMON_1 + i); + s_len = strlen (s); + monthtab[i].name = name = xmalloc (s_len + 1); + monthtab[i].val = i + 1; + + for (j = 0; j < s_len; j++) + name[j] = fold_toupper[to_uchar (s[j])]; + name[j] = '\0'; + } qsort ((void *) monthtab, MONTHS_PER_YEAR, - sizeof *monthtab, struct_month_cmp); + sizeof *monthtab, struct_month_cmp); } #endif } @@ -1159,43 +1159,43 @@ specify_nmerge (int oi, char c, char const *s) to open. We need at least nmerge + 3 (STDIN_FILENO, STDOUT_FILENO and STDERR_FILENO). */ unsigned int max_nmerge = ((getrlimit (RLIMIT_NOFILE, &rlimit) == 0 - ? rlimit.rlim_cur - : OPEN_MAX) - - 3); + ? rlimit.rlim_cur + : OPEN_MAX) + - 3); if (e == LONGINT_OK) { nmerge = n; if (nmerge != n) - e = LONGINT_OVERFLOW; + e = LONGINT_OVERFLOW; else - { - if (nmerge < 2) - { - error (0, 0, _("invalid --%s argument %s"), - long_options[oi].name, quote(s)); - error (SORT_FAILURE, 0, - _("minimum --%s argument is %s"), - long_options[oi].name, quote("2")); - } - else if (max_nmerge < nmerge) - { - e = LONGINT_OVERFLOW; - } - else - return; - } + { + if (nmerge < 2) + { + error (0, 0, _("invalid --%s argument %s"), + long_options[oi].name, quote(s)); + error (SORT_FAILURE, 0, + _("minimum --%s argument is %s"), + long_options[oi].name, quote("2")); + } + else if (max_nmerge < nmerge) + { + e = LONGINT_OVERFLOW; + } + else + return; + } } if (e == LONGINT_OVERFLOW) { char max_nmerge_buf[INT_BUFSIZE_BOUND (unsigned int)]; error (0, 0, _("--%s argument %s too large"), - long_options[oi].name, quote(s)); + long_options[oi].name, quote(s)); error (SORT_FAILURE, 0, - _("maximum --%s argument with current rlimit is %s"), - long_options[oi].name, - uinttostr (max_nmerge, max_nmerge_buf)); + _("maximum --%s argument with current rlimit is %s"), + long_options[oi].name, + uinttostr (max_nmerge, max_nmerge_buf)); } else xstrtol_fatal (e, oi, c, long_options, s); @@ -1213,9 +1213,9 @@ specify_sort_size (int oi, char c, char const *s) if (e == LONGINT_OK && ISDIGIT (suffix[-1])) { if (n <= UINTMAX_MAX / 1024) - n *= 1024; + n *= 1024; else - e = LONGINT_OVERFLOW; + e = LONGINT_OVERFLOW; } /* A 'b' suffix means bytes; a '%' suffix means percent of memory. */ @@ -1223,38 +1223,38 @@ specify_sort_size (int oi, char c, char const *s) switch (suffix[0]) { case 'b': - e = LONGINT_OK; - break; + e = LONGINT_OK; + break; case '%': - { - double mem = physmem_total () * n / 100; - - /* Use "<", not "<=", to avoid problems with rounding. */ - if (mem < UINTMAX_MAX) - { - n = mem; - e = LONGINT_OK; - } - else - e = LONGINT_OVERFLOW; - } - break; + { + double mem = physmem_total () * n / 100; + + /* Use "<", not "<=", to avoid problems with rounding. */ + if (mem < UINTMAX_MAX) + { + n = mem; + e = LONGINT_OK; + } + else + e = LONGINT_OVERFLOW; + } + break; } if (e == LONGINT_OK) { /* If multiple sort sizes are specified, take the maximum, so - that option order does not matter. */ + that option order does not matter. */ if (n < sort_size) - return; + return; sort_size = n; if (sort_size == n) - { - sort_size = MAX (sort_size, MIN_SORT_SIZE); - return; - } + { + sort_size = MAX (sort_size, MIN_SORT_SIZE); + return; + } e = LONGINT_OVERFLOW; } @@ -1312,8 +1312,8 @@ default_sort_size (void) static size_t sort_buffer_size (FILE *const *fps, size_t nfps, - char *const *files, size_t nfiles, - size_t line_bytes) + char *const *files, size_t nfiles, + size_t line_bytes) { /* A bound on the input size. If zero, the bound hasn't been determined yet. */ @@ -1335,36 +1335,36 @@ sort_buffer_size (FILE *const *fps, size_t nfps, size_t worst_case; if ((i < nfps ? fstat (fileno (fps[i]), &st) - : STREQ (files[i], "-") ? fstat (STDIN_FILENO, &st) - : stat (files[i], &st)) - != 0) - die (_("stat failed"), files[i]); + : STREQ (files[i], "-") ? fstat (STDIN_FILENO, &st) + : stat (files[i], &st)) + != 0) + die (_("stat failed"), files[i]); if (S_ISREG (st.st_mode)) - file_size = st.st_size; + file_size = st.st_size; else - { - /* The file has unknown size. If the user specified a sort - buffer size, use that; otherwise, guess the size. */ - if (sort_size) - return sort_size; - file_size = INPUT_FILE_SIZE_GUESS; - } + { + /* The file has unknown size. If the user specified a sort + buffer size, use that; otherwise, guess the size. */ + if (sort_size) + return sort_size; + file_size = INPUT_FILE_SIZE_GUESS; + } if (! size_bound) - { - size_bound = sort_size; - if (! size_bound) - size_bound = default_sort_size (); - } + { + size_bound = sort_size; + if (! size_bound) + size_bound = default_sort_size (); + } /* Add the amount of memory needed to represent the worst case - where the input consists entirely of newlines followed by a - single non-newline. Check for overflow. */ + where the input consists entirely of newlines followed by a + single non-newline. Check for overflow. */ worst_case = file_size * worst_case_per_input_byte + 1; if (file_size != worst_case / worst_case_per_input_byte - || size_bound - size <= worst_case) - return size_bound; + || size_bound - size <= worst_case) + return size_bound; size += worst_case; } @@ -1387,10 +1387,10 @@ initbuf (struct buffer *buf, size_t line_bytes, size_t alloc) alloc += sizeof (struct line) - alloc % sizeof (struct line); buf->buf = malloc (alloc); if (buf->buf) - break; + break; alloc /= 2; if (alloc <= line_bytes + 1) - xalloc_die (); + xalloc_die (); } buf->line_bytes = line_bytes; @@ -1423,18 +1423,18 @@ begfield (const struct line *line, const struct keyfield *key) if (tab != TAB_DEFAULT) while (ptr < lim && sword--) { - while (ptr < lim && *ptr != tab) - ++ptr; - if (ptr < lim) - ++ptr; + while (ptr < lim && *ptr != tab) + ++ptr; + if (ptr < lim) + ++ptr; } else while (ptr < lim && sword--) { - while (ptr < lim && blanks[to_uchar (*ptr)]) - ++ptr; - while (ptr < lim && !blanks[to_uchar (*ptr)]) - ++ptr; + while (ptr < lim && blanks[to_uchar (*ptr)]) + ++ptr; + while (ptr < lim && !blanks[to_uchar (*ptr)]) + ++ptr; } /* If we're ignoring leading blanks when computing the Start @@ -1471,18 +1471,18 @@ limfield (const struct line *line, const struct keyfield *key) if (tab != TAB_DEFAULT) while (ptr < lim && eword--) { - while (ptr < lim && *ptr != tab) - ++ptr; - if (ptr < lim && (eword | echar)) - ++ptr; + while (ptr < lim && *ptr != tab) + ++ptr; + if (ptr < lim && (eword | echar)) + ++ptr; } else while (ptr < lim && eword--) { - while (ptr < lim && blanks[to_uchar (*ptr)]) - ++ptr; - while (ptr < lim && !blanks[to_uchar (*ptr)]) - ++ptr; + while (ptr < lim && blanks[to_uchar (*ptr)]) + ++ptr; + while (ptr < lim && !blanks[to_uchar (*ptr)]) + ++ptr; } #ifdef POSIX_UNSPECIFIED @@ -1522,16 +1522,16 @@ limfield (const struct line *line, const struct keyfield *key) char *newlim; newlim = memchr (ptr, tab, lim - ptr); if (newlim) - lim = newlim; + lim = newlim; } else { char *newlim; newlim = ptr; while (newlim < lim && blanks[to_uchar (*newlim)]) - ++newlim; + ++newlim; while (newlim < lim && !blanks[to_uchar (*newlim)]) - ++newlim; + ++newlim; lim = newlim; } #endif @@ -1539,10 +1539,10 @@ limfield (const struct line *line, const struct keyfield *key) if (echar != 0) /* We need to skip over a portion of the end field. */ { /* If we're ignoring leading blanks when computing the End - of the field, skip past them here. */ + of the field, skip past them here. */ if (key->skipeblanks) - while (ptr < lim && blanks[to_uchar (*ptr)]) - ++ptr; + while (ptr < lim && blanks[to_uchar (*ptr)]) + ++ptr; /* Advance PTR by ECHAR (if possible), but no further than LIM. */ ptr = MIN (lim, ptr + echar); @@ -1584,85 +1584,85 @@ fillbuf (struct buffer *buf, FILE *fp, char const *file) char *line_start = buf->nlines ? line->text + line->length : buf->buf; while (line_bytes + 1 < avail) - { - /* Read as many bytes as possible, but do not read so many - bytes that there might not be enough room for the - corresponding line array. The worst case is when the - rest of the input file consists entirely of newlines, - except that the last byte is not a newline. */ - size_t readsize = (avail - 1) / (line_bytes + 1); - size_t bytes_read = fread (ptr, 1, readsize, fp); - char *ptrlim = ptr + bytes_read; - char *p; - avail -= bytes_read; - - if (bytes_read != readsize) - { - if (ferror (fp)) - die (_("read failed"), file); - if (feof (fp)) - { - buf->eof = true; - if (buf->buf == ptrlim) - return false; - if (ptrlim[-1] != eol) - *ptrlim++ = eol; - } - } - - /* Find and record each line in the just-read input. */ - while ((p = memchr (ptr, eol, ptrlim - ptr))) - { - ptr = p + 1; - line--; - line->text = line_start; - line->length = ptr - line_start; - mergesize = MAX (mergesize, line->length); - avail -= line_bytes; - - if (key) - { - /* Precompute the position of the first key for - efficiency. */ - line->keylim = (key->eword == SIZE_MAX - ? p - : limfield (line, key)); - - if (key->sword != SIZE_MAX) - line->keybeg = begfield (line, key); - else - { - if (key->skipsblanks) - while (blanks[to_uchar (*line_start)]) - line_start++; - line->keybeg = line_start; - } - } - - line_start = ptr; - } - - ptr = ptrlim; - if (buf->eof) - break; - } + { + /* Read as many bytes as possible, but do not read so many + bytes that there might not be enough room for the + corresponding line array. The worst case is when the + rest of the input file consists entirely of newlines, + except that the last byte is not a newline. */ + size_t readsize = (avail - 1) / (line_bytes + 1); + size_t bytes_read = fread (ptr, 1, readsize, fp); + char *ptrlim = ptr + bytes_read; + char *p; + avail -= bytes_read; + + if (bytes_read != readsize) + { + if (ferror (fp)) + die (_("read failed"), file); + if (feof (fp)) + { + buf->eof = true; + if (buf->buf == ptrlim) + return false; + if (ptrlim[-1] != eol) + *ptrlim++ = eol; + } + } + + /* Find and record each line in the just-read input. */ + while ((p = memchr (ptr, eol, ptrlim - ptr))) + { + ptr = p + 1; + line--; + line->text = line_start; + line->length = ptr - line_start; + mergesize = MAX (mergesize, line->length); + avail -= line_bytes; + + if (key) + { + /* Precompute the position of the first key for + efficiency. */ + line->keylim = (key->eword == SIZE_MAX + ? p + : limfield (line, key)); + + if (key->sword != SIZE_MAX) + line->keybeg = begfield (line, key); + else + { + if (key->skipsblanks) + while (blanks[to_uchar (*line_start)]) + line_start++; + line->keybeg = line_start; + } + } + + line_start = ptr; + } + + ptr = ptrlim; + if (buf->eof) + break; + } buf->used = ptr - buf->buf; buf->nlines = buffer_linelim (buf) - line; if (buf->nlines != 0) - { - buf->left = ptr - line_start; - merge_buffer_size = mergesize + MIN_MERGE_BUFFER_SIZE; - return true; - } + { + buf->left = ptr - line_start; + merge_buffer_size = mergesize + MIN_MERGE_BUFFER_SIZE; + return true; + } { - /* The current input line is too long to fit in the buffer. - Double the buffer size and try again, keeping it properly - aligned. */ - size_t line_alloc = buf->alloc / sizeof (struct line); - buf->buf = x2nrealloc (buf->buf, &line_alloc, sizeof (struct line)); - buf->alloc = line_alloc * sizeof (struct line); + /* The current input line is too long to fit in the buffer. + Double the buffer size and try again, keeping it properly + aligned. */ + size_t line_alloc = buf->alloc / sizeof (struct line); + buf->buf = x2nrealloc (buf->buf, &line_alloc, sizeof (struct line)); + buf->alloc = line_alloc * sizeof (struct line); } } } @@ -1746,9 +1746,9 @@ find_unit_order (const char *number, struct keyfield *key) p++; if (*p == decimal_point && ISDIGIT (*(p + 1))) - p += 2; + p += 2; else if (*p == thousands_sep && ISDIGIT (*(p + 1))) - p += 2; + p += 2; } int order = orders[*p]; @@ -1777,8 +1777,8 @@ human_numcompare (const char *a, const char *b, struct keyfield *key) int order_b = find_unit_order (b, key); return (order_a > order_b ? 1 - : order_a < order_b ? -1 - : strnumcmp (a, b, decimal_point, thousands_sep)); + : order_a < order_b ? -1 + : strnumcmp (a, b, decimal_point, thousands_sep)); } static int @@ -1803,11 +1803,11 @@ general_numcompare (const char *sa, const char *sb) conversion errors but before numbers; sort them by internal bit-pattern, for lack of a more portable alternative. */ return (a < b ? -1 - : a > b ? 1 - : a == b ? 0 - : b == b ? -1 - : a == a ? 1 - : memcmp ((char *) &a, (char *) &b, sizeof a)); + : a > b ? 1 + : a == b ? 0 + : b == b ? -1 + : a == a ? 1 + : memcmp ((char *) &a, (char *) &b, sizeof a)); } /* Return an integer in 1..12 of the month name MONTH with length LEN. @@ -1823,9 +1823,9 @@ getmonth (char const *month, size_t len) for (;;) { if (month == monthlim) - return 0; + return 0; if (!blanks[to_uchar (*month)]) - break; + break; ++month; } @@ -1836,20 +1836,20 @@ getmonth (char const *month, size_t len) char const *n = monthtab[ix].name; for (;; m++, n++) - { - if (!*n) - return monthtab[ix].val; - if (m == monthlim || fold_toupper[to_uchar (*m)] < to_uchar (*n)) - { - hi = ix; - break; - } - else if (fold_toupper[to_uchar (*m)] > to_uchar (*n)) - { - lo = ix + 1; - break; - } - } + { + if (!*n) + return monthtab[ix].val; + if (m == monthlim || fold_toupper[to_uchar (*m)] < to_uchar (*n)) + { + hi = ix; + break; + } + else if (fold_toupper[to_uchar (*m)] > to_uchar (*n)) + { + lo = ix + 1; + break; + } + } } while (lo < hi); @@ -1881,10 +1881,10 @@ random_state (size_t i) used++; if (allocated <= i) - { - state = X2NREALLOC (state, &allocated); - s = &state[i]; - } + { + state = X2NREALLOC (state, &allocated); + s = &state[i]; + } randread (randread_source, buf, sizeof buf); md5_init_ctx (s); @@ -1900,7 +1900,7 @@ random_state (size_t i) static int cmp_hashes (char const *texta, size_t lena, - char const *textb, size_t lenb) + char const *textb, size_t lenb) { /* Try random hashes until a pair of hashes disagree. But if the first pair of random hashes agree, check whether the keys are @@ -1916,9 +1916,9 @@ cmp_hashes (char const *texta, size_t lena, md5_process_bytes (textb, lenb, &s[1]); md5_finish_ctx (&s[1], dig[1]); diff = memcmp (dig[0], dig[1], sizeof dig[0]); if (diff != 0) - break; + break; if (i == 0 && lena == lenb && memcmp (texta, textb, lena) == 0) - break; + break; } return diff; @@ -1929,7 +1929,7 @@ cmp_hashes (char const *texta, size_t lena, static int compare_random (char *restrict texta, size_t lena, - char *restrict textb, size_t lenb) + char *restrict textb, size_t lenb) { int diff; @@ -1938,32 +1938,32 @@ compare_random (char *restrict texta, size_t lena, else { /* Transform the text into the basis of comparison, so that byte - strings that would otherwise considered to be equal are - considered equal here even if their bytes differ. */ + strings that would otherwise considered to be equal are + considered equal here even if their bytes differ. */ char *buf = NULL; char stackbuf[4000]; size_t tlena = xmemxfrm (stackbuf, sizeof stackbuf, texta, lena); bool a_fits = tlena <= sizeof stackbuf; size_t tlenb = xmemxfrm ((a_fits ? stackbuf + tlena : NULL), - (a_fits ? sizeof stackbuf - tlena : 0), - textb, lenb); + (a_fits ? sizeof stackbuf - tlena : 0), + textb, lenb); if (a_fits && tlena + tlenb <= sizeof stackbuf) - buf = stackbuf; + buf = stackbuf; else - { - /* Adding 1 to the buffer size lets xmemxfrm run a bit - faster by avoiding the need for an extra buffer copy. */ - buf = xmalloc (tlena + tlenb + 1); - xmemxfrm (buf, tlena + 1, texta, lena); - xmemxfrm (buf + tlena, tlenb + 1, textb, lenb); - } + { + /* Adding 1 to the buffer size lets xmemxfrm run a bit + faster by avoiding the need for an extra buffer copy. */ + buf = xmalloc (tlena + tlenb + 1); + xmemxfrm (buf, tlena + 1, texta, lena); + xmemxfrm (buf + tlena, tlenb + 1, textb, lenb); + } diff = cmp_hashes (buf, tlena, buf + tlena, tlenb); if (buf != stackbuf) - free (buf); + free (buf); } return diff; @@ -1974,7 +1974,7 @@ compare_random (char *restrict texta, size_t lena, static int compare_version (char *restrict texta, size_t lena, - char *restrict textb, size_t lenb) + char *restrict textb, size_t lenb) { int diff; @@ -2028,147 +2028,147 @@ keycompare (const struct line *a, const struct line *b) /* Actually compare the fields. */ if (key->random) - diff = compare_random (texta, lena, textb, lenb); + diff = compare_random (texta, lena, textb, lenb); else if (key->numeric | key->general_numeric | key->human_numeric) - { - char savea = *lima, saveb = *limb; - - *lima = *limb = '\0'; - diff = (key->numeric ? numcompare (texta, textb) - : key->general_numeric ? general_numcompare (texta, textb) - : human_numcompare (texta, textb, key)); - *lima = savea, *limb = saveb; - } + { + char savea = *lima, saveb = *limb; + + *lima = *limb = '\0'; + diff = (key->numeric ? numcompare (texta, textb) + : key->general_numeric ? general_numcompare (texta, textb) + : human_numcompare (texta, textb, key)); + *lima = savea, *limb = saveb; + } else if (key->version) - diff = compare_version (texta, lena, textb, lenb); + diff = compare_version (texta, lena, textb, lenb); else if (key->month) - diff = getmonth (texta, lena) - getmonth (textb, lenb); + diff = getmonth (texta, lena) - getmonth (textb, lenb); /* Sorting like this may become slow, so in a simple locale the user - can select a faster sort that is similar to ascii sort. */ + can select a faster sort that is similar to ascii sort. */ else if (hard_LC_COLLATE) - { - if (ignore || translate) - { - char buf[4000]; - size_t size = lena + 1 + lenb + 1; - char *copy_a = (size <= sizeof buf ? buf : xmalloc (size)); - char *copy_b = copy_a + lena + 1; - size_t new_len_a, new_len_b, i; - - /* Ignore and/or translate chars before comparing. */ - for (new_len_a = new_len_b = i = 0; i < MAX (lena, lenb); i++) - { - if (i < lena) - { - copy_a[new_len_a] = (translate - ? translate[to_uchar (texta[i])] - : texta[i]); - if (!ignore || !ignore[to_uchar (texta[i])]) - ++new_len_a; - } - if (i < lenb) - { - copy_b[new_len_b] = (translate - ? translate[to_uchar (textb[i])] - : textb [i]); - if (!ignore || !ignore[to_uchar (textb[i])]) - ++new_len_b; - } - } - - diff = xmemcoll (copy_a, new_len_a, copy_b, new_len_b); - - if (sizeof buf < size) - free (copy_a); - } - else if (lena == 0) - diff = - NONZERO (lenb); - else if (lenb == 0) - goto greater; - else - diff = xmemcoll (texta, lena, textb, lenb); - } + { + if (ignore || translate) + { + char buf[4000]; + size_t size = lena + 1 + lenb + 1; + char *copy_a = (size <= sizeof buf ? buf : xmalloc (size)); + char *copy_b = copy_a + lena + 1; + size_t new_len_a, new_len_b, i; + + /* Ignore and/or translate chars before comparing. */ + for (new_len_a = new_len_b = i = 0; i < MAX (lena, lenb); i++) + { + if (i < lena) + { + copy_a[new_len_a] = (translate + ? translate[to_uchar (texta[i])] + : texta[i]); + if (!ignore || !ignore[to_uchar (texta[i])]) + ++new_len_a; + } + if (i < lenb) + { + copy_b[new_len_b] = (translate + ? translate[to_uchar (textb[i])] + : textb [i]); + if (!ignore || !ignore[to_uchar (textb[i])]) + ++new_len_b; + } + } + + diff = xmemcoll (copy_a, new_len_a, copy_b, new_len_b); + + if (sizeof buf < size) + free (copy_a); + } + else if (lena == 0) + diff = - NONZERO (lenb); + else if (lenb == 0) + goto greater; + else + diff = xmemcoll (texta, lena, textb, lenb); + } else if (ignore) - { + { #define CMP_WITH_IGNORE(A, B) \ do \ { \ - for (;;) \ - { \ - while (texta < lima && ignore[to_uchar (*texta)]) \ - ++texta; \ - while (textb < limb && ignore[to_uchar (*textb)]) \ - ++textb; \ - if (! (texta < lima && textb < limb)) \ - break; \ - diff = to_uchar (A) - to_uchar (B); \ - if (diff) \ - goto not_equal; \ - ++texta; \ - ++textb; \ - } \ - \ - diff = (texta < lima) - (textb < limb); \ + for (;;) \ + { \ + while (texta < lima && ignore[to_uchar (*texta)]) \ + ++texta; \ + while (textb < limb && ignore[to_uchar (*textb)]) \ + ++textb; \ + if (! (texta < lima && textb < limb)) \ + break; \ + diff = to_uchar (A) - to_uchar (B); \ + if (diff) \ + goto not_equal; \ + ++texta; \ + ++textb; \ + } \ + \ + diff = (texta < lima) - (textb < limb); \ } \ while (0) - if (translate) - CMP_WITH_IGNORE (translate[to_uchar (*texta)], - translate[to_uchar (*textb)]); - else - CMP_WITH_IGNORE (*texta, *textb); - } + if (translate) + CMP_WITH_IGNORE (translate[to_uchar (*texta)], + translate[to_uchar (*textb)]); + else + CMP_WITH_IGNORE (*texta, *textb); + } else if (lena == 0) - diff = - NONZERO (lenb); + diff = - NONZERO (lenb); else if (lenb == 0) - goto greater; + goto greater; else - { - if (translate) - { - while (texta < lima && textb < limb) - { - diff = (to_uchar (translate[to_uchar (*texta++)]) - - to_uchar (translate[to_uchar (*textb++)])); - if (diff) - goto not_equal; - } - } - else - { - diff = memcmp (texta, textb, MIN (lena, lenb)); - if (diff) - goto not_equal; - } - diff = lena < lenb ? -1 : lena != lenb; - } + { + if (translate) + { + while (texta < lima && textb < limb) + { + diff = (to_uchar (translate[to_uchar (*texta++)]) + - to_uchar (translate[to_uchar (*textb++)])); + if (diff) + goto not_equal; + } + } + else + { + diff = memcmp (texta, textb, MIN (lena, lenb)); + if (diff) + goto not_equal; + } + diff = lena < lenb ? -1 : lena != lenb; + } if (diff) - goto not_equal; + goto not_equal; key = key->next; if (! key) - break; + break; /* Find the beginning and limit of the next field. */ if (key->eword != SIZE_MAX) - lima = limfield (a, key), limb = limfield (b, key); + lima = limfield (a, key), limb = limfield (b, key); else - lima = a->text + a->length - 1, limb = b->text + b->length - 1; + lima = a->text + a->length - 1, limb = b->text + b->length - 1; if (key->sword != SIZE_MAX) - texta = begfield (a, key), textb = begfield (b, key); + texta = begfield (a, key), textb = begfield (b, key); else - { - texta = a->text, textb = b->text; - if (key->skipsblanks) - { - while (texta < lima && blanks[to_uchar (*texta)]) - ++texta; - while (textb < limb && blanks[to_uchar (*textb)]) - ++textb; - } - } + { + texta = a->text, textb = b->text; + if (key->skipsblanks) + { + while (texta < lima && blanks[to_uchar (*texta)]) + ++texta; + while (textb < limb && blanks[to_uchar (*textb)]) + ++textb; + } + } } return 0; @@ -2195,7 +2195,7 @@ compare (const struct line *a, const struct line *b) { diff = keycompare (a, b); if (diff | unique | stable) - return diff; + return diff; } /* If the keys all compare equal (or no keys were specified) @@ -2232,7 +2232,7 @@ check (char const *file_name, char checkonly) bool ordered = true; initbuf (&buf, sizeof (struct line), - MAX (merge_buffer_size, sort_size)); + MAX (merge_buffer_size, sort_size)); temp.text = NULL; while (fillbuf (&buf, fp, file_name)) @@ -2241,59 +2241,59 @@ check (char const *file_name, char checkonly) struct line const *linebase = line - buf.nlines; /* Make sure the line saved from the old buffer contents is - less than or equal to the first line of the new buffer. */ + less than or equal to the first line of the new buffer. */ if (alloc && nonunique <= compare (&temp, line - 1)) - { - found_disorder: - { - if (checkonly == 'c') - { - struct line const *disorder_line = line - 1; - uintmax_t disorder_line_number = - buffer_linelim (&buf) - disorder_line + line_number; - char hr_buf[INT_BUFSIZE_BOUND (uintmax_t)]; - fprintf (stderr, _("%s: %s:%s: disorder: "), - program_name, file_name, - umaxtostr (disorder_line_number, hr_buf)); - write_bytes (disorder_line->text, disorder_line->length, - stderr, _("standard error")); - } - - ordered = false; - break; - } - } + { + found_disorder: + { + if (checkonly == 'c') + { + struct line const *disorder_line = line - 1; + uintmax_t disorder_line_number = + buffer_linelim (&buf) - disorder_line + line_number; + char hr_buf[INT_BUFSIZE_BOUND (uintmax_t)]; + fprintf (stderr, _("%s: %s:%s: disorder: "), + program_name, file_name, + umaxtostr (disorder_line_number, hr_buf)); + write_bytes (disorder_line->text, disorder_line->length, + stderr, _("standard error")); + } + + ordered = false; + break; + } + } /* Compare each line in the buffer with its successor. */ while (linebase < --line) - if (nonunique <= compare (line, line - 1)) - goto found_disorder; + if (nonunique <= compare (line, line - 1)) + goto found_disorder; line_number += buf.nlines; /* Save the last line of the buffer. */ if (alloc < line->length) - { - do - { - alloc *= 2; - if (! alloc) - { - alloc = line->length; - break; - } - } - while (alloc < line->length); - - temp.text = xrealloc (temp.text, alloc); - } + { + do + { + alloc *= 2; + if (! alloc) + { + alloc = line->length; + break; + } + } + while (alloc < line->length); + + temp.text = xrealloc (temp.text, alloc); + } memcpy (temp.text, line->text, line->length); temp.length = line->length; if (key) - { - temp.keybeg = temp.text + (line->keybeg - line->text); - temp.keylim = temp.text + (line->keylim - line->text); - } + { + temp.keybeg = temp.text + (line->keybeg - line->text); + temp.keylim = temp.text + (line->keylim - line->text); + } } xfclose (fp, file_name); @@ -2317,10 +2317,10 @@ open_input_files (struct sortfile *files, size_t nfiles, FILE ***pfps) for (i = 0; i < nfiles; i++) { fps[i] = (files[i].pid - ? open_temp (files[i].name, files[i].pid) - : stream_open (files[i].name, "r")); + ? open_temp (files[i].name, files[i].pid) + : stream_open (files[i].name, "r")); if (!fps[i]) - break; + break; } return i; @@ -2336,22 +2336,22 @@ open_input_files (struct sortfile *files, size_t nfiles, FILE ***pfps) static void mergefps (struct sortfile *files, size_t ntemps, size_t nfiles, - FILE *ofp, char const *output_file, FILE **fps) + FILE *ofp, char const *output_file, FILE **fps) { struct buffer *buffer = xnmalloc (nfiles, sizeof *buffer); - /* Input buffers for each file. */ + /* Input buffers for each file. */ struct line saved; /* Saved line storage for unique check. */ struct line const *savedline = NULL; - /* &saved if there is a saved line. */ + /* &saved if there is a saved line. */ size_t savealloc = 0; /* Size allocated for the saved line. */ struct line const **cur = xnmalloc (nfiles, sizeof *cur); - /* Current line in each line table. */ + /* Current line in each line table. */ struct line const **base = xnmalloc (nfiles, sizeof *base); - /* Base of each line table. */ + /* Base of each line table. */ size_t *ord = xnmalloc (nfiles, sizeof *ord); - /* Table representing a permutation of fps, - such that cur[ord[0]] is the smallest line - and will be next output. */ + /* Table representing a permutation of fps, + such that cur[ord[0]] is the smallest line + and will be next output. */ size_t i; size_t j; size_t t; @@ -2362,31 +2362,31 @@ mergefps (struct sortfile *files, size_t ntemps, size_t nfiles, for (i = 0; i < nfiles; ) { initbuf (&buffer[i], sizeof (struct line), - MAX (merge_buffer_size, sort_size / nfiles)); + MAX (merge_buffer_size, sort_size / nfiles)); if (fillbuf (&buffer[i], fps[i], files[i].name)) - { - struct line const *linelim = buffer_linelim (&buffer[i]); - cur[i] = linelim - 1; - base[i] = linelim - buffer[i].nlines; - i++; - } + { + struct line const *linelim = buffer_linelim (&buffer[i]); + cur[i] = linelim - 1; + base[i] = linelim - buffer[i].nlines; + i++; + } else - { - /* fps[i] is empty; eliminate it from future consideration. */ - xfclose (fps[i], files[i].name); - if (i < ntemps) - { - ntemps--; - zaptemp (files[i].name); - } - free (buffer[i].buf); - --nfiles; - for (j = i; j < nfiles; ++j) - { - files[j] = files[j + 1]; - fps[j] = fps[j + 1]; - } - } + { + /* fps[i] is empty; eliminate it from future consideration. */ + xfclose (fps[i], files[i].name); + if (i < ntemps) + { + ntemps--; + zaptemp (files[i].name); + } + free (buffer[i].buf); + --nfiles; + for (j = i; j < nfiles; ++j) + { + files[j] = files[j + 1]; + fps[j] = fps[j + 1]; + } + } } /* Set up the ord table according to comparisons among input lines. @@ -2404,112 +2404,112 @@ mergefps (struct sortfile *files, size_t ntemps, size_t nfiles, struct line const *smallest = cur[ord[0]]; /* If uniquified output is turned on, output only the first of - an identical series of lines. */ + an identical series of lines. */ if (unique) - { - if (savedline && compare (savedline, smallest)) - { - savedline = NULL; - write_bytes (saved.text, saved.length, ofp, output_file); - } - if (!savedline) - { - savedline = &saved; - if (savealloc < smallest->length) - { - do - if (! savealloc) - { - savealloc = smallest->length; - break; - } - while ((savealloc *= 2) < smallest->length); - - saved.text = xrealloc (saved.text, savealloc); - } - saved.length = smallest->length; - memcpy (saved.text, smallest->text, saved.length); - if (key) - { - saved.keybeg = - saved.text + (smallest->keybeg - smallest->text); - saved.keylim = - saved.text + (smallest->keylim - smallest->text); - } - } - } + { + if (savedline && compare (savedline, smallest)) + { + savedline = NULL; + write_bytes (saved.text, saved.length, ofp, output_file); + } + if (!savedline) + { + savedline = &saved; + if (savealloc < smallest->length) + { + do + if (! savealloc) + { + savealloc = smallest->length; + break; + } + while ((savealloc *= 2) < smallest->length); + + saved.text = xrealloc (saved.text, savealloc); + } + saved.length = smallest->length; + memcpy (saved.text, smallest->text, saved.length); + if (key) + { + saved.keybeg = + saved.text + (smallest->keybeg - smallest->text); + saved.keylim = + saved.text + (smallest->keylim - smallest->text); + } + } + } else - write_bytes (smallest->text, smallest->length, ofp, output_file); + write_bytes (smallest->text, smallest->length, ofp, output_file); /* Check if we need to read more lines into core. */ if (base[ord[0]] < smallest) - cur[ord[0]] = smallest - 1; + cur[ord[0]] = smallest - 1; else - { - if (fillbuf (&buffer[ord[0]], fps[ord[0]], files[ord[0]].name)) - { - struct line const *linelim = buffer_linelim (&buffer[ord[0]]); - cur[ord[0]] = linelim - 1; - base[ord[0]] = linelim - buffer[ord[0]].nlines; - } - else - { - /* We reached EOF on fps[ord[0]]. */ - for (i = 1; i < nfiles; ++i) - if (ord[i] > ord[0]) - --ord[i]; - --nfiles; - xfclose (fps[ord[0]], files[ord[0]].name); - if (ord[0] < ntemps) - { - ntemps--; - zaptemp (files[ord[0]].name); - } - free (buffer[ord[0]].buf); - for (i = ord[0]; i < nfiles; ++i) - { - fps[i] = fps[i + 1]; - files[i] = files[i + 1]; - buffer[i] = buffer[i + 1]; - cur[i] = cur[i + 1]; - base[i] = base[i + 1]; - } - for (i = 0; i < nfiles; ++i) - ord[i] = ord[i + 1]; - continue; - } - } + { + if (fillbuf (&buffer[ord[0]], fps[ord[0]], files[ord[0]].name)) + { + struct line const *linelim = buffer_linelim (&buffer[ord[0]]); + cur[ord[0]] = linelim - 1; + base[ord[0]] = linelim - buffer[ord[0]].nlines; + } + else + { + /* We reached EOF on fps[ord[0]]. */ + for (i = 1; i < nfiles; ++i) + if (ord[i] > ord[0]) + --ord[i]; + --nfiles; + xfclose (fps[ord[0]], files[ord[0]].name); + if (ord[0] < ntemps) + { + ntemps--; + zaptemp (files[ord[0]].name); + } + free (buffer[ord[0]].buf); + for (i = ord[0]; i < nfiles; ++i) + { + fps[i] = fps[i + 1]; + files[i] = files[i + 1]; + buffer[i] = buffer[i + 1]; + cur[i] = cur[i + 1]; + base[i] = base[i + 1]; + } + for (i = 0; i < nfiles; ++i) + ord[i] = ord[i + 1]; + continue; + } + } /* The new line just read in may be larger than other lines - already in main memory; push it back in the queue until we - encounter a line larger than it. Optimize for the common - case where the new line is smallest. */ + already in main memory; push it back in the queue until we + encounter a line larger than it. Optimize for the common + case where the new line is smallest. */ { - size_t lo = 1; - size_t hi = nfiles; - size_t probe = lo; - size_t ord0 = ord[0]; - size_t count_of_smaller_lines; - - while (lo < hi) - { - int cmp = compare (cur[ord0], cur[ord[probe]]); - if (cmp < 0 || (cmp == 0 && ord0 < ord[probe])) - hi = probe; - else - lo = probe + 1; - probe = (lo + hi) / 2; - } - - count_of_smaller_lines = lo - 1; - for (j = 0; j < count_of_smaller_lines; j++) - ord[j] = ord[j + 1]; - ord[count_of_smaller_lines] = ord0; + size_t lo = 1; + size_t hi = nfiles; + size_t probe = lo; + size_t ord0 = ord[0]; + size_t count_of_smaller_lines; + + while (lo < hi) + { + int cmp = compare (cur[ord0], cur[ord[probe]]); + if (cmp < 0 || (cmp == 0 && ord0 < ord[probe])) + hi = probe; + else + lo = probe + 1; + probe = (lo + hi) / 2; + } + + count_of_smaller_lines = lo - 1; + for (j = 0; j < count_of_smaller_lines; j++) + ord[j] = ord[j + 1]; + ord[count_of_smaller_lines] = ord0; } /* Free up some resources every once in a while. */ if (MAX_PROCS_BEFORE_REAP < nprocs) - reap_some (); + reap_some (); } if (unique && savedline) @@ -2538,7 +2538,7 @@ mergefps (struct sortfile *files, size_t ntemps, size_t nfiles, static size_t mergefiles (struct sortfile *files, size_t ntemps, size_t nfiles, - FILE *ofp, char const *output_file) + FILE *ofp, char const *output_file) { FILE **fps; size_t nopened = open_input_files (files, nfiles, &fps); @@ -2555,32 +2555,32 @@ mergefiles (struct sortfile *files, size_t ntemps, size_t nfiles, static inline void mergelines (struct line *t, - struct line const *lo, size_t nlo, - struct line const *hi, size_t nhi) + struct line const *lo, size_t nlo, + struct line const *hi, size_t nhi) { for (;;) if (compare (lo - 1, hi - 1) <= 0) { - *--t = *--lo; - if (! --nlo) - { - /* HI - NHI equalled T - (NLO + NHI) when this function - began. Therefore HI must equal T now, and there is no - need to copy from HI to T. */ - return; - } + *--t = *--lo; + if (! --nlo) + { + /* HI - NHI equalled T - (NLO + NHI) when this function + began. Therefore HI must equal T now, and there is no + need to copy from HI to T. */ + return; + } } else { - *--t = *--hi; - if (! --nhi) - { - do - *--t = *--lo; - while (--nlo); - - return; - } + *--t = *--hi; + if (! --nhi) + { + do + *--t = *--lo; + while (--nlo); + + return; + } } } @@ -2602,11 +2602,11 @@ sortlines (struct line *lines, size_t nlines, struct line *temp) if (nlines == 2) { if (0 < compare (&lines[-1], &lines[-2])) - { - struct line tmp = lines[-1]; - lines[-1] = lines[-2]; - lines[-2] = tmp; - } + { + struct line tmp = lines[-1]; + lines[-1] = lines[-2]; + lines[-2] = tmp; + } } else { @@ -2618,9 +2618,9 @@ sortlines (struct line *lines, size_t nlines, struct line *temp) sortlines (hi, nhi, temp); if (1 < nlo) - sortlines_temp (lo, nlo, sorted_lo); + sortlines_temp (lo, nlo, sorted_lo); else - sorted_lo[-1] = lo[-1]; + sorted_lo[-1] = lo[-1]; mergelines (lines, sorted_lo, nlo, hi, nhi); } @@ -2635,8 +2635,8 @@ sortlines_temp (struct line *lines, size_t nlines, struct line *temp) if (nlines == 2) { /* Declare `swap' as int, not bool, to work around a bug - <http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html> - in the IBM xlc 6.0.0.0 compiler in 64-bit mode. */ + <http://lists.gnu.org/archive/html/bug-coreutils/2005-10/msg00086.html> + in the IBM xlc 6.0.0.0 compiler in 64-bit mode. */ int swap = (0 < compare (&lines[-1], &lines[-2])); temp[-1] = lines[-1 - swap]; temp[-2] = lines[-2 + swap]; @@ -2651,7 +2651,7 @@ sortlines_temp (struct line *lines, size_t nlines, struct line *temp) sortlines_temp (hi, nhi, sorted_hi); if (1 < nlo) - sortlines (lo, nlo, temp); + sortlines (lo, nlo, temp); mergelines (temp, lo, nlo, sorted_hi, nhi); } @@ -2676,7 +2676,7 @@ sortlines_temp (struct line *lines, size_t nlines, struct line *temp) static size_t avoid_trashing_input (struct sortfile *files, size_t ntemps, - size_t nfiles, char const *outfile) + size_t nfiles, char const *outfile) { size_t i; bool got_outstat = false; @@ -2689,47 +2689,47 @@ avoid_trashing_input (struct sortfile *files, size_t ntemps, struct stat instat; if (outfile && STREQ (outfile, files[i].name) && !is_stdin) - same = true; + same = true; else - { - if (! got_outstat) - { - if ((outfile - ? stat (outfile, &outstat) - : fstat (STDOUT_FILENO, &outstat)) - != 0) - break; - got_outstat = true; - } - - same = (((is_stdin - ? fstat (STDIN_FILENO, &instat) - : stat (files[i].name, &instat)) - == 0) - && SAME_INODE (instat, outstat)); - } + { + if (! got_outstat) + { + if ((outfile + ? stat (outfile, &outstat) + : fstat (STDOUT_FILENO, &outstat)) + != 0) + break; + got_outstat = true; + } + + same = (((is_stdin + ? fstat (STDIN_FILENO, &instat) + : stat (files[i].name, &instat)) + == 0) + && SAME_INODE (instat, outstat)); + } if (same) - { - FILE *tftp; - pid_t pid; - char *temp = create_temp (&tftp, &pid); - size_t num_merged = 0; - do - { - num_merged += mergefiles (&files[i], 0, nfiles - i, tftp, temp); - files[i].name = temp; - files[i].pid = pid; - - if (i + num_merged < nfiles) - memmove(&files[i + 1], &files[i + num_merged], - num_merged * sizeof *files); - ntemps += 1; - nfiles -= num_merged - 1;; - i += num_merged; - } - while (i < nfiles); - } + { + FILE *tftp; + pid_t pid; + char *temp = create_temp (&tftp, &pid); + size_t num_merged = 0; + do + { + num_merged += mergefiles (&files[i], 0, nfiles - i, tftp, temp); + files[i].name = temp; + files[i].pid = pid; + + if (i + num_merged < nfiles) + memmove(&files[i + 1], &files[i + num_merged], + num_merged * sizeof *files); + ntemps += 1; + nfiles -= num_merged - 1;; + i += num_merged; + } + while (i < nfiles); + } } return nfiles; @@ -2753,7 +2753,7 @@ merge (struct sortfile *files, size_t ntemps, size_t nfiles, size_t out; /* nfiles % NMERGE; this counts input files that are left over - after all full-sized merges have been done. */ + after all full-sized merges have been done. */ size_t remainder; /* Number of easily-available slots at the next loop iteration. */ @@ -2763,40 +2763,40 @@ merge (struct sortfile *files, size_t ntemps, size_t nfiles, nmerge is bogus, increment by the maximum number of file descriptors allowed. */ for (out = in = 0; nmerge <= nfiles - in; out++) - { - FILE *tfp; - pid_t pid; - char *temp = create_temp (&tfp, &pid); - size_t num_merged = mergefiles (&files[in], MIN (ntemps, nmerge), - nmerge, tfp, temp); - ntemps -= MIN (ntemps, num_merged); - files[out].name = temp; - files[out].pid = pid; - in += num_merged; - } + { + FILE *tfp; + pid_t pid; + char *temp = create_temp (&tfp, &pid); + size_t num_merged = mergefiles (&files[in], MIN (ntemps, nmerge), + nmerge, tfp, temp); + ntemps -= MIN (ntemps, num_merged); + files[out].name = temp; + files[out].pid = pid; + in += num_merged; + } remainder = nfiles - in; cheap_slots = nmerge - out % nmerge; if (cheap_slots < remainder) - { - /* So many files remain that they can't all be put into the last - NMERGE-sized output window. Do one more merge. Merge as few - files as possible, to avoid needless I/O. */ - size_t nshortmerge = remainder - cheap_slots + 1; - FILE *tfp; - pid_t pid; - char *temp = create_temp (&tfp, &pid); - size_t num_merged = mergefiles (&files[in], MIN (ntemps, nshortmerge), - nshortmerge, tfp, temp); - ntemps -= MIN (ntemps, num_merged); - files[out].name = temp; - files[out++].pid = pid; - in += num_merged; - } + { + /* So many files remain that they can't all be put into the last + NMERGE-sized output window. Do one more merge. Merge as few + files as possible, to avoid needless I/O. */ + size_t nshortmerge = remainder - cheap_slots + 1; + FILE *tfp; + pid_t pid; + char *temp = create_temp (&tfp, &pid); + size_t num_merged = mergefiles (&files[in], MIN (ntemps, nshortmerge), + nshortmerge, tfp, temp); + ntemps -= MIN (ntemps, num_merged); + files[out].name = temp; + files[out++].pid = pid; + in += num_merged; + } /* Put the remaining input files into the last NMERGE-sized output - window, so they will be merged in the next pass. */ + window, so they will be merged in the next pass. */ memmove(&files[out], &files[in], (nfiles - in) * sizeof *files); ntemps += out; nfiles -= in - out; @@ -2815,33 +2815,33 @@ merge (struct sortfile *files, size_t ntemps, size_t nfiles, size_t nopened = open_input_files (files, nfiles, &fps); if (nopened == nfiles) - { - FILE *ofp = stream_open (output_file, "w"); - if (ofp) - { - mergefps (files, ntemps, nfiles, ofp, output_file, fps); - break; - } - if (errno != EMFILE || nopened <= 2) - die (_("open failed"), output_file); - } + { + FILE *ofp = stream_open (output_file, "w"); + if (ofp) + { + mergefps (files, ntemps, nfiles, ofp, output_file, fps); + break; + } + if (errno != EMFILE || nopened <= 2) + die (_("open failed"), output_file); + } else if (nopened <= 2) - die (_("open failed"), files[nopened].name); + die (_("open failed"), files[nopened].name); /* We ran out of file descriptors. Close one of the input - files, to gain a file descriptor. Then create a temporary - file with our spare file descriptor. Retry if that failed - (e.g., some other process could open a file between the time - we closed and tried to create). */ + files, to gain a file descriptor. Then create a temporary + file with our spare file descriptor. Retry if that failed + (e.g., some other process could open a file between the time + we closed and tried to create). */ FILE *tfp; pid_t pid; char *temp; do - { - nopened--; - xfclose (fps[nopened], files[nopened].name); - temp = maybe_create_temp (&tfp, &pid, ! (nopened <= 2)); - } + { + nopened--; + xfclose (fps[nopened], files[nopened].name); + temp = maybe_create_temp (&tfp, &pid, ! (nopened <= 2)); + } while (!temp); /* Merge into the newly allocated temporary. */ @@ -2874,67 +2874,67 @@ sort (char * const *files, size_t nfiles, char const *output_file) FILE *fp = xfopen (file, "r"); FILE *tfp; size_t bytes_per_line = (2 * sizeof (struct line) - - sizeof (struct line) / 2); + - sizeof (struct line) / 2); if (! buf.alloc) - initbuf (&buf, bytes_per_line, - sort_buffer_size (&fp, 1, files, nfiles, bytes_per_line)); + initbuf (&buf, bytes_per_line, + sort_buffer_size (&fp, 1, files, nfiles, bytes_per_line)); buf.eof = false; files++; nfiles--; while (fillbuf (&buf, fp, file)) - { - struct line *line; - struct line *linebase; - - if (buf.eof && nfiles - && (bytes_per_line + 1 - < (buf.alloc - buf.used - bytes_per_line * buf.nlines))) - { - /* End of file, but there is more input and buffer room. - Concatenate the next input file; this is faster in - the usual case. */ - buf.left = buf.used; - break; - } - - line = buffer_linelim (&buf); - linebase = line - buf.nlines; - if (1 < buf.nlines) - sortlines (line, buf.nlines, linebase); - if (buf.eof && !nfiles && !ntemps && !buf.left) - { - xfclose (fp, file); - tfp = xfopen (output_file, "w"); - temp_output = output_file; - output_file_created = true; - } - else - { - ++ntemps; - temp_output = create_temp (&tfp, NULL); - } - - do - { - line--; - write_bytes (line->text, line->length, tfp, temp_output); - if (unique) - while (linebase < line && compare (line, line - 1) == 0) - line--; - } - while (linebase < line); - - xfclose (tfp, temp_output); - - /* Free up some resources every once in a while. */ - if (MAX_PROCS_BEFORE_REAP < nprocs) - reap_some (); - - if (output_file_created) - goto finish; - } + { + struct line *line; + struct line *linebase; + + if (buf.eof && nfiles + && (bytes_per_line + 1 + < (buf.alloc - buf.used - bytes_per_line * buf.nlines))) + { + /* End of file, but there is more input and buffer room. + Concatenate the next input file; this is faster in + the usual case. */ + buf.left = buf.used; + break; + } + + line = buffer_linelim (&buf); + linebase = line - buf.nlines; + if (1 < buf.nlines) + sortlines (line, buf.nlines, linebase); + if (buf.eof && !nfiles && !ntemps && !buf.left) + { + xfclose (fp, file); + tfp = xfopen (output_file, "w"); + temp_output = output_file; + output_file_created = true; + } + else + { + ++ntemps; + temp_output = create_temp (&tfp, NULL); + } + + do + { + line--; + write_bytes (line->text, line->length, tfp, temp_output); + if (unique) + while (linebase < line && compare (line, line - 1) == 0) + line--; + } + while (linebase < line); + + xfclose (tfp, temp_output); + + /* Free up some resources every once in a while. */ + if (MAX_PROCS_BEFORE_REAP < nprocs) + reap_some (); + + if (output_file_created) + goto finish; + } xfclose (fp, file); } @@ -2947,11 +2947,11 @@ sort (char * const *files, size_t nfiles, char const *output_file) struct tempnode *node = temphead; struct sortfile *tempfiles = xnmalloc (ntemps, sizeof *tempfiles); for (i = 0; node; i++) - { - tempfiles[i].name = node->name; - tempfiles[i].pid = node->pid; - node = node->next; - } + { + tempfiles[i].name = node->name; + tempfiles[i].pid = node->pid; + node = node->next; + } merge (tempfiles, ntemps, ntemps, output_file); free (tempfiles); } @@ -2979,7 +2979,7 @@ static void badfieldspec (char const *spec, char const *msgid) { error (SORT_FAILURE, 0, _("%s: invalid field specification %s"), - _(msgid), quote (spec)); + _(msgid), quote (spec)); abort (); } @@ -3002,32 +3002,32 @@ check_ordering_compatibility (void) for (key = keylist; key; key = key->next) if ((1 < (key->random + key->numeric + key->general_numeric + key->month - + key->version + !!key->ignore + key->human_numeric)) - || (key->random && key->translate)) + + key->version + !!key->ignore + key->human_numeric)) + || (key->random && key->translate)) { - /* The following is too big, but guaranteed to be "big enough". */ - char opts[sizeof short_options]; - char *p = opts; - if (key->ignore == nondictionary) - *p++ = 'd'; - if (key->translate) - *p++ = 'f'; - if (key->general_numeric) - *p++ = 'g'; - if (key->human_numeric) - *p++ = 'h'; - if (key->ignore == nonprinting) - *p++ = 'i'; - if (key->month) - *p++ = 'M'; - if (key->numeric) - *p++ = 'n'; - if (key->version) - *p++ = 'V'; - if (key->random) - *p++ = 'R'; - *p = '\0'; - incompatible_options (opts); + /* The following is too big, but guaranteed to be "big enough". */ + char opts[sizeof short_options]; + char *p = opts; + if (key->ignore == nondictionary) + *p++ = 'd'; + if (key->translate) + *p++ = 'f'; + if (key->general_numeric) + *p++ = 'g'; + if (key->human_numeric) + *p++ = 'h'; + if (key->ignore == nonprinting) + *p++ = 'i'; + if (key->month) + *p++ = 'M'; + if (key->numeric) + *p++ = 'n'; + if (key->version) + *p++ = 'V'; + if (key->random) + *p++ = 'R'; + *p = '\0'; + incompatible_options (opts); } } @@ -3049,7 +3049,7 @@ parse_field_count (char const *string, size_t *val, char const *msgid) case LONGINT_INVALID_SUFFIX_CHAR: *val = n; if (*val == n) - break; + break; /* Fall through. */ case LONGINT_OVERFLOW: case LONGINT_OVERFLOW | LONGINT_INVALID_SUFFIX_CHAR: @@ -3058,8 +3058,8 @@ parse_field_count (char const *string, size_t *val, char const *msgid) case LONGINT_INVALID: if (msgid) - error (SORT_FAILURE, 0, _("%s: invalid count at start of %s"), - _(msgid), quote (string)); + error (SORT_FAILURE, 0, _("%s: invalid count at start of %s"), + _(msgid), quote (string)); return NULL; } @@ -3091,49 +3091,49 @@ set_ordering (const char *s, struct keyfield *key, enum blanktype blanktype) while (*s) { switch (*s) - { - case 'b': - if (blanktype == bl_start || blanktype == bl_both) - key->skipsblanks = true; - if (blanktype == bl_end || blanktype == bl_both) - key->skipeblanks = true; - break; - case 'd': - key->ignore = nondictionary; - break; - case 'f': - key->translate = fold_toupper; - break; - case 'g': - key->general_numeric = true; - break; - case 'h': - key->human_numeric = true; - break; - case 'i': - /* Option order should not matter, so don't let -i override - -d. -d implies -i, but -i does not imply -d. */ - if (! key->ignore) - key->ignore = nonprinting; - break; - case 'M': - key->month = true; - break; - case 'n': - key->numeric = true; - break; - case 'R': - key->random = true; - break; - case 'r': - key->reverse = true; - break; - case 'V': - key->version = true; - break; - default: - return (char *) s; - } + { + case 'b': + if (blanktype == bl_start || blanktype == bl_both) + key->skipsblanks = true; + if (blanktype == bl_end || blanktype == bl_both) + key->skipeblanks = true; + break; + case 'd': + key->ignore = nondictionary; + break; + case 'f': + key->translate = fold_toupper; + break; + case 'g': + key->general_numeric = true; + break; + case 'h': + key->human_numeric = true; + break; + case 'i': + /* Option order should not matter, so don't let -i override + -d. -d implies -i, but -i does not imply -d. */ + if (! key->ignore) + key->ignore = nonprinting; + break; + case 'M': + key->month = true; + break; + case 'n': + key->numeric = true; + break; + case 'R': + key->random = true; + break; + case 'r': + key->reverse = true; + break; + case 'V': + key->version = true; + break; + default: + return (char *) s; + } ++s; } return (char *) s; @@ -3205,22 +3205,22 @@ main (int argc, char **argv) size_t i; static int const sig[] = { - /* The usual suspects. */ - SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM, + /* The usual suspects. */ + SIGALRM, SIGHUP, SIGINT, SIGPIPE, SIGQUIT, SIGTERM, #ifdef SIGPOLL - SIGPOLL, + SIGPOLL, #endif #ifdef SIGPROF - SIGPROF, + SIGPROF, #endif #ifdef SIGVTALRM - SIGVTALRM, + SIGVTALRM, #endif #ifdef SIGXCPU - SIGXCPU, + SIGXCPU, #endif #ifdef SIGXFSZ - SIGXFSZ, + SIGXFSZ, #endif }; enum { nsigs = ARRAY_CARDINALITY (sig) }; @@ -3231,9 +3231,9 @@ main (int argc, char **argv) sigemptyset (&caught_signals); for (i = 0; i < nsigs; i++) { - sigaction (sig[i], NULL, &act); - if (act.sa_handler != SIG_IGN) - sigaddset (&caught_signals, sig[i]); + sigaction (sig[i], NULL, &act); + if (act.sa_handler != SIG_IGN) + sigaddset (&caught_signals, sig[i]); } act.sa_handler = sighandler; @@ -3242,14 +3242,14 @@ main (int argc, char **argv) for (i = 0; i < nsigs; i++) if (sigismember (&caught_signals, sig[i])) - sigaction (sig[i], &act, NULL); + sigaction (sig[i], &act, NULL); #else for (i = 0; i < nsigs; i++) if (signal (sig[i], SIG_IGN) != SIG_IGN) - { - signal (sig[i], sighandler); - siginterrupt (sig[i], 1); - } + { + signal (sig[i], sighandler); + siginterrupt (sig[i], 1); + } #endif } @@ -3270,256 +3270,256 @@ main (int argc, char **argv) for (;;) { /* Parse an operand as a file after "--" was seen; or if - pedantic and a file was seen, unless the POSIX version - predates 1003.1-2001 and -c was not seen and the operand is - "-o FILE" or "-oFILE". */ + pedantic and a file was seen, unless the POSIX version + predates 1003.1-2001 and -c was not seen and the operand is + "-o FILE" or "-oFILE". */ int oi = -1; if (c == -1 - || (posixly_correct && nfiles != 0 - && ! (obsolete_usage - && ! checkonly - && optind != argc - && argv[optind][0] == '-' && argv[optind][1] == 'o' - && (argv[optind][2] || optind + 1 != argc))) - || ((c = getopt_long (argc, argv, short_options, - long_options, &oi)) - == -1)) - { - if (argc <= optind) - break; - files[nfiles++] = argv[optind++]; - } + || (posixly_correct && nfiles != 0 + && ! (obsolete_usage + && ! checkonly + && optind != argc + && argv[optind][0] == '-' && argv[optind][1] == 'o' + && (argv[optind][2] || optind + 1 != argc))) + || ((c = getopt_long (argc, argv, short_options, + long_options, &oi)) + == -1)) + { + if (argc <= optind) + break; + files[nfiles++] = argv[optind++]; + } else switch (c) - { - case 1: - key = NULL; - if (optarg[0] == '+') - { - bool minus_pos_usage = (optind != argc && argv[optind][0] == '-' - && ISDIGIT (argv[optind][1])); - obsolete_usage |= minus_pos_usage & ~posixly_correct; - if (obsolete_usage) - { - /* Treat +POS1 [-POS2] as a key if possible; but silently - treat an operand as a file if it is not a valid +POS1. */ - key = key_init (&key_buf); - s = parse_field_count (optarg + 1, &key->sword, NULL); - if (s && *s == '.') - s = parse_field_count (s + 1, &key->schar, NULL); - if (! (key->sword | key->schar)) - key->sword = SIZE_MAX; - if (! s || *set_ordering (s, key, bl_start)) - key = NULL; - else - { - if (minus_pos_usage) - { - char const *optarg1 = argv[optind++]; - s = parse_field_count (optarg1 + 1, &key->eword, - N_("invalid number after `-'")); - if (*s == '.') - s = parse_field_count (s + 1, &key->echar, - N_("invalid number after `.'")); - if (*set_ordering (s, key, bl_end)) - badfieldspec (optarg1, - N_("stray character in field spec")); - } - insertkey (key); - } - } - } - if (! key) - files[nfiles++] = optarg; - break; - - case SORT_OPTION: - c = XARGMATCH ("--sort", optarg, sort_args, sort_types); - /* Fall through. */ - case 'b': - case 'd': - case 'f': - case 'g': - case 'h': - case 'i': - case 'M': - case 'n': - case 'r': - case 'R': - case 'V': - { - char str[2]; - str[0] = c; - str[1] = '\0'; - set_ordering (str, &gkey, bl_both); - } - break; - - case CHECK_OPTION: - c = (optarg - ? XARGMATCH ("--check", optarg, check_args, check_types) - : 'c'); - /* Fall through. */ - case 'c': - case 'C': - if (checkonly && checkonly != c) - incompatible_options ("cC"); - checkonly = c; - break; - - case COMPRESS_PROGRAM_OPTION: - if (compress_program && !STREQ (compress_program, optarg)) - error (SORT_FAILURE, 0, _("multiple compress programs specified")); - compress_program = optarg; - break; - - case FILES0_FROM_OPTION: - files_from = optarg; - break; - - case 'k': - key = key_init (&key_buf); - - /* Get POS1. */ - s = parse_field_count (optarg, &key->sword, - N_("invalid number at field start")); - if (! key->sword--) - { - /* Provoke with `sort -k0' */ - badfieldspec (optarg, N_("field number is zero")); - } - if (*s == '.') - { - s = parse_field_count (s + 1, &key->schar, - N_("invalid number after `.'")); - if (! key->schar--) - { - /* Provoke with `sort -k1.0' */ - badfieldspec (optarg, N_("character offset is zero")); - } - } - if (! (key->sword | key->schar)) - key->sword = SIZE_MAX; - s = set_ordering (s, key, bl_start); - if (*s != ',') - { - key->eword = SIZE_MAX; - key->echar = 0; - } - else - { - /* Get POS2. */ - s = parse_field_count (s + 1, &key->eword, - N_("invalid number after `,'")); - if (! key->eword--) - { - /* Provoke with `sort -k1,0' */ - badfieldspec (optarg, N_("field number is zero")); - } - if (*s == '.') - { - s = parse_field_count (s + 1, &key->echar, - N_("invalid number after `.'")); - } - s = set_ordering (s, key, bl_end); - } - if (*s) - badfieldspec (optarg, N_("stray character in field spec")); - insertkey (key); - break; - - case 'm': - mergeonly = true; - break; - - case NMERGE_OPTION: - specify_nmerge (oi, c, optarg); - break; - - case 'o': - if (outfile && !STREQ (outfile, optarg)) - error (SORT_FAILURE, 0, _("multiple output files specified")); - outfile = optarg; - break; - - case RANDOM_SOURCE_OPTION: - if (random_source && !STREQ (random_source, optarg)) - error (SORT_FAILURE, 0, _("multiple random sources specified")); - random_source = optarg; - break; - - case 's': - stable = true; - break; - - case 'S': - specify_sort_size (oi, c, optarg); - break; - - case 't': - { - char newtab = optarg[0]; - if (! newtab) - error (SORT_FAILURE, 0, _("empty tab")); - if (optarg[1]) - { - if (STREQ (optarg, "\\0")) - newtab = '\0'; - else - { - /* Provoke with `sort -txx'. Complain about - "multi-character tab" instead of "multibyte tab", so - that the diagnostic's wording does not need to be - changed once multibyte characters are supported. */ - error (SORT_FAILURE, 0, _("multi-character tab %s"), - quote (optarg)); - } - } - if (tab != TAB_DEFAULT && tab != newtab) - error (SORT_FAILURE, 0, _("incompatible tabs")); - tab = newtab; - } - break; - - case 'T': - add_temp_dir (optarg); - break; - - case 'u': - unique = true; - break; - - case 'y': - /* Accept and ignore e.g. -y0 for compatibility with Solaris 2.x - through Solaris 7. It is also accepted by many non-Solaris - "sort" implementations, e.g., AIX 5.2, HP-UX 11i v2, IRIX 6.5. - -y is marked as obsolete starting with Solaris 8 (1999), but is - still accepted as of Solaris 10 prerelease (2004). - - Solaris 2.5.1 "sort -y 100" reads the input file "100", but - emulate Solaris 8 and 9 "sort -y 100" which ignores the "100", - and which in general ignores the argument after "-y" if it - consists entirely of digits (it can even be empty). */ - if (optarg == argv[optind - 1]) - { - char const *p; - for (p = optarg; ISDIGIT (*p); p++) - continue; - optind -= (*p != '\0'); - } - break; - - case 'z': - eolchar = 0; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (SORT_FAILURE); - } + { + case 1: + key = NULL; + if (optarg[0] == '+') + { + bool minus_pos_usage = (optind != argc && argv[optind][0] == '-' + && ISDIGIT (argv[optind][1])); + obsolete_usage |= minus_pos_usage & ~posixly_correct; + if (obsolete_usage) + { + /* Treat +POS1 [-POS2] as a key if possible; but silently + treat an operand as a file if it is not a valid +POS1. */ + key = key_init (&key_buf); + s = parse_field_count (optarg + 1, &key->sword, NULL); + if (s && *s == '.') + s = parse_field_count (s + 1, &key->schar, NULL); + if (! (key->sword | key->schar)) + key->sword = SIZE_MAX; + if (! s || *set_ordering (s, key, bl_start)) + key = NULL; + else + { + if (minus_pos_usage) + { + char const *optarg1 = argv[optind++]; + s = parse_field_count (optarg1 + 1, &key->eword, + N_("invalid number after `-'")); + if (*s == '.') + s = parse_field_count (s + 1, &key->echar, + N_("invalid number after `.'")); + if (*set_ordering (s, key, bl_end)) + badfieldspec (optarg1, + N_("stray character in field spec")); + } + insertkey (key); + } + } + } + if (! key) + files[nfiles++] = optarg; + break; + + case SORT_OPTION: + c = XARGMATCH ("--sort", optarg, sort_args, sort_types); + /* Fall through. */ + case 'b': + case 'd': + case 'f': + case 'g': + case 'h': + case 'i': + case 'M': + case 'n': + case 'r': + case 'R': + case 'V': + { + char str[2]; + str[0] = c; + str[1] = '\0'; + set_ordering (str, &gkey, bl_both); + } + break; + + case CHECK_OPTION: + c = (optarg + ? XARGMATCH ("--check", optarg, check_args, check_types) + : 'c'); + /* Fall through. */ + case 'c': + case 'C': + if (checkonly && checkonly != c) + incompatible_options ("cC"); + checkonly = c; + break; + + case COMPRESS_PROGRAM_OPTION: + if (compress_program && !STREQ (compress_program, optarg)) + error (SORT_FAILURE, 0, _("multiple compress programs specified")); + compress_program = optarg; + break; + + case FILES0_FROM_OPTION: + files_from = optarg; + break; + + case 'k': + key = key_init (&key_buf); + + /* Get POS1. */ + s = parse_field_count (optarg, &key->sword, + N_("invalid number at field start")); + if (! key->sword--) + { + /* Provoke with `sort -k0' */ + badfieldspec (optarg, N_("field number is zero")); + } + if (*s == '.') + { + s = parse_field_count (s + 1, &key->schar, + N_("invalid number after `.'")); + if (! key->schar--) + { + /* Provoke with `sort -k1.0' */ + badfieldspec (optarg, N_("character offset is zero")); + } + } + if (! (key->sword | key->schar)) + key->sword = SIZE_MAX; + s = set_ordering (s, key, bl_start); + if (*s != ',') + { + key->eword = SIZE_MAX; + key->echar = 0; + } + else + { + /* Get POS2. */ + s = parse_field_count (s + 1, &key->eword, + N_("invalid number after `,'")); + if (! key->eword--) + { + /* Provoke with `sort -k1,0' */ + badfieldspec (optarg, N_("field number is zero")); + } + if (*s == '.') + { + s = parse_field_count (s + 1, &key->echar, + N_("invalid number after `.'")); + } + s = set_ordering (s, key, bl_end); + } + if (*s) + badfieldspec (optarg, N_("stray character in field spec")); + insertkey (key); + break; + + case 'm': + mergeonly = true; + break; + + case NMERGE_OPTION: + specify_nmerge (oi, c, optarg); + break; + + case 'o': + if (outfile && !STREQ (outfile, optarg)) + error (SORT_FAILURE, 0, _("multiple output files specified")); + outfile = optarg; + break; + + case RANDOM_SOURCE_OPTION: + if (random_source && !STREQ (random_source, optarg)) + error (SORT_FAILURE, 0, _("multiple random sources specified")); + random_source = optarg; + break; + + case 's': + stable = true; + break; + + case 'S': + specify_sort_size (oi, c, optarg); + break; + + case 't': + { + char newtab = optarg[0]; + if (! newtab) + error (SORT_FAILURE, 0, _("empty tab")); + if (optarg[1]) + { + if (STREQ (optarg, "\\0")) + newtab = '\0'; + else + { + /* Provoke with `sort -txx'. Complain about + "multi-character tab" instead of "multibyte tab", so + that the diagnostic's wording does not need to be + changed once multibyte characters are supported. */ + error (SORT_FAILURE, 0, _("multi-character tab %s"), + quote (optarg)); + } + } + if (tab != TAB_DEFAULT && tab != newtab) + error (SORT_FAILURE, 0, _("incompatible tabs")); + tab = newtab; + } + break; + + case 'T': + add_temp_dir (optarg); + break; + + case 'u': + unique = true; + break; + + case 'y': + /* Accept and ignore e.g. -y0 for compatibility with Solaris 2.x + through Solaris 7. It is also accepted by many non-Solaris + "sort" implementations, e.g., AIX 5.2, HP-UX 11i v2, IRIX 6.5. + -y is marked as obsolete starting with Solaris 8 (1999), but is + still accepted as of Solaris 10 prerelease (2004). + + Solaris 2.5.1 "sort -y 100" reads the input file "100", but + emulate Solaris 8 and 9 "sort -y 100" which ignores the "100", + and which in general ignores the argument after "-y" if it + consists entirely of digits (it can even be empty). */ + if (optarg == argv[optind - 1]) + { + char const *p; + for (p = optarg; ISDIGIT (*p); p++) + continue; + optind -= (*p != '\0'); + } + break; + + case 'z': + eolchar = 0; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (SORT_FAILURE); + } } if (files_from) @@ -3527,74 +3527,74 @@ main (int argc, char **argv) FILE *stream; /* When using --files0-from=F, you may not specify any files - on the command-line. */ + on the command-line. */ if (nfiles) - { - error (0, 0, _("extra operand %s"), quote (files[0])); - fprintf (stderr, "%s\n", - _("file operands cannot be combined with --files0-from")); - usage (SORT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (files[0])); + fprintf (stderr, "%s\n", + _("file operands cannot be combined with --files0-from")); + usage (SORT_FAILURE); + } if (STREQ (files_from, "-")) - stream = stdin; + stream = stdin; else - { - stream = fopen (files_from, "r"); - if (stream == NULL) - error (SORT_FAILURE, errno, _("cannot open %s for reading"), - quote (files_from)); - } + { + stream = fopen (files_from, "r"); + if (stream == NULL) + error (SORT_FAILURE, errno, _("cannot open %s for reading"), + quote (files_from)); + } readtokens0_init (&tok); if (! readtokens0 (stream, &tok) || fclose (stream) != 0) - error (SORT_FAILURE, 0, _("cannot read file names from %s"), - quote (files_from)); + error (SORT_FAILURE, 0, _("cannot read file names from %s"), + quote (files_from)); if (tok.n_tok) - { - size_t i; - free (files); - files = tok.tok; - nfiles = tok.n_tok; - for (i = 0; i < nfiles; i++) - { - if (STREQ (files[i], "-")) - error (SORT_FAILURE, 0, _("when reading file names from stdin, " - "no file name of %s allowed"), - quote (files[i])); - else if (files[i][0] == '\0') - { - /* Using the standard `filename:line-number:' prefix here is - not totally appropriate, since NUL is the separator, not NL, - but it might be better than nothing. */ - unsigned long int file_number = i + 1; - error (SORT_FAILURE, 0, - _("%s:%lu: invalid zero-length file name"), - quotearg_colon (files_from), file_number); - } - } - } + { + size_t i; + free (files); + files = tok.tok; + nfiles = tok.n_tok; + for (i = 0; i < nfiles; i++) + { + if (STREQ (files[i], "-")) + error (SORT_FAILURE, 0, _("when reading file names from stdin, " + "no file name of %s allowed"), + quote (files[i])); + else if (files[i][0] == '\0') + { + /* Using the standard `filename:line-number:' prefix here is + not totally appropriate, since NUL is the separator, not NL, + but it might be better than nothing. */ + unsigned long int file_number = i + 1; + error (SORT_FAILURE, 0, + _("%s:%lu: invalid zero-length file name"), + quotearg_colon (files_from), file_number); + } + } + } else - error (SORT_FAILURE, 0, _("no input from %s"), - quote (files_from)); + error (SORT_FAILURE, 0, _("no input from %s"), + quote (files_from)); } /* Inheritance of global options to individual keys. */ for (key = keylist; key; key = key->next) { if (! (key->ignore - || key->translate - || (key->skipsblanks - | key->reverse - | key->skipeblanks - | key->month - | key->numeric - | key->version - | key->general_numeric - | key->human_numeric - | key->random))) + || key->translate + || (key->skipsblanks + | key->reverse + | key->skipeblanks + | key->month + | key->numeric + | key->version + | key->general_numeric + | key->human_numeric + | key->random))) { key->ignore = gkey.ignore; key->translate = gkey.translate; @@ -3613,15 +3613,15 @@ main (int argc, char **argv) } if (!keylist && (gkey.ignore - || gkey.translate - || (gkey.skipsblanks - | gkey.skipeblanks - | gkey.month - | gkey.numeric - | gkey.general_numeric - | gkey.human_numeric - | gkey.random - | gkey.version))) + || gkey.translate + || (gkey.skipsblanks + | gkey.skipeblanks + | gkey.month + | gkey.numeric + | gkey.general_numeric + | gkey.human_numeric + | gkey.random + | gkey.version))) { insertkey (&gkey); need_random |= gkey.random; @@ -3635,7 +3635,7 @@ main (int argc, char **argv) { randread_source = randread_new (random_source, MD5_DIGEST_SIZE); if (! randread_source) - die (_("open failed"), random_source); + die (_("open failed"), random_source); } if (temp_dir_count == 0) @@ -3660,18 +3660,18 @@ main (int argc, char **argv) if (checkonly) { if (nfiles > 1) - error (SORT_FAILURE, 0, _("extra operand %s not allowed with -%c"), - quote (files[1]), checkonly); + error (SORT_FAILURE, 0, _("extra operand %s not allowed with -%c"), + quote (files[1]), checkonly); if (outfile) - { - static char opts[] = {0, 'o', 0}; - opts[0] = checkonly; - incompatible_options (opts); - } + { + static char opts[] = {0, 'o', 0}; + opts[0] = checkonly; + incompatible_options (opts); + } /* POSIX requires that sort return 1 IFF invoked with -c or -C and the - input is not properly sorted. */ + input is not properly sorted. */ exit (check (files[0], checkonly) ? EXIT_SUCCESS : SORT_OUT_OF_ORDER); } @@ -3681,7 +3681,7 @@ main (int argc, char **argv) size_t i; for (i = 0; i < nfiles; ++i) - sortfiles[i].name = files[i]; + sortfiles[i].name = files[i]; merge (sortfiles, 0, nfiles, outfile); IF_LINT (free (sortfiles)); diff --git a/src/split.c b/src/split.c index ca25c8baf..45c24aaa4 100644 --- a/src/split.c +++ b/src/split.c @@ -97,13 +97,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [INPUT [PREFIX]]\n\ "), - program_name); + program_name); fputs (_("\ Output fixed-size pieces of INPUT to PREFIXaa, PREFIXab, ...; default\n\ size is 1000 lines, and default PREFIX is `x'. With no INPUT, or when INPUT\n\ @@ -153,7 +153,7 @@ next_file_name (void) size_t outbase_length = strlen (outbase); size_t outfile_length = outbase_length + suffix_length; if (outfile_length + 1 < outbase_length) - xalloc_die (); + xalloc_die (); outfile = xmalloc (outfile_length + 1); outfile_mid = outfile + outbase_length; memcpy (outfile, outbase, outbase_length); @@ -163,15 +163,15 @@ next_file_name (void) #if ! _POSIX_NO_TRUNC && HAVE_PATHCONF && defined _PC_NAME_MAX /* POSIX requires that if the output file name is too long for - its directory, `split' must fail without creating any files. - This must be checked for explicitly on operating systems that - silently truncate file names. */ + its directory, `split' must fail without creating any files. + This must be checked for explicitly on operating systems that + silently truncate file names. */ { - char *dir = dir_name (outfile); - long name_max = pathconf (dir, _PC_NAME_MAX); - if (0 <= name_max && name_max < base_len (last_component (outfile))) - error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile); - free (dir); + char *dir = dir_name (outfile); + long name_max = pathconf (dir, _PC_NAME_MAX); + if (0 <= name_max && name_max < base_len (last_component (outfile))) + error (EXIT_FAILURE, ENAMETOOLONG, "%s", outfile); + free (dir); } #endif } @@ -181,14 +181,14 @@ next_file_name (void) size_t i = suffix_length; while (i-- != 0) - { - sufindex[i]++; - outfile_mid[i] = suffix_alphabet[sufindex[i]]; - if (outfile_mid[i]) - return; - sufindex[i] = 0; - outfile_mid[i] = suffix_alphabet[sufindex[i]]; - } + { + sufindex[i]++; + outfile_mid[i] = suffix_alphabet[sufindex[i]]; + if (outfile_mid[i]) + return; + sufindex[i] = 0; + outfile_mid[i] = suffix_alphabet[sufindex[i]]; + } error (EXIT_FAILURE, 0, _("output file suffixes exhausted")); } } @@ -203,17 +203,17 @@ cwrite (bool new_file_flag, const char *bp, size_t bytes) if (new_file_flag) { if (output_desc >= 0 && close (output_desc) < 0) - error (EXIT_FAILURE, errno, "%s", outfile); + error (EXIT_FAILURE, errno, "%s", outfile); next_file_name (); if (verbose) - fprintf (stdout, _("creating file %s\n"), quote (outfile)); + fprintf (stdout, _("creating file %s\n"), quote (outfile)); output_desc = open (outfile, - O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, - (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP - | S_IROTH | S_IWOTH)); + O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, + (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP + | S_IROTH | S_IWOTH)); if (output_desc < 0) - error (EXIT_FAILURE, errno, "%s", outfile); + error (EXIT_FAILURE, errno, "%s", outfile); } if (full_write (output_desc, bp, bytes) != bytes) error (EXIT_FAILURE, errno, "%s", outfile); @@ -239,27 +239,27 @@ bytes_split (uintmax_t n_bytes, char *buf, size_t bufsize) bp_out = buf; to_read = n_read; for (;;) - { - if (to_read < to_write) - { - if (to_read) /* do not write 0 bytes! */ - { - cwrite (new_file_flag, bp_out, to_read); - to_write -= to_read; - new_file_flag = false; - } - break; - } - else - { - size_t w = to_write; - cwrite (new_file_flag, bp_out, w); - bp_out += w; - to_read -= w; - new_file_flag = true; - to_write = n_bytes; - } - } + { + if (to_read < to_write) + { + if (to_read) /* do not write 0 bytes! */ + { + cwrite (new_file_flag, bp_out, to_read); + to_write -= to_read; + new_file_flag = false; + } + break; + } + else + { + size_t w = to_write; + cwrite (new_file_flag, bp_out, w); + bp_out += w; + to_read -= w; + new_file_flag = true; + to_write = n_bytes; + } + } } while (n_read == bufsize); } @@ -279,33 +279,33 @@ lines_split (uintmax_t n_lines, char *buf, size_t bufsize) { n_read = full_read (STDIN_FILENO, buf, bufsize); if (n_read == SAFE_READ_ERROR) - error (EXIT_FAILURE, errno, "%s", infile); + error (EXIT_FAILURE, errno, "%s", infile); bp = bp_out = buf; eob = bp + n_read; *eob = '\n'; for (;;) - { - bp = memchr (bp, '\n', eob - bp + 1); - if (bp == eob) - { - if (eob != bp_out) /* do not write 0 bytes! */ - { - size_t len = eob - bp_out; - cwrite (new_file_flag, bp_out, len); - new_file_flag = false; - } - break; - } - - ++bp; - if (++n >= n_lines) - { - cwrite (new_file_flag, bp_out, bp - bp_out); - bp_out = bp; - new_file_flag = true; - n = 0; - } - } + { + bp = memchr (bp, '\n', eob - bp + 1); + if (bp == eob) + { + if (eob != bp_out) /* do not write 0 bytes! */ + { + size_t len = eob - bp_out; + cwrite (new_file_flag, bp_out, len); + new_file_flag = false; + } + break; + } + + ++bp; + if (++n >= n_lines) + { + cwrite (new_file_flag, bp_out, bp - bp_out); + bp_out = bp; + new_file_flag = true; + n = 0; + } + } } while (n_read == bufsize); } @@ -331,37 +331,37 @@ line_bytes_split (size_t n_bytes) n_read = full_read (STDIN_FILENO, buf + n_buffered, n_bytes - n_buffered); if (n_read == SAFE_READ_ERROR) - error (EXIT_FAILURE, errno, "%s", infile); + error (EXIT_FAILURE, errno, "%s", infile); n_buffered += n_read; if (n_buffered != n_bytes) - { - if (n_buffered == 0) - break; - eof = true; - } + { + if (n_buffered == 0) + break; + eof = true; + } /* Find where to end this chunk. */ bp = buf + n_buffered; if (n_buffered == n_bytes) - { - while (bp > buf && bp[-1] != '\n') - bp--; - } + { + while (bp > buf && bp[-1] != '\n') + bp--; + } /* If chunk has no newlines, use all the chunk. */ if (bp == buf) - bp = buf + n_buffered; + bp = buf + n_buffered; /* Output the chars as one output file. */ cwrite (true, buf, bp - buf); /* Discard the chars we just output; move rest of chunk - down to be the start of the next chunk. Source and - destination probably overlap. */ + down to be the start of the next chunk. Source and + destination probably overlap. */ n_buffered -= bp - buf; if (n_buffered > 0) - memmove (buf, bp, n_buffered); + memmove (buf, bp, n_buffered); } while (!eof); free (buf); @@ -411,103 +411,103 @@ main (int argc, char **argv) c = getopt_long (argc, argv, "0123456789C:a:b:dl:", longopts, NULL); if (c == -1) - break; + break; switch (c) - { - case 'a': - { - unsigned long tmp; - if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK - || SIZE_MAX / sizeof (size_t) < tmp) - { - error (0, 0, _("%s: invalid suffix length"), optarg); - usage (EXIT_FAILURE); - } - suffix_length = tmp; - } - break; - - case 'b': - if (split_type != type_undef) - FAIL_ONLY_ONE_WAY (); - split_type = type_bytes; - if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK - || n_units == 0) - { - error (0, 0, _("%s: invalid number of bytes"), optarg); - usage (EXIT_FAILURE); - } - break; - - case 'l': - if (split_type != type_undef) - FAIL_ONLY_ONE_WAY (); - split_type = type_lines; - if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK - || n_units == 0) - { - error (0, 0, _("%s: invalid number of lines"), optarg); - usage (EXIT_FAILURE); - } - break; - - case 'C': - if (split_type != type_undef) - FAIL_ONLY_ONE_WAY (); - split_type = type_byteslines; - if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK - || n_units == 0 || SIZE_MAX < n_units) - { - error (0, 0, _("%s: invalid number of bytes"), optarg); - usage (EXIT_FAILURE); - } - break; - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - if (split_type == type_undef) - { - split_type = type_digits; - n_units = 0; - } - if (split_type != type_undef && split_type != type_digits) - FAIL_ONLY_ONE_WAY (); - if (digits_optind != 0 && digits_optind != this_optind) - n_units = 0; /* More than one number given; ignore other. */ - digits_optind = this_optind; - if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', uintmax_t)) - { - char buffer[INT_BUFSIZE_BOUND (uintmax_t)]; - error (EXIT_FAILURE, 0, - _("line count option -%s%c... is too large"), - umaxtostr (n_units, buffer), c); - } - break; - - case 'd': - suffix_alphabet = "0123456789"; - break; - - case VERBOSE_OPTION: - verbose = true; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'a': + { + unsigned long tmp; + if (xstrtoul (optarg, NULL, 10, &tmp, "") != LONGINT_OK + || SIZE_MAX / sizeof (size_t) < tmp) + { + error (0, 0, _("%s: invalid suffix length"), optarg); + usage (EXIT_FAILURE); + } + suffix_length = tmp; + } + break; + + case 'b': + if (split_type != type_undef) + FAIL_ONLY_ONE_WAY (); + split_type = type_bytes; + if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK + || n_units == 0) + { + error (0, 0, _("%s: invalid number of bytes"), optarg); + usage (EXIT_FAILURE); + } + break; + + case 'l': + if (split_type != type_undef) + FAIL_ONLY_ONE_WAY (); + split_type = type_lines; + if (xstrtoumax (optarg, NULL, 10, &n_units, "") != LONGINT_OK + || n_units == 0) + { + error (0, 0, _("%s: invalid number of lines"), optarg); + usage (EXIT_FAILURE); + } + break; + + case 'C': + if (split_type != type_undef) + FAIL_ONLY_ONE_WAY (); + split_type = type_byteslines; + if (xstrtoumax (optarg, NULL, 10, &n_units, multipliers) != LONGINT_OK + || n_units == 0 || SIZE_MAX < n_units) + { + error (0, 0, _("%s: invalid number of bytes"), optarg); + usage (EXIT_FAILURE); + } + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (split_type == type_undef) + { + split_type = type_digits; + n_units = 0; + } + if (split_type != type_undef && split_type != type_digits) + FAIL_ONLY_ONE_WAY (); + if (digits_optind != 0 && digits_optind != this_optind) + n_units = 0; /* More than one number given; ignore other. */ + digits_optind = this_optind; + if (!DECIMAL_DIGIT_ACCUMULATE (n_units, c - '0', uintmax_t)) + { + char buffer[INT_BUFSIZE_BOUND (uintmax_t)]; + error (EXIT_FAILURE, 0, + _("line count option -%s%c... is too large"), + umaxtostr (n_units, buffer), c); + } + break; + + case 'd': + suffix_alphabet = "0123456789"; + break; + + case VERBOSE_OPTION: + verbose = true; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } /* Handle default case. */ @@ -541,7 +541,7 @@ main (int argc, char **argv) if (! STREQ (infile, "-") && fd_reopen (STDIN_FILENO, infile, O_RDONLY, 0) < 0) error (EXIT_FAILURE, errno, _("cannot open %s for reading"), - quote (infile)); + quote (infile)); /* Binary I/O is safer when bytecounts are used. */ if (O_BINARY && ! isatty (STDIN_FILENO)) diff --git a/src/stat.c b/src/stat.c index 63c5911c4..330227027 100644 --- a/src/stat.c +++ b/src/stat.c @@ -22,7 +22,7 @@ ../m4/stat-prog.m4. */ #if (STAT_STATVFS \ && (HAVE_STRUCT_STATVFS_F_BASETYPE || HAVE_STRUCT_STATVFS_F_FSTYPENAME \ - || (! HAVE_STRUCT_STATFS_F_FSTYPENAME && HAVE_STRUCT_STATVFS_F_TYPE))) + || (! HAVE_STRUCT_STATFS_F_FSTYPENAME && HAVE_STRUCT_STATVFS_F_TYPE))) # define USE_STATVFS 1 #else # define USE_STATVFS 0 @@ -96,11 +96,11 @@ statfs (char const *filename, struct fs_info *buf) if (device < 0) { errno = (device == B_ENTRY_NOT_FOUND ? ENOENT - : device == B_BAD_VALUE ? EINVAL - : device == B_NAME_TOO_LONG ? ENAMETOOLONG - : device == B_NO_MEMORY ? ENOMEM - : device == B_FILE_ERROR ? EIO - : 0); + : device == B_BAD_VALUE ? EINVAL + : device == B_NAME_TOO_LONG ? ENAMETOOLONG + : device == B_NO_MEMORY ? ENOMEM + : device == B_FILE_ERROR ? EIO + : 0); return -1; } /* If successful, buf->dev will be == device. */ @@ -145,7 +145,7 @@ statfs (char const *filename, struct fs_info *buf) #define isodigit(c) ('0' <= (c) && (c) <= '7') #define octtobin(c) ((c) - '0') #define hextobin(c) ((c) >= 'a' && (c) <= 'f' ? (c) - 'a' + 10 : \ - (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0') + (c) >= 'A' && (c) <= 'F' ? (c) - 'A' + 10 : (c) - '0') #define PROGRAM_NAME "stat" @@ -197,23 +197,23 @@ human_fstype (STRUCT_STATVFS const *statfsbuf) # if defined __linux__ /* Compare with what's in libc: - f=/a/libc/sysdeps/unix/sysv/linux/linux_fsinfo.h - sed -n '/ADFS_SUPER_MAGIC/,/SYSFS_MAGIC/p' $f \ - | perl -n -e '/#define (.*?)_(?:SUPER_)MAGIC\s+0x(\S+)/' \ - -e 'and print "case S_MAGIC_$1: /\* 0x" . uc($2) . " *\/\n"' \ - | sort > sym_libc - perl -ne '/^\s+(case S_MAGIC_.*?): \/\* 0x(\S+) \*\//' \ - -e 'and do { $v=uc$2; print "$1: /\* 0x$v *\/\n"}' stat.c \ - | sort > sym_stat - diff -u sym_stat sym_libc + f=/a/libc/sysdeps/unix/sysv/linux/linux_fsinfo.h + sed -n '/ADFS_SUPER_MAGIC/,/SYSFS_MAGIC/p' $f \ + | perl -n -e '/#define (.*?)_(?:SUPER_)MAGIC\s+0x(\S+)/' \ + -e 'and print "case S_MAGIC_$1: /\* 0x" . uc($2) . " *\/\n"' \ + | sort > sym_libc + perl -ne '/^\s+(case S_MAGIC_.*?): \/\* 0x(\S+) \*\//' \ + -e 'and do { $v=uc$2; print "$1: /\* 0x$v *\/\n"}' stat.c \ + | sort > sym_stat + diff -u sym_stat sym_libc */ /* Also sync from the list in "man 2 statfs". */ /* IMPORTANT NOTE: Each of the following `case S_MAGIC_...:' - statements must be followed by a hexadecimal constant in - a comment. The S_MAGIC_... name and constant are automatically - combined to produce the #define directives in fs.h. */ + statements must be followed by a hexadecimal constant in + a comment. The S_MAGIC_... name and constant are automatically + combined to produce the #define directives in fs.h. */ case S_MAGIC_ADFS: /* 0xADF5 */ return "adfs"; @@ -384,11 +384,11 @@ human_fstype (STRUCT_STATVFS const *statfsbuf) # endif default: { - unsigned long int type = statfsbuf->f_type; - static char buf[sizeof "UNKNOWN (0x%lx)" - 3 - + (sizeof type * CHAR_BIT + 3) / 4]; - sprintf (buf, "UNKNOWN (0x%lx)", type); - return buf; + unsigned long int type = statfsbuf->f_type; + static char buf[sizeof "UNKNOWN (0x%lx)" - 3 + + (sizeof type * CHAR_BIT + 3) / 4]; + sprintf (buf, "UNKNOWN (0x%lx)", type); + return buf; } } #endif @@ -407,9 +407,9 @@ static char * human_time (struct timespec t) { static char str[MAX (INT_BUFSIZE_BOUND (intmax_t), - (INT_STRLEN_BOUND (int) /* YYYY */ - + 1 /* because YYYY might equal INT_MAX + 1900 */ - + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +ZZZZ"))]; + (INT_STRLEN_BOUND (int) /* YYYY */ + + 1 /* because YYYY might equal INT_MAX + 1900 */ + + sizeof "-MM-DD HH:MM:SS.NNNNNNNNN +ZZZZ"))]; struct tm const *tm = localtime (&t.tv_sec); if (tm == NULL) return timetostr (t.tv_sec, str); @@ -459,7 +459,7 @@ out_file_context (char const *filename, char *pformat, size_t prefix_len) : lgetfilecon (filename, &scontext)) < 0) { error (0, errno, _("failed to get security context of %s"), - quote (filename)); + quote (filename)); scontext = NULL; } strcpy (pformat + prefix_len, "s"); @@ -471,7 +471,7 @@ out_file_context (char const *filename, char *pformat, size_t prefix_len) /* print statfs info */ static void print_statfs (char *pformat, size_t prefix_len, char m, char const *filename, - void const *data) + void const *data) { STRUCT_STATVFS const *statfsbuf = data; @@ -484,26 +484,26 @@ print_statfs (char *pformat, size_t prefix_len, char m, char const *filename, case 'i': { #if STRUCT_STATXFS_F_FSID_IS_INTEGER - uintmax_t fsid = statfsbuf->f_fsid; + uintmax_t fsid = statfsbuf->f_fsid; #else - typedef unsigned int fsid_word; - verify (alignof (STRUCT_STATVFS) % alignof (fsid_word) == 0); - verify (offsetof (STRUCT_STATVFS, f_fsid) % alignof (fsid_word) == 0); - verify (sizeof statfsbuf->f_fsid % alignof (fsid_word) == 0); - fsid_word const *p = (fsid_word *) &statfsbuf->f_fsid; - - /* Assume a little-endian word order, as that is compatible - with glibc's statvfs implementation. */ - uintmax_t fsid = 0; - int words = sizeof statfsbuf->f_fsid / sizeof *p; - int i; - for (i = 0; i < words && i * sizeof *p < sizeof fsid; i++) - { - uintmax_t u = p[words - 1 - i]; - fsid |= u << (i * CHAR_BIT * sizeof *p); - } + typedef unsigned int fsid_word; + verify (alignof (STRUCT_STATVFS) % alignof (fsid_word) == 0); + verify (offsetof (STRUCT_STATVFS, f_fsid) % alignof (fsid_word) == 0); + verify (sizeof statfsbuf->f_fsid % alignof (fsid_word) == 0); + fsid_word const *p = (fsid_word *) &statfsbuf->f_fsid; + + /* Assume a little-endian word order, as that is compatible + with glibc's statvfs implementation. */ + uintmax_t fsid = 0; + int words = sizeof statfsbuf->f_fsid / sizeof *p; + int i; + for (i = 0; i < words && i * sizeof *p < sizeof fsid; i++) + { + uintmax_t u = p[words - 1 - i]; + fsid |= u << (i * CHAR_BIT * sizeof *p); + } #endif - out_uint_x (pformat, prefix_len, fsid); + out_uint_x (pformat, prefix_len, fsid); } break; @@ -534,10 +534,10 @@ print_statfs (char *pformat, size_t prefix_len, char m, char const *filename, break; case 'S': { - uintmax_t frsize = STATFS_FRSIZE (statfsbuf); - if (! frsize) - frsize = statfsbuf->f_bsize; - out_uint (pformat, prefix_len, frsize); + uintmax_t frsize = STATFS_FRSIZE (statfsbuf); + if (! frsize) + frsize = statfsbuf->f_bsize; + out_uint (pformat, prefix_len, frsize); } break; case 'c': @@ -558,7 +558,7 @@ print_statfs (char *pformat, size_t prefix_len, char m, char const *filename, /* print stat info */ static void print_stat (char *pformat, size_t prefix_len, char m, - char const *filename, void const *data) + char const *filename, void const *data) { struct stat *statbuf = (struct stat *) data; struct passwd *pw_ent; @@ -572,17 +572,17 @@ print_stat (char *pformat, size_t prefix_len, char m, case 'N': out_string (pformat, prefix_len, quote (filename)); if (S_ISLNK (statbuf->st_mode)) - { - char *linkname = areadlink_with_size (filename, statbuf->st_size); - if (linkname == NULL) - { - error (0, errno, _("cannot read symbolic link %s"), - quote (filename)); - return; - } - printf (" -> "); - out_string (pformat, prefix_len, quote (linkname)); - } + { + char *linkname = areadlink_with_size (filename, statbuf->st_size); + if (linkname == NULL) + { + error (0, errno, _("cannot read symbolic link %s"), + quote (filename)); + return; + } + printf (" -> "); + out_string (pformat, prefix_len, quote (linkname)); + } break; case 'd': out_uint (pformat, prefix_len, statbuf->st_dev); @@ -615,7 +615,7 @@ print_stat (char *pformat, size_t prefix_len, char m, setpwent (); pw_ent = getpwuid (statbuf->st_uid); out_string (pformat, prefix_len, - pw_ent ? pw_ent->pw_name : "UNKNOWN"); + pw_ent ? pw_ent->pw_name : "UNKNOWN"); break; case 'g': out_uint (pformat, prefix_len, statbuf->st_gid); @@ -624,7 +624,7 @@ print_stat (char *pformat, size_t prefix_len, char m, setgrent (); gw_ent = getgrgid (statbuf->st_gid); out_string (pformat, prefix_len, - gw_ent ? gw_ent->gr_name : "UNKNOWN"); + gw_ent ? gw_ent->gr_name : "UNKNOWN"); break; case 't': out_uint_x (pformat, prefix_len, major (statbuf->st_rdev)); @@ -649,27 +649,27 @@ print_stat (char *pformat, size_t prefix_len, char m, break; case 'X': if (TYPE_SIGNED (time_t)) - out_int (pformat, prefix_len, statbuf->st_atime); + out_int (pformat, prefix_len, statbuf->st_atime); else - out_uint (pformat, prefix_len, statbuf->st_atime); + out_uint (pformat, prefix_len, statbuf->st_atime); break; case 'y': out_string (pformat, prefix_len, human_time (get_stat_mtime (statbuf))); break; case 'Y': if (TYPE_SIGNED (time_t)) - out_int (pformat, prefix_len, statbuf->st_mtime); + out_int (pformat, prefix_len, statbuf->st_mtime); else - out_uint (pformat, prefix_len, statbuf->st_mtime); + out_uint (pformat, prefix_len, statbuf->st_mtime); break; case 'z': out_string (pformat, prefix_len, human_time (get_stat_ctime (statbuf))); break; case 'Z': if (TYPE_SIGNED (time_t)) - out_int (pformat, prefix_len, statbuf->st_ctime); + out_int (pformat, prefix_len, statbuf->st_ctime); else - out_uint (pformat, prefix_len, statbuf->st_ctime); + out_uint (pformat, prefix_len, statbuf->st_ctime); break; case 'C': out_file_context (filename, pformat, prefix_len); @@ -720,17 +720,17 @@ print_esc_char (char c) static void print_it (char const *format, char const *filename, - void (*print_func) (char *, size_t, char, char const *, void const *), - void const *data) + void (*print_func) (char *, size_t, char, char const *, void const *), + void const *data) { /* Add 2 to accommodate our conversion of the stat `%s' format string to the longer printf `%llu' one. */ enum { MAX_ADDITIONAL_BYTES = - (MAX (sizeof PRIdMAX, - MAX (sizeof PRIoMAX, MAX (sizeof PRIuMAX, sizeof PRIxMAX))) - - 1) + (MAX (sizeof PRIdMAX, + MAX (sizeof PRIoMAX, MAX (sizeof PRIuMAX, sizeof PRIxMAX))) + - 1) }; size_t n_alloc = strlen (format) + MAX_ADDITIONAL_BYTES + 1; char *dest = xmalloc (n_alloc); @@ -738,85 +738,85 @@ print_it (char const *format, char const *filename, for (b = format; *b; b++) { switch (*b) - { - case '%': - { - size_t len = strspn (b + 1, "#-+.I 0123456789"); - char const *fmt_char = b + len + 1; - memcpy (dest, b, len + 1); - - b = fmt_char; - switch (*fmt_char) - { - case '\0': - --b; - /* fall through */ - case '%': - if (0 < len) - { - dest[len + 1] = *fmt_char; - dest[len + 2] = '\0'; - error (EXIT_FAILURE, 0, _("%s: invalid directive"), - quotearg_colon (dest)); - } - putchar ('%'); - break; - default: - print_func (dest, len + 1, *fmt_char, filename, data); - break; - } - break; - } - - case '\\': - if ( ! interpret_backslash_escapes) - { - putchar ('\\'); - break; - } - ++b; - if (isodigit (*b)) - { - int esc_value = octtobin (*b); - int esc_length = 1; /* number of octal digits */ - for (++b; esc_length < 3 && isodigit (*b); - ++esc_length, ++b) - { - esc_value = esc_value * 8 + octtobin (*b); - } - putchar (esc_value); - --b; - } - else if (*b == 'x' && isxdigit (to_uchar (b[1]))) - { - int esc_value = hextobin (b[1]); /* Value of \xhh escape. */ - /* A hexadecimal \xhh escape sequence must have - 1 or 2 hex. digits. */ - ++b; - if (isxdigit (to_uchar (b[1]))) - { - ++b; - esc_value = esc_value * 16 + hextobin (*b); - } - putchar (esc_value); - } - else if (*b == '\0') - { - error (0, 0, _("warning: backslash at end of format")); - putchar ('\\'); - /* Arrange to exit the loop. */ - --b; - } - else - { - print_esc_char (*b); - } - break; - - default: - putchar (*b); - break; - } + { + case '%': + { + size_t len = strspn (b + 1, "#-+.I 0123456789"); + char const *fmt_char = b + len + 1; + memcpy (dest, b, len + 1); + + b = fmt_char; + switch (*fmt_char) + { + case '\0': + --b; + /* fall through */ + case '%': + if (0 < len) + { + dest[len + 1] = *fmt_char; + dest[len + 2] = '\0'; + error (EXIT_FAILURE, 0, _("%s: invalid directive"), + quotearg_colon (dest)); + } + putchar ('%'); + break; + default: + print_func (dest, len + 1, *fmt_char, filename, data); + break; + } + break; + } + + case '\\': + if ( ! interpret_backslash_escapes) + { + putchar ('\\'); + break; + } + ++b; + if (isodigit (*b)) + { + int esc_value = octtobin (*b); + int esc_length = 1; /* number of octal digits */ + for (++b; esc_length < 3 && isodigit (*b); + ++esc_length, ++b) + { + esc_value = esc_value * 8 + octtobin (*b); + } + putchar (esc_value); + --b; + } + else if (*b == 'x' && isxdigit (to_uchar (b[1]))) + { + int esc_value = hextobin (b[1]); /* Value of \xhh escape. */ + /* A hexadecimal \xhh escape sequence must have + 1 or 2 hex. digits. */ + ++b; + if (isxdigit (to_uchar (b[1]))) + { + ++b; + esc_value = esc_value * 16 + hextobin (*b); + } + putchar (esc_value); + } + else if (*b == '\0') + { + error (0, 0, _("warning: backslash at end of format")); + putchar ('\\'); + /* Arrange to exit the loop. */ + --b; + } + else + { + print_esc_char (*b); + } + break; + + default: + putchar (*b); + break; + } } free (dest); @@ -832,19 +832,19 @@ do_statfs (char const *filename, bool terse, char const *format) if (STATFS (filename, &statfsbuf) != 0) { error (0, errno, _("cannot read file system information for %s"), - quote (filename)); + quote (filename)); return false; } if (format == NULL) { format = (terse - ? "%n %i %l %t %s %S %b %f %a %c %d\n" - : " File: \"%n\"\n" - " ID: %-8i Namelen: %-7l Type: %T\n" - "Block size: %-10s Fundamental block size: %S\n" - "Blocks: Total: %-10b Free: %-10f Available: %a\n" - "Inodes: Total: %-10c Free: %d\n"); + ? "%n %i %l %t %s %S %b %f %a %c %d\n" + : " File: \"%n\"\n" + " ID: %-8i Namelen: %-7l Type: %T\n" + "Block size: %-10s Fundamental block size: %S\n" + "Blocks: Total: %-10b Free: %-10f Available: %a\n" + "Inodes: Total: %-10c Free: %d\n"); } print_it (format, filename, print_statfs, &statfsbuf); @@ -866,33 +866,33 @@ do_stat (char const *filename, bool terse, char const *format) if (format == NULL) { if (terse) - { - format = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o\n"; - } + { + format = "%n %s %b %f %u %g %D %i %h %t %T %X %Y %Z %o\n"; + } else - { - /* Temporary hack to match original output until conditional - implemented. */ - if (S_ISBLK (statbuf.st_mode) || S_ISCHR (statbuf.st_mode)) - { - format = - " File: %N\n" - " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n" - "Device: %Dh/%dd\tInode: %-10i Links: %-5h" - " Device type: %t,%T\n" - "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n" - "Access: %x\n" "Modify: %y\n" "Change: %z\n"; - } - else - { - format = - " File: %N\n" - " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n" - "Device: %Dh/%dd\tInode: %-10i Links: %h\n" - "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n" - "Access: %x\n" "Modify: %y\n" "Change: %z\n"; - } - } + { + /* Temporary hack to match original output until conditional + implemented. */ + if (S_ISBLK (statbuf.st_mode) || S_ISCHR (statbuf.st_mode)) + { + format = + " File: %N\n" + " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n" + "Device: %Dh/%dd\tInode: %-10i Links: %-5h" + " Device type: %t,%T\n" + "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n" + "Access: %x\n" "Modify: %y\n" "Change: %z\n"; + } + else + { + format = + " File: %N\n" + " Size: %-10s\tBlocks: %-10b IO Block: %-6o %F\n" + "Device: %Dh/%dd\tInode: %-10i Links: %h\n" + "Access: (%04a/%10.10A) Uid: (%5u/%8U) Gid: (%5g/%8G)\n" + "Access: %x\n" "Modify: %y\n" "Change: %z\n"; + } + } } print_it (format, filename, print_stat, &statbuf); return true; @@ -903,7 +903,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... FILE...\n"), program_name); @@ -1009,47 +1009,47 @@ main (int argc, char *argv[]) while ((c = getopt_long (argc, argv, "c:fLtZ", long_options, NULL)) != -1) { switch (c) - { - case PRINTF_OPTION: - format = optarg; - interpret_backslash_escapes = true; - trailing_delim = ""; - break; - - case 'c': - format = optarg; - interpret_backslash_escapes = false; - trailing_delim = "\n"; - break; - - case 'L': - follow_links = true; - break; - - case 'f': - fs = true; - break; - - case 't': - terse = true; - break; - - case 'Z': /* FIXME: remove in 2010 */ - /* Ignore, for compatibility with distributions - that implemented this before upstream. - But warn of impending removal. */ - error (0, 0, - _("the --context (-Z) option is obsolete and will be removed\n" - "in a future release")); - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case PRINTF_OPTION: + format = optarg; + interpret_backslash_escapes = true; + trailing_delim = ""; + break; + + case 'c': + format = optarg; + interpret_backslash_escapes = false; + trailing_delim = "\n"; + break; + + case 'L': + follow_links = true; + break; + + case 'f': + fs = true; + break; + + case 't': + terse = true; + break; + + case 'Z': /* FIXME: remove in 2010 */ + /* Ignore, for compatibility with distributions + that implemented this before upstream. + But warn of impending removal. */ + error (0, 0, + _("the --context (-Z) option is obsolete and will be removed\n" + "in a future release")); + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (argc == optind) @@ -1060,8 +1060,8 @@ main (int argc, char *argv[]) for (i = optind; i < argc; i++) ok &= (fs - ? do_statfs (argv[i], terse, format) - : do_stat (argv[i], terse, format)); + ? do_statfs (argv[i], terse, format) + : do_stat (argv[i], terse, format)); exit (ok ? EXIT_SUCCESS : EXIT_FAILURE); } diff --git a/src/stty.c b/src/stty.c index 389ab9eb9..37aee2803 100644 --- a/src/stty.c +++ b/src/stty.c @@ -419,7 +419,7 @@ static unsigned long int baud_to_value (speed_t speed); static bool recover_mode (char const *arg, struct termios *mode); static int screen_columns (void); static bool set_mode (struct mode_info const *info, bool reversed, - struct termios *mode); + struct termios *mode); static unsigned long int integer_arg (const char *s, unsigned long int max); static speed_t string_to_baud (const char *arg); static tcflag_t *mode_type_flag (enum mode_type type, struct termios *mode); @@ -427,16 +427,16 @@ static void display_all (struct termios *mode, char const *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, - const char *device_name); + struct termios *mode, + const char *device_name); static void display_speed (struct termios *mode, bool fancy); static void display_window_size (bool fancy, char const *device_name); static void sane_mode (struct termios *mode); static void set_control_char (struct control_info const *info, - const char *arg, - struct termios *mode); + const char *arg, + struct termios *mode); static void set_speed (enum speed_setting type, const char *arg, - struct termios *mode); + struct termios *mode); static void set_window_size (int rows, int cols, char const *device_name); /* The width of the screen, for output wrapping. */ @@ -479,15 +479,15 @@ wrapf (const char *message,...) if (0 < current_col) { if (max_col - current_col < buflen) - { - putchar ('\n'); - current_col = 0; - } + { + putchar ('\n'); + current_col = 0; + } else - { - putchar (' '); - current_col++; - } + { + putchar (' '); + current_col++; + } } fputs (buf, stdout); @@ -500,7 +500,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -508,7 +508,7 @@ Usage: %s [-F DEVICE | --file=DEVICE] [SETTING]...\n\ or: %s [-F DEVICE | --file=DEVICE] [-a|--all]\n\ or: %s [-F DEVICE | --file=DEVICE] [-g|--save]\n\ "), - program_name, program_name, program_name); + program_name, program_name, program_name); fputs (_("\ Print or change terminal characteristics.\n\ \n\ @@ -764,60 +764,60 @@ main (int argc, char **argv) short and long options, --, POSIXLY_CORRECT, etc. */ while ((optc = getopt_long (argc - argi, argv + argi, "-agF:", - longopts, NULL)) - != -1) + longopts, NULL)) + != -1) { switch (optc) - { - case 'a': - verbose_output = true; - output_type = all; - break; + { + case 'a': + verbose_output = true; + output_type = all; + break; - case 'g': - recoverable_output = true; - output_type = recoverable; - break; + case 'g': + recoverable_output = true; + output_type = recoverable; + break; - case 'F': - if (file_name) - error (EXIT_FAILURE, 0, _("only one device may be specified")); - file_name = optarg; - break; + case 'F': + if (file_name) + error (EXIT_FAILURE, 0, _("only one device may be specified")); + file_name = optarg; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - noargs = false; + default: + noargs = false; - /* Skip the argument containing this unrecognized option; - the 2nd pass will analyze it. */ - argi += opti; + /* Skip the argument containing this unrecognized option; + the 2nd pass will analyze it. */ + argi += opti; - /* Restart getopt_long from the first unskipped argument. */ - opti = 1; - optind = 0; + /* Restart getopt_long from the first unskipped argument. */ + opti = 1; + optind = 0; - break; - } + break; + } /* Clear fully-parsed arguments, so they don't confuse the 2nd pass. */ while (opti < optind) - argv[argi + opti++] = NULL; + argv[argi + opti++] = NULL; } /* Specifying both -a and -g gets an error. */ if (verbose_output & recoverable_output) error (EXIT_FAILURE, 0, - _("the options for verbose and stty-readable output styles are\n" - "mutually exclusive")); + _("the options for verbose and stty-readable output styles are\n" + "mutually exclusive")); /* Specifying any other arguments with -a or -g gets an error. */ if (!noargs && (verbose_output | recoverable_output)) error (EXIT_FAILURE, 0, - _("when specifying an output style, modes may not be set")); + _("when specifying an output style, modes may not be set")); /* 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 @@ -829,11 +829,11 @@ main (int argc, char **argv) int fdflags; device_name = file_name; if (fd_reopen (STDIN_FILENO, device_name, O_RDONLY | O_NONBLOCK, 0) < 0) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); if ((fdflags = fcntl (STDIN_FILENO, F_GETFL)) == -1 - || fcntl (STDIN_FILENO, F_SETFL, fdflags & ~O_NONBLOCK) < 0) - error (EXIT_FAILURE, errno, _("%s: couldn't reset non-blocking mode"), - device_name); + || fcntl (STDIN_FILENO, F_SETFL, fdflags & ~O_NONBLOCK) < 0) + error (EXIT_FAILURE, errno, _("%s: couldn't reset non-blocking mode"), + device_name); } else device_name = _("standard input"); @@ -859,199 +859,199 @@ main (int argc, char **argv) int i; if (! arg) - continue; + continue; if (arg[0] == '-') - { - ++arg; - reversed = true; - } + { + ++arg; + reversed = true; + } for (i = 0; mode_info[i].name != NULL; ++i) - { - if (STREQ (arg, mode_info[i].name)) - { - match_found = set_mode (&mode_info[i], reversed, &mode); - require_set_attr = true; - break; - } - } + { + if (STREQ (arg, mode_info[i].name)) + { + match_found = set_mode (&mode_info[i], reversed, &mode); + require_set_attr = true; + break; + } + } if (!match_found & reversed) - { - error (0, 0, _("invalid argument %s"), quote (arg - 1)); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("invalid argument %s"), quote (arg - 1)); + usage (EXIT_FAILURE); + } if (!match_found) - { - for (i = 0; control_info[i].name != NULL; ++i) - { - if (STREQ (arg, control_info[i].name)) - { - if (k == argc - 1) - { - error (0, 0, _("missing argument to %s"), quote (arg)); - usage (EXIT_FAILURE); - } - match_found = true; - ++k; - set_control_char (&control_info[i], argv[k], &mode); - require_set_attr = true; - break; - } - } - } + { + for (i = 0; control_info[i].name != NULL; ++i) + { + if (STREQ (arg, control_info[i].name)) + { + if (k == argc - 1) + { + error (0, 0, _("missing argument to %s"), quote (arg)); + usage (EXIT_FAILURE); + } + match_found = true; + ++k; + set_control_char (&control_info[i], argv[k], &mode); + require_set_attr = true; + break; + } + } + } if (!match_found) - { - if (STREQ (arg, "ispeed")) - { - if (k == argc - 1) - { - error (0, 0, _("missing argument to %s"), quote (arg)); - usage (EXIT_FAILURE); - } - ++k; - set_speed (input_speed, argv[k], &mode); - speed_was_set = true; - require_set_attr = true; - } - else if (STREQ (arg, "ospeed")) - { - if (k == argc - 1) - { - error (0, 0, _("missing argument to %s"), quote (arg)); - usage (EXIT_FAILURE); - } - ++k; - set_speed (output_speed, argv[k], &mode); - speed_was_set = true; - require_set_attr = true; - } + { + if (STREQ (arg, "ispeed")) + { + if (k == argc - 1) + { + error (0, 0, _("missing argument to %s"), quote (arg)); + usage (EXIT_FAILURE); + } + ++k; + set_speed (input_speed, argv[k], &mode); + speed_was_set = true; + require_set_attr = true; + } + else if (STREQ (arg, "ospeed")) + { + if (k == argc - 1) + { + error (0, 0, _("missing argument to %s"), quote (arg)); + usage (EXIT_FAILURE); + } + ++k; + set_speed (output_speed, argv[k], &mode); + speed_was_set = true; + require_set_attr = true; + } #ifdef TIOCGWINSZ - else if (STREQ (arg, "rows")) - { - if (k == argc - 1) - { - error (0, 0, _("missing argument to %s"), quote (arg)); - usage (EXIT_FAILURE); - } - ++k; - set_window_size (integer_arg (argv[k], INT_MAX), -1, - device_name); - } - else if (STREQ (arg, "cols") - || STREQ (arg, "columns")) - { - if (k == argc - 1) - { - error (0, 0, _("missing argument to %s"), quote (arg)); - usage (EXIT_FAILURE); - } - ++k; - set_window_size (-1, integer_arg (argv[k], INT_MAX), - device_name); - } - else if (STREQ (arg, "size")) - { - max_col = screen_columns (); - current_col = 0; - display_window_size (false, device_name); - } + else if (STREQ (arg, "rows")) + { + if (k == argc - 1) + { + error (0, 0, _("missing argument to %s"), quote (arg)); + usage (EXIT_FAILURE); + } + ++k; + set_window_size (integer_arg (argv[k], INT_MAX), -1, + device_name); + } + else if (STREQ (arg, "cols") + || STREQ (arg, "columns")) + { + if (k == argc - 1) + { + error (0, 0, _("missing argument to %s"), quote (arg)); + usage (EXIT_FAILURE); + } + ++k; + set_window_size (-1, integer_arg (argv[k], INT_MAX), + device_name); + } + else if (STREQ (arg, "size")) + { + max_col = screen_columns (); + current_col = 0; + display_window_size (false, device_name); + } #endif #ifdef HAVE_C_LINE - else if (STREQ (arg, "line")) - { - unsigned long int value; - if (k == argc - 1) - { - error (0, 0, _("missing argument to %s"), quote (arg)); - usage (EXIT_FAILURE); - } - ++k; - mode.c_line = value = integer_arg (argv[k], ULONG_MAX); - if (mode.c_line != value) - error (0, 0, _("invalid line discipline %s"), quote (argv[k])); - require_set_attr = true; - } -#endif - else if (STREQ (arg, "speed")) - { - max_col = screen_columns (); - display_speed (&mode, false); - } - else if (string_to_baud (arg) != (speed_t) -1) - { - set_speed (both_speeds, arg, &mode); - speed_was_set = true; - require_set_attr = true; - } - else - { - if (! recover_mode (arg, &mode)) - { - error (0, 0, _("invalid argument %s"), quote (arg)); - usage (EXIT_FAILURE); - } - require_set_attr = true; - } - } + else if (STREQ (arg, "line")) + { + unsigned long int value; + if (k == argc - 1) + { + error (0, 0, _("missing argument to %s"), quote (arg)); + usage (EXIT_FAILURE); + } + ++k; + mode.c_line = value = integer_arg (argv[k], ULONG_MAX); + if (mode.c_line != value) + error (0, 0, _("invalid line discipline %s"), quote (argv[k])); + require_set_attr = true; + } +#endif + else if (STREQ (arg, "speed")) + { + max_col = screen_columns (); + display_speed (&mode, false); + } + else if (string_to_baud (arg) != (speed_t) -1) + { + set_speed (both_speeds, arg, &mode); + speed_was_set = true; + require_set_attr = true; + } + else + { + if (! recover_mode (arg, &mode)) + { + error (0, 0, _("invalid argument %s"), quote (arg)); + usage (EXIT_FAILURE); + } + require_set_attr = true; + } + } } if (require_set_attr) { /* Initialize to all zeroes so there is no risk memcmp will report a - spurious difference in an uninitialized portion of the structure. */ + spurious difference in an uninitialized portion of the structure. */ DECLARE_ZEROED_AGGREGATE (struct termios, new_mode); if (tcsetattr (STDIN_FILENO, TCSADRAIN, &mode)) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); /* POSIX (according to Zlotnick's book) tcsetattr returns zero if - it performs *any* of the requested operations. This means it - can report `success' when it has actually failed to perform - some proper subset of the requested operations. To detect - this partial failure, get the current terminal attributes and - compare them to the requested ones. */ + it performs *any* of the requested operations. This means it + can report `success' when it has actually failed to perform + some proper subset of the requested operations. To detect + this partial failure, get the current terminal attributes and + compare them to the requested ones. */ if (tcgetattr (STDIN_FILENO, &new_mode)) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); /* Normally, one shouldn't use memcmp to compare structures that - may have `holes' containing uninitialized data, but we have been - careful to initialize the storage of these two variables to all - zeroes. One might think it more efficient simply to compare the - modified fields, but that would require enumerating those fields -- - and not all systems have the same fields in this structure. */ + may have `holes' containing uninitialized data, but we have been + careful to initialize the storage of these two variables to all + zeroes. One might think it more efficient simply to compare the + modified fields, but that would require enumerating those fields -- + and not all systems have the same fields in this structure. */ if (memcmp (&mode, &new_mode, sizeof (mode)) != 0) - { + { #ifdef CIBAUD - /* SunOS 4.1.3 (at least) has the problem that after this sequence, - tcgetattr (&m1); tcsetattr (&m1); tcgetattr (&m2); - sometimes (m1 != m2). The only difference is in the four bits - of the c_cflag field corresponding to the baud rate. To save - Sun users a little confusion, don't report an error if this - happens. But suppress the error only if we haven't tried to - set the baud rate explicitly -- otherwise we'd never give an - error for a true failure to set the baud rate. */ - - new_mode.c_cflag &= (~CIBAUD); - if (speed_was_set || memcmp (&mode, &new_mode, sizeof (mode)) != 0) -#endif - { - error (EXIT_FAILURE, 0, - _("%s: unable to perform all requested operations"), - device_name); + /* SunOS 4.1.3 (at least) has the problem that after this sequence, + tcgetattr (&m1); tcsetattr (&m1); tcgetattr (&m2); + sometimes (m1 != m2). The only difference is in the four bits + of the c_cflag field corresponding to the baud rate. To save + Sun users a little confusion, don't report an error if this + happens. But suppress the error only if we haven't tried to + set the baud rate explicitly -- otherwise we'd never give an + error for a true failure to set the baud rate. */ + + new_mode.c_cflag &= (~CIBAUD); + if (speed_was_set || memcmp (&mode, &new_mode, sizeof (mode)) != 0) +#endif + { + error (EXIT_FAILURE, 0, + _("%s: unable to perform all requested operations"), + device_name); #ifdef TESTING - { - size_t i; - printf ("new_mode: mode\n"); - for (i = 0; i < sizeof (new_mode); i++) - printf ("0x%02x: 0x%02x\n", - *(((unsigned char *) &new_mode) + i), - *(((unsigned char *) &mode) + i)); - } -#endif - } - } + { + size_t i; + printf ("new_mode: mode\n"); + for (i = 0; i < sizeof (new_mode); i++) + printf ("0x%02x: 0x%02x\n", + *(((unsigned char *) &new_mode) + i), + *(((unsigned char *) &mode) + i)); + } +#endif + } + } } exit (EXIT_SUCCESS); @@ -1074,189 +1074,189 @@ set_mode (struct mode_info const *info, bool reversed, struct termios *mode) { /* Combination mode. */ if (STREQ (info->name, "evenp") || STREQ (info->name, "parity")) - { - if (reversed) - mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; - else - mode->c_cflag = (mode->c_cflag & ~PARODD & ~CSIZE) | PARENB | CS7; - } + { + if (reversed) + mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; + else + mode->c_cflag = (mode->c_cflag & ~PARODD & ~CSIZE) | PARENB | CS7; + } else if (STREQ (info->name, "oddp")) - { - if (reversed) - mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; - else - mode->c_cflag = (mode->c_cflag & ~CSIZE) | CS7 | PARODD | PARENB; - } + { + if (reversed) + mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; + else + mode->c_cflag = (mode->c_cflag & ~CSIZE) | CS7 | PARODD | PARENB; + } else if (STREQ (info->name, "nl")) - { - if (reversed) - { - mode->c_iflag = (mode->c_iflag | ICRNL) & ~INLCR & ~IGNCR; - mode->c_oflag = (mode->c_oflag + { + if (reversed) + { + mode->c_iflag = (mode->c_iflag | ICRNL) & ~INLCR & ~IGNCR; + mode->c_oflag = (mode->c_oflag #ifdef ONLCR - | ONLCR + | ONLCR #endif - ) + ) #ifdef OCRNL - & ~OCRNL + & ~OCRNL #endif #ifdef ONLRET - & ~ONLRET + & ~ONLRET #endif - ; - } - else - { - mode->c_iflag = mode->c_iflag & ~ICRNL; + ; + } + else + { + mode->c_iflag = mode->c_iflag & ~ICRNL; #ifdef ONLCR - mode->c_oflag = mode->c_oflag & ~ONLCR; + mode->c_oflag = mode->c_oflag & ~ONLCR; #endif - } - } + } + } else if (STREQ (info->name, "ek")) - { - mode->c_cc[VERASE] = CERASE; - mode->c_cc[VKILL] = CKILL; - } + { + mode->c_cc[VERASE] = CERASE; + mode->c_cc[VKILL] = CKILL; + } else if (STREQ (info->name, "sane")) - sane_mode (mode); + sane_mode (mode); else if (STREQ (info->name, "cbreak")) - { - if (reversed) - mode->c_lflag |= ICANON; - else - mode->c_lflag &= ~ICANON; - } + { + if (reversed) + mode->c_lflag |= ICANON; + else + mode->c_lflag &= ~ICANON; + } else if (STREQ (info->name, "pass8")) - { - if (reversed) - { - mode->c_cflag = (mode->c_cflag & ~CSIZE) | CS7 | PARENB; - mode->c_iflag |= ISTRIP; - } - else - { - mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; - mode->c_iflag &= ~ISTRIP; - } - } + { + if (reversed) + { + mode->c_cflag = (mode->c_cflag & ~CSIZE) | CS7 | PARENB; + mode->c_iflag |= ISTRIP; + } + else + { + mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; + mode->c_iflag &= ~ISTRIP; + } + } else if (STREQ (info->name, "litout")) - { - if (reversed) - { - mode->c_cflag = (mode->c_cflag & ~CSIZE) | CS7 | PARENB; - mode->c_iflag |= ISTRIP; - mode->c_oflag |= OPOST; - } - else - { - mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; - mode->c_iflag &= ~ISTRIP; - mode->c_oflag &= ~OPOST; - } - } + { + if (reversed) + { + mode->c_cflag = (mode->c_cflag & ~CSIZE) | CS7 | PARENB; + mode->c_iflag |= ISTRIP; + mode->c_oflag |= OPOST; + } + else + { + mode->c_cflag = (mode->c_cflag & ~PARENB & ~CSIZE) | CS8; + mode->c_iflag &= ~ISTRIP; + mode->c_oflag &= ~OPOST; + } + } else if (STREQ (info->name, "raw") || STREQ (info->name, "cooked")) - { - if ((info->name[0] == 'r' && reversed) - || (info->name[0] == 'c' && !reversed)) - { - /* Cooked mode. */ - mode->c_iflag |= BRKINT | IGNPAR | ISTRIP | ICRNL | IXON; - mode->c_oflag |= OPOST; - mode->c_lflag |= ISIG | ICANON; + { + if ((info->name[0] == 'r' && reversed) + || (info->name[0] == 'c' && !reversed)) + { + /* Cooked mode. */ + mode->c_iflag |= BRKINT | IGNPAR | ISTRIP | ICRNL | IXON; + mode->c_oflag |= OPOST; + mode->c_lflag |= ISIG | ICANON; #if VMIN == VEOF - mode->c_cc[VEOF] = CEOF; + mode->c_cc[VEOF] = CEOF; #endif #if VTIME == VEOL - mode->c_cc[VEOL] = CEOL; -#endif - } - else - { - /* Raw mode. */ - mode->c_iflag = 0; - mode->c_oflag &= ~OPOST; - mode->c_lflag &= ~(ISIG | ICANON + mode->c_cc[VEOL] = CEOL; +#endif + } + else + { + /* Raw mode. */ + mode->c_iflag = 0; + mode->c_oflag &= ~OPOST; + mode->c_lflag &= ~(ISIG | ICANON #ifdef XCASE - | XCASE + | XCASE #endif - ); - mode->c_cc[VMIN] = 1; - mode->c_cc[VTIME] = 0; - } - } + ); + mode->c_cc[VMIN] = 1; + mode->c_cc[VTIME] = 0; + } + } #ifdef IXANY else if (STREQ (info->name, "decctlq")) - { - if (reversed) - mode->c_iflag |= IXANY; - else - mode->c_iflag &= ~IXANY; - } + { + if (reversed) + mode->c_iflag |= IXANY; + else + mode->c_iflag &= ~IXANY; + } #endif #ifdef TABDLY else if (STREQ (info->name, "tabs")) - { - if (reversed) - mode->c_oflag = (mode->c_oflag & ~TABDLY) | TAB3; - else - mode->c_oflag = (mode->c_oflag & ~TABDLY) | TAB0; - } + { + if (reversed) + mode->c_oflag = (mode->c_oflag & ~TABDLY) | TAB3; + else + mode->c_oflag = (mode->c_oflag & ~TABDLY) | TAB0; + } #else # ifdef OXTABS else if (STREQ (info->name, "tabs")) - { - if (reversed) - mode->c_oflag = mode->c_oflag | OXTABS; - else - mode->c_oflag = mode->c_oflag & ~OXTABS; - } + { + if (reversed) + mode->c_oflag = mode->c_oflag | OXTABS; + else + mode->c_oflag = mode->c_oflag & ~OXTABS; + } # endif #endif #if defined XCASE && defined IUCLC && defined OLCUC else if (STREQ (info->name, "lcase") - || STREQ (info->name, "LCASE")) - { - if (reversed) - { - mode->c_lflag &= ~XCASE; - mode->c_iflag &= ~IUCLC; - mode->c_oflag &= ~OLCUC; - } - else - { - mode->c_lflag |= XCASE; - mode->c_iflag |= IUCLC; - mode->c_oflag |= OLCUC; - } - } + || STREQ (info->name, "LCASE")) + { + if (reversed) + { + mode->c_lflag &= ~XCASE; + mode->c_iflag &= ~IUCLC; + mode->c_oflag &= ~OLCUC; + } + else + { + mode->c_lflag |= XCASE; + mode->c_iflag |= IUCLC; + mode->c_oflag |= OLCUC; + } + } #endif else if (STREQ (info->name, "crt")) - mode->c_lflag |= ECHOE + mode->c_lflag |= ECHOE #ifdef ECHOCTL - | ECHOCTL + | ECHOCTL #endif #ifdef ECHOKE - | ECHOKE + | ECHOKE #endif - ; + ; else if (STREQ (info->name, "dec")) - { - mode->c_cc[VINTR] = 3; /* ^C */ - mode->c_cc[VERASE] = 127; /* DEL */ - mode->c_cc[VKILL] = 21; /* ^U */ - mode->c_lflag |= ECHOE + { + mode->c_cc[VINTR] = 3; /* ^C */ + mode->c_cc[VERASE] = 127; /* DEL */ + mode->c_cc[VKILL] = 21; /* ^U */ + mode->c_lflag |= ECHOE #ifdef ECHOCTL - | ECHOCTL + | ECHOCTL #endif #ifdef ECHOKE - | ECHOKE + | ECHOKE #endif - ; + ; #ifdef IXANY - mode->c_iflag &= ~IXANY; + mode->c_iflag &= ~IXANY; #endif - } + } } else if (reversed) *bitsp = *bitsp & ~info->mask & ~info->bits; @@ -1268,7 +1268,7 @@ set_mode (struct mode_info const *info, bool reversed, struct termios *mode) static void set_control_char (struct control_info const *info, const char *arg, - struct termios *mode) + struct termios *mode) { unsigned long int value; @@ -1281,9 +1281,9 @@ set_control_char (struct control_info const *info, const char *arg, else if (arg[0] == '^' && arg[1] != '\0') /* Ignore any trailing junk. */ { if (arg[1] == '?') - value = 127; + value = 127; else - value = to_uchar (arg[1]) & ~0140; /* Non-letters get weird results. */ + value = to_uchar (arg[1]) & ~0140; /* Non-letters get weird results. */ } else value = integer_arg (arg, TYPE_MAXIMUM (cc_t)); @@ -1319,7 +1319,7 @@ set_window_size (int rows, int cols, char const *device_name) if (get_win_size (STDIN_FILENO, &win)) { if (errno != EINVAL) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); memset (&win, 0, sizeof (win)); } @@ -1361,10 +1361,10 @@ set_window_size (int rows, int cols, char const *device_name) win.ws_col = 1; if (ioctl (STDIN_FILENO, TIOCSWINSZ, (char *) &win)) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); if (ioctl (STDIN_FILENO, TIOCSSIZE, (char *) &ttysz)) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); return; } # endif @@ -1381,17 +1381,17 @@ display_window_size (bool fancy, char const *device_name) if (get_win_size (STDIN_FILENO, &win)) { if (errno != EINVAL) - error (EXIT_FAILURE, errno, "%s", device_name); + error (EXIT_FAILURE, errno, "%s", device_name); if (!fancy) - error (EXIT_FAILURE, 0, - _("%s: no size information for this device"), device_name); + error (EXIT_FAILURE, 0, + _("%s: no size information for this device"), device_name); } else { wrapf (fancy ? "rows %d; columns %d;" : "%d %d\n", - win.ws_row, win.ws_col); + win.ws_row, win.ws_col); if (!fancy) - current_col = 0; + current_col = 0; } } #endif @@ -1416,9 +1416,9 @@ screen_columns (void) char *col_string = getenv ("COLUMNS"); long int n_columns; if (!(col_string != NULL - && xstrtol (col_string, NULL, 0, &n_columns, "") == LONGINT_OK - && 0 < n_columns - && n_columns <= INT_MAX)) + && xstrtol (col_string, NULL, 0, &n_columns, "") == LONGINT_OK + && 0 < n_columns + && n_columns <= INT_MAX)) n_columns = 80; return n_columns; } @@ -1451,7 +1451,7 @@ mode_type_flag (enum mode_type type, struct termios *mode) static void display_settings (enum output_type output_type, struct termios *mode, - char const *device_name) + char const *device_name) { switch (output_type) { @@ -1489,29 +1489,29 @@ display_changed (struct termios *mode) for (i = 0; !STREQ (control_info[i].name, "min"); ++i) { if (mode->c_cc[control_info[i].offset] == control_info[i].saneval) - continue; + continue; /* If swtch is the same as susp, don't print both. */ #if VSWTCH == VSUSP if (STREQ (control_info[i].name, "swtch")) - continue; + continue; #endif /* If eof uses the same slot as min, only print whichever applies. */ #if VEOF == VMIN if ((mode->c_lflag & ICANON) == 0 - && (STREQ (control_info[i].name, "eof") - || STREQ (control_info[i].name, "eol"))) - continue; + && (STREQ (control_info[i].name, "eof") + || STREQ (control_info[i].name, "eol"))) + continue; #endif empty_line = false; wrapf ("%s = %s;", control_info[i].name, - visible (mode->c_cc[control_info[i].offset])); + visible (mode->c_cc[control_info[i].offset])); } if ((mode->c_lflag & ICANON) == 0) { wrapf ("min = %lu; time = %lu;\n", - (unsigned long int) mode->c_cc[VMIN], - (unsigned long int) mode->c_cc[VTIME]); + (unsigned long int) mode->c_cc[VMIN], + (unsigned long int) mode->c_cc[VTIME]); } else if (!empty_line) putchar ('\n'); @@ -1521,33 +1521,33 @@ display_changed (struct termios *mode) for (i = 0; mode_info[i].name != NULL; ++i) { if (mode_info[i].flags & OMIT) - continue; + continue; if (mode_info[i].type != prev_type) - { - if (!empty_line) - { - putchar ('\n'); - current_col = 0; - empty_line = true; - } - prev_type = mode_info[i].type; - } + { + if (!empty_line) + { + putchar ('\n'); + current_col = 0; + empty_line = true; + } + prev_type = mode_info[i].type; + } bitsp = mode_type_flag (mode_info[i].type, mode); mask = mode_info[i].mask ? mode_info[i].mask : mode_info[i].bits; if ((*bitsp & mask) == mode_info[i].bits) - { - if (mode_info[i].flags & SANE_UNSET) - { - wrapf ("%s", mode_info[i].name); - empty_line = false; - } - } + { + if (mode_info[i].flags & SANE_UNSET) + { + wrapf ("%s", mode_info[i].name); + empty_line = false; + } + } else if ((mode_info[i].flags & (SANE_SET | REV)) == (SANE_SET | REV)) - { - wrapf ("-%s", mode_info[i].name); - empty_line = false; - } + { + wrapf ("-%s", mode_info[i].name); + empty_line = false; + } } if (!empty_line) putchar ('\n'); @@ -1577,24 +1577,24 @@ display_all (struct termios *mode, char const *device_name) /* If swtch is the same as susp, don't print both. */ #if VSWTCH == VSUSP if (STREQ (control_info[i].name, "swtch")) - continue; + continue; #endif /* If eof uses the same slot as min, only print whichever applies. */ #if VEOF == VMIN if ((mode->c_lflag & ICANON) == 0 - && (STREQ (control_info[i].name, "eof") - || STREQ (control_info[i].name, "eol"))) - continue; + && (STREQ (control_info[i].name, "eof") + || STREQ (control_info[i].name, "eol"))) + continue; #endif wrapf ("%s = %s;", control_info[i].name, - visible (mode->c_cc[control_info[i].offset])); + visible (mode->c_cc[control_info[i].offset])); } #if VEOF == VMIN if ((mode->c_lflag & ICANON) == 0) #endif wrapf ("min = %lu; time = %lu;", - (unsigned long int) mode->c_cc[VMIN], - (unsigned long int) mode->c_cc[VTIME]); + (unsigned long int) mode->c_cc[VMIN], + (unsigned long int) mode->c_cc[VTIME]); if (current_col != 0) putchar ('\n'); current_col = 0; @@ -1602,20 +1602,20 @@ display_all (struct termios *mode, char const *device_name) for (i = 0; mode_info[i].name != NULL; ++i) { if (mode_info[i].flags & OMIT) - continue; + continue; if (mode_info[i].type != prev_type) - { - putchar ('\n'); - current_col = 0; - prev_type = mode_info[i].type; - } + { + putchar ('\n'); + current_col = 0; + prev_type = mode_info[i].type; + } bitsp = mode_type_flag (mode_info[i].type, mode); mask = mode_info[i].mask ? mode_info[i].mask : mode_info[i].bits; if ((*bitsp & mask) == mode_info[i].bits) - wrapf ("%s", mode_info[i].name); + wrapf ("%s", mode_info[i].name); else if (mode_info[i].flags & REV) - wrapf ("-%s", mode_info[i].name); + wrapf ("-%s", mode_info[i].name); } putchar ('\n'); current_col = 0; @@ -1626,11 +1626,11 @@ display_speed (struct termios *mode, bool fancy) { if (cfgetispeed (mode) == 0 || cfgetispeed (mode) == cfgetospeed (mode)) wrapf (fancy ? "speed %lu baud;" : "%lu\n", - baud_to_value (cfgetospeed (mode))); + 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))); + baud_to_value (cfgetispeed (mode)), + baud_to_value (cfgetospeed (mode))); if (!fancy) current_col = 0; } @@ -1641,10 +1641,10 @@ display_recoverable (struct termios *mode) size_t i; printf ("%lx:%lx:%lx:%lx", - (unsigned long int) mode->c_iflag, - (unsigned long int) mode->c_oflag, - (unsigned long int) mode->c_cflag, - (unsigned long int) mode->c_lflag); + (unsigned long int) mode->c_iflag, + (unsigned long int) mode->c_oflag, + (unsigned long int) mode->c_cflag, + (unsigned long int) mode->c_lflag); for (i = 0; i < NCCS; ++i) printf (":%lx", (unsigned long int) mode->c_cc[i]); putchar ('\n'); @@ -1653,7 +1653,7 @@ display_recoverable (struct termios *mode) /* NOTE: identical to below, modulo use of tcflag_t */ static int strtoul_tcflag_t (char const *s, int base, char **p, tcflag_t *result, - char delim) + char delim) { unsigned long ul; errno = 0; @@ -1689,7 +1689,7 @@ recover_mode (char const *arg, struct termios *mode) { char *p; if (strtoul_tcflag_t (s, 16, &p, flag + i, ':') != 0) - return false; + return false; s = p + 1; } mode->c_iflag = flag[0]; @@ -1702,7 +1702,7 @@ recover_mode (char const *arg, struct termios *mode) char *p; char delim = i < NCCS - 1 ? ':' : '\0'; if (strtoul_cc_t (s, 16, &p, mode->c_cc + i, delim) != 0) - return false; + return false; s = p + 1; } @@ -1817,7 +1817,7 @@ sane_mode (struct termios *mode) { #if VMIN == VEOF if (STREQ (control_info[i].name, "min")) - break; + break; #endif mode->c_cc[control_info[i].offset] = control_info[i].saneval; } @@ -1825,15 +1825,15 @@ sane_mode (struct termios *mode) for (i = 0; mode_info[i].name != NULL; ++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 = mode_type_flag (mode_info[i].type, mode); + *bitsp = (*bitsp & ~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 = mode_type_flag (mode_info[i].type, mode); + *bitsp = *bitsp & ~mode_info[i].mask & ~mode_info[i].bits; + } } } @@ -1852,32 +1852,32 @@ visible (cc_t ch) if (ch >= 32) { if (ch < 127) - *bpout++ = ch; + *bpout++ = ch; else if (ch == 127) - { - *bpout++ = '^'; - *bpout++ = '?'; - } + { + *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; - } - } + { + *bpout++ = 'M'; + *bpout++ = '-'; + if (ch >= 128 + 32) + { + if (ch < 128 + 127) + *bpout++ = ch - 128; + else + { + *bpout++ = '^'; + *bpout++ = '?'; + } + } + else + { + *bpout++ = '^'; + *bpout++ = ch - 128 + 64; + } + } } else { @@ -184,7 +184,7 @@ log_su (struct passwd const *pw, bool successful) if (!old_user) { /* getlogin can fail -- usually due to lack of utmp entry. - Resort to getpwuid. */ + Resort to getpwuid. */ struct passwd *pwd = getpwuid (getuid ()); old_user = (pwd ? pwd->pw_name : ""); } @@ -194,20 +194,20 @@ log_su (struct passwd const *pw, bool successful) /* 4.2BSD openlog doesn't have the third parameter. */ openlog (last_component (program_name), 0 # ifdef LOG_AUTH - , LOG_AUTH + , LOG_AUTH # endif - ); + ); syslog (LOG_NOTICE, # ifdef SYSLOG_NON_ROOT - "%s(to %s) %s on %s", + "%s(to %s) %s on %s", # else - "%s%s on %s", + "%s%s on %s", # endif - successful ? "" : "FAILED SU ", + successful ? "" : "FAILED SU ", # ifdef SYSLOG_NON_ROOT - new_user, + new_user, # endif - old_user, tty); + old_user, tty); closelog (); } #endif @@ -258,33 +258,33 @@ modify_environment (const struct passwd *pw, const char *shell) Unset all other environment variables. */ char const *term = getenv ("TERM"); if (term) - term = xstrdup (term); + term = xstrdup (term); environ = xmalloc ((6 + !!term) * sizeof (char *)); environ[0] = NULL; if (term) - xsetenv ("TERM", term); + xsetenv ("TERM", term); xsetenv ("HOME", pw->pw_dir); xsetenv ("SHELL", shell); xsetenv ("USER", pw->pw_name); xsetenv ("LOGNAME", pw->pw_name); xsetenv ("PATH", (pw->pw_uid - ? DEFAULT_LOGIN_PATH - : DEFAULT_ROOT_LOGIN_PATH)); + ? DEFAULT_LOGIN_PATH + : DEFAULT_ROOT_LOGIN_PATH)); } else { /* Set HOME, SHELL, and if not becoming a super-user, - USER and LOGNAME. */ + USER and LOGNAME. */ if (change_environment) - { - xsetenv ("HOME", pw->pw_dir); - xsetenv ("SHELL", shell); - if (pw->pw_uid) - { - xsetenv ("USER", pw->pw_name); - xsetenv ("LOGNAME", pw->pw_name); - } - } + { + xsetenv ("HOME", pw->pw_dir); + xsetenv ("SHELL", shell); + if (pw->pw_uid) + { + xsetenv ("USER", pw->pw_name); + xsetenv ("LOGNAME", pw->pw_name); + } + } } } @@ -312,7 +312,7 @@ change_identity (const struct passwd *pw) static void run_shell (char const *shell, char const *command, char **additional_args, - size_t n_additional_args) + size_t n_additional_args) { size_t n_args = 1 + fast_startup + 2 * !!command + n_additional_args + 1; char const **args = xnmalloc (n_args, sizeof *args); @@ -361,10 +361,10 @@ restricted_shell (const char *shell) while ((line = getusershell ()) != NULL) { if (*line != '#' && STREQ (line, shell)) - { - endusershell (); - return false; - } + { + endusershell (); + return false; + } } endusershell (); return true; @@ -375,7 +375,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [-] [USER [ARG]...]\n"), program_name); @@ -426,35 +426,35 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "c:flmps:", longopts, NULL)) != -1) { switch (optc) - { - case 'c': - command = optarg; - break; + { + case 'c': + command = optarg; + break; - case 'f': - fast_startup = true; - break; + case 'f': + fast_startup = true; + break; - case 'l': - simulate_login = true; - break; + case 'l': + simulate_login = true; + break; - case 'm': - case 'p': - change_environment = false; - break; + case 'm': + case 'p': + change_environment = false; + break; - case 's': - shell = optarg; - break; + case 's': + shell = optarg; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (optind < argc && STREQ (argv[optind], "-")) @@ -467,7 +467,7 @@ main (int argc, char **argv) pw = getpwnam (new_user); if (! (pw && pw->pw_name && pw->pw_name[0] && pw->pw_dir && pw->pw_dir[0] - && pw->pw_passwd)) + && pw->pw_passwd)) error (EXIT_FAILURE, 0, _("user %s does not exist"), new_user); /* Make a copy of the password information and point pw at the local @@ -482,8 +482,8 @@ main (int argc, char **argv) pw->pw_passwd = xstrdup (pw->pw_passwd); pw->pw_dir = xstrdup (pw->pw_dir); pw->pw_shell = xstrdup (pw->pw_shell && pw->pw_shell[0] - ? pw->pw_shell - : DEFAULT_SHELL); + ? pw->pw_shell + : DEFAULT_SHELL); endpwent (); if (!correct_password (pw)) @@ -505,9 +505,9 @@ main (int argc, char **argv) if (shell && getuid () != 0 && restricted_shell (pw->pw_shell)) { /* The user being su'd to has a nonstandard shell, and so is - probably a uucp account or has restricted access. Don't - compromise the account by allowing access with a standard - shell. */ + probably a uucp account or has restricted access. Don't + compromise the account by allowing access with a standard + shell. */ error (0, 0, _("using restricted shell %s"), pw->pw_shell); shell = NULL; } @@ -53,13 +53,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Print checksum and block counts for each FILE.\n\ \n\ @@ -98,16 +98,16 @@ bsd_sum_file (const char *file, int print_name) fp = stdin; have_read_stdin = true; if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); } else { fp = fopen (file, (O_BINARY ? "rb" : "r")); if (fp == NULL) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } } while ((ch = getc (fp)) != EOF) @@ -122,7 +122,7 @@ bsd_sum_file (const char *file, int print_name) { error (0, errno, "%s", file); if (!is_stdin) - fclose (fp); + fclose (fp); return false; } @@ -133,7 +133,7 @@ bsd_sum_file (const char *file, int print_name) } printf ("%05d %5s", checksum, - human_readable (total_bytes, hbuf, human_ceiling, 1, 1024)); + human_readable (total_bytes, hbuf, human_ceiling, 1, 1024)); if (print_name > 1) printf (" %s", file); putchar ('\n'); @@ -166,16 +166,16 @@ sysv_sum_file (const char *file, int print_name) fd = STDIN_FILENO; have_read_stdin = true; if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); } else { fd = open (file, O_RDONLY | O_BINARY); if (fd == -1) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } } while (1) @@ -184,18 +184,18 @@ sysv_sum_file (const char *file, int print_name) size_t bytes_read = safe_read (fd, buf, sizeof buf); if (bytes_read == 0) - break; + break; if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", file); - if (!is_stdin) - close (fd); - return false; - } + { + error (0, errno, "%s", file); + if (!is_stdin) + close (fd); + return false; + } for (i = 0; i < bytes_read; i++) - s += buf[i]; + s += buf[i]; total_bytes += bytes_read; } @@ -209,7 +209,7 @@ sysv_sum_file (const char *file, int print_name) checksum = (r & 0xffff) + (r >> 16); printf ("%d %s", checksum, - human_readable (total_bytes, hbuf, human_ceiling, 1, 512)); + human_readable (total_bytes, hbuf, human_ceiling, 1, 512)); if (print_name) printf (" %s", file); putchar ('\n'); @@ -238,22 +238,22 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "rs", longopts, NULL)) != -1) { switch (optc) - { - case 'r': /* For SysV compatibility. */ - sum_func = bsd_sum_file; - break; + { + case 'r': /* For SysV compatibility. */ + sum_func = bsd_sum_file; + break; - case 's': - sum_func = sysv_sum_file; - break; + case 's': + sum_func = sysv_sum_file; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } files_given = argc - optind; diff --git a/src/sync.c b/src/sync.c index 318f87675..593071347 100644 --- a/src/sync.c +++ b/src/sync.c @@ -35,7 +35,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]\n"), program_name); @@ -62,7 +62,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); diff --git a/src/system.h b/src/system.h index 74d86bbee..3a0550122 100644 --- a/src/system.h +++ b/src/system.h @@ -188,8 +188,8 @@ enum anyone knows of a system for which this limit is too small, please report it as a bug in this code. */ # define ST_BLKSIZE(statbuf) ((0 < (statbuf).st_blksize \ - && (statbuf).st_blksize <= SIZE_MAX / 8 + 1) \ - ? (statbuf).st_blksize : DEV_BSIZE) + && (statbuf).st_blksize <= SIZE_MAX / 8 + 1) \ + ? (statbuf).st_blksize : DEV_BSIZE) # if defined hpux || defined __hpux__ || defined __hpux /* HP-UX counts st_blocks in 1024-byte units. This loses when mixing HP-UX and BSD file systems with NFS. */ @@ -335,7 +335,7 @@ uid_t getuid (); Ensure that sizeof *(P) is *not* 1. In that case, it'd be better to use X2REALLOC, although not strictly necessary. */ #define X2NREALLOC(P, PN) ((void) verify_true (sizeof *(P) != 1), \ - x2nrealloc (P, PN, sizeof *(P))) + x2nrealloc (P, PN, sizeof *(P))) /* Using x2realloc (when appropriate) usually makes your code more readable than using x2nrealloc, but it also makes it so your @@ -370,7 +370,7 @@ readdir_ignoring_dot_and_dotdot (DIR *dirp) { struct dirent const *dp = readdir (dirp); if (dp == NULL || ! dot_or_dotdot (dp->d_name)) - return dp; + return dp; } } @@ -382,8 +382,8 @@ is_empty_dir (int fd_cwd, char const *dir) struct dirent const *dp; int saved_errno; int fd = openat (fd_cwd, dir, - (O_RDONLY | O_DIRECTORY - | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK)); + (O_RDONLY | O_DIRECTORY + | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK)); if (fd < 0) return false; @@ -621,22 +621,22 @@ static inline void emit_bug_reporting_address (void) { printf (_("\nReport %s bugs to %s\n"), last_component (program_name), - PACKAGE_BUGREPORT); + PACKAGE_BUGREPORT); /* FIXME 2010: use AC_PACKAGE_URL once we require autoconf-2.64 */ printf (_("%s home page: <http://www.gnu.org/software/%s/>\n"), - PACKAGE_NAME, PACKAGE); + PACKAGE_NAME, PACKAGE); fputs (_("General help using GNU software: <http://www.gnu.org/gethelp/>\n"), - stdout); + stdout); if (hard_locale (LC_MESSAGES)) { /* TRANSLATORS: Replace LANG_CODE in this URL with your language code - <http://translationproject.org/team/LANG_CODE.html> to form one of - the URLs at http://translationproject.org/team/. Otherwise, replace - the entire URL with your translation team's email address. */ + <http://translationproject.org/team/LANG_CODE.html> to form one of + the URLs at http://translationproject.org/team/. Otherwise, replace + the entire URL with your translation team's email address. */ printf (_("Report %s translation bugs to " - "<http://translationproject.org/team/>\n"), - last_component (program_name)); + "<http://translationproject.org/team/>\n"), + last_component (program_name)); } } @@ -646,8 +646,8 @@ static inline char * timetostr (time_t t, char *buf) { return (TYPE_SIGNED (time_t) - ? imaxtostr (t, buf) - : umaxtostr (t, buf)); + ? imaxtostr (t, buf) + : umaxtostr (t, buf)); } static inline char * diff --git a/src/tac-pipe.c b/src/tac-pipe.c index 17e86c070..1612e2d48 100644 --- a/src/tac-pipe.c +++ b/src/tac-pipe.c @@ -62,52 +62,52 @@ buf_init_from_stdin (Buf *x, char eol_byte) size_t bytes_read; if (buf == NULL) - { - /* Fall back on the code that relies on a temporary file. - Write all buffers to that file and free them. */ - /* FIXME */ - ok = false; - break; - } + { + /* Fall back on the code that relies on a temporary file. + Write all buffers to that file and free them. */ + /* FIXME */ + ok = false; + break; + } bytes_read = full_read (STDIN_FILENO, buf, BUFFER_SIZE); if (bytes_read != buffer_size && errno != 0) - error (EXIT_FAILURE, errno, _("read error")); + error (EXIT_FAILURE, errno, _("read error")); { - struct B_pair bp; - bp.start = buf; - bp.one_past_end = buf + bytes_read; - obstack_grow (OBS, &bp, sizeof (bp)); + struct B_pair bp; + bp.start = buf; + bp.one_past_end = buf + bytes_read; + obstack_grow (OBS, &bp, sizeof (bp)); } if (bytes_read != 0) - last_byte_is_eol_byte = (buf[bytes_read - 1] == eol_byte); + last_byte_is_eol_byte = (buf[bytes_read - 1] == eol_byte); if (bytes_read < BUFFER_SIZE) - break; + break; } if (ok) { /* If the file was non-empty and lacked an EOL_BYTE at its end, - then add a buffer containing just that one byte. */ + then add a buffer containing just that one byte. */ if (!last_byte_is_eol_byte) - { - char *buf = malloc (1); - if (buf == NULL) - { - /* FIXME: just like above */ - ok = false; - } - else - { - struct B_pair bp; - *buf = eol_byte; - bp.start = buf; - bp.one_past_end = buf + 1; - obstack_grow (OBS, &bp, sizeof (bp)); - } - } + { + char *buf = malloc (1); + if (buf == NULL) + { + /* FIXME: just like above */ + ok = false; + } + else + { + struct B_pair bp; + *buf = eol_byte; + bp.start = buf; + bp.one_past_end = buf + 1; + obstack_grow (OBS, &bp, sizeof (bp)); + } + } } x->n_bufs = obstack_object_size (OBS) / sizeof (x->p[0]); @@ -172,7 +172,7 @@ line_ptr_increment (const Buf *x, const Line_ptr *lp) static bool find_bol (const Buf *x, - const Line_ptr *last_bol, Line_ptr *new_bol, char eol_byte) + const Line_ptr *last_bol, Line_ptr *new_bol, char eol_byte) { size_t i; Line_ptr tmp; @@ -188,16 +188,16 @@ find_bol (const Buf *x, { char *nl = memrchr (x->p[i].start, last_bol_ptr, eol_byte); if (nl) - { - Line_ptr nl_pos; - nl_pos.i = i; - nl_pos.ptr = nl; - *new_bol = line_ptr_increment (x, &nl_pos); - return true; - } + { + Line_ptr nl_pos; + nl_pos.i = i; + nl_pos.ptr = nl; + *new_bol = line_ptr_increment (x, &nl_pos); + return true; + } if (i == 0) - break; + break; --i; last_bol_ptr = ONE_PAST_END (x, i); @@ -218,7 +218,7 @@ find_bol (const Buf *x, static void print_line (FILE *out_stream, const Buf *x, - const Line_ptr *bol, const Line_ptr *bol_next) + const Line_ptr *bol, const Line_ptr *bol_next) { size_t i; for (i = bol->i; i <= bol_next->i; i++) @@ -254,7 +254,7 @@ tac_mem () { Line_ptr new_bol; if (! find_bol (&x, &bol, &new_bol, eol_byte)) - break; + break; print_line (stdout, &x, &new_bol, &bol); bol = new_bol; } @@ -26,7 +26,7 @@ Options: -b, --before The separator is attached to the beginning - of the record that it precedes in the file. + of the record that it precedes in the file. -r, --regex The separator is a regular expression. -s, --separator=separator Use SEPARATOR as the record separator. @@ -127,13 +127,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Write each FILE to standard output, last line first.\n\ With no FILE, or when FILE is -, read standard input.\n\ @@ -248,133 +248,133 @@ tac_seekable (int input_fd, const char *file) for (;;) { /* Search backward from `match_start' - 1 to `G_buffer' for a match - with `separator'; for speed, use strncmp if `separator' contains no - metacharacters. - If the match succeeds, set `match_start' to point to the start of - the match and `match_length' to the length of the match. - Otherwise, make `match_start' < `G_buffer'. */ + with `separator'; for speed, use strncmp if `separator' contains no + metacharacters. + If the match succeeds, set `match_start' to point to the start of + the match and `match_length' to the length of the match. + Otherwise, make `match_start' < `G_buffer'. */ if (sentinel_length == 0) - { - size_t i = match_start - G_buffer; - regoff_t ri = i; - regoff_t range = 1 - ri; - regoff_t ret; - - if (1 < range) - error (EXIT_FAILURE, 0, _("record too large")); - - if (range == 1 - || ((ret = re_search (&compiled_separator, G_buffer, - i, i - 1, range, ®s)) - == -1)) - match_start = G_buffer - 1; - else if (ret == -2) - { - error (EXIT_FAILURE, 0, - _("error in regular expression search")); - } - else - { - match_start = G_buffer + regs.start[0]; - match_length = regs.end[0] - regs.start[0]; - } - } + { + size_t i = match_start - G_buffer; + regoff_t ri = i; + regoff_t range = 1 - ri; + regoff_t ret; + + if (1 < range) + error (EXIT_FAILURE, 0, _("record too large")); + + if (range == 1 + || ((ret = re_search (&compiled_separator, G_buffer, + i, i - 1, range, ®s)) + == -1)) + match_start = G_buffer - 1; + else if (ret == -2) + { + error (EXIT_FAILURE, 0, + _("error in regular expression search")); + } + else + { + match_start = G_buffer + regs.start[0]; + match_length = regs.end[0] - regs.start[0]; + } + } else - { - /* `match_length' is constant for non-regexp boundaries. */ - while (*--match_start != first_char - || (match_length1 && strncmp (match_start + 1, separator1, - match_length1))) - /* Do nothing. */ ; - } + { + /* `match_length' is constant for non-regexp boundaries. */ + while (*--match_start != first_char + || (match_length1 && strncmp (match_start + 1, separator1, + match_length1))) + /* Do nothing. */ ; + } /* Check whether we backed off the front of `G_buffer' without finding a match for `separator'. */ if (match_start < G_buffer) - { - if (file_pos == 0) - { - /* Hit the beginning of the file; print the remaining record. */ - output (G_buffer, past_end); - return true; - } - - saved_record_size = past_end - G_buffer; - if (saved_record_size > read_size) - { - /* `G_buffer_size' is about twice `read_size', so since - we want to read in another `read_size' bytes before - the data already in `G_buffer', we need to increase - `G_buffer_size'. */ - char *newbuffer; - size_t offset = sentinel_length ? sentinel_length : 1; - ptrdiff_t match_start_offset = match_start - G_buffer; - ptrdiff_t past_end_offset = past_end - G_buffer; - size_t old_G_buffer_size = G_buffer_size; - - read_size *= 2; - G_buffer_size = read_size * 2 + sentinel_length + 2; - if (G_buffer_size < old_G_buffer_size) - xalloc_die (); - newbuffer = xrealloc (G_buffer - offset, G_buffer_size); - newbuffer += offset; - /* Adjust the pointers for the new buffer location. */ - match_start = newbuffer + match_start_offset; - past_end = newbuffer + past_end_offset; - G_buffer = newbuffer; - } - - /* Back up to the start of the next bufferfull of the file. */ - if (file_pos >= read_size) - file_pos -= read_size; - else - { - read_size = file_pos; - file_pos = 0; - } - if (lseek (input_fd, file_pos, SEEK_SET) < 0) - error (0, errno, _("%s: seek failed"), quotearg_colon (file)); - - /* Shift the pending record data right to make room for the new. - The source and destination regions probably overlap. */ - memmove (G_buffer + read_size, G_buffer, saved_record_size); - past_end = G_buffer + read_size + saved_record_size; - /* For non-regexp searches, avoid unneccessary scanning. */ - if (sentinel_length) - match_start = G_buffer + read_size; - else - match_start = past_end; - - if (safe_read (input_fd, G_buffer, read_size) != read_size) - { - error (0, errno, _("%s: read error"), quotearg_colon (file)); - return false; - } - } + { + if (file_pos == 0) + { + /* Hit the beginning of the file; print the remaining record. */ + output (G_buffer, past_end); + return true; + } + + saved_record_size = past_end - G_buffer; + if (saved_record_size > read_size) + { + /* `G_buffer_size' is about twice `read_size', so since + we want to read in another `read_size' bytes before + the data already in `G_buffer', we need to increase + `G_buffer_size'. */ + char *newbuffer; + size_t offset = sentinel_length ? sentinel_length : 1; + ptrdiff_t match_start_offset = match_start - G_buffer; + ptrdiff_t past_end_offset = past_end - G_buffer; + size_t old_G_buffer_size = G_buffer_size; + + read_size *= 2; + G_buffer_size = read_size * 2 + sentinel_length + 2; + if (G_buffer_size < old_G_buffer_size) + xalloc_die (); + newbuffer = xrealloc (G_buffer - offset, G_buffer_size); + newbuffer += offset; + /* Adjust the pointers for the new buffer location. */ + match_start = newbuffer + match_start_offset; + past_end = newbuffer + past_end_offset; + G_buffer = newbuffer; + } + + /* Back up to the start of the next bufferfull of the file. */ + if (file_pos >= read_size) + file_pos -= read_size; + else + { + read_size = file_pos; + file_pos = 0; + } + if (lseek (input_fd, file_pos, SEEK_SET) < 0) + error (0, errno, _("%s: seek failed"), quotearg_colon (file)); + + /* Shift the pending record data right to make room for the new. + The source and destination regions probably overlap. */ + memmove (G_buffer + read_size, G_buffer, saved_record_size); + past_end = G_buffer + read_size + saved_record_size; + /* For non-regexp searches, avoid unneccessary scanning. */ + if (sentinel_length) + match_start = G_buffer + read_size; + else + match_start = past_end; + + if (safe_read (input_fd, G_buffer, read_size) != read_size) + { + error (0, errno, _("%s: read error"), quotearg_colon (file)); + return false; + } + } else - { - /* Found a match of `separator'. */ - if (separator_ends_record) - { - char *match_end = match_start + match_length; - - /* If this match of `separator' isn't at the end of the - file, print the record. */ - if (!first_time || match_end != past_end) - output (match_end, past_end); - past_end = match_end; - first_time = false; - } - else - { - output (match_start, past_end); - past_end = match_start; - } - - /* For non-regex matching, we can back up. */ - if (sentinel_length > 0) - match_start -= match_length - 1; - } + { + /* Found a match of `separator'. */ + if (separator_ends_record) + { + char *match_end = match_start + match_length; + + /* If this match of `separator' isn't at the end of the + file, print the record. */ + if (!first_time || match_end != past_end) + output (match_end, past_end); + past_end = match_end; + first_time = false; + } + else + { + output (match_start, past_end); + past_end = match_start; + } + + /* For non-regex matching, we can back up. */ + if (sentinel_length > 0) + match_start -= match_length - 1; + } } } @@ -435,7 +435,7 @@ copy_to_temp (FILE **g_tmp, char **g_tempfile, int input_fd, char const *file) char const * const Template = "%s/tacXXXXXX"; tempdir = getenv ("TMPDIR"); if (tempdir == NULL) - tempdir = DEFAULT_TMPDIR; + tempdir = DEFAULT_TMPDIR; /* Subtract 2 for `%s' and add 1 for the trailing NUL byte. */ template = xmalloc (strlen (tempdir) + strlen (Template) - 2 + 1); @@ -456,7 +456,7 @@ copy_to_temp (FILE **g_tmp, char **g_tempfile, int input_fd, char const *file) if (fd < 0) { error (0, errno, _("cannot create temporary file in %s"), - quote (tempdir)); + quote (tempdir)); return false; } @@ -475,18 +475,18 @@ copy_to_temp (FILE **g_tmp, char **g_tempfile, int input_fd, char const *file) { size_t bytes_read = safe_read (input_fd, G_buffer, read_size); if (bytes_read == 0) - break; + break; if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, _("%s: read error"), quotearg_colon (file)); - goto Fail; - } + { + error (0, errno, _("%s: read error"), quotearg_colon (file)); + goto Fail; + } if (fwrite (G_buffer, 1, bytes_read, tmp) != bytes_read) - { - error (0, errno, _("%s: write error"), quotearg_colon (tempfile)); - goto Fail; - } + { + error (0, errno, _("%s: write error"), quotearg_colon (tempfile)); + goto Fail; + } } if (fflush (tmp) != 0) @@ -513,7 +513,7 @@ tac_nonseekable (int input_fd, const char *file) FILE *tmp_stream; char *tmp_file; return (copy_to_temp (&tmp_stream, &tmp_file, input_fd, file) - && tac_seekable (fileno (tmp_stream), tmp_file)); + && tac_seekable (fileno (tmp_stream), tmp_file)); } /* Print FILE in reverse, copying it to a temporary @@ -534,23 +534,23 @@ tac_file (const char *filename) fd = STDIN_FILENO; filename = _("standard input"); if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); } else { fd = open (filename, O_RDONLY | O_BINARY); if (fd < 0) - { - error (0, errno, _("cannot open %s for reading"), quote (filename)); - return false; - } + { + error (0, errno, _("cannot open %s for reading"), quote (filename)); + return false; + } } file_size = lseek (fd, (off_t) 0, SEEK_END); ok = (file_size < 0 || isatty (fd) - ? tac_nonseekable (fd, filename) - : tac_seekable (fd, filename)); + ? tac_nonseekable (fd, filename) + : tac_seekable (fd, filename)); if (!is_stdin && close (fd) != 0) { @@ -588,23 +588,23 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "brs:", longopts, NULL)) != -1) { switch (optc) - { - case 'b': - separator_ends_record = false; - break; - case 'r': - sentinel_length = 0; - break; - case 's': - separator = optarg; - if (*separator == 0) - error (EXIT_FAILURE, 0, _("separator cannot be empty")); - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + { + case 'b': + separator_ends_record = false; + break; + case 'r': + sentinel_length = 0; + break; + case 's': + separator = optarg; + if (*separator == 0) + error (EXIT_FAILURE, 0, _("separator cannot be empty")); + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + usage (EXIT_FAILURE); + } } if (sentinel_length == 0) @@ -614,9 +614,9 @@ main (int argc, char **argv) compiled_separator.fastmap = compiled_separator_fastmap; compiled_separator.translate = NULL; error_message = re_compile_pattern (separator, strlen (separator), - &compiled_separator); + &compiled_separator); if (error_message) - error (EXIT_FAILURE, 0, "%s", error_message); + error (EXIT_FAILURE, 0, "%s", error_message); } else match_length = sentinel_length = strlen (separator); @@ -625,7 +625,7 @@ main (int argc, char **argv) while (sentinel_length >= read_size / 2) { if (SIZE_MAX / 2 < read_size) - xalloc_die (); + xalloc_die (); read_size *= 2; } half_buffer_size = read_size + sentinel_length + 1; @@ -644,8 +644,8 @@ main (int argc, char **argv) } file = (optind < argc - ? (char const *const *) &argv[optind] - : default_file_list); + ? (char const *const *) &argv[optind] + : default_file_list); if (O_BINARY && ! isatty (STDOUT_FILENO)) xfreopen (NULL, "wb", stdout); diff --git a/src/tail.c b/src/tail.c index 6f8370625..ceda5b6cd 100644 --- a/src/tail.c +++ b/src/tail.c @@ -236,13 +236,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); printf (_("\ Print the last %d lines of each FILE to standard output.\n\ With more than one FILE, precede each with a header giving the file name.\n\ @@ -272,9 +272,9 @@ Mandatory arguments to long options are mandatory for short options too.\n\ to see if it has been unlinked or renamed\n\ (this is the usual case of rotated log files)\n\ "), - DEFAULT_N_LINES, - DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS - ); + DEFAULT_N_LINES, + DEFAULT_MAX_N_UNCHANGED_STATS_BETWEEN_OPENS + ); fputs (_("\ --pid=PID with -f, terminate after process ID, PID dies\n\ -q, --quiet, --silent never output headers giving file names\n\ @@ -340,8 +340,8 @@ xwrite_stdout (char const *buffer, size_t n_bytes) static void record_open_fd (struct File_spec *f, int fd, - off_t size, struct stat const *st, - int blocking) + off_t size, struct stat const *st, + int blocking) { f->fd = fd; f->size = size; @@ -392,22 +392,22 @@ dump_remainder (const char *pretty_filename, int fd, uintmax_t n_bytes) size_t n = MIN (n_remaining, BUFSIZ); size_t bytes_read = safe_read (fd, buffer, n); if (bytes_read == SAFE_READ_ERROR) - { - if (errno != EAGAIN) - error (EXIT_FAILURE, errno, _("error reading %s"), - quote (pretty_filename)); - break; - } + { + if (errno != EAGAIN) + error (EXIT_FAILURE, errno, _("error reading %s"), + quote (pretty_filename)); + break; + } if (bytes_read == 0) - break; + break; xwrite_stdout (buffer, bytes_read); n_written += bytes_read; if (n_bytes != COPY_TO_EOF) - { - n_remaining -= bytes_read; - if (n_remaining == 0 || n_bytes == COPY_A_BUFFER) - break; - } + { + n_remaining -= bytes_read; + if (n_remaining == 0 || n_bytes == COPY_A_BUFFER) + break; + } } return n_written; @@ -433,15 +433,15 @@ xlseek (int fd, off_t offset, int whence, char const *filename) { case SEEK_SET: error (0, errno, _("%s: cannot seek to offset %s"), - filename, s); + filename, s); break; case SEEK_CUR: error (0, errno, _("%s: cannot seek to relative offset %s"), - filename, s); + filename, s); break; case SEEK_END: error (0, errno, _("%s: cannot seek to end-relative offset %s"), - filename, s); + filename, s); break; default: abort (); @@ -461,7 +461,7 @@ xlseek (int fd, off_t offset, int whence, char const *filename) static bool file_lines (const char *pretty_filename, int fd, uintmax_t n_lines, - off_t start_pos, off_t end_pos, uintmax_t *read_pos) + off_t start_pos, off_t end_pos, uintmax_t *read_pos) { char buffer[BUFSIZ]; size_t bytes_read; @@ -497,43 +497,43 @@ file_lines (const char *pretty_filename, int fd, uintmax_t n_lines, size_t n = bytes_read; while (n) - { - char const *nl; - nl = memrchr (buffer, '\n', n); - if (nl == NULL) - break; - n = nl - buffer; - if (n_lines-- == 0) - { - /* If this newline isn't the last character in the buffer, - output the part that is after it. */ - if (n != bytes_read - 1) - xwrite_stdout (nl + 1, bytes_read - (n + 1)); - *read_pos += dump_remainder (pretty_filename, fd, - end_pos - (pos + bytes_read)); - return true; - } - } + { + char const *nl; + nl = memrchr (buffer, '\n', n); + if (nl == NULL) + break; + n = nl - buffer; + if (n_lines-- == 0) + { + /* If this newline isn't the last character in the buffer, + output the part that is after it. */ + if (n != bytes_read - 1) + xwrite_stdout (nl + 1, bytes_read - (n + 1)); + *read_pos += dump_remainder (pretty_filename, fd, + end_pos - (pos + bytes_read)); + return true; + } + } /* Not enough newlines in that bufferfull. */ if (pos == start_pos) - { - /* Not enough lines in the file; print everything from - start_pos to the end. */ - xlseek (fd, start_pos, SEEK_SET, pretty_filename); - *read_pos = start_pos + dump_remainder (pretty_filename, fd, - end_pos); - return true; - } + { + /* Not enough lines in the file; print everything from + start_pos to the end. */ + xlseek (fd, start_pos, SEEK_SET, pretty_filename); + *read_pos = start_pos + dump_remainder (pretty_filename, fd, + end_pos); + return true; + } pos -= BUFSIZ; xlseek (fd, pos, SEEK_SET, pretty_filename); bytes_read = safe_read (fd, buffer, BUFSIZ); if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, _("error reading %s"), quote (pretty_filename)); - return false; - } + { + error (0, errno, _("error reading %s"), quote (pretty_filename)); + return false; + } *read_pos = pos + bytes_read; } @@ -549,7 +549,7 @@ file_lines (const char *pretty_filename, int fd, uintmax_t n_lines, static bool pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines, - uintmax_t *read_pos) + uintmax_t *read_pos) { struct linebuffer { @@ -574,7 +574,7 @@ pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines, { n_read = safe_read (fd, tmp->buffer, BUFSIZ); if (n_read == 0 || n_read == SAFE_READ_ERROR) - break; + break; tmp->nbytes = n_read; *read_pos += n_read; tmp->nlines = 0; @@ -582,13 +582,13 @@ pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines, /* Count the number of newlines just read. */ { - char const *buffer_end = tmp->buffer + n_read; - char const *p = tmp->buffer; - while ((p = memchr (p, '\n', buffer_end - p))) - { - ++p; - ++tmp->nlines; - } + char const *buffer_end = tmp->buffer + n_read; + char const *p = tmp->buffer; + while ((p = memchr (p, '\n', buffer_end - p))) + { + ++p; + ++tmp->nlines; + } } total_lines += tmp->nlines; @@ -596,28 +596,28 @@ pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines, one to it. This is because when reading from a pipe, `n_read' can often be very small. */ if (tmp->nbytes + last->nbytes < BUFSIZ) - { - memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); - last->nbytes += tmp->nbytes; - last->nlines += tmp->nlines; - } + { + memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); + last->nbytes += tmp->nbytes; + last->nlines += tmp->nlines; + } else - { - /* If there's not enough room, link the new buffer onto the end of - the list, then either free up the oldest buffer for the next - read if that would leave enough lines, or else malloc a new one. - Some compaction mechanism is possible but probably not - worthwhile. */ - last = last->next = tmp; - if (total_lines - first->nlines > n_lines) - { - tmp = first; - total_lines -= first->nlines; - first = first->next; - } - else - tmp = xmalloc (sizeof (LBUFFER)); - } + { + /* If there's not enough room, link the new buffer onto the end of + the list, then either free up the oldest buffer for the next + read if that would leave enough lines, or else malloc a new one. + Some compaction mechanism is possible but probably not + worthwhile. */ + last = last->next = tmp; + if (total_lines - first->nlines > n_lines) + { + tmp = first; + total_lines -= first->nlines; + first = first->next; + } + else + tmp = xmalloc (sizeof (LBUFFER)); + } } free (tmp); @@ -655,15 +655,15 @@ pipe_lines (const char *pretty_filename, int fd, uintmax_t n_lines, char const *buffer_end = tmp->buffer + tmp->nbytes; if (total_lines > n_lines) { - /* Skip `total_lines' - `n_lines' newlines. We made sure that - `total_lines' - `n_lines' <= `tmp->nlines'. */ - size_t j; - for (j = total_lines - n_lines; j; --j) - { - beg = memchr (beg, '\n', buffer_end - beg); - assert (beg); - ++beg; - } + /* Skip `total_lines' - `n_lines' newlines. We made sure that + `total_lines' - `n_lines' <= `tmp->nlines'. */ + size_t j; + for (j = total_lines - n_lines; j; --j) + { + beg = memchr (beg, '\n', buffer_end - beg); + assert (beg); + ++beg; + } } xwrite_stdout (beg, buffer_end - beg); @@ -688,7 +688,7 @@ free_lbuffers: static bool pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, - uintmax_t *read_pos) + uintmax_t *read_pos) { struct charbuffer { @@ -713,7 +713,7 @@ pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, { n_read = safe_read (fd, tmp->buffer, BUFSIZ); if (n_read == 0 || n_read == SAFE_READ_ERROR) - break; + break; *read_pos += n_read; tmp->nbytes = n_read; tmp->next = NULL; @@ -723,29 +723,29 @@ pipe_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, one to it. This is because when reading from a pipe, `nbytes' can often be very small. */ if (tmp->nbytes + last->nbytes < BUFSIZ) - { - memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); - last->nbytes += tmp->nbytes; - } + { + memcpy (&last->buffer[last->nbytes], tmp->buffer, tmp->nbytes); + last->nbytes += tmp->nbytes; + } else - { - /* If there's not enough room, link the new buffer onto the end of - the list, then either free up the oldest buffer for the next - read if that would leave enough characters, or else malloc a new - one. Some compaction mechanism is possible but probably not - worthwhile. */ - last = last->next = tmp; - if (total_bytes - first->nbytes > n_bytes) - { - tmp = first; - total_bytes -= first->nbytes; - first = first->next; - } - else - { - tmp = xmalloc (sizeof (CBUFFER)); - } - } + { + /* If there's not enough room, link the new buffer onto the end of + the list, then either free up the oldest buffer for the next + read if that would leave enough characters, or else malloc a new + one. Some compaction mechanism is possible but probably not + worthwhile. */ + last = last->next = tmp; + if (total_bytes - first->nbytes > n_bytes) + { + tmp = first; + total_bytes -= first->nbytes; + first = first->next; + } + else + { + tmp = xmalloc (sizeof (CBUFFER)); + } + } } free (tmp); @@ -789,7 +789,7 @@ free_cbuffers: static int start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, - uintmax_t *read_pos) + uintmax_t *read_pos) { char buffer[BUFSIZ]; @@ -797,22 +797,22 @@ start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, { size_t bytes_read = safe_read (fd, buffer, BUFSIZ); if (bytes_read == 0) - return -1; + return -1; if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, _("error reading %s"), quote (pretty_filename)); - return 1; - } + { + error (0, errno, _("error reading %s"), quote (pretty_filename)); + return 1; + } read_pos += bytes_read; if (bytes_read <= n_bytes) - n_bytes -= bytes_read; + n_bytes -= bytes_read; else - { - size_t n_remaining = bytes_read - n_bytes; - if (n_remaining) - xwrite_stdout (&buffer[n_bytes], n_remaining); - break; - } + { + size_t n_remaining = bytes_read - n_bytes; + if (n_remaining) + xwrite_stdout (&buffer[n_bytes], n_remaining); + break; + } } return 0; @@ -824,7 +824,7 @@ start_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, static int start_lines (const char *pretty_filename, int fd, uintmax_t n_lines, - uintmax_t *read_pos) + uintmax_t *read_pos) { if (n_lines == 0) return 0; @@ -836,25 +836,25 @@ start_lines (const char *pretty_filename, int fd, uintmax_t n_lines, size_t bytes_read = safe_read (fd, buffer, BUFSIZ); char *buffer_end = buffer + bytes_read; if (bytes_read == 0) /* EOF */ - return -1; + return -1; if (bytes_read == SAFE_READ_ERROR) /* error */ - { - error (0, errno, _("error reading %s"), quote (pretty_filename)); - return 1; - } + { + error (0, errno, _("error reading %s"), quote (pretty_filename)); + return 1; + } *read_pos += bytes_read; while ((p = memchr (p, '\n', buffer_end - p))) - { - ++p; - if (--n_lines == 0) - { - if (p < buffer_end) - xwrite_stdout (p, buffer_end - p); - return 0; - } - } + { + ++p; + if (--n_lines == 0) + { + if (p < buffer_end) + xwrite_stdout (p, buffer_end - p); + return 0; + } + } } } @@ -871,8 +871,8 @@ recheck (struct File_spec *f, bool blocking) int prev_errnum = f->errnum; bool new_file; int fd = (is_stdin - ? STDIN_FILENO - : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK))); + ? STDIN_FILENO + : open (f->name, O_RDONLY | (blocking ? 0 : O_NONBLOCK))); assert (valid_file_spec (f)); @@ -885,25 +885,25 @@ recheck (struct File_spec *f, bool blocking) ok = false; f->errnum = errno; if (!f->tailable) - { - if (was_tailable) - { - /* FIXME-maybe: detect the case in which the file first becomes - unreadable (perms), and later becomes readable again and can - be seen to be the same file (dev/ino). Otherwise, tail prints - the entire contents of the file when it becomes readable. */ - error (0, f->errnum, _("%s has become inaccessible"), - quote (pretty_name (f))); - } - else - { - /* say nothing... it's still not tailable */ - } - } + { + if (was_tailable) + { + /* FIXME-maybe: detect the case in which the file first becomes + unreadable (perms), and later becomes readable again and can + be seen to be the same file (dev/ino). Otherwise, tail prints + the entire contents of the file when it becomes readable. */ + error (0, f->errnum, _("%s has become inaccessible"), + quote (pretty_name (f))); + } + else + { + /* say nothing... it's still not tailable */ + } + } else if (prev_errnum != errno) - { - error (0, errno, "%s", pretty_name (f)); - } + { + error (0, errno, "%s", pretty_name (f)); + } } else if (!IS_TAILABLE_FILE_TYPE (new_stats.st_mode)) { @@ -911,7 +911,7 @@ recheck (struct File_spec *f, bool blocking) f->errnum = -1; error (0, 0, _("%s has been replaced with an untailable file;\ giving up on this name"), - quote (pretty_name (f))); + quote (pretty_name (f))); f->ignore = true; } else @@ -936,36 +936,36 @@ recheck (struct File_spec *f, bool blocking) { new_file = true; if (f->fd == -1) - { - error (0, 0, - _("%s has appeared; following end of new file"), - quote (pretty_name (f))); - } + { + error (0, 0, + _("%s has appeared; following end of new file"), + quote (pretty_name (f))); + } else - { - /* Close the old one. */ - close_fd (f->fd, pretty_name (f)); - - /* File has been replaced (e.g., via log rotation) -- - tail the new one. */ - error (0, 0, - _("%s has been replaced; following end of new file"), - quote (pretty_name (f))); - } + { + /* Close the old one. */ + close_fd (f->fd, pretty_name (f)); + + /* File has been replaced (e.g., via log rotation) -- + tail the new one. */ + error (0, 0, + _("%s has been replaced; following end of new file"), + quote (pretty_name (f))); + } } else { if (f->fd == -1) - { - /* This happens when one iteration finds the file missing, - then the preceding <dev,inode> pair is reused as the - file is recreated. */ - new_file = true; - } + { + /* This happens when one iteration finds the file missing, + then the preceding <dev,inode> pair is reused as the + file is recreated. */ + new_file = true; + } else - { - close_fd (fd, pretty_name (f)); - } + { + close_fd (fd, pretty_name (f)); + } } if (new_file) @@ -1002,7 +1002,7 @@ tail_forever (struct File_spec *f, size_t n_files, double sleep_interval) { /* Use blocking I/O as an optimization, when it's easy. */ bool blocking = (pid == 0 && follow_mode == Follow_descriptor - && n_files == 1 && ! S_ISREG (f[0].mode)); + && n_files == 1 && ! S_ISREG (f[0].mode)); size_t last; bool writer_is_dead = false; @@ -1014,132 +1014,132 @@ tail_forever (struct File_spec *f, size_t n_files, double sleep_interval) bool any_input = false; for (i = 0; i < n_files; i++) - { - int fd; - char const *name; - mode_t mode; - struct stat stats; - uintmax_t bytes_read; - - if (f[i].ignore) - continue; - - if (f[i].fd < 0) - { - recheck (&f[i], blocking); - continue; - } - - fd = f[i].fd; - name = pretty_name (&f[i]); - mode = f[i].mode; - - if (f[i].blocking != blocking) - { - int old_flags = fcntl (fd, F_GETFL); - int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK); - if (old_flags < 0 - || (new_flags != old_flags - && fcntl (fd, F_SETFL, new_flags) == -1)) - { - /* Don't update f[i].blocking if fcntl fails. */ - if (S_ISREG (f[i].mode) && errno == EPERM) - { - /* This happens when using tail -f on a file with - the append-only attribute. */ - } - else - error (EXIT_FAILURE, errno, - _("%s: cannot change nonblocking mode"), name); - } - else - f[i].blocking = blocking; - } - - if (!f[i].blocking) - { - if (fstat (fd, &stats) != 0) - { - f[i].fd = -1; - f[i].errnum = errno; - error (0, errno, "%s", name); - continue; - } - - if (f[i].mode == stats.st_mode - && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size) - && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0) - { - if ((max_n_unchanged_stats_between_opens - <= f[i].n_unchanged_stats++) - && follow_mode == Follow_name) - { - recheck (&f[i], f[i].blocking); - f[i].n_unchanged_stats = 0; - } - continue; - } - - /* This file has changed. Print out what we can, and - then keep looping. */ - - f[i].mtime = get_stat_mtime (&stats); - f[i].mode = stats.st_mode; - - /* reset counter */ - f[i].n_unchanged_stats = 0; - - if (S_ISREG (mode) && stats.st_size < f[i].size) - { - error (0, 0, _("%s: file truncated"), name); - last = i; - xlseek (fd, stats.st_size, SEEK_SET, name); - f[i].size = stats.st_size; - continue; - } - - if (i != last) - { - if (print_headers) - write_header (name); - last = i; - } - } - - bytes_read = dump_remainder (name, fd, - (f[i].blocking - ? COPY_A_BUFFER : COPY_TO_EOF)); - any_input |= (bytes_read != 0); - f[i].size += bytes_read; - } + { + int fd; + char const *name; + mode_t mode; + struct stat stats; + uintmax_t bytes_read; + + if (f[i].ignore) + continue; + + if (f[i].fd < 0) + { + recheck (&f[i], blocking); + continue; + } + + fd = f[i].fd; + name = pretty_name (&f[i]); + mode = f[i].mode; + + if (f[i].blocking != blocking) + { + int old_flags = fcntl (fd, F_GETFL); + int new_flags = old_flags | (blocking ? 0 : O_NONBLOCK); + if (old_flags < 0 + || (new_flags != old_flags + && fcntl (fd, F_SETFL, new_flags) == -1)) + { + /* Don't update f[i].blocking if fcntl fails. */ + if (S_ISREG (f[i].mode) && errno == EPERM) + { + /* This happens when using tail -f on a file with + the append-only attribute. */ + } + else + error (EXIT_FAILURE, errno, + _("%s: cannot change nonblocking mode"), name); + } + else + f[i].blocking = blocking; + } + + if (!f[i].blocking) + { + if (fstat (fd, &stats) != 0) + { + f[i].fd = -1; + f[i].errnum = errno; + error (0, errno, "%s", name); + continue; + } + + if (f[i].mode == stats.st_mode + && (! S_ISREG (stats.st_mode) || f[i].size == stats.st_size) + && timespec_cmp (f[i].mtime, get_stat_mtime (&stats)) == 0) + { + if ((max_n_unchanged_stats_between_opens + <= f[i].n_unchanged_stats++) + && follow_mode == Follow_name) + { + recheck (&f[i], f[i].blocking); + f[i].n_unchanged_stats = 0; + } + continue; + } + + /* This file has changed. Print out what we can, and + then keep looping. */ + + f[i].mtime = get_stat_mtime (&stats); + f[i].mode = stats.st_mode; + + /* reset counter */ + f[i].n_unchanged_stats = 0; + + if (S_ISREG (mode) && stats.st_size < f[i].size) + { + error (0, 0, _("%s: file truncated"), name); + last = i; + xlseek (fd, stats.st_size, SEEK_SET, name); + f[i].size = stats.st_size; + continue; + } + + if (i != last) + { + if (print_headers) + write_header (name); + last = i; + } + } + + bytes_read = dump_remainder (name, fd, + (f[i].blocking + ? COPY_A_BUFFER : COPY_TO_EOF)); + any_input |= (bytes_read != 0); + f[i].size += bytes_read; + } if (! any_live_files (f, n_files) && ! reopen_inaccessible_files) - { - error (0, 0, _("no files remaining")); - break; - } + { + error (0, 0, _("no files remaining")); + break; + } if ((!any_input | blocking) && fflush (stdout) != 0) - error (EXIT_FAILURE, errno, _("write error")); + error (EXIT_FAILURE, errno, _("write error")); /* If nothing was read, sleep and/or check for dead writers. */ if (!any_input) - { - if (writer_is_dead) - break; - - if (xnanosleep (sleep_interval)) - error (EXIT_FAILURE, errno, _("cannot read realtime clock")); - - /* Once the writer is dead, read the files once more to - avoid a race condition. */ - writer_is_dead = (pid != 0 - && kill (pid, 0) != 0 - /* Handle the case in which you cannot send a - signal to the writer, so kill fails and sets - errno to EPERM. */ - && errno != EPERM); - } + { + if (writer_is_dead) + break; + + if (xnanosleep (sleep_interval)) + error (EXIT_FAILURE, errno, _("cannot read realtime clock")); + + /* Once the writer is dead, read the files once more to + avoid a race condition. */ + writer_is_dead = (pid != 0 + && kill (pid, 0) != 0 + /* Handle the case in which you cannot send a + signal to the writer, so kill fails and sets + errno to EPERM. */ + && errno != EPERM); + } } } @@ -1401,7 +1401,7 @@ tail_forever_inotify (int wd, struct File_spec *f, size_t n_files, static bool tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, - uintmax_t *read_pos) + uintmax_t *read_pos) { struct stat stats; @@ -1414,50 +1414,50 @@ tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, if (from_start) { if ( ! presume_input_pipe - && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX) - { - xlseek (fd, n_bytes, SEEK_CUR, pretty_filename); - *read_pos += n_bytes; - } + && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX) + { + xlseek (fd, n_bytes, SEEK_CUR, pretty_filename); + *read_pos += n_bytes; + } else - { - int t = start_bytes (pretty_filename, fd, n_bytes, read_pos); - if (t) - return t < 0; - } + { + int t = start_bytes (pretty_filename, fd, n_bytes, read_pos); + if (t) + return t < 0; + } *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF); } else { if ( ! presume_input_pipe - && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX) - { - off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename); - off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename); - off_t diff = end_pos - current_pos; - /* Be careful here. The current position may actually be - beyond the end of the file. */ - off_t bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff; - off_t nb = n_bytes; - - if (bytes_remaining <= nb) - { - /* From the current position to end of file, there are no - more bytes than have been requested. So reposition the - file pointer to the incoming current position and print - everything after that. */ - *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename); - } - else - { - /* There are more bytes remaining than were requested. - Back up. */ - *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename); - } - *read_pos += dump_remainder (pretty_filename, fd, n_bytes); - } + && S_ISREG (stats.st_mode) && n_bytes <= OFF_T_MAX) + { + off_t current_pos = xlseek (fd, 0, SEEK_CUR, pretty_filename); + off_t end_pos = xlseek (fd, 0, SEEK_END, pretty_filename); + off_t diff = end_pos - current_pos; + /* Be careful here. The current position may actually be + beyond the end of the file. */ + off_t bytes_remaining = (diff = end_pos - current_pos) < 0 ? 0 : diff; + off_t nb = n_bytes; + + if (bytes_remaining <= nb) + { + /* From the current position to end of file, there are no + more bytes than have been requested. So reposition the + file pointer to the incoming current position and print + everything after that. */ + *read_pos = xlseek (fd, current_pos, SEEK_SET, pretty_filename); + } + else + { + /* There are more bytes remaining than were requested. + Back up. */ + *read_pos = xlseek (fd, -nb, SEEK_END, pretty_filename); + } + *read_pos += dump_remainder (pretty_filename, fd, n_bytes); + } else - return pipe_bytes (pretty_filename, fd, n_bytes, read_pos); + return pipe_bytes (pretty_filename, fd, n_bytes, read_pos); } return true; } @@ -1467,7 +1467,7 @@ tail_bytes (const char *pretty_filename, int fd, uintmax_t n_bytes, static bool tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines, - uintmax_t *read_pos) + uintmax_t *read_pos) { struct stat stats; @@ -1481,7 +1481,7 @@ tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines, { int t = start_lines (pretty_filename, fd, n_lines, read_pos); if (t) - return t < 0; + return t < 0; *read_pos += dump_remainder (pretty_filename, fd, COPY_TO_EOF); } else @@ -1490,29 +1490,29 @@ tail_lines (const char *pretty_filename, int fd, uintmax_t n_lines, off_t end_pos; /* Use file_lines only if FD refers to a regular file for - which lseek (... SEEK_END) works. */ + which lseek (... SEEK_END) works. */ if ( ! presume_input_pipe - && S_ISREG (stats.st_mode) - && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1 - && start_pos < (end_pos = lseek (fd, 0, SEEK_END))) - { - *read_pos = end_pos; - if (end_pos != 0 - && ! file_lines (pretty_filename, fd, n_lines, - start_pos, end_pos, read_pos)) - return false; - } + && S_ISREG (stats.st_mode) + && (start_pos = lseek (fd, 0, SEEK_CUR)) != -1 + && start_pos < (end_pos = lseek (fd, 0, SEEK_END))) + { + *read_pos = end_pos; + if (end_pos != 0 + && ! file_lines (pretty_filename, fd, n_lines, + start_pos, end_pos, read_pos)) + return false; + } else - { - /* Under very unlikely circumstances, it is possible to reach - this point after positioning the file pointer to end of file - via the `lseek (...SEEK_END)' above. In that case, reposition - the file pointer back to start_pos before calling pipe_lines. */ - if (start_pos != -1) - xlseek (fd, start_pos, SEEK_SET, pretty_filename); - - return pipe_lines (pretty_filename, fd, n_lines, read_pos); - } + { + /* Under very unlikely circumstances, it is possible to reach + this point after positioning the file pointer to end of file + via the `lseek (...SEEK_END)' above. In that case, reposition + the file pointer back to start_pos before calling pipe_lines. */ + if (start_pos != -1) + xlseek (fd, start_pos, SEEK_SET, pretty_filename); + + return pipe_lines (pretty_filename, fd, n_lines, read_pos); + } } return true; } @@ -1554,7 +1554,7 @@ tail_file (struct File_spec *f, uintmax_t n_units) have_read_stdin = true; fd = STDIN_FILENO; if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); } else fd = open (f->name, O_RDONLY | O_BINARY); @@ -1564,15 +1564,15 @@ tail_file (struct File_spec *f, uintmax_t n_units) if (fd == -1) { if (forever) - { - f->fd = -1; - f->errnum = errno; - f->ignore = false; - f->ino = 0; - f->dev = 0; - } + { + f->fd = -1; + f->errnum = errno; + f->ignore = false; + f->ino = 0; + f->dev = 0; + } error (0, errno, _("cannot open %s for reading"), - quote (pretty_name (f))); + quote (pretty_name (f))); ok = false; } else @@ -1580,56 +1580,56 @@ tail_file (struct File_spec *f, uintmax_t n_units) uintmax_t read_pos; if (print_headers) - write_header (pretty_name (f)); + write_header (pretty_name (f)); ok = tail (pretty_name (f), fd, n_units, &read_pos); if (forever) - { - struct stat stats; + { + struct stat stats; #if TEST_RACE_BETWEEN_FINAL_READ_AND_INITIAL_FSTAT - /* Before the tail function provided `read_pos', there was - a race condition described in the URL below. This sleep - call made the window big enough to exercise the problem. */ - sleep (1); + /* Before the tail function provided `read_pos', there was + a race condition described in the URL below. This sleep + call made the window big enough to exercise the problem. */ + sleep (1); #endif - f->errnum = ok - 1; - if (fstat (fd, &stats) < 0) - { - ok = false; - f->errnum = errno; - error (0, errno, _("error reading %s"), quote (pretty_name (f))); - } - else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode)) - { - error (0, 0, _("%s: cannot follow end of this type of file;\ + f->errnum = ok - 1; + if (fstat (fd, &stats) < 0) + { + ok = false; + f->errnum = errno; + error (0, errno, _("error reading %s"), quote (pretty_name (f))); + } + else if (!IS_TAILABLE_FILE_TYPE (stats.st_mode)) + { + error (0, 0, _("%s: cannot follow end of this type of file;\ giving up on this name"), - pretty_name (f)); - ok = false; - f->errnum = -1; - f->ignore = true; - } - - if (!ok) - { - close_fd (fd, pretty_name (f)); - f->fd = -1; - } - else - { - /* Note: we must use read_pos here, not stats.st_size, - to avoid a race condition described by Ken Raeburn: - http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */ - record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1)); - } - } + pretty_name (f)); + ok = false; + f->errnum = -1; + f->ignore = true; + } + + if (!ok) + { + close_fd (fd, pretty_name (f)); + f->fd = -1; + } + else + { + /* Note: we must use read_pos here, not stats.st_size, + to avoid a race condition described by Ken Raeburn: + http://mail.gnu.org/archive/html/bug-textutils/2003-05/msg00007.html */ + record_open_fd (f, fd, read_pos, &stats, (is_stdin ? -1 : 1)); + } + } else - { - if (!is_stdin && close (fd)) - { - error (0, errno, _("error reading %s"), quote (pretty_name (f))); - ok = false; - } - } + { + if (!is_stdin && close (fd)) + { + error (0, errno, _("error reading %s"), quote (pretty_name (f))); + ok = false; + } + } } return ok; @@ -1659,8 +1659,8 @@ parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units) /* With the obsolete form, there is one option string and at most one file argument. Watch out for "-" and "--", though. */ if (! (argc == 2 - || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1])) - || (3 <= argc && argc <= 4 && STREQ (argv[2], "--")))) + || (argc == 3 && ! (argv[2][0] == '-' && argv[2][1])) + || (3 <= argc && argc <= 4 && STREQ (argv[2], "--")))) return false; obsolete_usage = (posix2_version () < 200112); @@ -1674,18 +1674,18 @@ parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units) case '+': /* Leading "+" is a file name in the non-obsolete form. */ if (!obsolete_usage) - return false; + return false; t_from_start = true; break; case '-': /* In the non-obsolete form, "-" is standard input and "-c" - requires an option-argument. The obsolete multidigit options - are supported as a GNU extension even when conforming to - POSIX 1003.1-2001, so don't complain about them. */ + requires an option-argument. The obsolete multidigit options + are supported as a GNU extension even when conforming to + POSIX 1003.1-2001, so don't complain about them. */ if (!obsolete_usage && !p[p[0] == 'c']) - return false; + return false; t_from_start = false; break; @@ -1715,8 +1715,8 @@ parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units) if (n_string == n_string_end) *n_units = default_count; else if ((xstrtoumax (n_string, NULL, 10, n_units, "b") - & ~LONGINT_INVALID_SUFFIX_CHAR) - != LONGINT_OK) + & ~LONGINT_INVALID_SUFFIX_CHAR) + != LONGINT_OK) error (EXIT_FAILURE, 0, _("number in %s is too large"), quote (argv[1])); /* Set globals. */ @@ -1729,118 +1729,118 @@ parse_obsolete_option (int argc, char * const *argv, uintmax_t *n_units) static void parse_options (int argc, char **argv, - uintmax_t *n_units, enum header_mode *header_mode, - double *sleep_interval) + uintmax_t *n_units, enum header_mode *header_mode, + double *sleep_interval) { int c; while ((c = getopt_long (argc, argv, "c:n:fFqs:v0123456789", - long_options, NULL)) - != -1) + long_options, NULL)) + != -1) { switch (c) - { - case 'F': - forever = true; - follow_mode = Follow_name; - reopen_inaccessible_files = true; - break; - - case 'c': - case 'n': - count_lines = (c == 'n'); - if (*optarg == '+') - from_start = true; - else if (*optarg == '-') - ++optarg; - - { - strtol_error s_err; - s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0"); - if (s_err != LONGINT_OK) - { - error (EXIT_FAILURE, 0, "%s: %s", optarg, - (c == 'n' - ? _("invalid number of lines") - : _("invalid number of bytes"))); - } - } - break; - - case 'f': - case LONG_FOLLOW_OPTION: - forever = true; - if (optarg == NULL) - follow_mode = DEFAULT_FOLLOW_MODE; - else - follow_mode = XARGMATCH ("--follow", optarg, - follow_mode_string, follow_mode_map); - break; - - case RETRY_OPTION: - reopen_inaccessible_files = true; - break; - - case MAX_UNCHANGED_STATS_OPTION: - /* --max-unchanged-stats=N */ - if (xstrtoumax (optarg, NULL, 10, - &max_n_unchanged_stats_between_opens, - "") - != LONGINT_OK) - { - error (EXIT_FAILURE, 0, - _("%s: invalid maximum number of unchanged stats between opens"), - optarg); - } - break; - - case PID_OPTION: - { - strtol_error s_err; - unsigned long int tmp_ulong; - s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, ""); - if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX) - { - error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg); - } - pid = tmp_ulong; - } - break; - - case PRESUME_INPUT_PIPE_OPTION: - presume_input_pipe = true; - break; - - case 'q': - *header_mode = never; - break; - - case 's': - { - double s; - if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s)) - error (EXIT_FAILURE, 0, - _("%s: invalid number of seconds"), optarg); - *sleep_interval = s; - } - break; - - case 'v': - *header_mode = always; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - case '0': case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - error (EXIT_FAILURE, 0, - _("option used in invalid context -- %c"), c); - - default: - usage (EXIT_FAILURE); - } + { + case 'F': + forever = true; + follow_mode = Follow_name; + reopen_inaccessible_files = true; + break; + + case 'c': + case 'n': + count_lines = (c == 'n'); + if (*optarg == '+') + from_start = true; + else if (*optarg == '-') + ++optarg; + + { + strtol_error s_err; + s_err = xstrtoumax (optarg, NULL, 10, n_units, "bkKmMGTPEZY0"); + if (s_err != LONGINT_OK) + { + error (EXIT_FAILURE, 0, "%s: %s", optarg, + (c == 'n' + ? _("invalid number of lines") + : _("invalid number of bytes"))); + } + } + break; + + case 'f': + case LONG_FOLLOW_OPTION: + forever = true; + if (optarg == NULL) + follow_mode = DEFAULT_FOLLOW_MODE; + else + follow_mode = XARGMATCH ("--follow", optarg, + follow_mode_string, follow_mode_map); + break; + + case RETRY_OPTION: + reopen_inaccessible_files = true; + break; + + case MAX_UNCHANGED_STATS_OPTION: + /* --max-unchanged-stats=N */ + if (xstrtoumax (optarg, NULL, 10, + &max_n_unchanged_stats_between_opens, + "") + != LONGINT_OK) + { + error (EXIT_FAILURE, 0, + _("%s: invalid maximum number of unchanged stats between opens"), + optarg); + } + break; + + case PID_OPTION: + { + strtol_error s_err; + unsigned long int tmp_ulong; + s_err = xstrtoul (optarg, NULL, 10, &tmp_ulong, ""); + if (s_err != LONGINT_OK || tmp_ulong > PID_T_MAX) + { + error (EXIT_FAILURE, 0, _("%s: invalid PID"), optarg); + } + pid = tmp_ulong; + } + break; + + case PRESUME_INPUT_PIPE_OPTION: + presume_input_pipe = true; + break; + + case 'q': + *header_mode = never; + break; + + case 's': + { + double s; + if (! (xstrtod (optarg, NULL, &s, c_strtod) && 0 <= s)) + error (EXIT_FAILURE, 0, + _("%s: invalid number of seconds"), optarg); + *sleep_interval = s; + } + break; + + case 'v': + *header_mode = always; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + error (EXIT_FAILURE, 0, + _("option used in invalid context -- %c"), c); + + default: + usage (EXIT_FAILURE); + } } if (reopen_inaccessible_files && follow_mode != Follow_name) @@ -1848,7 +1848,7 @@ parse_options (int argc, char **argv, if (pid && !forever) error (0, 0, - _("warning: PID ignored; --pid=PID is useful only when following")); + _("warning: PID ignored; --pid=PID is useful only when following")); else if (pid && kill (pid, 0) != 0 && errno == ENOSYS) { error (0, 0, _("warning: --pid=PID is not supported on this system")); @@ -1899,7 +1899,7 @@ main (int argc, char **argv) if (from_start) { if (n_units) - --n_units; + --n_units; } if (optind < argc) @@ -1914,26 +1914,26 @@ main (int argc, char **argv) file = &dummy_stdin; /* POSIX says that -f is ignored if no file operand is specified - and standard input is a pipe. However, the GNU coding - standards say that program behavior should not depend on - device type, because device independence is an important - principle of the system's design. + and standard input is a pipe. However, the GNU coding + standards say that program behavior should not depend on + device type, because device independence is an important + principle of the system's design. - Follow the POSIX requirement only if POSIXLY_CORRECT is set. */ + Follow the POSIX requirement only if POSIXLY_CORRECT is set. */ if (forever && getenv ("POSIXLY_CORRECT")) - { - struct stat st; - int is_a_fifo_or_pipe = - (fstat (STDIN_FILENO, &st) != 0 ? -1 - : S_ISFIFO (st.st_mode) ? 1 - : HAVE_FIFO_PIPES == 1 ? 0 - : isapipe (STDIN_FILENO)); - if (is_a_fifo_or_pipe < 0) - error (EXIT_FAILURE, errno, _("standard input")); - if (is_a_fifo_or_pipe) - forever = false; - } + { + struct stat st; + int is_a_fifo_or_pipe = + (fstat (STDIN_FILENO, &st) != 0 ? -1 + : S_ISFIFO (st.st_mode) ? 1 + : HAVE_FIFO_PIPES == 1 ? 0 + : isapipe (STDIN_FILENO)); + if (is_a_fifo_or_pipe < 0) + error (EXIT_FAILURE, errno, _("standard input")); + if (is_a_fifo_or_pipe) + forever = false; + } } { @@ -1941,7 +1941,7 @@ main (int argc, char **argv) for (i = 0; i < n_files; i++) if (STREQ (file[i], "-")) - found_hyphen = true; + found_hyphen = true; /* When following by name, there must be a name. */ if (found_hyphen && follow_mode == Follow_name) @@ -1952,7 +1952,7 @@ main (int argc, char **argv) and that from any non-stdin files) might still be useful. */ if (forever && found_hyphen && isatty (STDIN_FILENO)) error (0, 0, _("warning: following standard input" - " indefinitely is ineffective")); + " indefinitely is ineffective")); } F = xnmalloc (n_files, sizeof *F); @@ -56,7 +56,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [FILE]...\n"), program_name); @@ -97,22 +97,22 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "ai", long_options, NULL)) != -1) { switch (optc) - { - case 'a': - append = true; - break; + { + case 'a': + append = true; + break; - case 'i': - ignore_interrupts = true; - break; + case 'i': + ignore_interrupts = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } if (ignore_interrupts) @@ -166,15 +166,15 @@ tee_files (int nfiles, const char **files) for (i = 1; i <= nfiles; i++) { descriptors[i] = (STREQ (files[i], "-") - ? stdout - : fopen (files[i], mode_string)); + ? stdout + : fopen (files[i], mode_string)); if (descriptors[i] == NULL) - { - error (0, errno, "%s", files[i]); - ok = false; - } + { + error (0, errno, "%s", files[i]); + ok = false; + } else - setvbuf (descriptors[i], NULL, _IONBF, 0); + setvbuf (descriptors[i], NULL, _IONBF, 0); } while (1) @@ -185,18 +185,18 @@ tee_files (int nfiles, const char **files) continue; #endif if (bytes_read <= 0) - break; + break; /* Write to all NFILES + 1 descriptors. - Standard output is the first one. */ + Standard output is the first one. */ for (i = 0; i <= nfiles; i++) - if (descriptors[i] - && fwrite (buffer, bytes_read, 1, descriptors[i]) != 1) - { - error (0, errno, "%s", files[i]); - descriptors[i] = NULL; - ok = false; - } + if (descriptors[i] + && fwrite (buffer, bytes_read, 1, descriptors[i]) != 1) + { + error (0, errno, "%s", files[i]); + descriptors[i] = NULL; + ok = false; + } } if (bytes_read == -1) @@ -208,10 +208,10 @@ tee_files (int nfiles, const char **files) /* Close the files, but not standard output. */ for (i = 1; i <= nfiles; i++) if (!STREQ (files[i], "-") - && descriptors[i] && fclose (descriptors[i]) != 0) + && descriptors[i] && fclose (descriptors[i]) != 0) { - error (0, errno, "%s", files[i]); - ok = false; + error (0, errno, "%s", files[i]); + ok = false; } free (descriptors); diff --git a/src/test.c b/src/test.c index 1825e901a..f7c689cf9 100644 --- a/src/test.c +++ b/src/test.c @@ -143,11 +143,11 @@ find_int (char const *string) if (ISDIGIT (*p++)) { while (ISDIGIT (*p)) - p++; + p++; while (isblank (to_uchar (*p))) - p++; + p++; if (!*p) - return number_start; + return number_start; } test_syntax_error (_("invalid integer %s"), quote (string)); @@ -174,9 +174,9 @@ static bool binop (char const *s) { return ((STREQ (s, "=")) || (STREQ (s, "!=")) || (STREQ (s, "-nt")) || - (STREQ (s, "-ot")) || (STREQ (s, "-ef")) || (STREQ (s, "-eq")) || - (STREQ (s, "-ne")) || (STREQ (s, "-lt")) || (STREQ (s, "-le")) || - (STREQ (s, "-gt")) || (STREQ (s, "-ge"))); + (STREQ (s, "-ot")) || (STREQ (s, "-ef")) || (STREQ (s, "-eq")) || + (STREQ (s, "-ne")) || (STREQ (s, "-lt")) || (STREQ (s, "-le")) || + (STREQ (s, "-gt")) || (STREQ (s, "-ge"))); } /* @@ -221,20 +221,20 @@ term (void) advance (true); for (nargs = 1; - pos + nargs < argc && ! STREQ (argv[pos + nargs], ")"); - nargs++) - if (nargs == 4) - { - nargs = argc - pos; - break; - } + pos + nargs < argc && ! STREQ (argv[pos + nargs], ")"); + nargs++) + if (nargs == 4) + { + nargs = argc - pos; + break; + } value = posixtest (nargs); if (argv[pos] == 0) - test_syntax_error (_("')' expected"), NULL); + test_syntax_error (_("')' expected"), NULL); else if (argv[pos][0] != ')' || argv[pos][1]) - test_syntax_error (_("')' expected, found %s"), argv[pos]); + test_syntax_error (_("')' expected, found %s"), argv[pos]); advance (false); } @@ -248,9 +248,9 @@ term (void) else if (argv[pos][0] == '-' && argv[pos][1] && argv[pos][2] == '\0') { if (test_unop (argv[pos])) - value = unary_operator (); + value = unary_operator (); else - test_syntax_error (_("%s: unary operator expected"), argv[pos]); + test_syntax_error (_("%s: unary operator expected"), argv[pos]); } else { @@ -285,76 +285,76 @@ binary_operator (bool l_is_l) { /* check for eq, nt, and stuff */ if ((((argv[op][1] == 'l' || argv[op][1] == 'g') - && (argv[op][2] == 'e' || argv[op][2] == 't')) - || (argv[op][1] == 'e' && argv[op][2] == 'q') - || (argv[op][1] == 'n' && argv[op][2] == 'e')) - && !argv[op][3]) - { - char lbuf[INT_BUFSIZE_BOUND (uintmax_t)]; - char rbuf[INT_BUFSIZE_BOUND (uintmax_t)]; - char const *l = (l_is_l - ? umaxtostr (strlen (argv[op - 1]), lbuf) - : find_int (argv[op - 1])); - char const *r = (r_is_l - ? umaxtostr (strlen (argv[op + 2]), rbuf) - : find_int (argv[op + 1])); - int cmp = strintcmp (l, r); - bool xe_operator = (argv[op][2] == 'e'); - pos += 3; - return (argv[op][1] == 'l' ? cmp < xe_operator - : argv[op][1] == 'g' ? cmp > - xe_operator - : (cmp != 0) == xe_operator); - } + && (argv[op][2] == 'e' || argv[op][2] == 't')) + || (argv[op][1] == 'e' && argv[op][2] == 'q') + || (argv[op][1] == 'n' && argv[op][2] == 'e')) + && !argv[op][3]) + { + char lbuf[INT_BUFSIZE_BOUND (uintmax_t)]; + char rbuf[INT_BUFSIZE_BOUND (uintmax_t)]; + char const *l = (l_is_l + ? umaxtostr (strlen (argv[op - 1]), lbuf) + : find_int (argv[op - 1])); + char const *r = (r_is_l + ? umaxtostr (strlen (argv[op + 2]), rbuf) + : find_int (argv[op + 1])); + int cmp = strintcmp (l, r); + bool xe_operator = (argv[op][2] == 'e'); + pos += 3; + return (argv[op][1] == 'l' ? cmp < xe_operator + : argv[op][1] == 'g' ? cmp > - xe_operator + : (cmp != 0) == xe_operator); + } switch (argv[op][1]) - { - default: - break; - - case 'n': - if (argv[op][2] == 't' && !argv[op][3]) - { - /* nt - newer than */ - struct timespec lt, rt; - bool le, re; - pos += 3; - if (l_is_l | r_is_l) - test_syntax_error (_("-nt does not accept -l"), NULL); - le = get_mtime (argv[op - 1], <); - re = get_mtime (argv[op + 1], &rt); - return le && (!re || timespec_cmp (lt, rt) > 0); - } - break; - - case 'e': - if (argv[op][2] == 'f' && !argv[op][3]) - { - /* ef - hard link? */ - pos += 3; - if (l_is_l | r_is_l) - test_syntax_error (_("-ef does not accept -l"), NULL); - return (stat (argv[op - 1], &stat_buf) == 0 - && stat (argv[op + 1], &stat_spare) == 0 - && stat_buf.st_dev == stat_spare.st_dev - && stat_buf.st_ino == stat_spare.st_ino); - } - break; - - case 'o': - if ('t' == argv[op][2] && '\000' == argv[op][3]) - { - /* ot - older than */ - struct timespec lt, rt; - bool le, re; - pos += 3; - if (l_is_l | r_is_l) - test_syntax_error (_("-ot does not accept -l"), NULL); - le = get_mtime (argv[op - 1], <); - re = get_mtime (argv[op + 1], &rt); - return re && (!le || timespec_cmp (lt, rt) < 0); - } - break; - } + { + default: + break; + + case 'n': + if (argv[op][2] == 't' && !argv[op][3]) + { + /* nt - newer than */ + struct timespec lt, rt; + bool le, re; + pos += 3; + if (l_is_l | r_is_l) + test_syntax_error (_("-nt does not accept -l"), NULL); + le = get_mtime (argv[op - 1], <); + re = get_mtime (argv[op + 1], &rt); + return le && (!re || timespec_cmp (lt, rt) > 0); + } + break; + + case 'e': + if (argv[op][2] == 'f' && !argv[op][3]) + { + /* ef - hard link? */ + pos += 3; + if (l_is_l | r_is_l) + test_syntax_error (_("-ef does not accept -l"), NULL); + return (stat (argv[op - 1], &stat_buf) == 0 + && stat (argv[op + 1], &stat_spare) == 0 + && stat_buf.st_dev == stat_spare.st_dev + && stat_buf.st_ino == stat_spare.st_ino); + } + break; + + case 'o': + if ('t' == argv[op][2] && '\000' == argv[op][3]) + { + /* ot - older than */ + struct timespec lt, rt; + bool le, re; + pos += 3; + if (l_is_l | r_is_l) + test_syntax_error (_("-ot does not accept -l"), NULL); + le = get_mtime (argv[op - 1], <); + re = get_mtime (argv[op + 1], &rt); + return re && (!le || timespec_cmp (lt, rt) < 0); + } + break; + } /* FIXME: is this dead code? */ test_syntax_error (_("unknown binary operator"), argv[op]); @@ -389,9 +389,9 @@ unary_operator (void) return false; /* All of the following unary operators use unary_advance (), which - checks to make sure that there is an argument, and then advances - pos right past it. This means that pos - 1 is the location of the - argument. */ + checks to make sure that there is an argument, and then advances + pos right past it. This means that pos - 1 is the location of the + argument. */ case 'a': /* file exists in the file system? */ case 'e': @@ -413,49 +413,49 @@ unary_operator (void) case 'O': /* File is owned by you? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && (geteuid () == stat_buf.st_uid)); + && (geteuid () == stat_buf.st_uid)); case 'G': /* File is owned by your group? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && (getegid () == stat_buf.st_gid)); + && (getegid () == stat_buf.st_gid)); case 'f': /* File is a file? */ unary_advance (); /* Under POSIX, -f is true if the given file exists - and is a regular file. */ + and is a regular file. */ return (stat (argv[pos - 1], &stat_buf) == 0 - && S_ISREG (stat_buf.st_mode)); + && S_ISREG (stat_buf.st_mode)); case 'd': /* File is a directory? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && S_ISDIR (stat_buf.st_mode)); + && S_ISDIR (stat_buf.st_mode)); case 's': /* File has something in it? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && 0 < stat_buf.st_size); + && 0 < stat_buf.st_size); case 'S': /* File is a socket? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && S_ISSOCK (stat_buf.st_mode)); + && S_ISSOCK (stat_buf.st_mode)); case 'c': /* File is character special? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && S_ISCHR (stat_buf.st_mode)); + && S_ISCHR (stat_buf.st_mode)); case 'b': /* File is block special? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && S_ISBLK (stat_buf.st_mode)); + && S_ISBLK (stat_buf.st_mode)); case 'p': /* File is a named pipe? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && S_ISFIFO (stat_buf.st_mode)); + && S_ISFIFO (stat_buf.st_mode)); case 'L': /* Same as -h */ /*FALLTHROUGH*/ @@ -463,32 +463,32 @@ unary_operator (void) case 'h': /* File is a symbolic link? */ unary_advance (); return (lstat (argv[pos - 1], &stat_buf) == 0 - && S_ISLNK (stat_buf.st_mode)); + && S_ISLNK (stat_buf.st_mode)); case 'u': /* File is setuid? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && (stat_buf.st_mode & S_ISUID)); + && (stat_buf.st_mode & S_ISUID)); case 'g': /* File is setgid? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && (stat_buf.st_mode & S_ISGID)); + && (stat_buf.st_mode & S_ISGID)); case 'k': /* File has sticky bit set? */ unary_advance (); return (stat (argv[pos - 1], &stat_buf) == 0 - && (stat_buf.st_mode & S_ISVTX)); + && (stat_buf.st_mode & S_ISVTX)); case 't': /* File (fd) is a terminal? */ { - long int fd; - char const *arg; - unary_advance (); - arg = find_int (argv[pos - 1]); - errno = 0; - fd = strtol (arg, NULL, 10); - return (errno != ERANGE && 0 <= fd && fd <= INT_MAX && isatty (fd)); + long int fd; + char const *arg; + unary_advance (); + arg = find_int (argv[pos - 1]); + errno = 0; + fd = strtol (arg, NULL, 10); + return (errno != ERANGE && 0 <= fd && fd <= INT_MAX && isatty (fd)); } case 'n': /* True if arg has some length. */ @@ -515,7 +515,7 @@ and (void) { value &= term (); if (! (pos < argc && STREQ (argv[pos], "-a"))) - return value; + return value; advance (false); } } @@ -534,7 +534,7 @@ or (void) { value |= and (); if (! (pos < argc && STREQ (argv[pos], "-o"))) - return value; + return value; advance (false); } } @@ -589,13 +589,13 @@ two_arguments (void) value = ! one_argument (); } else if (argv[pos][0] == '-' - && argv[pos][1] != '\0' - && argv[pos][2] == '\0') + && argv[pos][1] != '\0' + && argv[pos][2] == '\0') { if (test_unop (argv[pos])) - value = unary_operator (); + value = unary_operator (); else - test_syntax_error (_("%s: unary operator expected"), argv[pos]); + test_syntax_error (_("%s: unary operator expected"), argv[pos]); } else beyond (); @@ -636,37 +636,37 @@ posixtest (int nargs) switch (nargs) { case 1: - value = one_argument (); - break; + value = one_argument (); + break; case 2: - value = two_arguments (); - break; + value = two_arguments (); + break; case 3: - value = three_arguments (); - break; + value = three_arguments (); + break; case 4: - if (STREQ (argv[pos], "!")) - { - advance (true); - value = !three_arguments (); - break; - } - if (STREQ (argv[pos], "(") && STREQ (argv[pos + 3], ")")) - { - advance (false); - value = two_arguments (); - advance (false); - break; - } - /* FALLTHROUGH */ + if (STREQ (argv[pos], "!")) + { + advance (true); + value = !three_arguments (); + break; + } + if (STREQ (argv[pos], "(") && STREQ (argv[pos + 3], ")")) + { + advance (false); + value = two_arguments (); + advance (false); + break; + } + /* FALLTHROUGH */ case 5: default: - if (nargs <= 0) - abort (); - value = expr (); + if (nargs <= 0) + abort (); + value = expr (); } return (value); @@ -679,7 +679,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { fputs (_("\ @@ -818,25 +818,25 @@ main (int margc, char **margv) if (LBRACKET) { /* Recognize --help or --version, but only when invoked in the - "[" form, when the last argument is not "]". Use direct - parsing, rather than parse_long_options, to avoid accepting - abbreviations. POSIX allows "[ --help" and "[ --version" to - have the usual GNU behavior, but it requires "test --help" - and "test --version" to exit silently with status 0. */ + "[" form, when the last argument is not "]". Use direct + parsing, rather than parse_long_options, to avoid accepting + abbreviations. POSIX allows "[ --help" and "[ --version" to + have the usual GNU behavior, but it requires "test --help" + and "test --version" to exit silently with status 0. */ if (margc == 2) - { - if (STREQ (margv[1], "--help")) - usage (EXIT_SUCCESS); - - if (STREQ (margv[1], "--version")) - { - version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, - (char *) NULL); - test_exit (EXIT_SUCCESS); - } - } + { + if (STREQ (margv[1], "--help")) + usage (EXIT_SUCCESS); + + if (STREQ (margv[1], "--version")) + { + version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, + (char *) NULL); + test_exit (EXIT_SUCCESS); + } + } if (margc < 2 || !STREQ (margv[margc - 1], "]")) - test_syntax_error (_("missing `]'"), NULL); + test_syntax_error (_("missing `]'"), NULL); --margc; } diff --git a/src/touch.c b/src/touch.c index 3d6d9fac2..ed9847175 100644 --- a/src/touch.c +++ b/src/touch.c @@ -106,7 +106,7 @@ static int const time_masks[] = static void get_reldate (struct timespec *result, - char const *flex_date, struct timespec const *now) + char const *flex_date, struct timespec const *now) { if (! get_date (result, flex_date, now)) error (EXIT_FAILURE, 0, _("invalid date format %s"), quote (flex_date)); @@ -131,54 +131,54 @@ touch (const char *file) { /* Try to open FILE, creating it if necessary. */ fd = fd_reopen (STDIN_FILENO, file, - O_WRONLY | O_CREAT | O_NONBLOCK | O_NOCTTY, - S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); + O_WRONLY | O_CREAT | O_NONBLOCK | O_NOCTTY, + S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); /* Don't save a copy of errno if it's EISDIR, since that would lead - touch to give a bogus diagnostic for e.g., `touch /' (assuming - we don't own / or have write access to it). On Solaris 5.6, - and probably other systems, it is EINVAL. On SunOS4, it's EPERM. */ + touch to give a bogus diagnostic for e.g., `touch /' (assuming + we don't own / or have write access to it). On Solaris 5.6, + and probably other systems, it is EINVAL. On SunOS4, it's EPERM. */ if (fd == -1 && errno != EISDIR && errno != EINVAL && errno != EPERM) - open_errno = errno; + open_errno = errno; } if (change_times != (CH_ATIME | CH_MTIME)) { /* We're setting only one of the time values. stat the target to get - the other one. If we have the file descriptor already, use fstat. - Otherwise, either we're in no-create mode (and hence didn't call open) - or FILE is inaccessible or a directory, so we have to use stat. */ + the other one. If we have the file descriptor already, use fstat. + Otherwise, either we're in no-create mode (and hence didn't call open) + or FILE is inaccessible or a directory, so we have to use stat. */ if (fd != -1 ? fstat (fd, &sbuf) : stat (file, &sbuf)) - { - if (open_errno) - error (0, open_errno, _("creating %s"), quote (file)); - else - { - if (no_create && (errno == ENOENT || errno == EBADF)) - return true; - error (0, errno, _("failed to get attributes of %s"), - quote (file)); - } - if (fd == STDIN_FILENO) - close (fd); - return false; - } + { + if (open_errno) + error (0, open_errno, _("creating %s"), quote (file)); + else + { + if (no_create && (errno == ENOENT || errno == EBADF)) + return true; + error (0, errno, _("failed to get attributes of %s"), + quote (file)); + } + if (fd == STDIN_FILENO) + close (fd); + return false; + } } if (amtime_now) { /* Pass NULL to futimens so it will not fail if we have - write access to the file, but don't own it. */ + write access to the file, but don't own it. */ t = NULL; } else { timespec[0] = (change_times & CH_ATIME - ? newtime[0] - : get_stat_atime (&sbuf)); + ? newtime[0] + : get_stat_atime (&sbuf)); timespec[1] = (change_times & CH_MTIME - ? newtime[1] - : get_stat_mtime (&sbuf)); + ? newtime[1] + : get_stat_mtime (&sbuf)); t = timespec; } @@ -187,35 +187,35 @@ touch (const char *file) if (fd == STDIN_FILENO) { if (close (STDIN_FILENO) != 0) - { - error (0, errno, _("closing %s"), quote (file)); - return false; - } + { + error (0, errno, _("closing %s"), quote (file)); + return false; + } } else if (fd == STDOUT_FILENO) { /* Do not diagnose "touch -c - >&-". */ if (!ok && errno == EBADF && no_create - && change_times == (CH_ATIME | CH_MTIME)) - return true; + && change_times == (CH_ATIME | CH_MTIME)) + return true; } if (!ok) { if (open_errno) - { - /* The wording of this diagnostic should cover at least two cases: - - the file does not exist, but the parent directory is unwritable - - the file exists, but it isn't writable - I think it's not worth trying to distinguish them. */ - error (0, open_errno, _("cannot touch %s"), quote (file)); - } + { + /* The wording of this diagnostic should cover at least two cases: + - the file does not exist, but the parent directory is unwritable + - the file exists, but it isn't writable + I think it's not worth trying to distinguish them. */ + error (0, open_errno, _("cannot touch %s"), quote (file)); + } else - { - if (no_create && errno == ENOENT) - return true; - error (0, errno, _("setting times of %s"), quote (file)); - } + { + if (no_create && errno == ENOENT) + return true; + error (0, errno, _("setting times of %s"), quote (file)); + } return false; } @@ -227,7 +227,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... FILE...\n"), program_name); @@ -291,57 +291,57 @@ main (int argc, char **argv) while ((c = getopt_long (argc, argv, "acd:fmr:t:", longopts, &long_idx)) != -1) { switch (c) - { - case 'a': - change_times |= CH_ATIME; - break; - - case 'c': - no_create = true; - break; - - case 'd': - flex_date = optarg; - break; - - case 'f': - break; - - case 'm': - change_times |= CH_MTIME; - break; - - case 'r': - if (long_idx == 3) - error (0, 0, - _("warning: the --%s option is obsolete; use --reference"), - longopts[long_idx].name); - use_ref = true; - ref_file = optarg; - break; - - case 't': - if (! posixtime (&newtime[0].tv_sec, optarg, - PDS_LEADING_YEAR | PDS_CENTURY | PDS_SECONDS)) - error (EXIT_FAILURE, 0, _("invalid date format %s"), - quote (optarg)); - newtime[0].tv_nsec = 0; - newtime[1] = newtime[0]; - date_set = true; - break; - - case TIME_OPTION: /* --time */ - change_times |= XARGMATCH ("--time", optarg, - time_args, time_masks); - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'a': + change_times |= CH_ATIME; + break; + + case 'c': + no_create = true; + break; + + case 'd': + flex_date = optarg; + break; + + case 'f': + break; + + case 'm': + change_times |= CH_MTIME; + break; + + case 'r': + if (long_idx == 3) + error (0, 0, + _("warning: the --%s option is obsolete; use --reference"), + longopts[long_idx].name); + use_ref = true; + ref_file = optarg; + break; + + case 't': + if (! posixtime (&newtime[0].tv_sec, optarg, + PDS_LEADING_YEAR | PDS_CENTURY | PDS_SECONDS)) + error (EXIT_FAILURE, 0, _("invalid date format %s"), + quote (optarg)); + newtime[0].tv_nsec = 0; + newtime[1] = newtime[0]; + date_set = true; + break; + + case TIME_OPTION: /* --time */ + change_times |= XARGMATCH ("--time", optarg, + time_args, time_masks); + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (change_times == 0) @@ -357,69 +357,69 @@ main (int argc, char **argv) { struct stat ref_stats; if (stat (ref_file, &ref_stats)) - error (EXIT_FAILURE, errno, - _("failed to get attributes of %s"), quote (ref_file)); + error (EXIT_FAILURE, errno, + _("failed to get attributes of %s"), quote (ref_file)); newtime[0] = get_stat_atime (&ref_stats); newtime[1] = get_stat_mtime (&ref_stats); date_set = true; if (flex_date) - { - if (change_times & CH_ATIME) - get_reldate (&newtime[0], flex_date, &newtime[0]); - if (change_times & CH_MTIME) - get_reldate (&newtime[1], flex_date, &newtime[1]); - } + { + if (change_times & CH_ATIME) + get_reldate (&newtime[0], flex_date, &newtime[0]); + if (change_times & CH_MTIME) + get_reldate (&newtime[1], flex_date, &newtime[1]); + } } else { if (flex_date) - { - struct timespec now; - gettime (&now); - get_reldate (&newtime[0], flex_date, &now); - newtime[1] = newtime[0]; - date_set = true; - - /* If neither -a nor -m is specified, treat "-d now" as if - it were absent; this lets "touch" succeed more often in - the presence of restrictive permissions. */ - if (change_times == (CH_ATIME | CH_MTIME) - && newtime[0].tv_sec == now.tv_sec - && newtime[0].tv_nsec == now.tv_nsec) - { - /* Check that it really was "-d now", and not a time - stamp that just happens to be the current time. */ - struct timespec notnow, notnow1; - notnow.tv_sec = now.tv_sec ^ 1; - notnow.tv_nsec = now.tv_nsec; - get_reldate (¬now1, flex_date, ¬now); - if (notnow1.tv_sec == notnow.tv_sec - && notnow1.tv_nsec == notnow.tv_nsec) - date_set = false; - } - } + { + struct timespec now; + gettime (&now); + get_reldate (&newtime[0], flex_date, &now); + newtime[1] = newtime[0]; + date_set = true; + + /* If neither -a nor -m is specified, treat "-d now" as if + it were absent; this lets "touch" succeed more often in + the presence of restrictive permissions. */ + if (change_times == (CH_ATIME | CH_MTIME) + && newtime[0].tv_sec == now.tv_sec + && newtime[0].tv_nsec == now.tv_nsec) + { + /* Check that it really was "-d now", and not a time + stamp that just happens to be the current time. */ + struct timespec notnow, notnow1; + notnow.tv_sec = now.tv_sec ^ 1; + notnow.tv_nsec = now.tv_nsec; + get_reldate (¬now1, flex_date, ¬now); + if (notnow1.tv_sec == notnow.tv_sec + && notnow1.tv_nsec == notnow.tv_nsec) + date_set = false; + } + } } /* The obsolete `MMDDhhmm[YY]' form is valid IFF there are two or more non-option arguments. */ if (!date_set && 2 <= argc - optind && posix2_version () < 200112 && posixtime (&newtime[0].tv_sec, argv[optind], - PDS_TRAILING_YEAR | PDS_PRE_2000)) + PDS_TRAILING_YEAR | PDS_PRE_2000)) { newtime[0].tv_nsec = 0; newtime[1] = newtime[0]; date_set = true; if (! getenv ("POSIXLY_CORRECT")) - { - struct tm const *tm = localtime (&newtime[0].tv_sec); - error (0, 0, - _("warning: `touch %s' is obsolete; use " - "`touch -t %04ld%02d%02d%02d%02d.%02d'"), - argv[optind], - tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday, - tm->tm_hour, tm->tm_min, tm->tm_sec); - } + { + struct tm const *tm = localtime (&newtime[0].tv_sec); + error (0, 0, + _("warning: `touch %s' is obsolete; use " + "`touch -t %04ld%02d%02d%02d%02d.%02d'"), + argv[optind], + tm->tm_year + 1900L, tm->tm_mon + 1, tm->tm_mday, + tm->tm_hour, tm->tm_min, tm->tm_sec); + } optind++; } @@ -427,12 +427,12 @@ main (int argc, char **argv) if (!date_set) { if (change_times == (CH_ATIME | CH_MTIME)) - amtime_now = true; + amtime_now = true; else - { - gettime (&newtime[0]); - newtime[1] = newtime[0]; - } + { + gettime (&newtime[0]); + newtime[1] = newtime[0]; + } } if (optind == argc) @@ -107,21 +107,21 @@ struct List_element struct List_element *next; union { - unsigned char normal_char; - struct /* unnamed */ - { - unsigned char first_char; - unsigned char last_char; - } - range; - enum Char_class char_class; - unsigned char equiv_code; - struct /* unnamed */ - { - unsigned char the_repeated_char; - count repeat_count; - } - repeated_char; + unsigned char normal_char; + struct /* unnamed */ + { + unsigned char first_char; + unsigned char last_char; + } + range; + enum Char_class char_class; + unsigned char equiv_code; + struct /* unnamed */ + { + unsigned char the_repeated_char; + count repeat_count; + } + repeated_char; } u; }; @@ -280,13 +280,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... SET1 [SET2]\n\ "), - program_name); + program_name); fputs (_("\ Translate, squeeze, and/or delete characters from standard input,\n\ writing to standard output.\n\ @@ -445,94 +445,94 @@ unquote (char const *s, struct E_string *es) int oct_digit; switch (s[i]) - { - case '\\': - es->escaped[j] = true; - switch (s[i + 1]) - { - case '\\': - c = '\\'; - break; - case 'a': - c = '\a'; - break; - case 'b': - c = '\b'; - break; - case 'f': - c = '\f'; - break; - case 'n': - c = '\n'; - break; - case 'r': - c = '\r'; - break; - case 't': - c = '\t'; - break; - case 'v': - c = '\v'; - break; - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - c = s[i + 1] - '0'; - oct_digit = s[i + 2] - '0'; - if (0 <= oct_digit && oct_digit <= 7) - { - c = 8 * c + oct_digit; - ++i; - oct_digit = s[i + 2] - '0'; - if (0 <= oct_digit && oct_digit <= 7) - { - if (8 * c + oct_digit < N_CHARS) - { - c = 8 * c + oct_digit; - ++i; - } - else - { - /* A 3-digit octal number larger than \377 won't - fit in 8 bits. So we stop when adding the - next digit would put us over the limit and - give a warning about the ambiguity. POSIX - isn't clear on this, and we interpret this - lack of clarity as meaning the resulting behavior - is undefined, which means we're allowed to issue - a warning. */ - error (0, 0, _("warning: the ambiguous octal escape \ + { + case '\\': + es->escaped[j] = true; + switch (s[i + 1]) + { + case '\\': + c = '\\'; + break; + case 'a': + c = '\a'; + break; + case 'b': + c = '\b'; + break; + case 'f': + c = '\f'; + break; + case 'n': + c = '\n'; + break; + case 'r': + c = '\r'; + break; + case 't': + c = '\t'; + break; + case 'v': + c = '\v'; + break; + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + c = s[i + 1] - '0'; + oct_digit = s[i + 2] - '0'; + if (0 <= oct_digit && oct_digit <= 7) + { + c = 8 * c + oct_digit; + ++i; + oct_digit = s[i + 2] - '0'; + if (0 <= oct_digit && oct_digit <= 7) + { + if (8 * c + oct_digit < N_CHARS) + { + c = 8 * c + oct_digit; + ++i; + } + else + { + /* A 3-digit octal number larger than \377 won't + fit in 8 bits. So we stop when adding the + next digit would put us over the limit and + give a warning about the ambiguity. POSIX + isn't clear on this, and we interpret this + lack of clarity as meaning the resulting behavior + is undefined, which means we're allowed to issue + a warning. */ + error (0, 0, _("warning: the ambiguous octal escape \ \\%c%c%c is being\n\tinterpreted as the 2-byte sequence \\0%c%c, %c"), - s[i], s[i + 1], s[i + 2], - s[i], s[i + 1], s[i + 2]); - } - } - } - break; - case '\0': - error (0, 0, _("warning: an unescaped backslash " - "at end of string is not portable")); - /* POSIX is not clear about this. */ - es->escaped[j] = false; - i--; - c = '\\'; - break; - default: - c = s[i + 1]; - break; - } - ++i; - es->s[j++] = c; - break; - default: - es->s[j++] = s[i]; - break; - } + s[i], s[i + 1], s[i + 2], + s[i], s[i + 1], s[i + 2]); + } + } + } + break; + case '\0': + error (0, 0, _("warning: an unescaped backslash " + "at end of string is not portable")); + /* POSIX is not clear about this. */ + es->escaped[j] = false; + i--; + c = '\\'; + break; + default: + c = s[i + 1]; + break; + } + ++i; + es->s[j++] = c; + break; + default: + es->s[j++] = s[i]; + break; + } } es->len = j; return true; @@ -548,7 +548,7 @@ look_up_char_class (char const *class_str, size_t len) for (i = 0; i < ARRAY_CARDINALITY (char_class_name); i++) if (strncmp (class_str, char_class_name[i], len) == 0 - && strlen (char_class_name[i]) == len) + && strlen (char_class_name[i]) == len) return i; return CC_NO_CLASS; } @@ -596,42 +596,42 @@ make_printable_str (char const *s, size_t len) unsigned char c = s[i]; switch (c) - { - case '\\': - tmp = "\\"; - break; - case '\a': - tmp = "\\a"; - break; - case '\b': - tmp = "\\b"; - break; - case '\f': - tmp = "\\f"; - break; - case '\n': - tmp = "\\n"; - break; - case '\r': - tmp = "\\r"; - break; - case '\t': - tmp = "\\t"; - break; - case '\v': - tmp = "\\v"; - break; - default: - if (isprint (c)) - { - buf[0] = c; - buf[1] = '\0'; - } - else - sprintf (buf, "\\%03o", c); - tmp = buf; - break; - } + { + case '\\': + tmp = "\\"; + break; + case '\a': + tmp = "\\a"; + break; + case '\b': + tmp = "\\b"; + break; + case '\f': + tmp = "\\f"; + break; + case '\n': + tmp = "\\n"; + break; + case '\r': + tmp = "\\r"; + break; + case '\t': + tmp = "\\t"; + break; + case '\v': + tmp = "\\v"; + break; + default: + if (isprint (c)) + { + buf[0] = c; + buf[1] = '\0'; + } + else + sprintf (buf, "\\%03o", c); + tmp = buf; + break; + } p = stpcpy (p, tmp); } return printable_buf; @@ -671,7 +671,7 @@ append_range (struct Spec_list *list, unsigned char first, unsigned char last) error (0, 0, _("range-endpoints of `%s-%s' are in reverse collating sequence order"), - tmp1, tmp2); + tmp1, tmp2); free (tmp1); free (tmp2); return false; @@ -694,7 +694,7 @@ append_range (struct Spec_list *list, unsigned char first, unsigned char last) static bool append_char_class (struct Spec_list *list, - char const *char_class_str, size_t len) + char const *char_class_str, size_t len) { enum Char_class char_class; struct List_element *new; @@ -719,7 +719,7 @@ append_char_class (struct Spec_list *list, static void append_repeated_char (struct Spec_list *list, unsigned char the_char, - count repeat_count) + count repeat_count) { struct List_element *new; @@ -741,7 +741,7 @@ append_repeated_char (struct Spec_list *list, unsigned char the_char, static bool append_equiv_class (struct Spec_list *list, - char const *equiv_class_str, size_t len) + char const *equiv_class_str, size_t len) { struct List_element *new; @@ -765,16 +765,16 @@ append_equiv_class (struct Spec_list *list, static bool find_closing_delim (const struct E_string *es, size_t start_idx, - char pre_bracket_char, size_t *result_idx) + char pre_bracket_char, size_t *result_idx) { size_t i; for (i = start_idx; i < es->len - 1; i++) if (es->s[i] == pre_bracket_char && es->s[i + 1] == ']' - && !es->escaped[i] && !es->escaped[i + 1]) + && !es->escaped[i] && !es->escaped[i + 1]) { - *result_idx = i; - return true; + *result_idx = i; + return true; } return false; } @@ -791,8 +791,8 @@ find_closing_delim (const struct E_string *es, size_t start_idx, static int find_bracketed_repeat (const struct E_string *es, size_t start_idx, - unsigned char *char_to_repeat, count *repeat_count, - size_t *closing_bracket_idx) + unsigned char *char_to_repeat, count *repeat_count, + size_t *closing_bracket_idx) { size_t i; @@ -803,38 +803,38 @@ find_bracketed_repeat (const struct E_string *es, size_t start_idx, for (i = start_idx + 2; i < es->len && !es->escaped[i]; i++) { if (es->s[i] == ']') - { - size_t digit_str_len = i - start_idx - 2; - - *char_to_repeat = es->s[start_idx]; - if (digit_str_len == 0) - { - /* We've matched [c*] -- no explicit repeat count. */ - *repeat_count = 0; - } - else - { - /* Here, we have found [c*s] where s should be a string - of octal (if it starts with `0') or decimal digits. */ - char const *digit_str = &es->s[start_idx + 2]; - char *d_end; - if ((xstrtoumax (digit_str, &d_end, *digit_str == '0' ? 8 : 10, - repeat_count, NULL) - != LONGINT_OK) - || REPEAT_COUNT_MAXIMUM < *repeat_count - || digit_str + digit_str_len != d_end) - { - char *tmp = make_printable_str (digit_str, digit_str_len); - error (0, 0, - _("invalid repeat count %s in [c*n] construct"), - quote (tmp)); - free (tmp); - return -2; - } - } - *closing_bracket_idx = i; - return 0; - } + { + size_t digit_str_len = i - start_idx - 2; + + *char_to_repeat = es->s[start_idx]; + if (digit_str_len == 0) + { + /* We've matched [c*] -- no explicit repeat count. */ + *repeat_count = 0; + } + else + { + /* Here, we have found [c*s] where s should be a string + of octal (if it starts with `0') or decimal digits. */ + char const *digit_str = &es->s[start_idx + 2]; + char *d_end; + if ((xstrtoumax (digit_str, &d_end, *digit_str == '0' ? 8 : 10, + repeat_count, NULL) + != LONGINT_OK) + || REPEAT_COUNT_MAXIMUM < *repeat_count + || digit_str + digit_str_len != d_end) + { + char *tmp = make_printable_str (digit_str, digit_str_len); + error (0, 0, + _("invalid repeat count %s in [c*n] construct"), + quote (tmp)); + free (tmp); + return -2; + } + } + *closing_bracket_idx = i; + return 0; + } } return -1; /* No bracket found. */ } @@ -863,10 +863,10 @@ star_digits_closebracket (const struct E_string *es, size_t idx) - [:str:] Character class where `str' is one of the 12 valid strings. - [=c=] Equivalence class where `c' is any single character. - [c*n] Repeat the single character `c' `n' times. n may be omitted. - However, if `n' is present, it must be a non-negative octal or - decimal integer. + However, if `n' is present, it must be a non-negative octal or + decimal integer. - r-s Range of characters from `r' to `s'. The second endpoint must - not precede the first in the current collating sequence. + not precede the first in the current collating sequence. - c Any other character is interpreted as itself. */ static bool @@ -887,120 +887,120 @@ build_spec_list (const struct E_string *es, struct Spec_list *result) for (i = 0; i + 2 < es->len; /* empty */) { if (es_match (es, i, '[')) - { - bool matched_multi_char_construct; - size_t closing_bracket_idx; - unsigned char char_to_repeat; - count repeat_count; - int err; - - matched_multi_char_construct = true; - if (es_match (es, i + 1, ':') || es_match (es, i + 1, '=')) - { - size_t closing_delim_idx; - - if (find_closing_delim (es, i + 2, p[i + 1], &closing_delim_idx)) - { - size_t opnd_str_len = closing_delim_idx - 1 - (i + 2) + 1; - char const *opnd_str = p + i + 2; - - if (opnd_str_len == 0) - { - if (p[i + 1] == ':') - error (0, 0, _("missing character class name `[::]'")); - else - error (0, 0, - _("missing equivalence class character `[==]'")); - return false; - } - - if (p[i + 1] == ':') - { - /* FIXME: big comment. */ - if (!append_char_class (result, opnd_str, opnd_str_len)) - { - if (star_digits_closebracket (es, i + 2)) - goto try_bracketed_repeat; - else - { - char *tmp = make_printable_str (opnd_str, - opnd_str_len); - error (0, 0, _("invalid character class %s"), - quote (tmp)); - free (tmp); - return false; - } - } - } - else - { - /* FIXME: big comment. */ - if (!append_equiv_class (result, opnd_str, opnd_str_len)) - { - if (star_digits_closebracket (es, i + 2)) - goto try_bracketed_repeat; - else - { - char *tmp = make_printable_str (opnd_str, - opnd_str_len); - error (0, 0, - _("%s: equivalence class operand must be a single character"), - tmp); - free (tmp); - return false; - } - } - } - - i = closing_delim_idx + 2; - continue; - } - /* Else fall through. This could be [:*] or [=*]. */ - } - - try_bracketed_repeat: - - /* Determine whether this is a bracketed repeat range - matching the RE \[.\*(dec_or_oct_number)?\]. */ - err = find_bracketed_repeat (es, i + 1, &char_to_repeat, - &repeat_count, - &closing_bracket_idx); - if (err == 0) - { - append_repeated_char (result, char_to_repeat, repeat_count); - i = closing_bracket_idx + 1; - } - else if (err == -1) - { - matched_multi_char_construct = false; - } - else - { - /* Found a string that looked like [c*n] but the - numeric part was invalid. */ - return false; - } - - if (matched_multi_char_construct) - continue; - - /* We reach this point if P does not match [:str:], [=c=], - [c*n], or [c*]. Now, see if P looks like a range `[-c' - (from `[' to `c'). */ - } + { + bool matched_multi_char_construct; + size_t closing_bracket_idx; + unsigned char char_to_repeat; + count repeat_count; + int err; + + matched_multi_char_construct = true; + if (es_match (es, i + 1, ':') || es_match (es, i + 1, '=')) + { + size_t closing_delim_idx; + + if (find_closing_delim (es, i + 2, p[i + 1], &closing_delim_idx)) + { + size_t opnd_str_len = closing_delim_idx - 1 - (i + 2) + 1; + char const *opnd_str = p + i + 2; + + if (opnd_str_len == 0) + { + if (p[i + 1] == ':') + error (0, 0, _("missing character class name `[::]'")); + else + error (0, 0, + _("missing equivalence class character `[==]'")); + return false; + } + + if (p[i + 1] == ':') + { + /* FIXME: big comment. */ + if (!append_char_class (result, opnd_str, opnd_str_len)) + { + if (star_digits_closebracket (es, i + 2)) + goto try_bracketed_repeat; + else + { + char *tmp = make_printable_str (opnd_str, + opnd_str_len); + error (0, 0, _("invalid character class %s"), + quote (tmp)); + free (tmp); + return false; + } + } + } + else + { + /* FIXME: big comment. */ + if (!append_equiv_class (result, opnd_str, opnd_str_len)) + { + if (star_digits_closebracket (es, i + 2)) + goto try_bracketed_repeat; + else + { + char *tmp = make_printable_str (opnd_str, + opnd_str_len); + error (0, 0, + _("%s: equivalence class operand must be a single character"), + tmp); + free (tmp); + return false; + } + } + } + + i = closing_delim_idx + 2; + continue; + } + /* Else fall through. This could be [:*] or [=*]. */ + } + + try_bracketed_repeat: + + /* Determine whether this is a bracketed repeat range + matching the RE \[.\*(dec_or_oct_number)?\]. */ + err = find_bracketed_repeat (es, i + 1, &char_to_repeat, + &repeat_count, + &closing_bracket_idx); + if (err == 0) + { + append_repeated_char (result, char_to_repeat, repeat_count); + i = closing_bracket_idx + 1; + } + else if (err == -1) + { + matched_multi_char_construct = false; + } + else + { + /* Found a string that looked like [c*n] but the + numeric part was invalid. */ + return false; + } + + if (matched_multi_char_construct) + continue; + + /* We reach this point if P does not match [:str:], [=c=], + [c*n], or [c*]. Now, see if P looks like a range `[-c' + (from `[' to `c'). */ + } /* Look ahead one char for ranges like a-z. */ if (es_match (es, i + 1, '-')) - { - if (!append_range (result, p[i], p[i + 2])) - return false; - i += 3; - } + { + if (!append_range (result, p[i], p[i + 2])) + return false; + i += 3; + } else - { - append_normal_char (result, p[i]); - ++i; - } + { + append_normal_char (result, p[i]); + ++i; + } } /* Now handle the (2 or fewer) remaining characters p[i]..p[es->len - 1]. */ @@ -1063,53 +1063,53 @@ get_next (struct Spec_list *s, enum Upper_Lower_class *class) case RE_RANGE: if (s->state == NEW_ELEMENT) - s->state = p->u.range.first_char; + s->state = p->u.range.first_char; else - ++(s->state); + ++(s->state); return_val = s->state; if (s->state == p->u.range.last_char) - { - s->tail = p->next; - s->state = NEW_ELEMENT; - } + { + s->tail = p->next; + s->state = NEW_ELEMENT; + } break; case RE_CHAR_CLASS: if (class) - { - switch (p->u.char_class) - { - case CC_LOWER: - *class = UL_LOWER; - break; - case CC_UPPER: - *class = UL_UPPER; - break; - default: - break; - } - } + { + switch (p->u.char_class) + { + case CC_LOWER: + *class = UL_LOWER; + break; + case CC_UPPER: + *class = UL_UPPER; + break; + default: + break; + } + } if (s->state == NEW_ELEMENT) - { - for (i = 0; i < N_CHARS; i++) - if (is_char_class_member (p->u.char_class, i)) - break; - assert (i < N_CHARS); - s->state = i; - } + { + for (i = 0; i < N_CHARS; i++) + if (is_char_class_member (p->u.char_class, i)) + break; + assert (i < N_CHARS); + s->state = i; + } assert (is_char_class_member (p->u.char_class, s->state)); return_val = s->state; for (i = s->state + 1; i < N_CHARS; i++) - if (is_char_class_member (p->u.char_class, i)) - break; + if (is_char_class_member (p->u.char_class, i)) + break; if (i < N_CHARS) - s->state = i; + s->state = i; else - { - s->tail = p->next; - s->state = NEW_ELEMENT; - } + { + s->tail = p->next; + s->state = NEW_ELEMENT; + } break; case RE_EQUIV_CLASS: @@ -1126,25 +1126,25 @@ get_next (struct Spec_list *s, enum Upper_Lower_class *class) case RE_REPEATED_CHAR: /* Here, a repeat count of n == 0 means don't repeat at all. */ if (p->u.repeated_char.repeat_count == 0) - { - s->tail = p->next; - s->state = NEW_ELEMENT; - return_val = get_next (s, class); - } + { + s->tail = p->next; + s->state = NEW_ELEMENT; + return_val = get_next (s, class); + } else - { - if (s->state == NEW_ELEMENT) - { - s->state = 0; - } - ++(s->state); - return_val = p->u.repeated_char.the_repeated_char; - if (s->state == p->u.repeated_char.repeat_count) - { - s->tail = p->next; - s->state = NEW_ELEMENT; - } - } + { + if (s->state == NEW_ELEMENT) + { + s->state = 0; + } + ++(s->state); + return_val = p->u.repeated_char.the_repeated_char; + if (s->state == p->u.repeated_char.repeat_count) + { + s->tail = p->next; + s->state = NEW_ELEMENT; + } + } break; default: @@ -1206,61 +1206,61 @@ get_spec_stats (struct Spec_list *s) count new_length; switch (p->type) - { - case RE_NORMAL_CHAR: - len = 1; - break; - - case RE_RANGE: - assert (p->u.range.last_char >= p->u.range.first_char); - len = p->u.range.last_char - p->u.range.first_char + 1; - break; - - case RE_CHAR_CLASS: - s->has_char_class = true; - for (i = 0; i < N_CHARS; i++) - if (is_char_class_member (p->u.char_class, i)) - ++len; - switch (p->u.char_class) - { - case CC_UPPER: - case CC_LOWER: - break; - default: - s->has_restricted_char_class = true; - break; - } - break; - - case RE_EQUIV_CLASS: - for (i = 0; i < N_CHARS; i++) - if (is_equiv_class_member (p->u.equiv_code, i)) - ++len; - s->has_equiv_class = true; - break; - - case RE_REPEATED_CHAR: - if (p->u.repeated_char.repeat_count > 0) - len = p->u.repeated_char.repeat_count; - else - { - s->indefinite_repeat_element = p; - ++(s->n_indefinite_repeats); - } - break; - - default: - abort (); - break; - } + { + case RE_NORMAL_CHAR: + len = 1; + break; + + case RE_RANGE: + assert (p->u.range.last_char >= p->u.range.first_char); + len = p->u.range.last_char - p->u.range.first_char + 1; + break; + + case RE_CHAR_CLASS: + s->has_char_class = true; + for (i = 0; i < N_CHARS; i++) + if (is_char_class_member (p->u.char_class, i)) + ++len; + switch (p->u.char_class) + { + case CC_UPPER: + case CC_LOWER: + break; + default: + s->has_restricted_char_class = true; + break; + } + break; + + case RE_EQUIV_CLASS: + for (i = 0; i < N_CHARS; i++) + if (is_equiv_class_member (p->u.equiv_code, i)) + ++len; + s->has_equiv_class = true; + break; + + case RE_REPEATED_CHAR: + if (p->u.repeated_char.repeat_count > 0) + len = p->u.repeated_char.repeat_count; + else + { + s->indefinite_repeat_element = p; + ++(s->n_indefinite_repeats); + } + break; + + default: + abort (); + break; + } /* Check for arithmetic overflow in computing length. Also, reject - any length greater than the maximum repeat count, in case the - length is later used to compute the repeat count for an - indefinite element. */ + any length greater than the maximum repeat count, in case the + length is later used to compute the repeat count for an + indefinite element. */ new_length = length + len; if (! (length <= new_length && new_length <= REPEAT_COUNT_MAXIMUM)) - error (EXIT_FAILURE, 0, _("too many characters in set")); + error (EXIT_FAILURE, 0, _("too many characters in set")); length = new_length; } @@ -1282,7 +1282,7 @@ get_s2_spec_stats (struct Spec_list *s2, count len_s1) if (len_s1 >= s2->length && s2->n_indefinite_repeats == 1) { s2->indefinite_repeat_element->u.repeated_char.repeat_count = - len_s1 - s2->length; + len_s1 - s2->length; s2->length = len_s1; } } @@ -1347,8 +1347,8 @@ string2_extend (const struct Spec_list *s1, struct Spec_list *s2) break; case RE_CHAR_CLASS: for (i = N_CHARS - 1; i >= 0; i--) - if (is_char_class_member (p->u.char_class, i)) - break; + if (is_char_class_member (p->u.char_class, i)) + break; assert (i >= 0); char_to_repeat = i; break; @@ -1408,7 +1408,7 @@ validate (struct Spec_list *s1, struct Spec_list *s2) if (s1->n_indefinite_repeats > 0) { error (EXIT_FAILURE, 0, - _("the [c*] repeat construct may not appear in string1")); + _("the [c*] repeat construct may not appear in string1")); } if (s2) @@ -1416,57 +1416,57 @@ validate (struct Spec_list *s1, struct Spec_list *s2) get_s2_spec_stats (s2, s1->length); if (s2->n_indefinite_repeats > 1) - { - error (EXIT_FAILURE, 0, - _("only one [c*] repeat construct may appear in string2")); - } + { + error (EXIT_FAILURE, 0, + _("only one [c*] repeat construct may appear in string2")); + } if (translating) - { - if (s2->has_equiv_class) - { - error (EXIT_FAILURE, 0, - _("[=c=] expressions may not appear in string2 \ + { + if (s2->has_equiv_class) + { + error (EXIT_FAILURE, 0, + _("[=c=] expressions may not appear in string2 \ when translating")); - } - - if (s1->length > s2->length) - { - if (!truncate_set1) - { - /* string2 must be non-empty unless --truncate-set1 is - given or string1 is empty. */ - - if (s2->length == 0) - error (EXIT_FAILURE, 0, - _("when not truncating set1, string2 must be non-empty")); - string2_extend (s1, s2); - } - } - - if (complement && s1->has_char_class - && ! (s2->length == s1->length && homogeneous_spec_list (s2))) - { - error (EXIT_FAILURE, 0, - _("when translating with complemented character classes,\ + } + + if (s1->length > s2->length) + { + if (!truncate_set1) + { + /* string2 must be non-empty unless --truncate-set1 is + given or string1 is empty. */ + + if (s2->length == 0) + error (EXIT_FAILURE, 0, + _("when not truncating set1, string2 must be non-empty")); + string2_extend (s1, s2); + } + } + + if (complement && s1->has_char_class + && ! (s2->length == s1->length && homogeneous_spec_list (s2))) + { + error (EXIT_FAILURE, 0, + _("when translating with complemented character classes,\ \nstring2 must map all characters in the domain to one")); - } + } - if (s2->has_restricted_char_class) - { - error (EXIT_FAILURE, 0, - _("when translating, the only character classes that may \ + if (s2->has_restricted_char_class) + { + error (EXIT_FAILURE, 0, + _("when translating, the only character classes that may \ appear in\nstring2 are `upper' and `lower'")); - } - } + } + } else - /* Not translating. */ - { - if (s2->n_indefinite_repeats > 0) - error (EXIT_FAILURE, 0, - _("the [c*] construct may appear in string2 only \ + /* Not translating. */ + { + if (s2->n_indefinite_repeats > 0) + error (EXIT_FAILURE, 0, + _("the [c*] construct may appear in string2 only \ when translating")); - } + } } } @@ -1494,74 +1494,74 @@ squeeze_filter (char *buf, size_t size, size_t (*reader) (char *, size_t)) size_t begin; if (i >= nr) - { - nr = reader (buf, size); - if (nr == 0) - break; - i = 0; - } + { + nr = reader (buf, size); + if (nr == 0) + break; + i = 0; + } begin = i; if (char_to_squeeze == NOT_A_CHAR) - { - size_t out_len; - /* Here, by being a little tricky, we can get a significant - performance increase in most cases when the input is - reasonably large. Since tr will modify the input only - if two consecutive (and identical) input characters are - in the squeeze set, we can step by two through the data - when searching for a character in the squeeze set. This - means there may be a little more work in a few cases and - perhaps twice as much work in the worst cases where most - of the input is removed by squeezing repeats. But most - uses of this functionality seem to remove less than 20-30% - of the input. */ - for (; i < nr && !in_squeeze_set[to_uchar (buf[i])]; i += 2) - continue; - - /* There is a special case when i == nr and we've just - skipped a character (the last one in buf) that is in - the squeeze set. */ - if (i == nr && in_squeeze_set[to_uchar (buf[i - 1])]) - --i; - - if (i >= nr) - out_len = nr - begin; - else - { - char_to_squeeze = buf[i]; - /* We're about to output buf[begin..i]. */ - out_len = i - begin + 1; - - /* But since we stepped by 2 in the loop above, - out_len may be one too large. */ - if (i > 0 && buf[i - 1] == char_to_squeeze) - --out_len; - - /* Advance i to the index of first character to be - considered when looking for a char different from - char_to_squeeze. */ - ++i; - } - if (out_len > 0 - && fwrite (&buf[begin], 1, out_len, stdout) != out_len) - error (EXIT_FAILURE, errno, _("write error")); - } + { + size_t out_len; + /* Here, by being a little tricky, we can get a significant + performance increase in most cases when the input is + reasonably large. Since tr will modify the input only + if two consecutive (and identical) input characters are + in the squeeze set, we can step by two through the data + when searching for a character in the squeeze set. This + means there may be a little more work in a few cases and + perhaps twice as much work in the worst cases where most + of the input is removed by squeezing repeats. But most + uses of this functionality seem to remove less than 20-30% + of the input. */ + for (; i < nr && !in_squeeze_set[to_uchar (buf[i])]; i += 2) + continue; + + /* There is a special case when i == nr and we've just + skipped a character (the last one in buf) that is in + the squeeze set. */ + if (i == nr && in_squeeze_set[to_uchar (buf[i - 1])]) + --i; + + if (i >= nr) + out_len = nr - begin; + else + { + char_to_squeeze = buf[i]; + /* We're about to output buf[begin..i]. */ + out_len = i - begin + 1; + + /* But since we stepped by 2 in the loop above, + out_len may be one too large. */ + if (i > 0 && buf[i - 1] == char_to_squeeze) + --out_len; + + /* Advance i to the index of first character to be + considered when looking for a char different from + char_to_squeeze. */ + ++i; + } + if (out_len > 0 + && fwrite (&buf[begin], 1, out_len, stdout) != out_len) + error (EXIT_FAILURE, errno, _("write error")); + } if (char_to_squeeze != NOT_A_CHAR) - { - /* Advance i to index of first char != char_to_squeeze - (or to nr if all the rest of the characters in this - buffer are the same as char_to_squeeze). */ - for (; i < nr && buf[i] == char_to_squeeze; i++) - continue; - if (i < nr) - char_to_squeeze = NOT_A_CHAR; - /* If (i >= nr) we've squeezed the last character in this buffer. - So now we have to read a new buffer and continue comparing - characters against char_to_squeeze. */ - } + { + /* Advance i to index of first char != char_to_squeeze + (or to nr if all the rest of the characters in this + buffer are the same as char_to_squeeze). */ + for (; i < nr && buf[i] == char_to_squeeze; i++) + continue; + if (i < nr) + char_to_squeeze = NOT_A_CHAR; + /* If (i >= nr) we've squeezed the last character in this buffer. + So now we have to read a new buffer and continue comparing + characters against char_to_squeeze. */ + } } } @@ -1594,7 +1594,7 @@ read_and_delete (char *buf, size_t size) size_t nr = plain_read (buf, size); if (nr == 0) - return 0; + return 0; /* This first loop may be a waste of code, but gives much better performance when no characters are deleted in @@ -1602,12 +1602,12 @@ read_and_delete (char *buf, size_t size) of buf[i] into buf[n_saved] when it would be a NOP. */ for (i = 0; i < nr && !in_delete_set[to_uchar (buf[i])]; i++) - continue; + continue; n_saved = i; for (++i; i < nr; i++) - if (!in_delete_set[to_uchar (buf[i])]) - buf[n_saved++] = buf[i]; + if (!in_delete_set[to_uchar (buf[i])]) + buf[n_saved++] = buf[i]; } while (n_saved == 0); @@ -1672,32 +1672,32 @@ main (int argc, char **argv) while ((c = getopt_long (argc, argv, "+cCdst", long_options, NULL)) != -1) { switch (c) - { - case 'c': - case 'C': - complement = true; - break; + { + case 'c': + case 'C': + complement = true; + break; - case 'd': - delete = true; - break; + case 'd': + delete = true; + break; - case 's': - squeeze_repeats = true; - break; + case 's': + squeeze_repeats = true; + break; - case 't': - truncate_set1 = true; - break; + case 't': + truncate_set1 = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - break; - } + default: + usage (EXIT_FAILURE); + break; + } } non_option_args = argc - optind; @@ -1708,16 +1708,16 @@ main (int argc, char **argv) if (non_option_args < min_operands) { if (non_option_args == 0) - error (0, 0, _("missing operand")); + error (0, 0, _("missing operand")); else - { - error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); - fprintf (stderr, "%s\n", - _(squeeze_repeats - ? N_("Two strings must be given when " - "both deleting and squeezing repeats.") - : N_("Two strings must be given when translating."))); - } + { + error (0, 0, _("missing operand after %s"), quote (argv[argc - 1])); + fprintf (stderr, "%s\n", + _(squeeze_repeats + ? N_("Two strings must be given when " + "both deleting and squeezing repeats.") + : N_("Two strings must be given when translating."))); + } usage (EXIT_FAILURE); } @@ -1725,9 +1725,9 @@ main (int argc, char **argv) { error (0, 0, _("extra operand %s"), quote (argv[optind + max_operands])); if (non_option_args == 2) - fprintf (stderr, "%s\n", - _("Only one string may be given when " - "deleting without squeezing repeats.")); + fprintf (stderr, "%s\n", + _("Only one string may be given when " + "deleting without squeezing repeats.")); usage (EXIT_FAILURE); } @@ -1739,7 +1739,7 @@ main (int argc, char **argv) { spec_init (s2); if (!parse_str (argv[optind + 1], s2)) - exit (EXIT_FAILURE); + exit (EXIT_FAILURE); } else s2 = NULL; @@ -1764,13 +1764,13 @@ main (int argc, char **argv) set_initialize (s1, complement, in_delete_set); for (;;) - { - size_t nr = read_and_delete (io_buf, sizeof io_buf); - if (nr == 0) - break; - if (fwrite (io_buf, 1, nr, stdout) != nr) - error (EXIT_FAILURE, errno, _("write error")); - } + { + size_t nr = read_and_delete (io_buf, sizeof io_buf); + if (nr == 0) + break; + if (fwrite (io_buf, 1, nr, stdout) != nr) + error (EXIT_FAILURE, errno, _("write error")); + } } else if (squeeze_repeats && delete && non_option_args == 2) { @@ -1781,111 +1781,111 @@ main (int argc, char **argv) else if (translating) { if (complement) - { - int i; - bool *in_s1 = in_delete_set; - - set_initialize (s1, false, in_s1); - s2->state = BEGIN_STATE; - for (i = 0; i < N_CHARS; i++) - xlate[i] = i; - for (i = 0; i < N_CHARS; i++) - { - if (!in_s1[i]) - { - int ch = get_next (s2, NULL); - assert (ch != -1 || truncate_set1); - if (ch == -1) - { - /* This will happen when tr is invoked like e.g. - tr -cs A-Za-z0-9 '\012'. */ - break; - } - xlate[i] = ch; - } - } - } + { + int i; + bool *in_s1 = in_delete_set; + + set_initialize (s1, false, in_s1); + s2->state = BEGIN_STATE; + for (i = 0; i < N_CHARS; i++) + xlate[i] = i; + for (i = 0; i < N_CHARS; i++) + { + if (!in_s1[i]) + { + int ch = get_next (s2, NULL); + assert (ch != -1 || truncate_set1); + if (ch == -1) + { + /* This will happen when tr is invoked like e.g. + tr -cs A-Za-z0-9 '\012'. */ + break; + } + xlate[i] = ch; + } + } + } else - { - int c1, c2; - int i; - bool case_convert = false; - enum Upper_Lower_class class_s1; - enum Upper_Lower_class class_s2; - - for (i = 0; i < N_CHARS; i++) - xlate[i] = i; - s1->state = BEGIN_STATE; - s2->state = BEGIN_STATE; - for (;;) - { - /* When the previous pair identified case-converting classes, - advance S1 and S2 so that each points to the following - construct. */ - if (case_convert) - { - skip_construct (s1); - skip_construct (s2); - case_convert = false; - } - - c1 = get_next (s1, &class_s1); - c2 = get_next (s2, &class_s2); - - /* When translating and there is an [:upper:] or [:lower:] - class in SET2, then there must be a corresponding [:lower:] - or [:upper:] class in SET1. */ - if (class_s1 == UL_NONE - && (class_s2 == UL_LOWER || class_s2 == UL_UPPER)) - error (EXIT_FAILURE, 0, - _("misaligned [:upper:] and/or [:lower:] construct")); - - if (class_s1 == UL_LOWER && class_s2 == UL_UPPER) - { - case_convert = true; - for (i = 0; i < N_CHARS; i++) - if (islower (i)) - xlate[i] = toupper (i); - } - else if (class_s1 == UL_UPPER && class_s2 == UL_LOWER) - { - case_convert = true; - for (i = 0; i < N_CHARS; i++) - if (isupper (i)) - xlate[i] = tolower (i); - } - else if ((class_s1 == UL_LOWER && class_s2 == UL_LOWER) - || (class_s1 == UL_UPPER && class_s2 == UL_UPPER)) - { - /* POSIX says the behavior of `tr "[:upper:]" "[:upper:]"' - is undefined. Treat it as a no-op. */ - } - else - { - /* The following should have been checked by validate... */ - if (c1 == -1 || c2 == -1) - break; - xlate[c1] = c2; - } - } - assert (c1 == -1 || truncate_set1); - } + { + int c1, c2; + int i; + bool case_convert = false; + enum Upper_Lower_class class_s1; + enum Upper_Lower_class class_s2; + + for (i = 0; i < N_CHARS; i++) + xlate[i] = i; + s1->state = BEGIN_STATE; + s2->state = BEGIN_STATE; + for (;;) + { + /* When the previous pair identified case-converting classes, + advance S1 and S2 so that each points to the following + construct. */ + if (case_convert) + { + skip_construct (s1); + skip_construct (s2); + case_convert = false; + } + + c1 = get_next (s1, &class_s1); + c2 = get_next (s2, &class_s2); + + /* When translating and there is an [:upper:] or [:lower:] + class in SET2, then there must be a corresponding [:lower:] + or [:upper:] class in SET1. */ + if (class_s1 == UL_NONE + && (class_s2 == UL_LOWER || class_s2 == UL_UPPER)) + error (EXIT_FAILURE, 0, + _("misaligned [:upper:] and/or [:lower:] construct")); + + if (class_s1 == UL_LOWER && class_s2 == UL_UPPER) + { + case_convert = true; + for (i = 0; i < N_CHARS; i++) + if (islower (i)) + xlate[i] = toupper (i); + } + else if (class_s1 == UL_UPPER && class_s2 == UL_LOWER) + { + case_convert = true; + for (i = 0; i < N_CHARS; i++) + if (isupper (i)) + xlate[i] = tolower (i); + } + else if ((class_s1 == UL_LOWER && class_s2 == UL_LOWER) + || (class_s1 == UL_UPPER && class_s2 == UL_UPPER)) + { + /* POSIX says the behavior of `tr "[:upper:]" "[:upper:]"' + is undefined. Treat it as a no-op. */ + } + else + { + /* The following should have been checked by validate... */ + if (c1 == -1 || c2 == -1) + break; + xlate[c1] = c2; + } + } + assert (c1 == -1 || truncate_set1); + } if (squeeze_repeats) - { - set_initialize (s2, false, in_squeeze_set); - squeeze_filter (io_buf, sizeof io_buf, read_and_xlate); - } + { + set_initialize (s2, false, in_squeeze_set); + squeeze_filter (io_buf, sizeof io_buf, read_and_xlate); + } else - { - for (;;) - { - size_t bytes_read = read_and_xlate (io_buf, sizeof io_buf); - if (bytes_read == 0) - break; - if (fwrite (io_buf, 1, bytes_read, stdout) != bytes_read) - error (EXIT_FAILURE, errno, _("write error")); - } - } + { + for (;;) + { + size_t bytes_read = read_and_xlate (io_buf, sizeof io_buf); + if (bytes_read == 0) + break; + if (fwrite (io_buf, 1, bytes_read, stdout) != bytes_read) + error (EXIT_FAILURE, errno, _("write error")); + } + } } if (close (STDIN_FILENO) != 0) diff --git a/src/true.c b/src/true.c index 46b41b988..66d1e0111 100644 --- a/src/true.c +++ b/src/true.c @@ -39,11 +39,11 @@ usage (int status) Usage: %s [ignored command line arguments]\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); printf ("%s\n\n", - _(EXIT_STATUS == EXIT_SUCCESS - ? N_("Exit with a status code indicating success.") - : N_("Exit with a status code indicating failure."))); + _(EXIT_STATUS == EXIT_SUCCESS + ? N_("Exit with a status code indicating success.") + : N_("Exit with a status code indicating failure."))); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); printf (USAGE_BUILTIN_WARNING, PROGRAM_NAME); @@ -67,11 +67,11 @@ main (int argc, char **argv) if (argc == 2) { if (STREQ (argv[1], "--help")) - usage (EXIT_STATUS); + usage (EXIT_STATUS); if (STREQ (argv[1], "--version")) - version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, - (char *) NULL); + version_etc (stdout, PROGRAM_NAME, PACKAGE_NAME, Version, AUTHORS, + (char *) NULL); } exit (EXIT_STATUS); diff --git a/src/tsort.c b/src/tsort.c index 614ba9dba..d74b62091 100644 --- a/src/tsort.c +++ b/src/tsort.c @@ -76,7 +76,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ @@ -141,120 +141,120 @@ search_item (struct item *root, const char *str) /* A2. Compare. */ a = strcmp (str, p->str); if (a == 0) - return p; + return p; /* A3 & A4. Move left & right. */ if (a < 0) - q = p->left; + q = p->left; else - q = p->right; + q = p->right; if (q == NULL) - { - /* A5. Insert. */ - q = new_item (str); - - /* A3 & A4. (continued). */ - if (a < 0) - p->left = q; - else - p->right = q; - - /* A6. Adjust balance factors. */ - assert (!STREQ (str, s->str)); - if (strcmp (str, s->str) < 0) - { - r = p = s->left; - a = -1; - } - else - { - r = p = s->right; - a = 1; - } - - while (p != q) - { - assert (!STREQ (str, p->str)); - if (strcmp (str, p->str) < 0) - { - p->balance = -1; - p = p->left; - } - else - { - p->balance = 1; - p = p->right; - } - } - - /* A7. Balancing act. */ - if (s->balance == 0 || s->balance == -a) - { - s->balance += a; - return q; - } - - if (r->balance == a) - { - /* A8. Single Rotation. */ - p = r; - if (a < 0) - { - s->left = r->right; - r->right = s; - } - else - { - s->right = r->left; - r->left = s; - } - s->balance = r->balance = 0; - } - else - { - /* A9. Double rotation. */ - if (a < 0) - { - p = r->right; - r->right = p->left; - p->left = r; - s->left = p->right; - p->right = s; - } - else - { - p = r->left; - r->left = p->right; - p->right = r; - s->right = p->left; - p->left = s; - } - - s->balance = 0; - r->balance = 0; - if (p->balance == a) - s->balance = -a; - else if (p->balance == -a) - r->balance = a; - p->balance = 0; - } - - /* A10. Finishing touch. */ - if (s == t->right) - t->right = p; - else - t->left = p; - - return q; - } + { + /* A5. Insert. */ + q = new_item (str); + + /* A3 & A4. (continued). */ + if (a < 0) + p->left = q; + else + p->right = q; + + /* A6. Adjust balance factors. */ + assert (!STREQ (str, s->str)); + if (strcmp (str, s->str) < 0) + { + r = p = s->left; + a = -1; + } + else + { + r = p = s->right; + a = 1; + } + + while (p != q) + { + assert (!STREQ (str, p->str)); + if (strcmp (str, p->str) < 0) + { + p->balance = -1; + p = p->left; + } + else + { + p->balance = 1; + p = p->right; + } + } + + /* A7. Balancing act. */ + if (s->balance == 0 || s->balance == -a) + { + s->balance += a; + return q; + } + + if (r->balance == a) + { + /* A8. Single Rotation. */ + p = r; + if (a < 0) + { + s->left = r->right; + r->right = s; + } + else + { + s->right = r->left; + r->left = s; + } + s->balance = r->balance = 0; + } + else + { + /* A9. Double rotation. */ + if (a < 0) + { + p = r->right; + r->right = p->left; + p->left = r; + s->left = p->right; + p->right = s; + } + else + { + p = r->left; + r->left = p->right; + p->right = r; + s->right = p->left; + p->left = s; + } + + s->balance = 0; + r->balance = 0; + if (p->balance == a) + s->balance = -a; + else if (p->balance == -a) + r->balance = a; + p->balance = 0; + } + + /* A10. Finishing touch. */ + if (s == t->right) + t->right = p; + else + t->left = p; + + return q; + } /* A3 & A4. (continued). */ if (q->balance) - { - t = p; - s = q; - } + { + t = p; + s = q; + } p = q; } @@ -293,9 +293,9 @@ scan_zeros (struct item *k) if (k->count == 0 && k->str) { if (head == NULL) - head = k; + head = k; else - zeros->qlink = k; + zeros->qlink = k; zeros = k; } @@ -327,67 +327,67 @@ detect_loop (struct item *k) if (k->count > 0) { /* K does not have to be part of a cycle. It is however part of - a graph that contains a cycle. */ + a graph that contains a cycle. */ if (loop == NULL) - /* Start traversing the graph at K. */ - loop = k; + /* Start traversing the graph at K. */ + loop = k; else - { - struct successor **p = &k->top; - - while (*p) - { - if ((*p)->suc == loop) - { - if (k->qlink) - { - /* We have found a loop. Retrace our steps. */ - while (loop) - { - struct item *tmp = loop->qlink; - - fprintf (stderr, "%s: %s\n", program_name, - loop->str); - - /* Until we encounter K again. */ - if (loop == k) - { - /* Remove relation. */ - (*p)->suc->count--; - *p = (*p)->next; - break; - } - - /* Tidy things up since we might have to + { + struct successor **p = &k->top; + + while (*p) + { + if ((*p)->suc == loop) + { + if (k->qlink) + { + /* We have found a loop. Retrace our steps. */ + while (loop) + { + struct item *tmp = loop->qlink; + + fprintf (stderr, "%s: %s\n", program_name, + loop->str); + + /* Until we encounter K again. */ + if (loop == k) + { + /* Remove relation. */ + (*p)->suc->count--; + *p = (*p)->next; + break; + } + + /* Tidy things up since we might have to detect another loop. */ - loop->qlink = NULL; - loop = tmp; - } + loop->qlink = NULL; + loop = tmp; + } - while (loop) - { - struct item *tmp = loop->qlink; + while (loop) + { + struct item *tmp = loop->qlink; - loop->qlink = NULL; - loop = tmp; - } + loop->qlink = NULL; + loop = tmp; + } - /* Since we have found the loop, stop walking + /* Since we have found the loop, stop walking the tree. */ - return true; - } - else - { - k->qlink = loop; - loop = k; - break; - } - } - - p = &(*p)->next; - } - } + return true; + } + else + { + k->qlink = loop; + loop = k; + break; + } + } + + p = &(*p)->next; + } + } } return false; @@ -404,13 +404,13 @@ recurse_tree (struct item *root, bool (*action) (struct item *)) else { if (root->left != NULL) - if (recurse_tree (root->left, action)) - return true; + if (recurse_tree (root->left, action)) + return true; if ((*action) (root)) - return true; + return true; if (root->right != NULL) - if (recurse_tree (root->right, action)) - return true; + if (recurse_tree (root->right, action)) + return true; } return false; @@ -451,24 +451,24 @@ tsort (const char *file) /* T2. Next Relation. */ size_t len = readtoken (stdin, DELIM, sizeof (DELIM) - 1, &tokenbuffer); if (len == (size_t) -1) - break; + break; assert (len != 0); k = search_item (root, tokenbuffer.buffer); if (j) - { - /* T3. Record the relation. */ - record_relation (j, k); - k = NULL; - } + { + /* T3. Record the relation. */ + record_relation (j, k); + k = NULL; + } j = k; } if (k != NULL) error (EXIT_FAILURE, 0, _("%s: input contains an odd number of tokens"), - file); + file); /* T1. Initialize (N <- n). */ walk_tree (root, count_items); @@ -479,48 +479,48 @@ tsort (const char *file) walk_tree (root, scan_zeros); while (head) - { - struct successor *p = head->top; - - /* T5. Output front of queue. */ - puts (head->str); - head->str = NULL; /* Avoid printing the same string twice. */ - n_strings--; - - /* T6. Erase relations. */ - while (p) - { - p->suc->count--; - if (p->suc->count == 0) - { - zeros->qlink = p->suc; - zeros = p->suc; - } - - p = p->next; - } - - /* T7. Remove from queue. */ - head = head->qlink; - } + { + struct successor *p = head->top; + + /* T5. Output front of queue. */ + puts (head->str); + head->str = NULL; /* Avoid printing the same string twice. */ + n_strings--; + + /* T6. Erase relations. */ + while (p) + { + p->suc->count--; + if (p->suc->count == 0) + { + zeros->qlink = p->suc; + zeros = p->suc; + } + + p = p->next; + } + + /* T7. Remove from queue. */ + head = head->qlink; + } /* T8. End of process. */ if (n_strings > 0) - { - /* The input contains a loop. */ - error (0, 0, _("%s: input contains a loop:"), file); - ok = false; - - /* Print the loop and remove a relation to break it. */ - do - walk_tree (root, detect_loop); - while (loop); - } + { + /* The input contains a loop. */ + error (0, 0, _("%s: input contains a loop:"), file); + ok = false; + + /* Print the loop and remove a relation to break it. */ + do + walk_tree (root, detect_loop); + while (loop); + } } if (fclose (stdin) != 0) error (EXIT_FAILURE, errno, "%s", - is_stdin ? _("standard input") : quote (file)); + is_stdin ? _("standard input") : quote (file)); return ok; } @@ -539,7 +539,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -59,7 +59,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]...\n"), program_name); @@ -95,18 +95,18 @@ main (int argc, char **argv) while ((optc = getopt_long (argc, argv, "s", longopts, NULL)) != -1) { switch (optc) - { - case 's': - silent = true; - break; + { + case 's': + silent = true; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (TTY_FAILURE); - } + default: + usage (TTY_FAILURE); + } } if (optind < argc) @@ -116,9 +116,9 @@ main (int argc, char **argv) if (!silent) { if (tty) - puts (tty); + puts (tty); else - puts (_("not a tty")); + puts (_("not a tty")); } exit (isatty (STDIN_FILENO) ? EXIT_SUCCESS : EXIT_FAILURE); diff --git a/src/uname.c b/src/uname.c index 12dc7d53d..63b3374e3 100644 --- a/src/uname.c +++ b/src/uname.c @@ -116,7 +116,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]...\n"), program_name); @@ -139,14 +139,14 @@ Print certain system information. With no OPTION, same as -s.\n\ -i, --hardware-platform print the hardware platform or \"unknown\"\n\ -o, --operating-system print the operating system\n\ "), stdout); - } + } else { - fputs (_("\ + fputs (_("\ Print machine architecture.\n\ \n\ "), stdout); - } + } fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); @@ -181,71 +181,71 @@ decode_switches (int argc, char **argv) if (uname_mode == UNAME_ARCH) { while ((c = getopt_long (argc, argv, "", - arch_long_options, NULL)) != -1) - { - switch (c) - { - case_GETOPT_HELP_CHAR; + arch_long_options, NULL)) != -1) + { + switch (c) + { + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, ARCH_AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, ARCH_AUTHORS); - default: - usage (EXIT_FAILURE); - } + default: + usage (EXIT_FAILURE); + } } toprint = PRINT_MACHINE; } else { while ((c = getopt_long (argc, argv, "asnrvmpio", - uname_long_options, NULL)) != -1) + uname_long_options, NULL)) != -1) { - switch (c) - { - case 'a': - toprint = UINT_MAX; - break; + switch (c) + { + case 'a': + toprint = UINT_MAX; + break; - case 's': - toprint |= PRINT_KERNEL_NAME; - break; + case 's': + toprint |= PRINT_KERNEL_NAME; + break; - case 'n': - toprint |= PRINT_NODENAME; - break; + case 'n': + toprint |= PRINT_NODENAME; + break; - case 'r': - toprint |= PRINT_KERNEL_RELEASE; - break; + case 'r': + toprint |= PRINT_KERNEL_RELEASE; + break; - case 'v': - toprint |= PRINT_KERNEL_VERSION; - break; + case 'v': + toprint |= PRINT_KERNEL_VERSION; + break; - case 'm': - toprint |= PRINT_MACHINE; - break; + case 'm': + toprint |= PRINT_MACHINE; + break; - case 'p': - toprint |= PRINT_PROCESSOR; - break; + case 'p': + toprint |= PRINT_PROCESSOR; + break; - case 'i': - toprint |= PRINT_HARDWARE_PLATFORM; - break; + case 'i': + toprint |= PRINT_HARDWARE_PLATFORM; + break; - case 'o': - toprint |= PRINT_OPERATING_SYSTEM; - break; + case 'o': + toprint |= PRINT_OPERATING_SYSTEM; + break; - case_GETOPT_HELP_CHAR; + case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - usage (EXIT_FAILURE); - } - } + default: + usage (EXIT_FAILURE); + } + } } if (argc != optind) @@ -280,23 +280,23 @@ main (int argc, char **argv) if (toprint & (PRINT_KERNEL_NAME | PRINT_NODENAME | PRINT_KERNEL_RELEASE - | PRINT_KERNEL_VERSION | PRINT_MACHINE)) + | PRINT_KERNEL_VERSION | PRINT_MACHINE)) { struct utsname name; if (uname (&name) == -1) - error (EXIT_FAILURE, errno, _("cannot get system name")); + error (EXIT_FAILURE, errno, _("cannot get system name")); if (toprint & PRINT_KERNEL_NAME) - print_element (name.sysname); + print_element (name.sysname); if (toprint & PRINT_NODENAME) - print_element (name.nodename); + print_element (name.nodename); if (toprint & PRINT_KERNEL_RELEASE) - print_element (name.release); + print_element (name.release); if (toprint & PRINT_KERNEL_VERSION) - print_element (name.version); + print_element (name.version); if (toprint & PRINT_MACHINE) - print_element (name.machine); + print_element (name.machine); } if (toprint & PRINT_PROCESSOR) @@ -304,43 +304,43 @@ main (int argc, char **argv) char const *element = unknown; #if HAVE_SYSINFO && defined SI_ARCHITECTURE { - static char processor[257]; - if (0 <= sysinfo (SI_ARCHITECTURE, processor, sizeof processor)) - element = processor; + static char processor[257]; + if (0 <= sysinfo (SI_ARCHITECTURE, processor, sizeof processor)) + element = processor; } #endif #ifdef UNAME_PROCESSOR if (element == unknown) - { - static char processor[257]; - size_t s = sizeof processor; - static int mib[] = { CTL_HW, UNAME_PROCESSOR }; - if (sysctl (mib, 2, processor, &s, 0, 0) >= 0) - element = processor; + { + static char processor[257]; + size_t s = sizeof processor; + static int mib[] = { CTL_HW, UNAME_PROCESSOR }; + if (sysctl (mib, 2, processor, &s, 0, 0) >= 0) + element = processor; # ifdef __APPLE__ - /* This kludge works around a bug in Mac OS X. */ - if (element == unknown) - { - cpu_type_t cputype; - size_t s = sizeof cputype; - NXArchInfo const *ai; - if (sysctlbyname ("hw.cputype", &cputype, &s, NULL, 0) == 0 - && (ai = NXGetArchInfoFromCpuType (cputype, - CPU_SUBTYPE_MULTIPLE)) - != NULL) - element = ai->name; - - /* Hack "safely" around the ppc vs. powerpc return value. */ - if (cputype == CPU_TYPE_POWERPC - && strncmp (element, "ppc", 3) == 0) - element = "powerpc"; - } + /* This kludge works around a bug in Mac OS X. */ + if (element == unknown) + { + cpu_type_t cputype; + size_t s = sizeof cputype; + NXArchInfo const *ai; + if (sysctlbyname ("hw.cputype", &cputype, &s, NULL, 0) == 0 + && (ai = NXGetArchInfoFromCpuType (cputype, + CPU_SUBTYPE_MULTIPLE)) + != NULL) + element = ai->name; + + /* Hack "safely" around the ppc vs. powerpc return value. */ + if (cputype == CPU_TYPE_POWERPC + && strncmp (element, "ppc", 3) == 0) + element = "powerpc"; + } # endif - } + } #endif if (! (toprint == UINT_MAX && element == unknown)) - print_element (element); + print_element (element); } if (toprint & PRINT_HARDWARE_PLATFORM) @@ -348,24 +348,24 @@ main (int argc, char **argv) char const *element = unknown; #if HAVE_SYSINFO && defined SI_PLATFORM { - static char hardware_platform[257]; - if (0 <= sysinfo (SI_PLATFORM, - hardware_platform, sizeof hardware_platform)) - element = hardware_platform; + static char hardware_platform[257]; + if (0 <= sysinfo (SI_PLATFORM, + hardware_platform, sizeof hardware_platform)) + element = hardware_platform; } #endif #ifdef UNAME_HARDWARE_PLATFORM if (element == unknown) - { - static char hardware_platform[257]; - size_t s = sizeof hardware_platform; - static int mib[] = { CTL_HW, UNAME_HARDWARE_PLATFORM }; - if (sysctl (mib, 2, hardware_platform, &s, 0, 0) >= 0) - element = hardware_platform; - } + { + static char hardware_platform[257]; + size_t s = sizeof hardware_platform; + static int mib[] = { CTL_HW, UNAME_HARDWARE_PLATFORM }; + if (sysctl (mib, 2, hardware_platform, &s, 0, 0) >= 0) + element = hardware_platform; + } #endif if (! (toprint == UINT_MAX && element == unknown)) - print_element (element); + print_element (element); } if (toprint & PRINT_OPERATING_SYSTEM) diff --git a/src/unexpand.c b/src/unexpand.c index 9f6a6d7a2..bfe22964e 100644 --- a/src/unexpand.c +++ b/src/unexpand.c @@ -24,12 +24,12 @@ --tabs=tab1[,tab2[,...]] -t tab1[,tab2[,...]] -tab1[,tab2[,...]] If only one tab stop is given, set the tabs tab1 - columns apart instead of the default 8. Otherwise, - set the tabs at columns tab1, tab2, etc. (numbered from - 0); preserve any blanks beyond the tab stops given. + columns apart instead of the default 8. Otherwise, + set the tabs at columns tab1, tab2, etc. (numbered from + 0); preserve any blanks beyond the tab stops given. --all -a Use tabs wherever they would replace 2 or more blanks, - not just at the beginnings of lines. + not just at the beginnings of lines. David MacKenzie <djm@gnu.ai.mit.edu> */ @@ -107,13 +107,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ "), - program_name); + program_name); fputs (_("\ Convert blanks in each FILE to tabs, writing to standard output.\n\ With no FILE, or when FILE is -, read standard input.\n\ @@ -150,7 +150,7 @@ add_tab_stop (uintmax_t tabval) if (max_column_width < column_width) { if (SIZE_MAX < column_width) - error (EXIT_FAILURE, 0, _("tabs are too far apart")); + error (EXIT_FAILURE, 0, _("tabs are too far apart")); max_column_width = column_width; } } @@ -169,38 +169,38 @@ parse_tab_stops (char const *stops) for (; *stops; stops++) { if (*stops == ',' || isblank (to_uchar (*stops))) - { - if (have_tabval) - add_tab_stop (tabval); - have_tabval = false; - } + { + if (have_tabval) + add_tab_stop (tabval); + have_tabval = false; + } else if (ISDIGIT (*stops)) - { - if (!have_tabval) - { - tabval = 0; - have_tabval = true; - num_start = stops; - } - - /* Detect overflow. */ - if (!DECIMAL_DIGIT_ACCUMULATE (tabval, *stops - '0', uintmax_t)) - { - size_t len = strspn (num_start, "0123456789"); - char *bad_num = xstrndup (num_start, len); - error (0, 0, _("tab stop is too large %s"), quote (bad_num)); - free (bad_num); - ok = false; - stops = num_start + len - 1; - } - } + { + if (!have_tabval) + { + tabval = 0; + have_tabval = true; + num_start = stops; + } + + /* Detect overflow. */ + if (!DECIMAL_DIGIT_ACCUMULATE (tabval, *stops - '0', uintmax_t)) + { + size_t len = strspn (num_start, "0123456789"); + char *bad_num = xstrndup (num_start, len); + error (0, 0, _("tab stop is too large %s"), quote (bad_num)); + free (bad_num); + ok = false; + stops = num_start + len - 1; + } + } else - { - error (0, 0, _("tab size contains invalid character(s): %s"), - quote (stops)); - ok = false; - break; - } + { + error (0, 0, _("tab size contains invalid character(s): %s"), + quote (stops)); + ok = false; + break; + } } if (!ok) @@ -222,9 +222,9 @@ validate_tab_stops (uintmax_t const *tabs, size_t entries) for (i = 0; i < entries; i++) { if (tabs[i] == 0) - error (EXIT_FAILURE, 0, _("tab size cannot be 0")); + error (EXIT_FAILURE, 0, _("tab size cannot be 0")); if (tabs[i] <= prev_tab) - error (EXIT_FAILURE, 0, _("tab sizes must be ascending")); + error (EXIT_FAILURE, 0, _("tab sizes must be ascending")); prev_tab = tabs[i]; } } @@ -243,33 +243,33 @@ next_file (FILE *fp) if (fp) { if (ferror (fp)) - { - error (0, errno, "%s", prev_file); - exit_status = EXIT_FAILURE; - } + { + error (0, errno, "%s", prev_file); + exit_status = EXIT_FAILURE; + } if (STREQ (prev_file, "-")) - clearerr (fp); /* Also clear EOF. */ + clearerr (fp); /* Also clear EOF. */ else if (fclose (fp) != 0) - { - error (0, errno, "%s", prev_file); - exit_status = EXIT_FAILURE; - } + { + error (0, errno, "%s", prev_file); + exit_status = EXIT_FAILURE; + } } while ((file = *file_list++) != NULL) { if (STREQ (file, "-")) - { - have_read_stdin = true; - prev_file = file; - return stdin; - } + { + have_read_stdin = true; + prev_file = file; + return stdin; + } fp = fopen (file, "r"); if (fp) - { - prev_file = file; - return fp; - } + { + prev_file = file; + return fp; + } error (0, errno, "%s", file); exit_status = EXIT_FAILURE; } @@ -308,7 +308,7 @@ unexpand (void) /* The following variables have valid values only when CONVERT - is true: */ + is true: */ /* Column of next input character. */ uintmax_t column = 0; @@ -323,8 +323,8 @@ unexpand (void) bool one_blank_before_tab_stop = false; /* If true, the previous input character was a blank. This is - initially true, since initial strings of blanks are treated - as if the line was preceded by a blank. */ + initially true, since initial strings of blanks are treated + as if the line was preceded by a blank. */ bool prev_blank = true; /* Number of pending columns of blanks. */ @@ -334,113 +334,113 @@ unexpand (void) /* Convert a line of text. */ do - { - while ((c = getc (fp)) < 0 && (fp = next_file (fp))) - continue; - - if (convert) - { - bool blank = !! isblank (c); - - if (blank) - { - if (next_tab_column <= column) - { - if (tab_size) - next_tab_column = - column + (tab_size - column % tab_size); - else - for (;;) - if (tab_index == first_free_tab) - { - convert = false; - break; - } - else - { - uintmax_t tab = tab_list[tab_index++]; - if (column < tab) - { - next_tab_column = tab; - break; - } - } - } - - if (convert) - { - if (next_tab_column < column) - error (EXIT_FAILURE, 0, _("input line is too long")); - - if (c == '\t') - { - column = next_tab_column; - - /* Discard pending blanks, unless it was a single - blank just before the previous tab stop. */ - if (! (pending == 1 && one_blank_before_tab_stop)) - { - pending = 0; - one_blank_before_tab_stop = false; - } - } - else - { - column++; - - if (! (prev_blank && column == next_tab_column)) - { - /* It is not yet known whether the pending blanks - will be replaced by tabs. */ - if (column == next_tab_column) - one_blank_before_tab_stop = true; - pending_blank[pending++] = c; - prev_blank = true; - continue; - } - - /* Replace the pending blanks by a tab or two. */ - pending_blank[0] = c = '\t'; - pending = one_blank_before_tab_stop; - } - } - } - else if (c == '\b') - { - /* Go back one column, and force recalculation of the - next tab stop. */ - column -= !!column; - next_tab_column = column; - tab_index -= !!tab_index; - } - else - { - column++; - if (!column) - error (EXIT_FAILURE, 0, _("input line is too long")); - } - - if (pending) - { - if (fwrite (pending_blank, 1, pending, stdout) != pending) - error (EXIT_FAILURE, errno, _("write error")); - pending = 0; - one_blank_before_tab_stop = false; - } - - prev_blank = blank; - convert &= convert_entire_line | blank; - } - - if (c < 0) - { - free (pending_blank); - return; - } - - if (putchar (c) < 0) - error (EXIT_FAILURE, errno, _("write error")); - } + { + while ((c = getc (fp)) < 0 && (fp = next_file (fp))) + continue; + + if (convert) + { + bool blank = !! isblank (c); + + if (blank) + { + if (next_tab_column <= column) + { + if (tab_size) + next_tab_column = + column + (tab_size - column % tab_size); + else + for (;;) + if (tab_index == first_free_tab) + { + convert = false; + break; + } + else + { + uintmax_t tab = tab_list[tab_index++]; + if (column < tab) + { + next_tab_column = tab; + break; + } + } + } + + if (convert) + { + if (next_tab_column < column) + error (EXIT_FAILURE, 0, _("input line is too long")); + + if (c == '\t') + { + column = next_tab_column; + + /* Discard pending blanks, unless it was a single + blank just before the previous tab stop. */ + if (! (pending == 1 && one_blank_before_tab_stop)) + { + pending = 0; + one_blank_before_tab_stop = false; + } + } + else + { + column++; + + if (! (prev_blank && column == next_tab_column)) + { + /* It is not yet known whether the pending blanks + will be replaced by tabs. */ + if (column == next_tab_column) + one_blank_before_tab_stop = true; + pending_blank[pending++] = c; + prev_blank = true; + continue; + } + + /* Replace the pending blanks by a tab or two. */ + pending_blank[0] = c = '\t'; + pending = one_blank_before_tab_stop; + } + } + } + else if (c == '\b') + { + /* Go back one column, and force recalculation of the + next tab stop. */ + column -= !!column; + next_tab_column = column; + tab_index -= !!tab_index; + } + else + { + column++; + if (!column) + error (EXIT_FAILURE, 0, _("input line is too long")); + } + + if (pending) + { + if (fwrite (pending_blank, 1, pending, stdout) != pending) + error (EXIT_FAILURE, errno, _("write error")); + pending = 0; + one_blank_before_tab_stop = false; + } + + prev_blank = blank; + convert &= convert_entire_line | blank; + } + + if (c < 0) + { + free (pending_blank); + return; + } + + if (putchar (c) < 0) + error (EXIT_FAILURE, errno, _("write error")); + } while (c != '\n'); } } @@ -471,39 +471,39 @@ main (int argc, char **argv) first_free_tab = 0; while ((c = getopt_long (argc, argv, ",0123456789at:", longopts, NULL)) - != -1) + != -1) { switch (c) - { - case '?': - usage (EXIT_FAILURE); - case 'a': - convert_entire_line = true; - break; - case 't': - convert_entire_line = true; - parse_tab_stops (optarg); - break; - case CONVERT_FIRST_ONLY_OPTION: - convert_first_only = true; - break; - case ',': - if (have_tabval) - add_tab_stop (tabval); - have_tabval = false; - break; - case_GETOPT_HELP_CHAR; - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - default: - if (!have_tabval) - { - tabval = 0; - have_tabval = true; - } - if (!DECIMAL_DIGIT_ACCUMULATE (tabval, c - '0', uintmax_t)) - error (EXIT_FAILURE, 0, _("tab stop value is too large")); - break; - } + { + case '?': + usage (EXIT_FAILURE); + case 'a': + convert_entire_line = true; + break; + case 't': + convert_entire_line = true; + parse_tab_stops (optarg); + break; + case CONVERT_FIRST_ONLY_OPTION: + convert_first_only = true; + break; + case ',': + if (have_tabval) + add_tab_stop (tabval); + have_tabval = false; + break; + case_GETOPT_HELP_CHAR; + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + default: + if (!have_tabval) + { + tabval = 0; + have_tabval = true; + } + if (!DECIMAL_DIGIT_ACCUMULATE (tabval, c - '0', uintmax_t)) + error (EXIT_FAILURE, 0, _("tab stop value is too large")); + break; + } } if (convert_first_only) diff --git a/src/uniq.c b/src/uniq.c index 0a16b670e..13aaebccc 100644 --- a/src/uniq.c +++ b/src/uniq.c @@ -127,13 +127,13 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [INPUT [OUTPUT]]\n\ "), - program_name); + program_name); fputs (_("\ Filter adjacent matching lines from INPUT (or standard input),\n\ writing to OUTPUT (or standard output).\n\ @@ -215,9 +215,9 @@ find_field (struct linebuffer const *line) for (count = 0; count < skip_fields; count++) { while (i < size && isblank (to_uchar (lp[i]))) - i++; + i++; while (i < size && !isblank (to_uchar (lp[i]))) - i++; + i++; } for (count = 0; count < skip_chars && i < size; count++) @@ -258,11 +258,11 @@ different (char *old, char *new, size_t oldlen, size_t newlen) static void writeline (struct linebuffer const *line, - bool match, uintmax_t linecount) + bool match, uintmax_t linecount) { if (! (linecount == 0 ? output_unique - : !match ? output_first_repeated - : output_later_repeated)) + : !match ? output_first_repeated + : output_later_repeated)) return; if (countmode == count_occurrences) @@ -304,24 +304,24 @@ check_file (const char *infile, const char *outfile, char delimiter) size_t prevlen IF_LINT (= 0); while (!feof (stdin)) - { - char *thisfield; - size_t thislen; - if (readlinebuffer_delim (thisline, stdin, delimiter) == 0) - break; - thisfield = find_field (thisline); - thislen = thisline->length - 1 - (thisfield - thisline->buffer); - if (prevline->length == 0 - || different (thisfield, prevfield, thislen, prevlen)) - { - fwrite (thisline->buffer, sizeof (char), - thisline->length, stdout); - - SWAP_LINES (prevline, thisline); - prevfield = thisfield; - prevlen = thislen; - } - } + { + char *thisfield; + size_t thislen; + if (readlinebuffer_delim (thisline, stdin, delimiter) == 0) + break; + thisfield = find_field (thisline); + thislen = thisline->length - 1 - (thisfield - thisline->buffer); + if (prevline->length == 0 + || different (thisfield, prevfield, thislen, prevlen)) + { + fwrite (thisline->buffer, sizeof (char), + thisline->length, stdout); + + SWAP_LINES (prevline, thisline); + prevfield = thisfield; + prevlen = thislen; + } + } } else { @@ -331,59 +331,59 @@ check_file (const char *infile, const char *outfile, char delimiter) bool first_delimiter = true; if (readlinebuffer_delim (prevline, stdin, delimiter) == 0) - goto closefiles; + goto closefiles; prevfield = find_field (prevline); prevlen = prevline->length - 1 - (prevfield - prevline->buffer); while (!feof (stdin)) - { - bool match; - char *thisfield; - size_t thislen; - if (readlinebuffer_delim (thisline, stdin, delimiter) == 0) - { - if (ferror (stdin)) - goto closefiles; - break; - } - thisfield = find_field (thisline); - thislen = thisline->length - 1 - (thisfield - thisline->buffer); - match = !different (thisfield, prevfield, thislen, prevlen); - match_count += match; - - if (match_count == UINTMAX_MAX) - { - if (count_occurrences) - error (EXIT_FAILURE, 0, _("too many repeated lines")); - match_count--; - } + { + bool match; + char *thisfield; + size_t thislen; + if (readlinebuffer_delim (thisline, stdin, delimiter) == 0) + { + if (ferror (stdin)) + goto closefiles; + break; + } + thisfield = find_field (thisline); + thislen = thisline->length - 1 - (thisfield - thisline->buffer); + match = !different (thisfield, prevfield, thislen, prevlen); + match_count += match; + + if (match_count == UINTMAX_MAX) + { + if (count_occurrences) + error (EXIT_FAILURE, 0, _("too many repeated lines")); + match_count--; + } if (delimit_groups != DM_NONE) - { - if (!match) - { - if (match_count) /* a previous match */ - first_delimiter = false; /* Only used when DM_SEPARATE */ - } - else if (match_count == 1) - { - if ((delimit_groups == DM_PREPEND) - || (delimit_groups == DM_SEPARATE - && !first_delimiter)) - putchar (delimiter); - } - } - - if (!match || output_later_repeated) - { - writeline (prevline, match, match_count); - SWAP_LINES (prevline, thisline); - prevfield = thisfield; - prevlen = thislen; - if (!match) - match_count = 0; - } - } + { + if (!match) + { + if (match_count) /* a previous match */ + first_delimiter = false; /* Only used when DM_SEPARATE */ + } + else if (match_count == 1) + { + if ((delimit_groups == DM_PREPEND) + || (delimit_groups == DM_SEPARATE + && !first_delimiter)) + putchar (delimiter); + } + } + + if (!match || output_later_repeated) + { + writeline (prevline, match, match_count); + SWAP_LINES (prevline, thisline); + prevfield = thisfield; + prevlen = thislen; + if (!match) + match_count = 0; + } + } writeline (prevline, false, match_count); } @@ -440,121 +440,121 @@ main (int argc, char **argv) obsolete. */ if (optc == -1 - || (posixly_correct && nfiles != 0) - || ((optc = getopt_long (argc, argv, - "-0123456789Dcdf:is:uw:z", longopts, NULL)) - == -1)) - { - if (argc <= optind) - break; - if (nfiles == 2) - { - error (0, 0, _("extra operand %s"), quote (argv[optind])); - usage (EXIT_FAILURE); - } - file[nfiles++] = argv[optind++]; - } + || (posixly_correct && nfiles != 0) + || ((optc = getopt_long (argc, argv, + "-0123456789Dcdf:is:uw:z", longopts, NULL)) + == -1)) + { + if (argc <= optind) + break; + if (nfiles == 2) + { + error (0, 0, _("extra operand %s"), quote (argv[optind])); + usage (EXIT_FAILURE); + } + file[nfiles++] = argv[optind++]; + } else switch (optc) - { - case 1: - { - unsigned long int size; - if (optarg[0] == '+' - && posix2_version () < 200112 - && xstrtoul (optarg, NULL, 10, &size, "") == LONGINT_OK - && size <= SIZE_MAX) - skip_chars = size; - else if (nfiles == 2) - { - error (0, 0, _("extra operand %s"), quote (optarg)); - usage (EXIT_FAILURE); - } - else - file[nfiles++] = optarg; - } - break; - - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - { - if (skip_field_option_type == SFO_NEW) - skip_fields = 0; - - if (!DECIMAL_DIGIT_ACCUMULATE (skip_fields, optc - '0', size_t)) - skip_fields = SIZE_MAX; - - skip_field_option_type = SFO_OBSOLETE; - } - break; - - case 'c': - countmode = count_occurrences; - break; - - case 'd': - output_unique = false; - break; - - case 'D': - output_unique = false; - output_later_repeated = true; - if (optarg == NULL) - delimit_groups = DM_NONE; - else - delimit_groups = XARGMATCH ("--all-repeated", optarg, - delimit_method_string, - delimit_method_map); - break; - - case 'f': - skip_field_option_type = SFO_NEW; - skip_fields = size_opt (optarg, - N_("invalid number of fields to skip")); - break; - - case 'i': - ignore_case = true; - break; - - case 's': - skip_chars = size_opt (optarg, - N_("invalid number of bytes to skip")); - break; - - case 'u': - output_first_repeated = false; - break; - - case 'w': - check_chars = size_opt (optarg, - N_("invalid number of bytes to compare")); - break; - - case 'z': - delimiter = '\0'; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 1: + { + unsigned long int size; + if (optarg[0] == '+' + && posix2_version () < 200112 + && xstrtoul (optarg, NULL, 10, &size, "") == LONGINT_OK + && size <= SIZE_MAX) + skip_chars = size; + else if (nfiles == 2) + { + error (0, 0, _("extra operand %s"), quote (optarg)); + usage (EXIT_FAILURE); + } + else + file[nfiles++] = optarg; + } + break; + + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + { + if (skip_field_option_type == SFO_NEW) + skip_fields = 0; + + if (!DECIMAL_DIGIT_ACCUMULATE (skip_fields, optc - '0', size_t)) + skip_fields = SIZE_MAX; + + skip_field_option_type = SFO_OBSOLETE; + } + break; + + case 'c': + countmode = count_occurrences; + break; + + case 'd': + output_unique = false; + break; + + case 'D': + output_unique = false; + output_later_repeated = true; + if (optarg == NULL) + delimit_groups = DM_NONE; + else + delimit_groups = XARGMATCH ("--all-repeated", optarg, + delimit_method_string, + delimit_method_map); + break; + + case 'f': + skip_field_option_type = SFO_NEW; + skip_fields = size_opt (optarg, + N_("invalid number of fields to skip")); + break; + + case 'i': + ignore_case = true; + break; + + case 's': + skip_chars = size_opt (optarg, + N_("invalid number of bytes to skip")); + break; + + case 'u': + output_first_repeated = false; + break; + + case 'w': + check_chars = size_opt (optarg, + N_("invalid number of bytes to compare")); + break; + + case 'z': + delimiter = '\0'; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (countmode == count_occurrences && output_later_repeated) { error (0, 0, - _("printing all duplicated lines and repeat counts is meaningless")); + _("printing all duplicated lines and repeat counts is meaningless")); usage (EXIT_FAILURE); } diff --git a/src/unlink.c b/src/unlink.c index c82733f50..47cbfb2e3 100644 --- a/src/unlink.c +++ b/src/unlink.c @@ -40,14 +40,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s FILE\n\ or: %s OPTION\n"), program_name, program_name); fputs (_("Call the unlink function to remove the specified FILE.\n\n"), - stdout); + stdout); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); emit_bug_reporting_address (); @@ -67,7 +67,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); diff --git a/src/uptime.c b/src/uptime.c index 78cd52b2a..175fe8f73 100644 --- a/src/uptime.c +++ b/src/uptime.c @@ -68,13 +68,13 @@ print_uptime (size_t n, const STRUCT_UTMP *this) char buf[BUFSIZ]; char *b = fgets (buf, BUFSIZ, fp); if (b == buf) - { - char *end_ptr; - double upsecs = c_strtod (buf, &end_ptr); - if (buf != end_ptr) - uptime = (0 <= upsecs && upsecs < TYPE_MAXIMUM (time_t) - ? upsecs : -1); - } + { + char *end_ptr; + double upsecs = c_strtod (buf, &end_ptr); + if (buf != end_ptr) + uptime = (0 <= upsecs && upsecs < TYPE_MAXIMUM (time_t) + ? upsecs : -1); + } fclose (fp); } @@ -108,7 +108,7 @@ print_uptime (size_t n, const STRUCT_UTMP *this) { entries += IS_USER_PROCESS (this); if (UT_TYPE_BOOT_TIME (this)) - boot_time = UT_TIME_MEMBER (this); + boot_time = UT_TIME_MEMBER (this); ++this; } #endif @@ -118,7 +118,7 @@ print_uptime (size_t n, const STRUCT_UTMP *this) #endif { if (boot_time == 0) - error (EXIT_FAILURE, errno, _("couldn't get boot time")); + error (EXIT_FAILURE, errno, _("couldn't get boot time")); uptime = time_now - boot_time; } updays = uptime / 86400; @@ -137,15 +137,15 @@ print_uptime (size_t n, const STRUCT_UTMP *this) else { if (0 < updays) - printf (ngettext ("up %ld day %2d:%02d, ", - "up %ld days %2d:%02d, ", - select_plural (updays)), - updays, uphours, upmins); + printf (ngettext ("up %ld day %2d:%02d, ", + "up %ld days %2d:%02d, ", + select_plural (updays)), + updays, uphours, upmins); else - printf ("up %2d:%02d, ", uphours, upmins); + printf ("up %2d:%02d, ", uphours, upmins); } printf (ngettext ("%lu user", "%lu users", entries), - (unsigned long int) entries); + (unsigned long int) entries); #if defined HAVE_GETLOADAVG || defined C_GETLOADAVG loads = getloadavg (avg, 3); @@ -158,13 +158,13 @@ print_uptime (size_t n, const STRUCT_UTMP *this) else { if (loads > 0) - printf (_(", load average: %.2f"), avg[0]); + printf (_(", load average: %.2f"), avg[0]); if (loads > 1) - printf (", %.2f", avg[1]); + printf (", %.2f", avg[1]); if (loads > 2) - printf (", %.2f", avg[2]); + printf (", %.2f", avg[2]); if (loads > 0) - putchar ('\n'); + putchar ('\n'); } } @@ -191,7 +191,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [FILE]\n"), program_name); @@ -201,9 +201,9 @@ the number of users on the system, and the average number of jobs\n\ in the run queue over the last 1, 5 and 15 minutes.")); #ifdef __linux__ /* It would be better to introduce a configure test for this, - but such a test is hard to write. For the moment then, we - have a hack which depends on the preprocessor used at compile - time to tell us what the running kernel is. Ugh. */ + but such a test is hard to write. For the moment then, we + have a hack which depends on the preprocessor used at compile + time to tell us what the running kernel is. Ugh. */ printf(_(" \ Processes in\n\ an uninterruptible sleep state also contribute to the load average.\n")); @@ -213,7 +213,7 @@ an uninterruptible sleep state also contribute to the load average.\n")); printf (_("\ If FILE is not specified, use %s. %s as FILE is common.\n\ \n"), - UTMP_FILE, WTMP_FILE); + UTMP_FILE, WTMP_FILE); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); emit_bug_reporting_address (); @@ -233,7 +233,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); diff --git a/src/users.c b/src/users.c index f47180756..d5115c691 100644 --- a/src/users.c +++ b/src/users.c @@ -53,14 +53,14 @@ list_entries_users (size_t n, const STRUCT_UTMP *this) while (n--) { if (IS_USER_PROCESS (this)) - { - char *trimmed_name; + { + char *trimmed_name; - trimmed_name = extract_trimmed_name (this); + trimmed_name = extract_trimmed_name (this); - u[n_entries] = trimmed_name; - ++n_entries; - } + u[n_entries] = trimmed_name; + ++n_entries; + } this++; } @@ -100,7 +100,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [FILE]\n"), program_name); @@ -109,7 +109,7 @@ Output who is currently logged in according to FILE.\n\ If FILE is not specified, use %s. %s as FILE is common.\n\ \n\ "), - UTMP_FILE, WTMP_FILE); + UTMP_FILE, WTMP_FILE); fputs (HELP_OPTION_DESCRIPTION, stdout); fputs (VERSION_OPTION_DESCRIPTION, stdout); emit_bug_reporting_address (); @@ -129,7 +129,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -106,14 +106,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [OPTION]... [FILE]...\n\ or: %s [OPTION]... --files0-from=F\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Print newline, word, and byte counts for each FILE, and a total line if\n\ more than one FILE is specified. With no FILE, or when FILE is -,\n\ @@ -140,11 +140,11 @@ read standard input.\n\ associated with the specified counters. */ static void write_counts (uintmax_t lines, - uintmax_t words, - uintmax_t chars, - uintmax_t bytes, - uintmax_t linelength, - const char *file) + uintmax_t words, + uintmax_t chars, + uintmax_t bytes, + uintmax_t linelength, + const char *file) { static char const format_sp_int[] = " %*s"; char const *format_int = format_sp_int + 1; @@ -225,52 +225,52 @@ wc (int fd, char const *file_x, struct fstatus *fstatus) off_t current_pos, end_pos; if (0 < fstatus->failed) - fstatus->failed = fstat (fd, &fstatus->st); + fstatus->failed = fstat (fd, &fstatus->st); if (! fstatus->failed && S_ISREG (fstatus->st.st_mode) - && (current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1 - && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1) - { - /* Be careful here. The current position may actually be - beyond the end of the file. As in the example above. */ - bytes = end_pos < current_pos ? 0 : end_pos - current_pos; - } + && (current_pos = lseek (fd, (off_t) 0, SEEK_CUR)) != -1 + && (end_pos = lseek (fd, (off_t) 0, SEEK_END)) != -1) + { + /* Be careful here. The current position may actually be + beyond the end of the file. As in the example above. */ + bytes = end_pos < current_pos ? 0 : end_pos - current_pos; + } else - { - while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) - { - if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", file); - ok = false; - break; - } - bytes += bytes_read; - } - } + { + while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) + { + if (bytes_read == SAFE_READ_ERROR) + { + error (0, errno, "%s", file); + ok = false; + break; + } + bytes += bytes_read; + } + } } else if (!count_chars && !count_complicated) { /* Use a separate loop when counting only lines or lines and bytes -- - but not chars or words. */ + but not chars or words. */ while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) - { - char *p = buf; - - if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", file); - ok = false; - break; - } - - while ((p = memchr (p, '\n', (buf + bytes_read) - p))) - { - ++p; - ++lines; - } - bytes += bytes_read; - } + { + char *p = buf; + + if (bytes_read == SAFE_READ_ERROR) + { + error (0, errno, "%s", file); + ok = false; + break; + } + + while ((p = memchr (p, '\n', (buf + bytes_read) - p))) + { + ++p; + ++lines; + } + bytes += bytes_read; + } } #if MB_LEN_MAX > 1 # define SUPPORT_OLD_MBRTOWC 1 @@ -282,133 +282,133 @@ wc (int fd, char const *file_x, struct fstatus *fstatus) bool in_shift = false; # if SUPPORT_OLD_MBRTOWC /* Back-up the state before each multibyte character conversion and - move the last incomplete character of the buffer to the front - of the buffer. This is needed because we don't know whether - the `mbrtowc' function updates the state when it returns -2, - - this is the ISO C 99 and glibc-2.2 behaviour - or not - amended - ANSI C, glibc-2.1 and Solaris 5.7 behaviour. We don't have an - autoconf test for this, yet. */ + move the last incomplete character of the buffer to the front + of the buffer. This is needed because we don't know whether + the `mbrtowc' function updates the state when it returns -2, - + this is the ISO C 99 and glibc-2.2 behaviour - or not - amended + ANSI C, glibc-2.1 and Solaris 5.7 behaviour. We don't have an + autoconf test for this, yet. */ size_t prev = 0; /* number of bytes carried over from previous round */ # else const size_t prev = 0; # endif while ((bytes_read = safe_read (fd, buf + prev, BUFFER_SIZE - prev)) > 0) - { - const char *p; + { + const char *p; # if SUPPORT_OLD_MBRTOWC - mbstate_t backup_state; + mbstate_t backup_state; # endif - if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", file); - ok = false; - break; - } - - bytes += bytes_read; - p = buf; - bytes_read += prev; - do - { - wchar_t wide_char; - size_t n; - - if (!in_shift && is_basic (*p)) - { - /* Handle most ASCII characters quickly, without calling - mbrtowc(). */ - n = 1; - wide_char = *p; - } - else - { - in_shift = true; + if (bytes_read == SAFE_READ_ERROR) + { + error (0, errno, "%s", file); + ok = false; + break; + } + + bytes += bytes_read; + p = buf; + bytes_read += prev; + do + { + wchar_t wide_char; + size_t n; + + if (!in_shift && is_basic (*p)) + { + /* Handle most ASCII characters quickly, without calling + mbrtowc(). */ + n = 1; + wide_char = *p; + } + else + { + in_shift = true; # if SUPPORT_OLD_MBRTOWC - backup_state = state; + backup_state = state; # endif - n = mbrtowc (&wide_char, p, bytes_read, &state); - if (n == (size_t) -2) - { + n = mbrtowc (&wide_char, p, bytes_read, &state); + if (n == (size_t) -2) + { # if SUPPORT_OLD_MBRTOWC - state = backup_state; + state = backup_state; # endif - break; - } - if (n == (size_t) -1) - { - /* Remember that we read a byte, but don't complain - about the error. Because of the decoding error, - this is a considered to be byte but not a - character (that is, chars is not incremented). */ - p++; - bytes_read--; - continue; - } - if (mbsinit (&state)) - in_shift = false; - if (n == 0) - { - wide_char = 0; - n = 1; - } - } - p += n; - bytes_read -= n; - chars++; - switch (wide_char) - { - case '\n': - lines++; - /* Fall through. */ - case '\r': - case '\f': - if (linepos > linelength) - linelength = linepos; - linepos = 0; - goto mb_word_separator; - case '\t': - linepos += 8 - (linepos % 8); - goto mb_word_separator; - case ' ': - linepos++; - /* Fall through. */ - case '\v': - mb_word_separator: - words += in_word; - in_word = false; - break; - default: - if (iswprint (wide_char)) - { - int width = wcwidth (wide_char); - if (width > 0) - linepos += width; - if (iswspace (wide_char)) - goto mb_word_separator; - in_word = true; - } - break; - } - } - while (bytes_read > 0); + break; + } + if (n == (size_t) -1) + { + /* Remember that we read a byte, but don't complain + about the error. Because of the decoding error, + this is a considered to be byte but not a + character (that is, chars is not incremented). */ + p++; + bytes_read--; + continue; + } + if (mbsinit (&state)) + in_shift = false; + if (n == 0) + { + wide_char = 0; + n = 1; + } + } + p += n; + bytes_read -= n; + chars++; + switch (wide_char) + { + case '\n': + lines++; + /* Fall through. */ + case '\r': + case '\f': + if (linepos > linelength) + linelength = linepos; + linepos = 0; + goto mb_word_separator; + case '\t': + linepos += 8 - (linepos % 8); + goto mb_word_separator; + case ' ': + linepos++; + /* Fall through. */ + case '\v': + mb_word_separator: + words += in_word; + in_word = false; + break; + default: + if (iswprint (wide_char)) + { + int width = wcwidth (wide_char); + if (width > 0) + linepos += width; + if (iswspace (wide_char)) + goto mb_word_separator; + in_word = true; + } + break; + } + } + while (bytes_read > 0); # if SUPPORT_OLD_MBRTOWC - if (bytes_read > 0) - { - if (bytes_read == BUFFER_SIZE) - { - /* Encountered a very long redundant shift sequence. */ - p++; - bytes_read--; - } - memmove (buf, p, bytes_read); - } - prev = bytes_read; + if (bytes_read > 0) + { + if (bytes_read == BUFFER_SIZE) + { + /* Encountered a very long redundant shift sequence. */ + p++; + bytes_read--; + } + memmove (buf, p, bytes_read); + } + prev = bytes_read; # endif - } + } if (linepos > linelength) - linelength = linepos; + linelength = linepos; words += in_word; } #endif @@ -418,55 +418,55 @@ wc (int fd, char const *file_x, struct fstatus *fstatus) uintmax_t linepos = 0; while ((bytes_read = safe_read (fd, buf, BUFFER_SIZE)) > 0) - { - const char *p = buf; - if (bytes_read == SAFE_READ_ERROR) - { - error (0, errno, "%s", file); - ok = false; - break; - } - - bytes += bytes_read; - do - { - switch (*p++) - { - case '\n': - lines++; - /* Fall through. */ - case '\r': - case '\f': - if (linepos > linelength) - linelength = linepos; - linepos = 0; - goto word_separator; - case '\t': - linepos += 8 - (linepos % 8); - goto word_separator; - case ' ': - linepos++; - /* Fall through. */ - case '\v': - word_separator: - words += in_word; - in_word = false; - break; - default: - if (isprint (to_uchar (p[-1]))) - { - linepos++; - if (isspace (to_uchar (p[-1]))) - goto word_separator; - in_word = true; - } - break; - } - } - while (--bytes_read); - } + { + const char *p = buf; + if (bytes_read == SAFE_READ_ERROR) + { + error (0, errno, "%s", file); + ok = false; + break; + } + + bytes += bytes_read; + do + { + switch (*p++) + { + case '\n': + lines++; + /* Fall through. */ + case '\r': + case '\f': + if (linepos > linelength) + linelength = linepos; + linepos = 0; + goto word_separator; + case '\t': + linepos += 8 - (linepos % 8); + goto word_separator; + case ' ': + linepos++; + /* Fall through. */ + case '\v': + word_separator: + words += in_word; + in_word = false; + break; + default: + if (isprint (to_uchar (p[-1]))) + { + linepos++; + if (isspace (to_uchar (p[-1]))) + goto word_separator; + in_word = true; + } + break; + } + } + while (--bytes_read); + } if (linepos > linelength) - linelength = linepos; + linelength = linepos; words += in_word; } @@ -491,27 +491,27 @@ wc_file (char const *file, struct fstatus *fstatus) { have_read_stdin = true; if (O_BINARY && ! isatty (STDIN_FILENO)) - xfreopen (NULL, "rb", stdin); + xfreopen (NULL, "rb", stdin); return wc (STDIN_FILENO, file, fstatus); } else { int fd = open (file, O_RDONLY | O_BINARY); if (fd == -1) - { - error (0, errno, "%s", file); - return false; - } + { + error (0, errno, "%s", file); + return false; + } else - { - bool ok = wc (fd, file, fstatus); - if (close (fd) != 0) - { - error (0, errno, "%s", file); - return false; - } - return ok; - } + { + bool ok = wc (fd, file, fstatus); + if (close (fd) != 0) + { + error (0, errno, "%s", file); + return false; + } + return ok; + } } } @@ -528,18 +528,18 @@ get_input_fstatus (int nfiles, char *const *file) if (nfiles == 0 || (nfiles == 1 - && ((print_lines + print_words + print_chars - + print_bytes + print_linelength) - == 1))) + && ((print_lines + print_words + print_chars + + print_bytes + print_linelength) + == 1))) fstatus[0].failed = 1; else { int i; for (i = 0; i < nfiles; i++) - fstatus[i].failed = (! file[i] || STREQ (file[i], "-") - ? fstat (STDIN_FILENO, &fstatus[i].st) - : stat (file[i], &fstatus[i].st)); + fstatus[i].failed = (! file[i] || STREQ (file[i], "-") + ? fstat (STDIN_FILENO, &fstatus[i].st) + : stat (file[i], &fstatus[i].st)); } return fstatus; @@ -561,18 +561,18 @@ compute_number_width (int nfiles, struct fstatus const *fstatus) int i; for (i = 0; i < nfiles; i++) - if (! fstatus[i].failed) - { - if (S_ISREG (fstatus[i].st.st_mode)) - regular_total += fstatus[i].st.st_size; - else - minimum_width = 7; - } + if (! fstatus[i].failed) + { + if (S_ISREG (fstatus[i].st.st_mode)) + regular_total += fstatus[i].st.st_size; + else + minimum_width = 7; + } for (; 10 <= regular_total; regular_total /= 10) - width++; + width++; if (width < minimum_width) - width = minimum_width; + width = minimum_width; } return width; @@ -606,39 +606,39 @@ main (int argc, char **argv) switch (optc) { case 'c': - print_bytes = true; - break; + print_bytes = true; + break; case 'm': - print_chars = true; - break; + print_chars = true; + break; case 'l': - print_lines = true; - break; + print_lines = true; + break; case 'w': - print_words = true; - break; + print_words = true; + break; case 'L': - print_linelength = true; - break; + print_linelength = true; + break; case FILES0_FROM_OPTION: - files_from = optarg; - break; + files_from = optarg; + break; case_GETOPT_HELP_CHAR; case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); default: - usage (EXIT_FAILURE); + usage (EXIT_FAILURE); } if (! (print_lines | print_words | print_chars | print_bytes - | print_linelength)) + | print_linelength)) print_lines = print_words = print_bytes = true; bool read_tokens = false; @@ -648,47 +648,47 @@ main (int argc, char **argv) FILE *stream; /* When using --files0-from=F, you may not specify any files - on the command-line. */ + on the command-line. */ if (optind < argc) - { - error (0, 0, _("extra operand %s"), quote (argv[optind])); - fprintf (stderr, "%s\n", - _("file operands cannot be combined with --files0-from")); - usage (EXIT_FAILURE); - } + { + error (0, 0, _("extra operand %s"), quote (argv[optind])); + fprintf (stderr, "%s\n", + _("file operands cannot be combined with --files0-from")); + usage (EXIT_FAILURE); + } if (STREQ (files_from, "-")) - stream = stdin; + stream = stdin; else - { - stream = fopen (files_from, "r"); - if (stream == NULL) - error (EXIT_FAILURE, errno, _("cannot open %s for reading"), - quote (files_from)); - } + { + stream = fopen (files_from, "r"); + if (stream == NULL) + error (EXIT_FAILURE, errno, _("cannot open %s for reading"), + quote (files_from)); + } /* Read the file list into RAM if we can detect its size and that - size is reasonable. Otherwise, we'll read a name at a time. */ + size is reasonable. Otherwise, we'll read a name at a time. */ struct stat st; if (fstat (fileno (stream), &st) == 0 - && S_ISREG (st.st_mode) - && st.st_size <= MIN (10 * 1024 * 1024, physmem_available () / 2)) - { - read_tokens = true; - readtokens0_init (&tok); - if (! readtokens0 (stream, &tok) || fclose (stream) != 0) - error (EXIT_FAILURE, 0, _("cannot read file names from %s"), - quote (files_from)); - files = tok.tok; - nfiles = tok.n_tok; - ai = argv_iter_init_argv (files); - } + && S_ISREG (st.st_mode) + && st.st_size <= MIN (10 * 1024 * 1024, physmem_available () / 2)) + { + read_tokens = true; + readtokens0_init (&tok); + if (! readtokens0 (stream, &tok) || fclose (stream) != 0) + error (EXIT_FAILURE, 0, _("cannot read file names from %s"), + quote (files_from)); + files = tok.tok; + nfiles = tok.n_tok; + ai = argv_iter_init_argv (files); + } else - { - files = NULL; - nfiles = 0; - ai = argv_iter_init_stream (stream); - } + { + files = NULL; + nfiles = 0; + ai = argv_iter_init_stream (stream); + } } else { @@ -709,55 +709,55 @@ main (int argc, char **argv) enum argv_iter_err ai_err; char *file_name = argv_iter (ai, &ai_err); if (ai_err == AI_ERR_EOF) - break; + break; if (!file_name) - { - switch (ai_err) - { - case AI_ERR_READ: - error (0, errno, _("%s: read error"), quote (files_from)); - skip_file = true; - continue; - case AI_ERR_MEM: - xalloc_die (); - default: - assert (!"unexpected error code from argv_iter"); - } - } + { + switch (ai_err) + { + case AI_ERR_READ: + error (0, errno, _("%s: read error"), quote (files_from)); + skip_file = true; + continue; + case AI_ERR_MEM: + xalloc_die (); + default: + assert (!"unexpected error code from argv_iter"); + } + } if (files_from && STREQ (files_from, "-") && STREQ (file_name, "-")) - { - /* Give a better diagnostic in an unusual case: - printf - | wc --files0-from=- */ - error (0, 0, _("when reading file names from stdin, " - "no file name of %s allowed"), - quote (file_name)); - skip_file = true; - } + { + /* Give a better diagnostic in an unusual case: + printf - | wc --files0-from=- */ + error (0, 0, _("when reading file names from stdin, " + "no file name of %s allowed"), + quote (file_name)); + skip_file = true; + } if (!file_name[0]) - { - /* Diagnose a zero-length file name. When it's one - among many, knowing the record number may help. - FIXME: currently print the record number only with - --files0-from=FILE. Maybe do it for argv, too? */ - if (files_from == NULL) - error (0, 0, "%s", _("invalid zero-length file name")); - else - { - /* Using the standard `filename:line-number:' prefix here is - not totally appropriate, since NUL is the separator, not NL, - but it might be better than nothing. */ - unsigned long int file_number = argv_iter_n_args (ai); - error (0, 0, "%s:%lu: %s", quotearg_colon (files_from), - file_number, _("invalid zero-length file name")); - } - skip_file = true; - } + { + /* Diagnose a zero-length file name. When it's one + among many, knowing the record number may help. + FIXME: currently print the record number only with + --files0-from=FILE. Maybe do it for argv, too? */ + if (files_from == NULL) + error (0, 0, "%s", _("invalid zero-length file name")); + else + { + /* Using the standard `filename:line-number:' prefix here is + not totally appropriate, since NUL is the separator, not NL, + but it might be better than nothing. */ + unsigned long int file_number = argv_iter_n_args (ai); + error (0, 0, "%s:%lu: %s", quotearg_colon (files_from), + file_number, _("invalid zero-length file name")); + } + skip_file = true; + } if (skip_file) - ok = false; + ok = false; else - ok &= wc_file (file_name, &fstatus[nfiles ? i : 0]); + ok &= wc_file (file_name, &fstatus[nfiles ? i : 0]); } /* No arguments on the command line is fine. That means read from stdin. @@ -771,7 +771,7 @@ main (int argc, char **argv) if (1 < argv_iter_n_args (ai)) write_counts (total_lines, total_words, total_chars, total_bytes, - max_line_length, _("total")); + max_line_length, _("total")); argv_iter_free (ai); diff --git a/src/wheel-gen.pl b/src/wheel-gen.pl index 987619de3..96fb48f05 100755 --- a/src/wheel-gen.pl +++ b/src/wheel-gen.pl @@ -50,7 +50,7 @@ sub is_prime ($) and return 0; $d += $w; $q < $d - and last; + and last; $w = 2; } return 1; @@ -68,12 +68,12 @@ sub is_prime ($) for (my $i = 3; ; $i += 2) { if (is_prime $i) - { - push @primes, $i; - $product *= $i; - ++$n_primes == $wheel_size - and last; - } + { + push @primes, $i; + $product *= $i; + ++$n_primes == $wheel_size + and last; + } } my $ws_m1 = $wheel_size - 1; @@ -92,20 +92,20 @@ EOF { my $rel_prime = 1; foreach my $divisor (@primes) - { - $i != $divisor && $i % $divisor == 0 - and $rel_prime = 0; - } + { + $i != $divisor && $i % $divisor == 0 + and $rel_prime = 0; + } if ($rel_prime) - { - #warn $i, ' ', $i - $prev, "\n"; - push @increments, $i - $prev; - $prev = $i; - - $product + 1 < $i - and last; - } + { + #warn $i, ' ', $i - $prev, "\n"; + push @increments, $i - $prev; + $prev = $i; + + $product + 1 < $i + and last; + } } print join (",\n", @increments), "\n"; @@ -195,15 +195,15 @@ idle_string (time_t when, time_t boottime) { int seconds_idle = now - when; if (seconds_idle < 60) - return " . "; + return " . "; else - { - static char idle_hhmm[IDLESTR_LEN]; - sprintf (idle_hhmm, "%02d:%02d", - seconds_idle / (60 * 60), - (seconds_idle % (60 * 60)) / 60); - return idle_hhmm; - } + { + static char idle_hhmm[IDLESTR_LEN]; + sprintf (idle_hhmm, "%02d:%02d", + seconds_idle / (60 * 60), + (seconds_idle % (60 * 60)) / 60); + return idle_hhmm; + } } return _(" old "); @@ -238,9 +238,9 @@ time_string (const STRUCT_UTMP *utmp_ent) pids, etc. */ static void print_line (int userlen, const char *user, const char state, - int linelen, const char *line, - const char *time_str, const char *idle, const char *pid, - const char *comment, const char *exitstr) + int linelen, const char *line, + const char *time_str, const char *idle, const char *pid, + const char *comment, const char *exitstr) { static char mesg[3] = { ' ', 'x', '\0' }; char *buf; @@ -268,29 +268,29 @@ print_line (int userlen, const char *user, const char state, *x_exitstr = '\0'; err = asprintf (&buf, - "%-8.*s" - "%s" - " %-12.*s" - " %-*s" - "%s" - "%s" - " %-8s" - "%s" - , - userlen, user ? user : " .", - include_mesg ? mesg : "", - linelen, line, - time_format_width, - time_str, - x_idle, - x_pid, - /* FIXME: it's not really clear whether the following - field should be in the short_output. A strict reading - of SUSv2 would suggest not, but I haven't seen any - implementations that actually work that way... */ - comment, - x_exitstr - ); + "%-8.*s" + "%s" + " %-12.*s" + " %-*s" + "%s" + "%s" + " %-8s" + "%s" + , + userlen, user ? user : " .", + include_mesg ? mesg : "", + linelen, line, + time_format_width, + time_str, + x_idle, + x_pid, + /* FIXME: it's not really clear whether the following + field should be in the short_output. A strict reading + of SUSv2 would suggest not, but I haven't seen any + implementations that actually work that way... */ + comment, + x_exitstr + ); if (err == -1) xalloc_die (); @@ -339,7 +339,7 @@ print_user (const STRUCT_UTMP *utmp_ent, time_t boottime) { strcpy (line, DEV_DIR_WITH_TRAILING_SLASH); strncpy (line + DEV_DIR_LEN, utmp_ent->ut_line, - sizeof (utmp_ent->ut_line)); + sizeof (utmp_ent->ut_line)); line[DEV_DIR_LEN + sizeof (utmp_ent->ut_line)] = '\0'; } @@ -373,61 +373,61 @@ print_user (const STRUCT_UTMP *utmp_ent, time_t boottime) /* Look for an X display. */ display = strchr (ut_host, ':'); if (display) - *display++ = '\0'; + *display++ = '\0'; if (*ut_host && do_lookup) - { - /* See if we can canonicalize it. */ - host = canon_host (ut_host); - } + { + /* See if we can canonicalize it. */ + host = canon_host (ut_host); + } if (! host) - host = ut_host; + host = ut_host; if (display) - { - if (hostlen < strlen (host) + strlen (display) + 4) - { - hostlen = strlen (host) + strlen (display) + 4; - hoststr = xrealloc (hoststr, hostlen); - } - sprintf (hoststr, "(%s:%s)", host, display); - } + { + if (hostlen < strlen (host) + strlen (display) + 4) + { + hostlen = strlen (host) + strlen (display) + 4; + hoststr = xrealloc (hoststr, hostlen); + } + sprintf (hoststr, "(%s:%s)", host, display); + } else - { - if (hostlen < strlen (host) + 3) - { - hostlen = strlen (host) + 3; - hoststr = xrealloc (hoststr, hostlen); - } - sprintf (hoststr, "(%s)", host); - } + { + if (hostlen < strlen (host) + 3) + { + hostlen = strlen (host) + 3; + hoststr = xrealloc (hoststr, hostlen); + } + sprintf (hoststr, "(%s)", host); + } if (host != ut_host) - free (host); + free (host); } else { if (hostlen < 1) - { - hostlen = 1; - hoststr = xrealloc (hoststr, hostlen); - } + { + hostlen = 1; + hoststr = xrealloc (hoststr, hostlen); + } *hoststr = '\0'; } #endif print_line (sizeof UT_USER (utmp_ent), UT_USER (utmp_ent), mesg, - sizeof utmp_ent->ut_line, utmp_ent->ut_line, - time_string (utmp_ent), idlestr, pidstr, - hoststr ? hoststr : "", ""); + sizeof utmp_ent->ut_line, utmp_ent->ut_line, + time_string (utmp_ent), idlestr, pidstr, + hoststr ? hoststr : "", ""); } static void print_boottime (const STRUCT_UTMP *utmp_ent) { print_line (-1, "", ' ', -1, _("system boot"), - time_string (utmp_ent), "", "", "", ""); + time_string (utmp_ent), "", "", "", ""); } static char * @@ -449,17 +449,17 @@ print_deadprocs (const STRUCT_UTMP *utmp_ent) if (!exitstr) exitstr = xmalloc (strlen (_("term=")) - + INT_STRLEN_BOUND (UT_EXIT_E_TERMINATION (utmp_ent)) + 1 - + strlen (_("exit=")) - + INT_STRLEN_BOUND (UT_EXIT_E_EXIT (utmp_ent)) - + 1); + + INT_STRLEN_BOUND (UT_EXIT_E_TERMINATION (utmp_ent)) + 1 + + strlen (_("exit=")) + + INT_STRLEN_BOUND (UT_EXIT_E_EXIT (utmp_ent)) + + 1); sprintf (exitstr, "%s%d %s%d", _("term="), UT_EXIT_E_TERMINATION (utmp_ent), - _("exit="), UT_EXIT_E_EXIT (utmp_ent)); + _("exit="), UT_EXIT_E_EXIT (utmp_ent)); /* FIXME: add idle time? */ print_line (-1, "", ' ', sizeof utmp_ent->ut_line, utmp_ent->ut_line, - time_string (utmp_ent), "", pidstr, comment, exitstr); + time_string (utmp_ent), "", pidstr, comment, exitstr); free (comment); } @@ -472,7 +472,7 @@ print_login (const STRUCT_UTMP *utmp_ent) /* FIXME: add idle time? */ print_line (-1, _("LOGIN"), ' ', sizeof utmp_ent->ut_line, utmp_ent->ut_line, - time_string (utmp_ent), "", pidstr, comment, ""); + time_string (utmp_ent), "", pidstr, comment, ""); free (comment); } @@ -483,7 +483,7 @@ print_initspawn (const STRUCT_UTMP *utmp_ent) PIDSTR_DECL_AND_INIT (pidstr, utmp_ent); print_line (-1, "", ' ', sizeof utmp_ent->ut_line, utmp_ent->ut_line, - time_string (utmp_ent), "", pidstr, comment, ""); + time_string (utmp_ent), "", pidstr, comment, ""); free (comment); } @@ -492,7 +492,7 @@ print_clockchange (const STRUCT_UTMP *utmp_ent) { /* FIXME: handle NEW_TIME & OLD_TIME both */ print_line (-1, "", ' ', -1, _("clock change"), - time_string (utmp_ent), "", "", "", ""); + time_string (utmp_ent), "", "", "", ""); } static void @@ -511,7 +511,7 @@ print_runlevel (const STRUCT_UTMP *utmp_ent) sprintf (comment, "%s%c", _("last="), (last == 'N') ? 'S' : last); print_line (-1, "", ' ', -1, runlevline, time_string (utmp_ent), - "", "", c_isprint (last) ? comment : "", ""); + "", "", c_isprint (last) ? comment : "", ""); return; } @@ -527,16 +527,16 @@ list_entries_who (size_t n, const STRUCT_UTMP *utmp_buf) while (n--) { if (IS_USER_PROCESS (utmp_buf)) - { - char *trimmed_name; + { + char *trimmed_name; - trimmed_name = extract_trimmed_name (utmp_buf); + trimmed_name = extract_trimmed_name (utmp_buf); - printf ("%s%s", separator, trimmed_name); - free (trimmed_name); - separator = " "; - entries++; - } + printf ("%s%s", separator, trimmed_name); + free (trimmed_name); + separator = " "; + entries++; + } utmp_buf++; } printf (_("\n# users=%lu\n"), entries); @@ -546,7 +546,7 @@ static void print_heading (void) { print_line (-1, _("NAME"), ' ', -1, _("LINE"), _("TIME"), _("IDLE"), - _("PID"), _("COMMENT"), _("EXIT")); + _("PID"), _("COMMENT"), _("EXIT")); } /* Display UTMP_BUF, which should have N entries. */ @@ -563,38 +563,38 @@ scan_entries (size_t n, const STRUCT_UTMP *utmp_buf) { ttyname_b = ttyname (STDIN_FILENO); if (!ttyname_b) - return; + return; if (strncmp (ttyname_b, DEV_DIR_WITH_TRAILING_SLASH, DEV_DIR_LEN) == 0) - ttyname_b += DEV_DIR_LEN; /* Discard /dev/ prefix. */ + ttyname_b += DEV_DIR_LEN; /* Discard /dev/ prefix. */ } while (n--) { if (!my_line_only || - strncmp (ttyname_b, utmp_buf->ut_line, - sizeof (utmp_buf->ut_line)) == 0) - { - if (need_users && IS_USER_PROCESS (utmp_buf)) - print_user (utmp_buf, boottime); - else if (need_runlevel && UT_TYPE_RUN_LVL (utmp_buf)) - print_runlevel (utmp_buf); - else if (need_boottime && UT_TYPE_BOOT_TIME (utmp_buf)) - print_boottime (utmp_buf); - /* I've never seen one of these, so I don't know what it should - look like :^) - FIXME: handle OLD_TIME also, perhaps show the delta? */ - else if (need_clockchange && UT_TYPE_NEW_TIME (utmp_buf)) - print_clockchange (utmp_buf); - else if (need_initspawn && UT_TYPE_INIT_PROCESS (utmp_buf)) - print_initspawn (utmp_buf); - else if (need_login && UT_TYPE_LOGIN_PROCESS (utmp_buf)) - print_login (utmp_buf); - else if (need_deadprocs && UT_TYPE_DEAD_PROCESS (utmp_buf)) - print_deadprocs (utmp_buf); - } + strncmp (ttyname_b, utmp_buf->ut_line, + sizeof (utmp_buf->ut_line)) == 0) + { + if (need_users && IS_USER_PROCESS (utmp_buf)) + print_user (utmp_buf, boottime); + else if (need_runlevel && UT_TYPE_RUN_LVL (utmp_buf)) + print_runlevel (utmp_buf); + else if (need_boottime && UT_TYPE_BOOT_TIME (utmp_buf)) + print_boottime (utmp_buf); + /* I've never seen one of these, so I don't know what it should + look like :^) + FIXME: handle OLD_TIME also, perhaps show the delta? */ + else if (need_clockchange && UT_TYPE_NEW_TIME (utmp_buf)) + print_clockchange (utmp_buf); + else if (need_initspawn && UT_TYPE_INIT_PROCESS (utmp_buf)) + print_initspawn (utmp_buf); + else if (need_login && UT_TYPE_LOGIN_PROCESS (utmp_buf)) + print_login (utmp_buf); + else if (need_deadprocs && UT_TYPE_DEAD_PROCESS (utmp_buf)) + print_deadprocs (utmp_buf); + } if (UT_TYPE_BOOT_TIME (utmp_buf)) - boottime = UT_TIME_MEMBER (utmp_buf); + boottime = UT_TIME_MEMBER (utmp_buf); utmp_buf++; } @@ -624,7 +624,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]... [ FILE | ARG1 ARG2 ]\n"), program_name); @@ -685,96 +685,96 @@ main (int argc, char **argv) atexit (close_stdout); while ((optc = getopt_long (argc, argv, "abdlmpqrstuwHT", longopts, NULL)) - != -1) + != -1) { switch (optc) - { - case 'a': - need_boottime = true; - need_deadprocs = true; - need_login = true; - need_initspawn = true; - need_runlevel = true; - need_clockchange = true; - need_users = true; - include_mesg = true; - include_idle = true; - include_exit = true; - assumptions = false; - break; - - case 'b': - need_boottime = true; - assumptions = false; - break; - - case 'd': - need_deadprocs = true; - include_idle = true; - include_exit = true; - assumptions = false; - break; - - case 'H': - include_heading = true; - break; - - case 'l': - need_login = true; - include_idle = true; - assumptions = false; - break; - - case 'm': - my_line_only = true; - break; - - case 'p': - need_initspawn = true; - assumptions = false; - break; - - case 'q': - short_list = true; - break; - - case 'r': - need_runlevel = true; - include_idle = true; - assumptions = false; - break; - - case 's': - short_output = true; - break; - - case 't': - need_clockchange = true; - assumptions = false; - break; - - case 'T': - case 'w': - include_mesg = true; - break; - - case 'u': - need_users = true; - include_idle = true; - assumptions = false; - break; - - case LOOKUP_OPTION: - do_lookup = true; - break; - - case_GETOPT_HELP_CHAR; - - case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); - - default: - usage (EXIT_FAILURE); - } + { + case 'a': + need_boottime = true; + need_deadprocs = true; + need_login = true; + need_initspawn = true; + need_runlevel = true; + need_clockchange = true; + need_users = true; + include_mesg = true; + include_idle = true; + include_exit = true; + assumptions = false; + break; + + case 'b': + need_boottime = true; + assumptions = false; + break; + + case 'd': + need_deadprocs = true; + include_idle = true; + include_exit = true; + assumptions = false; + break; + + case 'H': + include_heading = true; + break; + + case 'l': + need_login = true; + include_idle = true; + assumptions = false; + break; + + case 'm': + my_line_only = true; + break; + + case 'p': + need_initspawn = true; + assumptions = false; + break; + + case 'q': + short_list = true; + break; + + case 'r': + need_runlevel = true; + include_idle = true; + assumptions = false; + break; + + case 's': + short_output = true; + break; + + case 't': + need_clockchange = true; + assumptions = false; + break; + + case 'T': + case 'w': + include_mesg = true; + break; + + case 'u': + need_users = true; + include_idle = true; + assumptions = false; + break; + + case LOOKUP_OPTION: + do_lookup = true; + break; + + case_GETOPT_HELP_CHAR; + + case_GETOPT_VERSION_CHAR (PROGRAM_NAME, AUTHORS); + + default: + usage (EXIT_FAILURE); + } } if (assumptions) diff --git a/src/whoami.c b/src/whoami.c index 4c84d5830..928f69e45 100644 --- a/src/whoami.c +++ b/src/whoami.c @@ -40,7 +40,7 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("Usage: %s [OPTION]...\n"), program_name); @@ -71,7 +71,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -89,6 +89,6 @@ main (int argc, char **argv) exit (EXIT_SUCCESS); } fprintf (stderr, _("%s: cannot find name for user ID %lu\n"), - program_name, (unsigned long int) uid); + program_name, (unsigned long int) uid); exit (EXIT_FAILURE); } @@ -36,14 +36,14 @@ usage (int status) { if (status != EXIT_SUCCESS) fprintf (stderr, _("Try `%s --help' for more information.\n"), - program_name); + program_name); else { printf (_("\ Usage: %s [STRING]...\n\ or: %s OPTION\n\ "), - program_name, program_name); + program_name, program_name); fputs (_("\ Repeatedly output a line with all specified STRING(s), or `y'.\n\ @@ -68,7 +68,7 @@ main (int argc, char **argv) atexit (close_stdout); parse_long_options (argc, argv, PROGRAM_NAME, PACKAGE_NAME, Version, - usage, AUTHORS, (char const *) NULL); + usage, AUTHORS, (char const *) NULL); if (getopt_long (argc, argv, "+", NULL, NULL) != -1) usage (EXIT_FAILURE); @@ -82,11 +82,11 @@ main (int argc, char **argv) { int i; for (i = optind; i < argc; i++) - if (fputs (argv[i], stdout) == EOF - || putchar (i == argc - 1 ? '\n' : ' ') == EOF) - { - error (0, errno, _("standard output")); - exit (EXIT_FAILURE); - } + if (fputs (argv[i], stdout) == EOF + || putchar (i == argc - 1 ? '\n' : ' ') == EOF) + { + error (0, errno, _("standard output")); + exit (EXIT_FAILURE); + } } } diff --git a/tests/Coreutils.pm b/tests/Coreutils.pm index 544747673..fb3d0a227 100644 --- a/tests/Coreutils.pm +++ b/tests/Coreutils.pm @@ -29,7 +29,7 @@ use File::Compare qw(compare); my $debug = $ENV{DEBUG}; my @Types = qw (IN IN_PIPE OUT ERR AUX CMP EXIT PRE POST OUT_SUBST - ERR_SUBST ENV ENV_DEL); + ERR_SUBST ENV ENV_DEL); my %Types = map {$_ => 1} @Types; my %Zero_one_type = map {$_ => 1} qw (OUT ERR EXIT PRE POST OUT_SUBST ERR_SUBST ENV); @@ -135,7 +135,7 @@ sub _compare_files ($$$$$) { my $info = (defined $in_or_out ? "std$in_or_out " : ''); warn "$program_name: test $test_name: ${info}mismatch, comparing " - . "$actual (actual) and $expected (expected)\n"; + . "$actual (actual) and $expected (expected)\n"; # Ignore any failure, discard stderr. system "diff -c $actual $expected 2>/dev/null"; } @@ -156,14 +156,14 @@ sub _process_file_spec ($$$$$) { my $n = keys %$file_spec; die "$program_name: $test_name: $type spec has $n elements --" - . " expected 1\n" - if $n != 1; + . " expected 1\n" + if $n != 1; ($file_name, $contents) = each %$file_spec; # This happens for the AUX hash in an io_spec like this: # {CMP=> ['zy123utsrqponmlkji', {'@AUX@'=> undef}]}, defined $contents - or return $file_name; + or return $file_name; } else { @@ -171,10 +171,10 @@ sub _process_file_spec ($$$$$) } my $is_junk_file = (! defined $file_name - || (($type eq 'IN' || $type eq 'AUX' || $type eq 'CMP') - && defined $contents)); + || (($type eq 'IN' || $type eq 'AUX' || $type eq 'CMP') + && defined $contents)); my $file = _create_file ($program_name, $test_name, - $file_name, $contents); + $file_name, $contents); if ($is_junk_file) { @@ -184,8 +184,8 @@ sub _process_file_spec ($$$$$) { # FIXME: put $srcdir in here somewhere warn "$program_name: $test_name: specified file `$file' does" - . " not exist\n" - if ! -f "$srcdir/$file"; + . " not exist\n" + if ! -f "$srcdir/$file"; } return $file; @@ -198,8 +198,8 @@ sub _at_replace ($$) { my $f = $map->{$eo}; $f - and $s =~ /\@$eo\@/ - and $s =~ s/\@$eo\@/$f/g; + and $s =~ /\@$eo\@/ + and $s =~ s/\@$eo\@/$f/g; } return $s; } @@ -241,33 +241,33 @@ sub run_tests ($$$$$) { my $test_name = $t->[0]; if ($seen{$test_name}) - { - warn "$program_name: $test_name: duplicate test name\n"; - $bad_test_name = 1; - } + { + warn "$program_name: $test_name: duplicate test name\n"; + $bad_test_name = 1; + } $seen{$test_name} = 1; if (0) - { - my $t8 = lc substr $test_name, 0, 8; - if ($seen_8dot3{$t8}) - { - warn "$program_name: 8.3 test name conflict: " - . "$test_name, $seen_8dot3{$t8}\n"; - $bad_test_name = 1; - } - $seen_8dot3{$t8} = $test_name; - } + { + my $t8 = lc substr $test_name, 0, 8; + if ($seen_8dot3{$t8}) + { + warn "$program_name: 8.3 test name conflict: " + . "$test_name, $seen_8dot3{$t8}\n"; + $bad_test_name = 1; + } + $seen_8dot3{$t8} = $test_name; + } # The test name may be no longer than 30 bytes. # Yes, this is an arbitrary limit. If it causes trouble, # consider removing it. my $max = 30; if ($max < length $test_name) - { - warn "$program_name: $test_name: test name is too long (> $max)\n"; - $bad_test_name = 1; - } + { + warn "$program_name: $test_name: test name is too long (> $max)\n"; + $bad_test_name = 1; + } } return 1 if $bad_test_name; @@ -294,150 +294,150 @@ sub run_tests ($$$$$) my $env_prefix = ''; my $input_pipe_cmd; foreach $io_spec (@$t) - { - if (!ref $io_spec) - { - push @args, $io_spec; - next; - } - - if (ref $io_spec ne 'HASH') - { - eval 'use Data::Dumper'; - die "$program_name: $test_name: invalid entry in test spec; " - . "expected HASH-ref,\nbut got this:\n" - . Data::Dumper->Dump ([\$io_spec], ['$io_spec']) . "\n"; - } - - my $n = keys %$io_spec; - die "$program_name: $test_name: spec has $n elements --" - . " expected 1\n" - if $n != 1; - my ($type, $val) = each %$io_spec; - die "$program_name: $test_name: invalid key `$type' in test spec\n" - if ! $Types{$type}; - - # Make sure there's no more than one of OUT, ERR, EXIT, etc. - die "$program_name: $test_name: more than one $type spec\n" - if $Zero_one_type{$type} and $seen_type{$type}++; - - if ($type eq 'PRE' or $type eq 'POST') - { - $expect->{$type} = $val; - next; - } - - if ($type eq 'CMP') - { - my $t = ref $val; - $t && $t eq 'ARRAY' - or die "$program_name: $test_name: invalid CMP spec\n"; - @$val == 2 - or die "$program_name: $test_name: invalid CMP list; must have" - . " exactly 2 elements\n"; - my @cmp_files; - foreach my $e (@$val) - { - my $r = ref $e; - $r && $r ne 'HASH' - and die "$program_name: $test_name: invalid element ($r)" - . " in CMP list; only scalars and hash references " - . "are allowed\n"; - if ($r && $r eq 'HASH') - { - my $n = keys %$e; - $n == 1 - or die "$program_name: $test_name: CMP spec has $n " - . "elements -- expected 1\n"; - - # Replace any `@AUX@' in the key of %$e. - my ($ff, $val) = each %$e; - my $new_ff = _at_replace $expect, $ff; - if ($new_ff ne $ff) - { - $e->{$new_ff} = $val; - delete $e->{$ff}; - } - } - my $cmp_file = _process_file_spec ($program_name, $test_name, - $e, $type, \@junk_files); - push @cmp_files, $cmp_file; - } - push @post_compare, [@cmp_files]; - - $expect->{$type} = $val; - next; - } - - if ($type eq 'EXIT') - { - die "$program_name: $test_name: invalid EXIT code\n" - if $val !~ /^\d+$/; - # FIXME: make sure $data is numeric - $expect->{EXIT} = $val; - next; - } - - if ($type =~ /^(OUT|ERR)_SUBST$/) - { - $expect->{RESULT_SUBST} ||= {}; - $expect->{RESULT_SUBST}->{$1} = $val; - next; - } - - if ($type eq 'ENV') - { - $env_prefix = "$val "; - next; - } - - if ($type eq 'ENV_DEL') - { - push @env_delete, $val; - next; - } - - my $file = _process_file_spec ($program_name, $test_name, $val, - $type, \@junk_files); - - if ($type eq 'IN' || $type eq 'IN_PIPE') - { - my $quoted_file = _shell_quote $file; - if ($type eq 'IN_PIPE') - { - defined $input_pipe_cmd - and die "$program_name: $test_name: only one input" - . " may be specified with IN_PIPE\n"; - $input_pipe_cmd = "cat $quoted_file |"; - } - else - { - push @args, $quoted_file; - } - } - elsif ($type eq 'AUX' || $type eq 'OUT' || $type eq 'ERR') - { - $expect->{$type} = $file; - } - else - { - die "$program_name: $test_name: invalid type: $type\n" - } - } + { + if (!ref $io_spec) + { + push @args, $io_spec; + next; + } + + if (ref $io_spec ne 'HASH') + { + eval 'use Data::Dumper'; + die "$program_name: $test_name: invalid entry in test spec; " + . "expected HASH-ref,\nbut got this:\n" + . Data::Dumper->Dump ([\$io_spec], ['$io_spec']) . "\n"; + } + + my $n = keys %$io_spec; + die "$program_name: $test_name: spec has $n elements --" + . " expected 1\n" + if $n != 1; + my ($type, $val) = each %$io_spec; + die "$program_name: $test_name: invalid key `$type' in test spec\n" + if ! $Types{$type}; + + # Make sure there's no more than one of OUT, ERR, EXIT, etc. + die "$program_name: $test_name: more than one $type spec\n" + if $Zero_one_type{$type} and $seen_type{$type}++; + + if ($type eq 'PRE' or $type eq 'POST') + { + $expect->{$type} = $val; + next; + } + + if ($type eq 'CMP') + { + my $t = ref $val; + $t && $t eq 'ARRAY' + or die "$program_name: $test_name: invalid CMP spec\n"; + @$val == 2 + or die "$program_name: $test_name: invalid CMP list; must have" + . " exactly 2 elements\n"; + my @cmp_files; + foreach my $e (@$val) + { + my $r = ref $e; + $r && $r ne 'HASH' + and die "$program_name: $test_name: invalid element ($r)" + . " in CMP list; only scalars and hash references " + . "are allowed\n"; + if ($r && $r eq 'HASH') + { + my $n = keys %$e; + $n == 1 + or die "$program_name: $test_name: CMP spec has $n " + . "elements -- expected 1\n"; + + # Replace any `@AUX@' in the key of %$e. + my ($ff, $val) = each %$e; + my $new_ff = _at_replace $expect, $ff; + if ($new_ff ne $ff) + { + $e->{$new_ff} = $val; + delete $e->{$ff}; + } + } + my $cmp_file = _process_file_spec ($program_name, $test_name, + $e, $type, \@junk_files); + push @cmp_files, $cmp_file; + } + push @post_compare, [@cmp_files]; + + $expect->{$type} = $val; + next; + } + + if ($type eq 'EXIT') + { + die "$program_name: $test_name: invalid EXIT code\n" + if $val !~ /^\d+$/; + # FIXME: make sure $data is numeric + $expect->{EXIT} = $val; + next; + } + + if ($type =~ /^(OUT|ERR)_SUBST$/) + { + $expect->{RESULT_SUBST} ||= {}; + $expect->{RESULT_SUBST}->{$1} = $val; + next; + } + + if ($type eq 'ENV') + { + $env_prefix = "$val "; + next; + } + + if ($type eq 'ENV_DEL') + { + push @env_delete, $val; + next; + } + + my $file = _process_file_spec ($program_name, $test_name, $val, + $type, \@junk_files); + + if ($type eq 'IN' || $type eq 'IN_PIPE') + { + my $quoted_file = _shell_quote $file; + if ($type eq 'IN_PIPE') + { + defined $input_pipe_cmd + and die "$program_name: $test_name: only one input" + . " may be specified with IN_PIPE\n"; + $input_pipe_cmd = "cat $quoted_file |"; + } + else + { + push @args, $quoted_file; + } + } + elsif ($type eq 'AUX' || $type eq 'OUT' || $type eq 'ERR') + { + $expect->{$type} = $file; + } + else + { + die "$program_name: $test_name: invalid type: $type\n" + } + } # Expect an exit status of zero if it's not specified. $expect->{EXIT} ||= 0; # Allow ERR to be omitted -- in that case, expect no error output. foreach my $eo (qw (OUT ERR)) - { - if (!exists $expect->{$eo}) - { - $expect->{$eo} = _create_file ($program_name, $test_name, - undef, ''); - push @junk_files, $expect->{$eo}; - } - } + { + if (!exists $expect->{$eo}) + { + $expect->{$eo} = _create_file ($program_name, $test_name, + undef, ''); + push @junk_files, $expect->{$eo}; + } + } # FIXME: Does it ever make sense to specify a filename *and* contents # in OUT or ERR spec? @@ -445,10 +445,10 @@ sub run_tests ($$$$$) # FIXME: this is really suboptimal... my @new_args; foreach my $a (@args) - { - $a = _at_replace $expect, $a; - push @new_args, $a; - } + { + $a = _at_replace $expect, $a; + push @new_args, $a; + } @args = @new_args; warn "$test_name...\n" if $verbose; @@ -459,112 +459,112 @@ sub run_tests ($$$$$) push @junk_files, $actual{OUT}, $actual{ERR}; my @cmd = (@prog, @args, "> $actual{OUT}", "2> $actual{ERR}"); $env_prefix - and unshift @cmd, $env_prefix; + and unshift @cmd, $env_prefix; defined $input_pipe_cmd - and unshift @cmd, $input_pipe_cmd; + and unshift @cmd, $input_pipe_cmd; my $cmd_str = join (' ', @cmd); # Delete from the environment any symbols specified by syntax # like this: {ENV_DEL => 'TZ'}. my %pushed_env; foreach my $env_sym (@env_delete) - { - my $val = delete $ENV{$env_sym}; - defined $val - and $pushed_env{$env_sym} = $val; - } + { + my $val = delete $ENV{$env_sym}; + defined $val + and $pushed_env{$env_sym} = $val; + } warn "Running command: `$cmd_str'\n" if $debug; my $rc = 0xffff & system $cmd_str; # Restore any environment setting we changed via a deletion. foreach my $env_sym (keys %pushed_env) - { - $ENV{$env_sym} = $pushed_env{$env_sym}; - } + { + $ENV{$env_sym} = $pushed_env{$env_sym}; + } if ($rc == 0xff00) - { - warn "$program_name: test $test_name failed: command failed:\n" - . " `$cmd_str': $!\n"; - $fail = 1; - goto cleanup; - } + { + warn "$program_name: test $test_name failed: command failed:\n" + . " `$cmd_str': $!\n"; + $fail = 1; + goto cleanup; + } $rc >>= 8 if $rc > 0x80; if ($expect->{EXIT} != $rc) - { - warn "$program_name: test $test_name failed: exit status mismatch:" - . " expected $expect->{EXIT}, got $rc\n"; - $fail = 1; - goto cleanup; - } + { + warn "$program_name: test $test_name failed: exit status mismatch:" + . " expected $expect->{EXIT}, got $rc\n"; + $fail = 1; + goto cleanup; + } my %actual_data; # Record actual stdout and stderr contents, if POST may need them. if ($expect->{POST}) - { - foreach my $eo (qw (OUT ERR)) - { - my $out_file = $actual{$eo}; - open IN, $out_file - or (warn "$program_name: cannot open $out_file for reading: $!\n"), - $fail = 1, next; - $actual_data{$eo} = <IN>; - close IN - or (warn "$program_name: failed to read $out_file: $!\n"), - $fail = 1; - } - } + { + foreach my $eo (qw (OUT ERR)) + { + my $out_file = $actual{$eo}; + open IN, $out_file + or (warn "$program_name: cannot open $out_file for reading: $!\n"), + $fail = 1, next; + $actual_data{$eo} = <IN>; + close IN + or (warn "$program_name: failed to read $out_file: $!\n"), + $fail = 1; + } + } foreach my $eo (qw (OUT ERR)) - { - my $subst_expr = $expect->{RESULT_SUBST}->{$eo}; - if (defined $subst_expr) - { - my $out = $actual{$eo}; - my $orig = "$out.orig"; - - # Move $out aside (to $orig), then recreate $out - # by transforming each line of $orig via $subst_expr. - rename $out, $orig - or (warn "$program_name: cannot rename $out to $orig: $!\n"), - $fail = 1, next; - open IN, $orig - or (warn "$program_name: cannot open $orig for reading: $!\n"), - $fail = 1, (unlink $orig), next; - unlink $orig - or (warn "$program_name: cannot unlink $orig: $!\n"), - $fail = 1; - open OUT, ">$out" - or (warn "$program_name: cannot open $out for writing: $!\n"), - $fail = 1, next; - while (defined (my $line = <IN>)) - { - eval "\$_ = \$line; $subst_expr; \$line = \$_"; - print OUT $line; - } - close IN; - close OUT - or (warn "$program_name: failed to write $out: $!\n"), - $fail = 1, next; - } - - my $eo_lower = lc $eo; - _compare_files ($program_name, $test_name, $eo_lower, - $actual{$eo}, $expect->{$eo}) - and $fail = 1; - } + { + my $subst_expr = $expect->{RESULT_SUBST}->{$eo}; + if (defined $subst_expr) + { + my $out = $actual{$eo}; + my $orig = "$out.orig"; + + # Move $out aside (to $orig), then recreate $out + # by transforming each line of $orig via $subst_expr. + rename $out, $orig + or (warn "$program_name: cannot rename $out to $orig: $!\n"), + $fail = 1, next; + open IN, $orig + or (warn "$program_name: cannot open $orig for reading: $!\n"), + $fail = 1, (unlink $orig), next; + unlink $orig + or (warn "$program_name: cannot unlink $orig: $!\n"), + $fail = 1; + open OUT, ">$out" + or (warn "$program_name: cannot open $out for writing: $!\n"), + $fail = 1, next; + while (defined (my $line = <IN>)) + { + eval "\$_ = \$line; $subst_expr; \$line = \$_"; + print OUT $line; + } + close IN; + close OUT + or (warn "$program_name: failed to write $out: $!\n"), + $fail = 1, next; + } + + my $eo_lower = lc $eo; + _compare_files ($program_name, $test_name, $eo_lower, + $actual{$eo}, $expect->{$eo}) + and $fail = 1; + } foreach my $pair (@post_compare) - { - my ($expected, $actual) = @$pair; - _compare_files $program_name, $test_name, undef, $actual, $expected - and $fail = 1; - } + { + my ($expected, $actual) = @$pair; + _compare_files $program_name, $test_name, undef, $actual, $expected + and $fail = 1; + } cleanup: $expect->{POST} - and &{$expect->{POST}} ($actual_data{OUT}, $actual_data{ERR}); + and &{$expect->{POST}} ($actual_data{OUT}, $actual_data{ERR}); } @@ -595,19 +595,19 @@ sub triple_test($) my @args; my @list_of_hash; foreach my $e (@$t) - { - !ref $e - and push (@args, $e), next; - - ref $e && ref $e eq 'HASH' - or (warn "$0: $t->[0]: unexpected entry type\n"), next; - defined $e->{IN} - and (push @in, $e->{IN}), next; - push @list_of_hash, $e; - } + { + !ref $e + and push (@args, $e), next; + + ref $e && ref $e eq 'HASH' + or (warn "$0: $t->[0]: unexpected entry type\n"), next; + defined $e->{IN} + and (push @in, $e->{IN}), next; + push @list_of_hash, $e; + } # Add variants IFF there is exactly one input file. @in == 1 - or next; + or next; shift @args; # discard test name push @new, ["$t->[0].r", @args, '<', {IN => $in[0]}, @list_of_hash]; push @new, ["$t->[0].p", @args, {IN_PIPE => $in[0]}, @list_of_hash]; diff --git a/tests/CuTmpdir.pm b/tests/CuTmpdir.pm index 0af5d94cf..1f9f08d0c 100644 --- a/tests/CuTmpdir.pm +++ b/tests/CuTmpdir.pm @@ -78,10 +78,10 @@ sub import { my ($sig) = @_; if ($$ == $original_pid and defined $dir) { - chmod_tree; - # Older versions of File::Temp lack this method. - exists &File::Temp::cleanup - and &File::Temp::cleanup; + chmod_tree; + # Older versions of File::Temp lack this method. + exists &File::Temp::cleanup + and &File::Temp::cleanup; } $SIG{$sig} = 'DEFAULT'; kill $sig, $$; diff --git a/tests/chgrp/basic b/tests/chgrp/basic index 14df019cf..2c0d7fae6 100755 --- a/tests/chgrp/basic +++ b/tests/chgrp/basic @@ -108,7 +108,7 @@ test "`ls -C -c -t f g`" = 'f g' || \ *darwin7.9.*|*darwin8.*) echo ignoring known MacOS X-specific chgrp failure 1>&2 ;; *) echo $host_triplet: no-change chgrp failed to update ctime 1>&2; - fail=1 ;; + fail=1 ;; esac } diff --git a/tests/chmod/usage b/tests/chmod/usage index 734c447ca..1f1894427 100755 --- a/tests/chmod/usage +++ b/tests/chmod/usage @@ -81,7 +81,7 @@ for case in $cases; do # Test for misparsing args by creating all $files but $file. # chmod has a bug if it succeeds even though $file is absent. rm -f -- $all_files && touch -- $files && rm -- $file \ - || framework_failure + || framework_failure chmod $args 2>/dev/null && fail=1 done ;; diff --git a/tests/chown/separator b/tests/chown/separator index 4bcaf32d1..4ee285647 100755 --- a/tests/chown/separator +++ b/tests/chown/separator @@ -58,8 +58,8 @@ for u in $id_u "$id_un" ''; do esac for sep in $seps; do case $u$sep$g in - [0-9]*$sep) chown "$u$sep$g" . 2> /dev/null && fail=1 ;; - *) chown "$u$sep$g" . || fail=1 ;; + [0-9]*$sep) chown "$u$sep$g" . 2> /dev/null && fail=1 ;; + *) chown "$u$sep$g" . || fail=1 ;; esac done done diff --git a/tests/cp/cp-mv-backup b/tests/cp/cp-mv-backup index d179d6617..59d03a3ef 100755 --- a/tests/cp/cp-mv-backup +++ b/tests/cp/cp-mv-backup @@ -41,7 +41,7 @@ for prog in cp mv; do for initial_files in 'x' 'x y' 'x y y~' 'x y y.~1~' 'x y y~ y.~1~'; do for opt in none off numbered t existing nil simple never; do touch $initial_files - $prog --backup=$opt x y || fail=1 + $prog --backup=$opt x y || fail=1 echo $initial_files $opt: `ls [xy]*`; rm -f x y y~ y.~?~ done done diff --git a/tests/cp/perm b/tests/cp/perm index 11c4b3ba1..7cc6f419e 100755 --- a/tests/cp/perm +++ b/tests/cp/perm @@ -37,39 +37,39 @@ for u in 31 37 2; do for cmd in mv 'cp -p' cp; do for force in '' -f; do for existing_dest in yes no; do - for g_perm in r w x rw wx xr rwx; do - for o_perm in r w x rw wx xr rwx; do - touch src || exit 1 - chmod u=r,g=rx,o= src || exit 1 - expected_perms=$(stat --format=%A src) - rm -f dest - test $existing_dest = yes && { - touch dest || exit 1 - chmod u=rw,g=$g_perm,o=$o_perm dest || exit 1 - } - $cmd $force src dest || exit 1 - test "$cmd" = mv && test -f src && exit 1 - test "$cmd" = cp && { test -f src || exit 1; } - actual_perms=$(stat --format=%A dest) + for g_perm in r w x rw wx xr rwx; do + for o_perm in r w x rw wx xr rwx; do + touch src || exit 1 + chmod u=r,g=rx,o= src || exit 1 + expected_perms=$(stat --format=%A src) + rm -f dest + test $existing_dest = yes && { + touch dest || exit 1 + chmod u=rw,g=$g_perm,o=$o_perm dest || exit 1 + } + $cmd $force src dest || exit 1 + test "$cmd" = mv && test -f src && exit 1 + test "$cmd" = cp && { test -f src || exit 1; } + actual_perms=$(stat --format=%A dest) - case "$cmd:$force:$existing_dest" in - cp:*:yes) - _g_perm=`echo rwx|sed 's/[^'$g_perm']/-/g'` - _o_perm=`echo rwx|sed 's/[^'$o_perm']/-/g'` - expected_perms=-rw-$_g_perm$_o_perm - ;; - cp:*:no) - test $u = 37 && - expected_perms=`echo $expected_perms|sed 's/.....$/-----/'` - test $u = 31 && - expected_perms=`echo $expected_perms|sed 's/..\(..\).$/--\1-/'` - ;; - esac - test _$actual_perms = _$expected_perms || exit 1 - # Perform only one iteration when there's no existing destination. - test $existing_dest = no && break 3 - done - done + case "$cmd:$force:$existing_dest" in + cp:*:yes) + _g_perm=`echo rwx|sed 's/[^'$g_perm']/-/g'` + _o_perm=`echo rwx|sed 's/[^'$o_perm']/-/g'` + expected_perms=-rw-$_g_perm$_o_perm + ;; + cp:*:no) + test $u = 37 && + expected_perms=`echo $expected_perms|sed 's/.....$/-----/'` + test $u = 31 && + expected_perms=`echo $expected_perms|sed 's/..\(..\).$/--\1-/'` + ;; + esac + test _$actual_perms = _$expected_perms || exit 1 + # Perform only one iteration when there's no existing destination. + test $existing_dest = no && break 3 + done + done done done done diff --git a/tests/cp/same-file b/tests/cp/same-file index 1556011aa..6d57ebd6a 100755 --- a/tests/cp/same-file +++ b/tests/cp/same-file @@ -53,7 +53,7 @@ contents=XYZ for args in 'foo symlink' 'symlink foo' 'foo foo' 'sl1 sl2' 'foo hardlink'; do for options in '' -d -f -df --rem -b -bd -bf -bdf \ - -l -dl -fl -dfl -bl -bdl -bfl -bdfl; do + -l -dl -fl -dfl -bl -bdl -bfl -bdfl; do case $args$options in # These tests are not portable. # They all involve making a hard link to a symbolic link. @@ -61,28 +61,28 @@ for args in 'foo symlink' 'symlink foo' 'foo foo' 'sl1 sl2' 'foo hardlink'; do # by doing "continue" here and eliminating the corresponding # expected output lines below. Don't do that anymore. 'symlink foo'-dfl) - continue;; + continue;; 'symlink foo'-bdl) - continue;; + continue;; 'symlink foo'-bdfl) - continue;; + continue;; 'sl1 sl2'-dfl) - continue;; + continue;; 'sl1 sl2'-bd*l) - continue;; + continue;; 'sl1 sl2'-dl) - continue;; + continue;; esac # cont'd Instead, skip them only on systems for which link does # dereference a symlink. Detect and skip such tests here. case $hard_link_to_symlink_does_the_deref:$args:$options in 'yes:sl1 sl2:-fl') - continue ;; + continue ;; 'yes:sl1 sl2:-bl') - continue ;; + continue ;; 'yes:sl1 sl2:-bfl') - continue ;; + continue ;; esac rm -rf dir @@ -95,37 +95,37 @@ for args in 'foo symlink' 'symlink foo' 'foo foo' 'sl1 sl2' 'foo hardlink'; do case "$args" in *sl2*) ln -s foo sl2;; esac ( ( - # echo 1>&2 cp $options $args - cp $options $args 2>_err - echo $? $options - - # Normalize the program name and diagnostics in the error output, - # and put brackets around the output. - if test -s _err; then - sed ' - s/^[^:]*:\([^:]*\).*/cp:\1/ - 1s/^/[/ - $s/$/]/ - ' _err + # echo 1>&2 cp $options $args + cp $options $args 2>_err + echo $? $options + + # Normalize the program name and diagnostics in the error output, + # and put brackets around the output. + if test -s _err; then + sed ' + s/^[^:]*:\([^:]*\).*/cp:\1/ + 1s/^/[/ + $s/$/]/ + ' _err fi - # Strip off all but the file names. - ls=`ls -gG --ignore=_err . \ - | sed \ - -e '/^total /d' \ - -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//'` - echo "($ls)" - # Make sure the original is unchanged and that - # the destination is a copy. - for f in $args; do - if test -f $f; then - case "`cat $f`" in - "$contents") ;; - *) echo cp FAILED;; - esac - else - echo symlink-loop - fi - done + # Strip off all but the file names. + ls=`ls -gG --ignore=_err . \ + | sed \ + -e '/^total /d' \ + -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//'` + echo "($ls)" + # Make sure the original is unchanged and that + # the destination is a copy. + for f in $args; do + if test -f $f; then + case "`cat $f`" in + "$contents") ;; + *) echo cp FAILED;; + esac + else + echo symlink-loop + fi + done ) | tr '\n' ' ' echo ) | sed 's/ *$//' diff --git a/tests/df/total-verify b/tests/df/total-verify index 809f70d02..7b6273d2d 100755 --- a/tests/df/total-verify +++ b/tests/df/total-verify @@ -39,13 +39,13 @@ while (<>) or die "$0: invalid input line\n: $_"; if ($1 eq 'total' && $5 eq '') { - $total == $2 or die "$total != $2"; - $used == $3 or die "$used != $3"; - $avail == $4 or die "$avail != $4"; - my $line = <>; - defined $line - and die "$0: extra line(s) after totals\n"; - exit 0; + $total == $2 or die "$total != $2"; + $used == $3 or die "$used != $3"; + $avail == $4 or die "$avail != $4"; + my $line = <>; + defined $line + and die "$0: extra line(s) after totals\n"; + exit 0; } $total += $2 unless $2 eq '-'; $used += $3 unless $3 eq '-'; diff --git a/tests/du/files0-from b/tests/du/files0-from index ada0a8903..3e36d5ae5 100755 --- a/tests/du/files0-from +++ b/tests/du/files0-from @@ -31,7 +31,7 @@ my @Tests = # invalid extra command line argument ['f-extra-arg', '--files0-from=- no-such', {IN=>"a"}, {EXIT=>1}, {ERR => "$prog: extra operand `no-such'\n" - . "file operands cannot be combined with --files0-from\n" + . "file operands cannot be combined with --files0-from\n" . "Try `$prog --help' for more information.\n"} ], diff --git a/tests/ls/stat-vs-dirent b/tests/ls/stat-vs-dirent index e8d2118ad..c1d7ff55a 100755 --- a/tests/ls/stat-vs-dirent +++ b/tests/ls/stat-vs-dirent @@ -45,9 +45,9 @@ while :; do # buggy file systems, at mount points. if test "$d_ino" != "$st_ino"; then echo "$0: test failed: $t/$file: d_ino($d_ino) != st_ino($st_ino) - This may indicate a flaw in your kernel or file system implementation. - The flaw isn't serious for coreutils, but it might break other tools, - so you should report it to your operating system vendor." 1>&2 + This may indicate a flaw in your kernel or file system implementation. + The flaw isn't serious for coreutils, but it might break other tools, + so you should report it to your operating system vendor." 1>&2 # This test fails too often, and we don't want to be distracted # with reports, since the code that could be affected by the losing diff --git a/tests/misc/base64 b/tests/misc/base64 index a9c088805..7439ff738 100755 --- a/tests/misc/base64 +++ b/tests/misc/base64 @@ -114,25 +114,25 @@ foreach my $t (@Tests) foreach my $e (@$t) { ref $e && ref $e eq 'HASH' - or next; + or next; defined $e->{EXIT} - and $exit_val = $e->{EXIT}; - defined $e->{IN} - and $in = $e->{IN}; - if (defined $e->{OUT}) - { - my $t = $e->{OUT}; - push @out, $t; - my $len = length $t; - foreach my $i (0..$len) - { - my $u = $t; - substr ($u, $i, 0) = "\n"; - push @out, $u; - 10 <= $i - and last; - } - } + and $exit_val = $e->{EXIT}; + defined $e->{IN} + and $in = $e->{IN}; + if (defined $e->{OUT}) + { + my $t = $e->{OUT}; + push @out, $t; + my $len = length $t; + foreach my $i (0..$len) + { + my $u = $t; + substr ($u, $i, 0) = "\n"; + push @out, $u; + 10 <= $i + and last; + } + } } $exit_val and next; @@ -140,8 +140,8 @@ foreach my $t (@Tests) my $i = 0; foreach my $o (@out) { - push @new, ["d$i-$t->[0]", '--decode', {IN => $o}, {OUT => $in}]; - ++$i; + push @new, ["d$i-$t->[0]", '--decode', {IN => $o}, {OUT => $in}]; + ++$i; } } push @Tests, @new; diff --git a/tests/misc/basename b/tests/misc/basename index 1fad8b273..48b11afc3 100755 --- a/tests/misc/basename +++ b/tests/misc/basename @@ -26,7 +26,7 @@ use File::stat; my $stat_single = stat('/'); my $stat_double = stat('//'); my $double_slash = ($stat_single->dev == $stat_double->dev - && $stat_single->ino == $stat_double->ino) ? '/' : '//'; + && $stat_single->ino == $stat_double->ino) ? '/' : '//'; my $prog = 'basename'; @@ -67,8 +67,8 @@ foreach $t (@Tests) my $e; foreach $e (@$t) { - $e->{OUT} = "$e->{OUT}\n" - if ref $e eq 'HASH' and exists $e->{OUT}; + $e->{OUT} = "$e->{OUT}\n" + if ref $e eq 'HASH' and exists $e->{OUT}; } } diff --git a/tests/misc/comm b/tests/misc/comm index 80a0c2dd3..1f2e82722 100755 --- a/tests/misc/comm +++ b/tests/misc/comm @@ -58,17 +58,17 @@ my @Tests = # invalid missing command line argument (1) ['missing-arg1', $inputs[0], {EXIT=>1}, {ERR => "$prog: missing operand after `a'\n" - . "Try `$prog --help' for more information.\n"}], + . "Try `$prog --help' for more information.\n"}], # invalid missing command line argument (both) ['missing-arg2', {EXIT=>1}, {ERR => "$prog: missing operand\n" - . "Try `$prog --help' for more information.\n"}], + . "Try `$prog --help' for more information.\n"}], # invalid extra command line argument ['extra-arg', @inputs, 'no-such', {EXIT=>1}, {ERR => "$prog: extra operand `no-such'\n" - . "Try `$prog --help' for more information.\n"}], + . "Try `$prog --help' for more information.\n"}], # out-of-order input ['ooo', {IN=>{a=>"1\n3"}}, {IN=>{b=>"3\n2"}}, {EXIT=>1}, @@ -88,13 +88,13 @@ my @Tests = ['ooo4', {IN=>{a=>"3\n1\n0"}}, {IN=>{b=>"3\n2\n0"}}, {EXIT=>1}, {OUT => "\t\t3\n1\n0\n\t2\n\t0\n"}, {ERR => "$prog: file 1 is not in sorted order\n". - "$prog: file 2 is not in sorted order\n" }], + "$prog: file 2 is not in sorted order\n" }], # both inputs out-of-order on last pair ['ooo5', {IN=>{a=>"3\n1"}}, {IN=>{b=>"3\n2"}}, {EXIT=>1}, {OUT => "\t\t3\n1\n\t2\n"}, {ERR => "$prog: file 1 is not in sorted order\n". - "$prog: file 2 is not in sorted order\n" }], + "$prog: file 2 is not in sorted order\n" }], # first input out-of-order extended ['ooo5b', {IN=>{a=>"0\n3\n1"}}, {IN=>{b=>"2\n3"}}, {EXIT=>1}, diff --git a/tests/misc/date b/tests/misc/date index 78b7bc569..1d8767a1c 100755 --- a/tests/misc/date +++ b/tests/misc/date @@ -128,7 +128,7 @@ my @Tests = ['next-y', "-d '$d1 next year' '+%Y-%m-%d %T'", {OUT=>"$dy $t0"}], ['utc-0', "-u -d '08/01/97 6:00' '+%D,%H:%M'", {OUT=>"08/01/97,06:00"}, - {ENV => 'TZ=UTC+4'}], + {ENV => 'TZ=UTC+4'}], ['utc-0a', "-u -d '08/01/97 6:00 UTC +4 hours' '+%D,%H:%M'", {OUT=>"08/01/97,10:00"}], @@ -189,7 +189,7 @@ my @Tests = # Relative days, no time, across time zones. ['relative-3', "-I -d '2006-04-23 21 days ago'", {OUT=>"2006-04-02"}, - {ENV=>'TZ=PST8PDT,M4.1.0,M10.5.0'}], + {ENV=>'TZ=PST8PDT,M4.1.0,M10.5.0'}], # This would infloop (or appear to) prior to coreutils-4.5.5, # due to a bug in strftime.c. @@ -243,8 +243,8 @@ my @Tests = # Unfortunately (for ease of testing), if you set TZ at all, this # failure is not triggered, hence the removal of TZ from the environment. ['cross-dst', "-d'2005-03-27 +1 day'", '+%Y', {OUT=>"2005"}, - {ENV_DEL => 'TZ'}, - ], + {ENV_DEL => 'TZ'}, + ], ['empty-fmt', '+', {OUT=>""}], @@ -284,9 +284,9 @@ my @Tests = foreach my $i (1..364) { push @Tests, ["cross-dst$i", - "-d'2005-01-01 +$i day'", '+%Y', {OUT=>"2005"}, - {ENV_DEL => 'TZ'}, - ]; + "-d'2005-01-01 +$i day'", '+%Y', {OUT=>"2005"}, + {ENV_DEL => 'TZ'}, + ]; } # Append "\n" to each OUT=> RHS if the expected exit value is either @@ -297,12 +297,12 @@ foreach my $t (@Tests) foreach my $e (@$t) { ref $e && ref $e eq 'HASH' && defined $e->{EXIT} - and $exit_val = $e->{EXIT}; + and $exit_val = $e->{EXIT}; } foreach my $e (@$t) { ref $e && ref $e eq 'HASH' && defined $e->{OUT} && ! $exit_val - and $e->{OUT} .= "\n"; + and $e->{OUT} .= "\n"; } } diff --git a/tests/misc/date-next-dow b/tests/misc/date-next-dow index 0809c65d0..9abdb62e9 100755 --- a/tests/misc/date-next-dow +++ b/tests/misc/date-next-dow @@ -55,12 +55,12 @@ foreach my $t (@Tests) foreach my $e (@$t) { ref $e && ref $e eq 'HASH' && defined $e->{EXIT} - and $exit_val = $e->{EXIT}; + and $exit_val = $e->{EXIT}; } foreach my $e (@$t) { ref $e && ref $e eq 'HASH' && defined $e->{OUT} && ! $exit_val - and $e->{OUT} .= "\n"; + and $e->{OUT} .= "\n"; } } diff --git a/tests/misc/dirname b/tests/misc/dirname index d7a1f34be..3358d1099 100755 --- a/tests/misc/dirname +++ b/tests/misc/dirname @@ -27,7 +27,7 @@ use File::stat; my $stat_single = stat('/'); my $stat_double = stat('//'); my $double_slash = ($stat_single->dev == $stat_double->dev - && $stat_single->ino == $stat_double->ino) ? '/' : '//'; + && $stat_single->ino == $stat_double->ino) ? '/' : '//'; my $prog = 'dirname'; @@ -61,8 +61,8 @@ foreach $t (@Tests) my $e; foreach $e (@$t) { - $e->{OUT} = "$e->{OUT}\n" - if ref $e eq 'HASH' and exists $e->{OUT}; + $e->{OUT} = "$e->{OUT}\n" + if ref $e eq 'HASH' and exists $e->{OUT}; } } diff --git a/tests/misc/expr b/tests/misc/expr index 4f1191903..ec1b51ff4 100755 --- a/tests/misc/expr +++ b/tests/misc/expr @@ -159,7 +159,7 @@ my @Tests = ['fail-b', '9 9', {ERR => "$prog: syntax error\n"}, {EXIT => 2}], ['fail-c', {ERR => "$prog: missing operand\n" - . "Try `$prog --help' for more information.\n"}, + . "Try `$prog --help' for more information.\n"}, {EXIT => 2}], ['bignum-add', "$big + 1", {OUT => $big_p1}], @@ -182,8 +182,8 @@ foreach $t (@Tests) my $e; foreach $e (@$t) { - $e->{OUT} .= "\n" - if ref $e eq 'HASH' and exists $e->{OUT}; + $e->{OUT} .= "\n" + if ref $e eq 'HASH' and exists $e->{OUT}; } } diff --git a/tests/misc/factor b/tests/misc/factor index dcf6bc00e..9c640b33b 100755 --- a/tests/misc/factor +++ b/tests/misc/factor @@ -79,14 +79,14 @@ foreach $t (@Tests) # Don't fiddle with expected OUT string if there's a nonzero exit status. foreach my $e (@$t) { - ref $e eq 'HASH' && exists $e->{EXIT} && $e->{EXIT} - and next Test; + ref $e eq 'HASH' && exists $e->{EXIT} && $e->{EXIT} + and next Test; } foreach my $e (@$t) { - ref $e eq 'HASH' && exists $e->{OUT} - and $e->{OUT} = "$arg1: $e->{OUT}\n" + ref $e eq 'HASH' && exists $e->{OUT} + and $e->{OUT} = "$arg1: $e->{OUT}\n" } } diff --git a/tests/misc/head-elide-tail b/tests/misc/head-elide-tail index 089ae76c6..8fc8686b5 100755 --- a/tests/misc/head-elide-tail +++ b/tests/misc/head-elide-tail @@ -63,39 +63,39 @@ if ($ENV{RUN_EXPENSIVE_TESTS}) my $s = "abcdefghijklmnopqrst"; for my $file_size (0..20) { - for my $n_elide (0..20) - { - my $input = substr $s, 0, $file_size; - my $out_len = $n_elide < $file_size ? $file_size - $n_elide : 0; - my $output = substr $input, 0, $out_len; - my $t = ["elideb$file_size-$n_elide", "--bytes=-$n_elide", - {IN=>$input}, {OUT=>$output}]; - push @Tests, $t; - my @u = @$t; - # Insert the ---presume-input-pipe option. - $u[0] .= 'p'; - $u[1] .= ' ---presume-input-pipe'; - push @Tests, \@u; - } + for my $n_elide (0..20) + { + my $input = substr $s, 0, $file_size; + my $out_len = $n_elide < $file_size ? $file_size - $n_elide : 0; + my $output = substr $input, 0, $out_len; + my $t = ["elideb$file_size-$n_elide", "--bytes=-$n_elide", + {IN=>$input}, {OUT=>$output}]; + push @Tests, $t; + my @u = @$t; + # Insert the ---presume-input-pipe option. + $u[0] .= 'p'; + $u[1] .= ' ---presume-input-pipe'; + push @Tests, \@u; + } } $s =~ s/(.)/$1\n/g; for my $file_size (0..20) { - for my $n_elide (0..20) - { - my $input = substr $s, 0, 2 * $file_size; - my $out_len = $n_elide < $file_size ? $file_size - $n_elide : 0; - my $output = substr $input, 0, 2 * $out_len; - my $t = ["elidel$file_size-$n_elide", "--lines=-$n_elide", - {IN=>$input}, {OUT=>$output}]; - push @Tests, $t; - my @u = @$t; - # Insert the ---presume-input-pipe option. - $u[0] .= 'p'; - $u[1] .= ' ---presume-input-pipe'; - push @Tests, \@u; - } + for my $n_elide (0..20) + { + my $input = substr $s, 0, 2 * $file_size; + my $out_len = $n_elide < $file_size ? $file_size - $n_elide : 0; + my $output = substr $input, 0, 2 * $out_len; + my $t = ["elidel$file_size-$n_elide", "--lines=-$n_elide", + {IN=>$input}, {OUT=>$output}]; + push @Tests, $t; + my @u = @$t; + # Insert the ---presume-input-pipe option. + $u[0] .= 'p'; + $u[1] .= ' ---presume-input-pipe'; + push @Tests, \@u; + } } } diff --git a/tests/misc/help-version b/tests/misc/help-version index d03a38c01..9afe8af8b 100755 --- a/tests/misc/help-version +++ b/tests/misc/help-version @@ -77,11 +77,11 @@ for lang in C fr da; do eval "expected=\$expected_failure_status_$prog" test x$expected = x && expected=1 if test $status = $expected; then - : # ok + : # ok else - fail=1 - echo "*** $i: bad exit status \`$status' (expected $expected)," 1>&2 - echo " with --help or --version output redirected to /dev/full" 1>&2 + fail=1 + echo "*** $i: bad exit status \`$status' (expected $expected)," 1>&2 + echo " with --help or --version output redirected to /dev/full" 1>&2 fi fi done diff --git a/tests/misc/ls-misc b/tests/misc/ls-misc index bcd64e34c..63810a559 100755 --- a/tests/misc/ls-misc +++ b/tests/misc/ls-misc @@ -57,12 +57,12 @@ sub setuid_setup() { my $test = shell_quote "$ENV{abs_top_builddir}/src/test"; system (qq(touch setuid && chmod u+s setuid && $test -u setuid && - touch setgid && chmod g+s setgid && $test -g setgid && - mkdir sticky && chmod +t sticky && $test -k sticky && - mkdir owt && chmod +t,o+w owt && $test -k owt && - mkdir owr && chmod o+w owr)) == 0 - or (warn "$program_name: cannot create setuid/setgid/sticky files," - . "so can't run this test\n"), exit 77; + touch setgid && chmod g+s setgid && $test -g setgid && + mkdir sticky && chmod +t sticky && $test -k sticky && + mkdir owt && chmod +t,o+w owt && $test -k owt && + mkdir owr && chmod o+w owr)) == 0 + or (warn "$program_name: cannot create setuid/setgid/sticky files," + . "so can't run this test\n"), exit 77; } sub mk_file(@) @@ -70,7 +70,7 @@ sub mk_file(@) foreach my $f (@_) { open (F, '>', $f) && close F - or die "creating $f: $!\n"; + or die "creating $f: $!\n"; } } @@ -80,31 +80,31 @@ my $mkdir = {PRE => sub {mkdir_d}}; my $rmdir = {POST => sub {rmdir_d}}; my $mkdir_reg = {PRE => sub {mkdir_d; mk_file 'd/f' }}; my $rmdir_reg = {POST => sub {unlink 'd/f' or die "d/f: $!\n"; - rmdir 'd' or die "d: $!\n"}}; + rmdir 'd' or die "d: $!\n"}}; my $mkdir2 = {PRE => sub {mkdir 'd',0755 or die "d: $!\n"; - mkdir 'd/e',0755 or die "d/e: $!\n" }}; + mkdir 'd/e',0755 or die "d/e: $!\n" }}; my $rmdir2 = {POST => sub {rmdir 'd/e' or die "d/e: $!\n"; - rmdir 'd' or die "d: $!\n" }}; + rmdir 'd' or die "d: $!\n" }}; my $target = {PRE => sub { - mkdir 'd',0755 or die "d: $!\n"; - symlink '.', 'd/X' or die "d/X: $!\n"; - push_ls_colors('ln=target') - }}; + mkdir 'd',0755 or die "d: $!\n"; + symlink '.', 'd/X' or die "d/X: $!\n"; + push_ls_colors('ln=target') + }}; my $target2 = {POST => sub {unlink 'd/X' or die "d/X: $!\n"; - rmdir 'd' or die "d: $!\n"; - restore_ls_colors - }}; + rmdir 'd' or die "d: $!\n"; + restore_ls_colors + }}; my $slink_d = {PRE => sub {symlink '/', 'd' or die "d: $!\n"; push_ls_colors('ln=01;36:di=01;34:or=40;31;01') }}; my $unlink_d = {POST => sub {unlink 'd' or die "d: $!\n"; restore_ls_colors}}; my $mkdir_d_slink = {PRE => sub {mkdir 'd',0755 or die "d: $!\n"; - symlink '/', 'd/s' or die "d/s: $!\n" }}; + symlink '/', 'd/s' or die "d/s: $!\n" }}; my $rmdir_d_slink = {POST => sub {unlink 'd/s' or die "d/s: $!\n"; - rmdir 'd' or die "d: $!\n" }}; + rmdir 'd' or die "d: $!\n" }}; sub make_j_d () { @@ -118,7 +118,7 @@ my @v_files = ((map { ".$_" } @v1), @v1); my $exe_in_subdir = {PRE => sub { make_j_d (); push_ls_colors('ex=01;32') }}; my $remove_j = {POST => sub {unlink 'j/d' or die "j/d: $!\n"; rmdir 'j' or die "j: $!\n"; - restore_ls_colors }}; + restore_ls_colors }}; my $e = "\e[0m"; my $q_bell = {IN => {"q\a" => ''}}; @@ -156,11 +156,11 @@ my @Tests = # Test for a bug that was fixed in coreutils-4.5.4. ['sl-F-color', '-F --color=always d', - {OUT => "$e\e[01;36md$e\@\n\e[m"}, - $slink_d, $unlink_d], + {OUT => "$e\e[01;36md$e\@\n\e[m"}, + $slink_d, $unlink_d], ['sl-dF-color', '-dF --color=always d', - {OUT => "$e\e[01;36md$e\@\n\e[m"}, - $slink_d, $unlink_d], + {OUT => "$e\e[01;36md$e\@\n\e[m"}, + $slink_d, $unlink_d], # A listing with no output should have no color sequences at all. ['no-c-empty', '--color=always d', {OUT => ""}, $mkdir, $rmdir], @@ -176,44 +176,44 @@ my @Tests = ['sl-dangle', '--color=always d', {OUT => "$e\e[40;31;01mX$e\n\e[m"}, {PRE => sub { - mkdir 'd',0755 or die "d: $!\n"; - symlink 'non-existent', 'd/X' or die "d/X: $!\n"; - push_ls_colors('or=40;31;01') - }}, + mkdir 'd',0755 or die "d: $!\n"; + symlink 'non-existent', 'd/X' or die "d/X: $!\n"; + push_ls_colors('or=40;31;01') + }}, {POST => sub {unlink 'd/X' or die "d/X: $!\n"; - rmdir 'd' or die "d: $!\n"; - restore_ls_colors; }}, + rmdir 'd' or die "d: $!\n"; + restore_ls_colors; }}, ], # Test for a bug that was introduced in coreutils-4.5.4; fixed in 4.5.5. # To demonstrate it, the file in question (with executable bit set) # must not be a command line argument. ['color-exe1', '--color=always j', - {OUT => "$e\e[01;32md$e\n\e[m"}, - $exe_in_subdir, $remove_j], + {OUT => "$e\e[01;32md$e\n\e[m"}, + $exe_in_subdir, $remove_j], # From Stéphane Chazelas. ['no-a-isdir-b', 'no-dir d', - {OUT => "d:\n"}, - {ERR => "ls: cannot access no-dir: No such file or directory\n"}, - $mkdir, $rmdir, {EXIT => 2}], + {OUT => "d:\n"}, + {ERR => "ls: cannot access no-dir: No such file or directory\n"}, + $mkdir, $rmdir, {EXIT => 2}], ['recursive-2', '-R d', {OUT => "d:\ne\n\nd/e:\n"}, $mkdir2, $rmdir2], ['setuid-etc', '-1 -d --color=always owr owt setgid setuid sticky', - {OUT => - "$e\e[34;42mowr$e\n" - . "\e[30;42mowt$e\n" - . "\e[30;43msetgid$e\n" - . "\e[37;41msetuid$e\n" - . "\e[37;44msticky$e\n" - . "\e[m" - }, - - {POST => sub { + {OUT => + "$e\e[34;42mowr$e\n" + . "\e[30;42mowt$e\n" + . "\e[30;43msetgid$e\n" + . "\e[37;41msetuid$e\n" + . "\e[37;44msticky$e\n" + . "\e[m" + }, + + {POST => sub { unlink qw(setuid setgid); - foreach my $dir (qw(owr owt sticky)) {rmdir $dir} }}, - ], + foreach my $dir (qw(owr owt sticky)) {rmdir $dir} }}, + ], # For 5.97 and earlier, --file-type acted like --indicator-style=slash. ['file-type', '--file-type d', {OUT => "s@\n"}, diff --git a/tests/misc/md5sum b/tests/misc/md5sum index c19a50405..2fb024d16 100755 --- a/tests/misc/md5sum +++ b/tests/misc/md5sum @@ -31,42 +31,42 @@ my @Tests = ['2', {IN=> {f=> 'a'}}, {OUT=>"0cc175b9c0f1b6a831c399e269772661 f\n"}], ['3', {IN=> {f=> 'abc'}}, {OUT=>"900150983cd24fb0d6963f7d28e17f72 f\n"}], ['4', {IN=> {f=> 'message digest'}}, - {OUT=>"f96b697d7cb7938d525a2f31aaf161d0 f\n"}], + {OUT=>"f96b697d7cb7938d525a2f31aaf161d0 f\n"}], ['5', {IN=> {f=> 'abcdefghijklmnopqrstuvwxyz'}}, - {OUT=>"c3fcd3d76192e4007dfb496cca67e13b f\n"}], + {OUT=>"c3fcd3d76192e4007dfb496cca67e13b f\n"}], ['6', {IN=> {f=> join ('', 'A'..'Z', 'a'..'z', '0'..'9')}}, - {OUT=>"d174ab98d277d9f5a5611c2c9f419d9f f\n"}], + {OUT=>"d174ab98d277d9f5a5611c2c9f419d9f f\n"}], ['7', {IN=> {f=> '1234567890' x 8}}, - {OUT=>"57edf4a22be3c955ac49da2e2107b67a f\n"}], + {OUT=>"57edf4a22be3c955ac49da2e2107b67a f\n"}], ['backslash', {IN=> {".\\foo"=> ''}}, - {OUT=>"\\$degenerate .\\\\foo\n"}], + {OUT=>"\\$degenerate .\\\\foo\n"}], ['check-1', '--check', {AUX=> {f=> ''}}, - {IN=> {'f.md5' => "$degenerate f\n"}}, - {OUT=>"f: OK\n"}], + {IN=> {'f.md5' => "$degenerate f\n"}}, + {OUT=>"f: OK\n"}], ['check-2', '--check', '--status', {IN=>{'f.md5' => "$degenerate f\n"}}, - {AUX=> {f=> 'foo'}}, {EXIT=> 1}], + {AUX=> {f=> 'foo'}}, {EXIT=> 1}], ['check-quiet1', '--check', '--quiet', {AUX=> {f=> ''}}, - {IN=> {'f.md5' => "$degenerate f\n"}}, - {OUT=>""}], + {IN=> {'f.md5' => "$degenerate f\n"}}, + {OUT=>""}], ['check-quiet2', '--check', '--quiet', - {IN=>{'f.md5' => "$degenerate f\n"}}, - {AUX=> {f=> 'foo'}}, {OUT=>"f: FAILED\n"}, - {ERR=>"md5sum: WARNING: 1 of 1 computed" - . " checksum did NOT match\n"}, - {EXIT=> 1}], + {IN=>{'f.md5' => "$degenerate f\n"}}, + {AUX=> {f=> 'foo'}}, {OUT=>"f: FAILED\n"}, + {ERR=>"md5sum: WARNING: 1 of 1 computed" + . " checksum did NOT match\n"}, + {EXIT=> 1}], # The sha1sum and md5sum drivers share a lot of code. # Ensure that md5sum does *not* share the part that makes # sha1sum accept BSD format. ['check-bsd', '--check', {IN=> {'f.sha1' => "SHA1 (f) = $degenerate\n"}}, - {AUX=> {f=> ''}}, - {ERR=>"md5sum: f.sha1: no properly formatted " - . "MD5 checksum lines found\n"}, - {EXIT=> 1}], + {AUX=> {f=> ''}}, + {ERR=>"md5sum: f.sha1: no properly formatted " + . "MD5 checksum lines found\n"}, + {EXIT=> 1}], ['check-bsd2', '--check', {IN=> {'f.md5' => "MD5 (f) = $degenerate\n"}}, - {AUX=> {f=> ''}}, {OUT=>"f: OK\n"}], + {AUX=> {f=> ''}}, {OUT=>"f: OK\n"}], ['check-bsd3', '--check', '--status', - {IN=> {'f.md5' => "MD5 (f) = $degenerate\n"}}, - {AUX=> {f=> 'bar'}}, {EXIT=> 1}], + {IN=> {'f.md5' => "MD5 (f) = $degenerate\n"}}, + {AUX=> {f=> 'bar'}}, {EXIT=> 1}], ['bsd-segv', '--check', {IN=> {'z' => "MD5 ("}}, {EXIT=> 1}, {ERR=> "$prog: z: no properly formatted MD5 checksum lines found\n"}], diff --git a/tests/misc/od b/tests/misc/od index 538bce8a0..a83fe4c8c 100755 --- a/tests/misc/od +++ b/tests/misc/od @@ -51,7 +51,7 @@ my @Tests = {IN=>{i=>'c'}}, {OUT=>''}], # Skip the sum of the lengths of the first three inputs, printing the 4th. ['j-bug4', '-c -j 3 -An', {IN=>{g=>'a'}}, {IN=>{h=>'b'}}, - {IN=>{i=>'c'}}, {IN=>{j=>'d'}}, {OUT=>" d\n"}], + {IN=>{i=>'c'}}, {IN=>{j=>'d'}}, {OUT=>" d\n"}], # Ensure that od -j doesn't fseek across a nonempty file in /proc, # even if the kernel reports that the file has stat.st_size = 0. diff --git a/tests/misc/pwd-long b/tests/misc/pwd-long index b3ddd083a..207e7549c 100755 --- a/tests/misc/pwd-long +++ b/tests/misc/pwd-long @@ -45,11 +45,11 @@ sub normalize_to_cwd_relative ($$$) { $slash = index $dir, '/', $slash + 1; $slash <= -1 - and die "$ME: $dir does not contain old CWD\n"; + and die "$ME: $dir does not contain old CWD\n"; my $dir_prefix = $slash ? substr ($dir, 0, $slash) : '/'; my ($d, $i) = (stat $dir_prefix)[0, 1]; $d == $dev && $i == $ino - and return substr $dir, $slash + 1; + and return substr $dir, $slash + 1; } } diff --git a/tests/misc/seq b/tests/misc/seq index b34833da2..21eafcf0a 100755 --- a/tests/misc/seq +++ b/tests/misc/seq @@ -102,7 +102,7 @@ my @Tests = # fail to print the "2,0" endpoint. ['locale-dec-pt', qw(-0.1 0.1 2), {OUT => [qw(-0.1 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0 - 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0)]}, + 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9 2.0)]}, {ENV => "LC_ALL=$locale"}, {OUT_SUBST => 's/,/./g'}, @@ -116,8 +116,8 @@ foreach $t (@Tests) my $e; foreach $e (@$t) { - $e->{OUT} = join ("\n", @{$e->{OUT}}) . "\n" - if ref $e eq 'HASH' and exists $e->{OUT}; + $e->{OUT} = join ("\n", @{$e->{OUT}}) . "\n" + if ref $e eq 'HASH' and exists $e->{OUT}; } } diff --git a/tests/misc/sha1sum b/tests/misc/sha1sum index 043c5904a..3f09abaae 100755 --- a/tests/misc/sha1sum +++ b/tests/misc/sha1sum @@ -28,38 +28,38 @@ my $sha_degenerate = "da39a3ee5e6b4b0d3255bfef95601890afd80709"; my @Tests = ( ['s1', {IN=> {f=> ''}}, - {OUT=>"$sha_degenerate f\n"}], + {OUT=>"$sha_degenerate f\n"}], ['s2', {IN=> {f=> 'a'}}, - {OUT=>"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8 f\n"}], + {OUT=>"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8 f\n"}], ['s3', {IN=> {f=> 'abc'}}, - {OUT=>"a9993e364706816aba3e25717850c26c9cd0d89d f\n"}], + {OUT=>"a9993e364706816aba3e25717850c26c9cd0d89d f\n"}], ['s4', {IN=> {f=> 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'}}, - {OUT=>"84983e441c3bd26ebaae4aa1f95129e5e54670f1 f\n"}], + {OUT=>"84983e441c3bd26ebaae4aa1f95129e5e54670f1 f\n"}], ['s5', {IN=> {f=> 'abcdefghijklmnopqrstuvwxyz'}}, - {OUT=>"32d10c7b8cf96570ca04ce37f2a19d84240d3a89 f\n"}], + {OUT=>"32d10c7b8cf96570ca04ce37f2a19d84240d3a89 f\n"}], ['s6', {IN=> {f=> join ('', 'A'..'Z', 'a'..'z', '0'..'9')}}, - {OUT=>"761c457bf73b14d27e9e9265c46f4b4dda11f940 f\n"}], + {OUT=>"761c457bf73b14d27e9e9265c46f4b4dda11f940 f\n"}], ['s7', {IN=> {f=> '1234567890' x 8}}, - {OUT=>"50abf5706a150990a08b2c5ea40fa0e585554732 f\n"}], + {OUT=>"50abf5706a150990a08b2c5ea40fa0e585554732 f\n"}], ['million-a', {IN=> {f=> 'a' x 1000000}}, - {OUT=>"34aa973cd4c4daa4f61eeb2bdbad27316534016f f\n"}], + {OUT=>"34aa973cd4c4daa4f61eeb2bdbad27316534016f f\n"}], ['bs-sha', {IN=> {".\\foo"=> ''}}, - {OUT=>"\\$sha_degenerate .\\\\foo\n"}], + {OUT=>"\\$sha_degenerate .\\\\foo\n"}], # The sha1sum and md5sum drivers share a lot of code. # Ensure that sha1sum does *not* share the part that makes # md5sum accept BSD format. ['check-bsd', '--check', {IN=> {'f.md5' => "MD5 (f) = $sha_degenerate\n"}}, - {AUX=> {f=> ''}}, - {ERR=>"sha1sum: f.md5: no properly formatted " - . "SHA1 checksum lines found\n"}, - {EXIT=> 1}], + {AUX=> {f=> ''}}, + {ERR=>"sha1sum: f.md5: no properly formatted " + . "SHA1 checksum lines found\n"}, + {EXIT=> 1}], ['check-bsd2', '--check', - {IN=> {'f.sha1' => "SHA1 (f) = $sha_degenerate\n"}}, - {AUX=> {f=> ''}}, {OUT=>"f: OK\n"}], + {IN=> {'f.sha1' => "SHA1 (f) = $sha_degenerate\n"}}, + {AUX=> {f=> ''}}, {OUT=>"f: OK\n"}], ['check-bsd3', '--check', '--status', - {IN=> {'f.sha1' => "SHA1 (f) = $sha_degenerate\n"}}, - {AUX=> {f=> 'bar'}}, {EXIT=> 1}], + {IN=> {'f.sha1' => "SHA1 (f) = $sha_degenerate\n"}}, + {AUX=> {f=> 'bar'}}, {EXIT=> 1}], ['bsd-segv', '--check', {IN=> {'z' => "SHA1 ("}}, {EXIT=> 1}, {ERR=> "$prog: z: no properly formatted SHA1 checksum lines found\n"}], ); diff --git a/tests/misc/sha224sum b/tests/misc/sha224sum index f9e9ac0d3..aace96c96 100755 --- a/tests/misc/sha224sum +++ b/tests/misc/sha224sum @@ -26,12 +26,12 @@ use strict; my @Tests = ( ['s3', {IN=> {f=> 'abc'}}, - {OUT=>"23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7 f\n"}], + {OUT=>"23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7 f\n"}], ['s4', {IN=> {f=> 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'}}, - {OUT=>"75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525 f\n"}], + {OUT=>"75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525 f\n"}], ['s8', {IN=> {f=> 'a' x 1000000}}, - {OUT=>"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67 f\n"}], + {OUT=>"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67 f\n"}], ); # Insert the `--text' argument for each test. diff --git a/tests/misc/sha256sum b/tests/misc/sha256sum index 99c5e1ebd..d85f24884 100755 --- a/tests/misc/sha256sum +++ b/tests/misc/sha256sum @@ -28,16 +28,16 @@ my $sha_degenerate = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b78 my @Tests = ( ['s1', {IN=> {f=> ''}}, - {OUT=>"$sha_degenerate f\n"}], + {OUT=>"$sha_degenerate f\n"}], ['s2', {IN=> {f=> 'a'}}, - {OUT=>"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb f\n"}], + {OUT=>"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb f\n"}], ['s3', {IN=> {f=> 'abc'}}, - {OUT=>"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad f\n"}], + {OUT=>"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad f\n"}], ['s4', {IN=> {f=> 'abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'}}, - {OUT=>"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1 f\n"}], + {OUT=>"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1 f\n"}], ['s8', {IN=> {f=> 'a' x 1000000}}, - {OUT=>"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 f\n"}], + {OUT=>"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0 f\n"}], ); # Insert the `--text' argument for each test. diff --git a/tests/misc/sha384sum b/tests/misc/sha384sum index 858949166..c5818e263 100755 --- a/tests/misc/sha384sum +++ b/tests/misc/sha384sum @@ -28,16 +28,16 @@ my $sha_degenerate = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63 my @Tests = ( ['s1', {IN=> {f=> ''}}, - {OUT=>"$sha_degenerate f\n"}], + {OUT=>"$sha_degenerate f\n"}], ['s2', {IN=> {f=> 'a'}}, - {OUT=>"54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31 f\n"}], + {OUT=>"54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31 f\n"}], ['s3', {IN=> {f=> 'abc'}}, - {OUT=>"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7 f\n"}], + {OUT=>"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7 f\n"}], ['s4', {IN=> {f=> 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu'}}, - {OUT=>"09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039 f\n"}], + {OUT=>"09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039 f\n"}], ['s8', {IN=> {f=> 'a' x 1000000}}, - {OUT=>"9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985 f\n"}], + {OUT=>"9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b07b8b3dc38ecc4ebae97ddd87f3d8985 f\n"}], ); # Insert the `--text' argument for each test. diff --git a/tests/misc/sha512sum b/tests/misc/sha512sum index f9f8e5d6f..9a45602c4 100755 --- a/tests/misc/sha512sum +++ b/tests/misc/sha512sum @@ -28,16 +28,16 @@ my $sha_degenerate = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d3 my @Tests = ( ['s1', {IN=> {f=> ''}}, - {OUT=>"$sha_degenerate f\n"}], + {OUT=>"$sha_degenerate f\n"}], ['s2', {IN=> {f=> 'a'}}, - {OUT=>"1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75 f\n"}], + {OUT=>"1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75 f\n"}], ['s3', {IN=> {f=> 'abc'}}, - {OUT=>"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f f\n"}], + {OUT=>"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f f\n"}], ['s4', {IN=> {f=> 'abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu'}}, - {OUT=>"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909 f\n"}], + {OUT=>"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909 f\n"}], ['s8', {IN=> {f=> 'a' x 1000000}}, - {OUT=>"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b f\n"}], + {OUT=>"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973ebde0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b f\n"}], ); # Insert the `--text' argument for each test. diff --git a/tests/misc/sort-files0-from b/tests/misc/sort-files0-from index 50ad0909c..6ac1e6b4f 100755 --- a/tests/misc/sort-files0-from +++ b/tests/misc/sort-files0-from @@ -31,8 +31,8 @@ my @Tests = # invalid extra command line argument ['f-extra-arg', '--files0-from=- no-such', {IN=>"a"}, {EXIT=>2}, {ERR => "$prog: extra operand `no-such'\n" - . "file operands cannot be combined with --files0-from\n" - . "Try `$prog --help' for more information.\n"} + . "file operands cannot be combined with --files0-from\n" + . "Try `$prog --help' for more information.\n"} ], # missing input file diff --git a/tests/misc/sort-merge b/tests/misc/sort-merge index c10a59db2..aedd64c64 100755 --- a/tests/misc/sort-merge +++ b/tests/misc/sort-merge @@ -43,11 +43,11 @@ my @Tests = # check validation of --batch-size option ['nmerge-0', "-m --batch-size=0", @inputs, {ERR=>"$prog: invalid --batch-size argument `0'\n". - "$prog: minimum --batch-size argument is `2'\n"}, {EXIT=>2}], + "$prog: minimum --batch-size argument is `2'\n"}, {EXIT=>2}], ['nmerge-1', "-m --batch-size=1", @inputs, {ERR=>"$prog: invalid --batch-size argument `1'\n". - "$prog: minimum --batch-size argument is `2'\n"}, {EXIT=>2}], + "$prog: minimum --batch-size argument is `2'\n"}, {EXIT=>2}], ['nmerge-neg', "-m --batch-size=-1", @inputs, {ERR=>"$prog: invalid --batch-size argument `-1'\n"}, {EXIT=>2}], @@ -56,9 +56,9 @@ my @Tests = {ERR=>"$prog: invalid --batch-size argument `a'\n"}, {EXIT=>2}], ['nmerge-big', "-m --batch-size=$bigint", @inputs, - {ERR_SUBST=>'s/(current rlimit is) \d+/$1/'}, + {ERR_SUBST=>'s/(current rlimit is) \d+/$1/'}, {ERR=>"$prog: --batch-size argument `$bigint' too large\n". - "$prog: maximum --batch-size argument with current rlimit is\n"}, + "$prog: maximum --batch-size argument with current rlimit is\n"}, {EXIT=>2}], # This should work since nmerge >= the number of input files @@ -69,12 +69,12 @@ my @Tests = ['nmerge-no', "-m --batch-size=2 -T$badtmp", @inputs, {ERR_SUBST=>"s|': .*|':|"}, {ERR=>"$prog: cannot create temporary file in `$badtmp':\n"}, - {EXIT=>2}], + {EXIT=>2}], # This used to fail because setting batch-size without also setting # buffer size would cause the buffer size to be set to the minimum. ['batch-size', "--batch-size=16 -T$badtmp", {IN=> {big=> $big_input}}, - {OUT=>$big_input}], + {OUT=>$big_input}], ); my $save_temps = $ENV{DEBUG}; diff --git a/tests/misc/sort-version b/tests/misc/sort-version index 401262bcd..32b0ed258 100755 --- a/tests/misc/sort-version +++ b/tests/misc/sort-version @@ -24,86 +24,86 @@ fi . $srcdir/test-lib.sh cat > in <<- _EOF_ - gcc-c++-10.fc9.tar.gz - gcc-c++-10.8.12-0.7rc2.fc9.tar.bz2 - glibc-2-0.1.beta1.fc10.rpm - glibc-common-5-0.2.beta2.fc9.ebuild - glibc-common-5-0.2b.deb - glibc-common-11b.ebuild - glibc-common-11-0.6rc2.ebuild - libstdc++-0.5.8.11-0.7rc2.fc10.tar.gz - libstdc++-4a.fc8.tar.gz - libstdc++-4.10.4.20040204svn.rpm - libstdc++-devel-3.fc8.ebuild - libstdc++-devel-3a.fc9.tar.gz - libstdc++-devel-8.fc8.deb - libstdc++-devel-8.6.2-0.4b.fc8 - nss_ldap-1-0.2b.fc9.tar.bz2 - nss_ldap-1-0.6rc2.fc8.tar.gz - nss_ldap-1.0-0.1a.tar.gz - nss_ldap-10beta1.fc8.tar.gz - nss_ldap-10.11.8.6.20040204cvs.fc10.ebuild - string start 5.0.0 end of str - string start 5.1.0 end of str - string start 5.10.0 end of str - string start 5.2.0 end of str - string start 5.20.0 end of str - string start 5.3.0 end of str - string start 5.30.0 end of str - string start 5.4.0 end of str - string start 5.40.0 end of str - string start 5.5.0 end of str - string start 5.50.0 end of str - string start 5.6.0 end of str - string start 5.60.0 end of str - string start 5.7.0 end of str - string start 5.70.0 end of str - string start 5.8.0 end of str - string start 5.80.0 end of str - string start 5.9.0 end of str - string start 5.90.0 end of str - _EOF_ + gcc-c++-10.fc9.tar.gz + gcc-c++-10.8.12-0.7rc2.fc9.tar.bz2 + glibc-2-0.1.beta1.fc10.rpm + glibc-common-5-0.2.beta2.fc9.ebuild + glibc-common-5-0.2b.deb + glibc-common-11b.ebuild + glibc-common-11-0.6rc2.ebuild + libstdc++-0.5.8.11-0.7rc2.fc10.tar.gz + libstdc++-4a.fc8.tar.gz + libstdc++-4.10.4.20040204svn.rpm + libstdc++-devel-3.fc8.ebuild + libstdc++-devel-3a.fc9.tar.gz + libstdc++-devel-8.fc8.deb + libstdc++-devel-8.6.2-0.4b.fc8 + nss_ldap-1-0.2b.fc9.tar.bz2 + nss_ldap-1-0.6rc2.fc8.tar.gz + nss_ldap-1.0-0.1a.tar.gz + nss_ldap-10beta1.fc8.tar.gz + nss_ldap-10.11.8.6.20040204cvs.fc10.ebuild + string start 5.0.0 end of str + string start 5.1.0 end of str + string start 5.10.0 end of str + string start 5.2.0 end of str + string start 5.20.0 end of str + string start 5.3.0 end of str + string start 5.30.0 end of str + string start 5.4.0 end of str + string start 5.40.0 end of str + string start 5.5.0 end of str + string start 5.50.0 end of str + string start 5.6.0 end of str + string start 5.60.0 end of str + string start 5.7.0 end of str + string start 5.70.0 end of str + string start 5.8.0 end of str + string start 5.80.0 end of str + string start 5.9.0 end of str + string start 5.90.0 end of str + _EOF_ cat > exp <<- _EOF_ - gcc-c++-10.fc9.tar.gz - gcc-c++-10.8.12-0.7rc2.fc9.tar.bz2 - glibc-2-0.1.beta1.fc10.rpm - glibc-common-5-0.2.beta2.fc9.ebuild - glibc-common-5-0.2b.deb - glibc-common-11b.ebuild - glibc-common-11-0.6rc2.ebuild - libstdc++-0.5.8.11-0.7rc2.fc10.tar.gz - libstdc++-4a.fc8.tar.gz - libstdc++-4.10.4.20040204svn.rpm - libstdc++-devel-3.fc8.ebuild - libstdc++-devel-3a.fc9.tar.gz - libstdc++-devel-8.fc8.deb - libstdc++-devel-8.6.2-0.4b.fc8 - nss_ldap-1-0.2b.fc9.tar.bz2 - nss_ldap-1-0.6rc2.fc8.tar.gz - nss_ldap-1.0-0.1a.tar.gz - nss_ldap-10beta1.fc8.tar.gz - nss_ldap-10.11.8.6.20040204cvs.fc10.ebuild - string start 5.0.0 end of str - string start 5.1.0 end of str - string start 5.2.0 end of str - string start 5.3.0 end of str - string start 5.4.0 end of str - string start 5.5.0 end of str - string start 5.6.0 end of str - string start 5.7.0 end of str - string start 5.8.0 end of str - string start 5.9.0 end of str - string start 5.10.0 end of str - string start 5.20.0 end of str - string start 5.30.0 end of str - string start 5.40.0 end of str - string start 5.50.0 end of str - string start 5.60.0 end of str - string start 5.70.0 end of str - string start 5.80.0 end of str - string start 5.90.0 end of str - _EOF_ + gcc-c++-10.fc9.tar.gz + gcc-c++-10.8.12-0.7rc2.fc9.tar.bz2 + glibc-2-0.1.beta1.fc10.rpm + glibc-common-5-0.2.beta2.fc9.ebuild + glibc-common-5-0.2b.deb + glibc-common-11b.ebuild + glibc-common-11-0.6rc2.ebuild + libstdc++-0.5.8.11-0.7rc2.fc10.tar.gz + libstdc++-4a.fc8.tar.gz + libstdc++-4.10.4.20040204svn.rpm + libstdc++-devel-3.fc8.ebuild + libstdc++-devel-3a.fc9.tar.gz + libstdc++-devel-8.fc8.deb + libstdc++-devel-8.6.2-0.4b.fc8 + nss_ldap-1-0.2b.fc9.tar.bz2 + nss_ldap-1-0.6rc2.fc8.tar.gz + nss_ldap-1.0-0.1a.tar.gz + nss_ldap-10beta1.fc8.tar.gz + nss_ldap-10.11.8.6.20040204cvs.fc10.ebuild + string start 5.0.0 end of str + string start 5.1.0 end of str + string start 5.2.0 end of str + string start 5.3.0 end of str + string start 5.4.0 end of str + string start 5.5.0 end of str + string start 5.6.0 end of str + string start 5.7.0 end of str + string start 5.8.0 end of str + string start 5.9.0 end of str + string start 5.10.0 end of str + string start 5.20.0 end of str + string start 5.30.0 end of str + string start 5.40.0 end of str + string start 5.50.0 end of str + string start 5.60.0 end of str + string start 5.70.0 end of str + string start 5.80.0 end of str + string start 5.90.0 end of str + _EOF_ fail=0 sort --sort=version -o out in || fail=1 diff --git a/tests/misc/stat-printf b/tests/misc/stat-printf index b459e3bd1..05ff5a23c 100755 --- a/tests/misc/stat-printf +++ b/tests/misc/stat-printf @@ -40,7 +40,7 @@ my @Tests = ['hex-1', q!--printf='\x34\xf' .!, {OUT=>"\x34\xf"}], ['hex-2', q!--printf='.\x18p\xfq' .!, {OUT=>".\x18p\x0fq"}], ['hex-3', q!--printf='\x' .!, {OUT=>'x'}, - {ERR=>"$prog: warning: unrecognized escape `\\x'\n"}], + {ERR=>"$prog: warning: unrecognized escape `\\x'\n"}], # With --format, there *is* a trailing newline. ['f-nl', "--format=%n .", {OUT=>".\n"}], @@ -49,12 +49,12 @@ my @Tests = ['end-pct', "--printf=% .", {OUT=>"%"}], ['pct-pct', "--printf=%% .", {OUT=>"%"}], ['end-bs', "--printf='\\' .", {OUT=>'\\'}, - {ERR=>"$prog: warning: backslash at end of format\n"}], + {ERR=>"$prog: warning: backslash at end of format\n"}], ['err-1', "--printf=%9% .", {EXIT => 1}, - {ERR=>"$prog: %9%: invalid directive\n"}], + {ERR=>"$prog: %9%: invalid directive\n"}], ['err-2', "--printf=%9 .", {EXIT => 1}, - {ERR=>"$prog: %9: invalid directive\n"}], + {ERR=>"$prog: %9: invalid directive\n"}], ); my $save_temps = $ENV{DEBUG}; diff --git a/tests/misc/stty b/tests/misc/stty index b607ec08c..a7f93ca75 100755 --- a/tests/misc/stty +++ b/tests/misc/stty @@ -87,13 +87,13 @@ if test -n "$RUN_LONG_TESTS"; then rev1=`eval echo "\\\$REV_$opt1"` rev2=`eval echo "\\\$REV_$opt2"` if test -n "$rev1"; then - stty -$opt1 $opt2 || fail=1 + stty -$opt1 $opt2 || fail=1 fi if test -n "$rev2"; then - stty $opt1 -$opt2 || fail=1 + stty $opt1 -$opt2 || fail=1 fi if test "$rev1$rev2" = 11; then - stty -$opt1 -$opt2 || fail=1 + stty -$opt1 -$opt2 || fail=1 fi done done diff --git a/tests/misc/sum b/tests/misc/sum index 875960753..af3d7f80f 100755 --- a/tests/misc/sum +++ b/tests/misc/sum @@ -34,7 +34,7 @@ my @Tests = ['4', {IN=> {f=> 'message digest'}}, {OUT=>"26423 1\n"}], ['5', {IN=> {f=> 'abcdefghijklmnopqrstuvwxyz'}}, {OUT=>"53553 1\n"}], ['6', {IN=> {f=> join ('', 'A'..'Z', 'a'..'z', '0'..'9')}}, - {OUT=>"25587 1\n"}], + {OUT=>"25587 1\n"}], ['7', {IN=> {f=> '1234567890' x 8}}, {OUT=>"21845 1\n"}], ['a-r-1k', '-r', {IN=> {f=> $in_1k}}, {OUT=>"65409 1\n"}], @@ -49,7 +49,7 @@ my @Tests = ['5s', '-s', {IN=> {f=> 'abcdefghijklmnopqrstuvwxyz'}}, {OUT=>"2847 1 f\n"}], ['6s', '-s', {IN=> {f=> join ('', 'A'..'Z', 'a'..'z', '0'..'9')}}, - {OUT=>"5387 1 f\n"}], + {OUT=>"5387 1 f\n"}], ['7s', '-s', {IN=> {f=> '1234567890' x 8}}, {OUT=>"4200 1 f\n"}], ); diff --git a/tests/misc/tee b/tests/misc/tee index 1701b1430..86eca7d05 100755 --- a/tests/misc/tee +++ b/tests/misc/tee @@ -28,12 +28,12 @@ nums=`seq 9` || framework_failure fail=0 for n in 0 $nums; do - files=`seq $n` - rm -f $files - tee $files <sample >out || fail=1 - for f in out $files; do - compare sample $f || fail=1 - done + files=`seq $n` + rm -f $files + tee $files <sample >out || fail=1 + for f in out $files; do + compare sample $f || fail=1 + done done Exit $fail diff --git a/tests/misc/test b/tests/misc/test index dc20261d4..ff66261aa 100755 --- a/tests/misc/test +++ b/tests/misc/test @@ -33,12 +33,12 @@ sub digest_test ($) foreach my $e (@$t) { !ref $e - and push (@args, $e), next; + and push (@args, $e), next; ref $e eq 'HASH' - or (warn "$0: $t->[0]: unexpected entry type\n"), next; + or (warn "$0: $t->[0]: unexpected entry type\n"), next; exists $e->{EXIT} - and $ret = $e->{EXIT}, next; + and $ret = $e->{EXIT}, next; push @list_of_hashref, $e; } @@ -70,16 +70,16 @@ sub add_inverse_op_tests($) # Generate corresponding tests of inverse ops. # E.g. generate tests of `-ge' from those of `-lt'. foreach my $op (qw(gt lt eq)) - { - if ($test_name =~ /$op-/ && $flags =~ / -$op /) - { - my $inv = $inverse_op{$op}; - $test_name =~ s/$op/$inv/; - $flags =~ s/-$op/-$inv/; - $ret = 1 - $ret; - push (@new, [$test_name, $flags, {EXIT=>$ret}, @$LoH]); - } - } + { + if ($test_name =~ /$op-/ && $flags =~ / -$op /) + { + my $inv = $inverse_op{$op}; + $test_name =~ s/$op/$inv/; + $flags =~ s/-$op/-$inv/; + $ret = 1 - $ret; + push (@new, [$test_name, $flags, {EXIT=>$ret}, @$LoH]); + } + } } return @new; } @@ -93,8 +93,8 @@ sub add_pn_tests($) # There are a few exceptions. my %not_N = map {$_ => 1} qw (1a); my %not_P = map {$_ => 1} qw (1a - streq-6 strne-6 - paren-1 paren-2 paren-3 paren-4 paren-5); + streq-6 strne-6 + paren-1 paren-2 paren-3 paren-4 paren-5); foreach my $t (@$tests) { push @new, $t; @@ -104,13 +104,13 @@ sub add_pn_tests($) next if $ret == 2; push (@new, ["N-$test_name", "! $flags", {EXIT=>1-$ret}, @$LoH]) - unless $not_N{$test_name}; + unless $not_N{$test_name}; push (@new, ["P-$test_name", "'(' $flags ')'", {EXIT=>$ret}, @$LoH]) - unless $not_P{$test_name}; + unless $not_P{$test_name}; push (@new, ["NP-$test_name", "! '(' $flags ')'", {EXIT=>1-$ret}, @$LoH]) - unless $not_P{$test_name}; + unless $not_P{$test_name}; push (@new, ["NNP-$test_name", "! ! '(' $flags ')'", {EXIT=>$ret, @$LoH}]) - unless $not_P{$test_name}; + unless $not_P{$test_name}; } return @new; diff --git a/tests/misc/tty-eof b/tests/misc/tty-eof index ee33864d9..13ddbc8a3 100755 --- a/tests/misc/tty-eof +++ b/tests/misc/tty-eof @@ -67,10 +67,10 @@ $@ and (warn "$ME: this script requires Perl's Expect package >=1.11\n"), my $exp = new Expect; $exp->log_user(0); $exp->spawn("$cmd 2> $stderr") - or (warn "$ME: cannot run `$cmd': $!\n"), $fail=1, next; + or (warn "$ME: cannot run `$cmd': $!\n"), $fail=1, next; # No input for cut -f2. $cmd =~ /^cut/ - or $exp->send("a b\n"); + or $exp->send("a b\n"); $exp->send("\cD"); # This is Control-D. FIXME: what if that's not EOF? $exp->expect (0, '-re', "^a b\\r?\$"); my $found = $exp->expect (1, '-re', "^.+\$"); @@ -78,32 +78,32 @@ $@ and (warn "$ME: this script requires Perl's Expect package >=1.11\n"), $exp->expect(1, 'eof'); # Expect no output from cut, since we gave it no input. defined $found || $cmd =~ /^cut/ - or (warn "$ME: $cmd didn't produce expected output\n"), - $fail=1, next; + or (warn "$ME: $cmd didn't produce expected output\n"), + $fail=1, next; defined $exp->exitstatus - or (warn "$ME: $cmd didn't exit after ^D from standard input\n"), - $fail=1, next; + or (warn "$ME: $cmd didn't exit after ^D from standard input\n"), + $fail=1, next; my $s = $exp->exitstatus; $s == 0 - or (warn "$ME: $cmd exited with status $s (expected 0)\n"), - $fail=1; + or (warn "$ME: $cmd exited with status $s (expected 0)\n"), + $fail=1; $exp->hard_close(); # dd normally writes to stderr. If it exits successfully, we're done. $cmd eq 'dd' && $s == 0 - and next; + and next; if (-s $stderr) - { - warn "$ME: $cmd wrote to stderr:\n"; - system "cat $stderr"; - $fail = 1; - } + { + warn "$ME: $cmd wrote to stderr:\n"; + system "cat $stderr"; + $fail = 1; + } } continue { unlink $stderr - or warn "$ME: failed to remove stderr file from $cmd, $stderr: $!\n"; + or warn "$ME: failed to remove stderr file from $cmd, $stderr: $!\n"; } exit $fail diff --git a/tests/misc/uniq b/tests/misc/uniq index 3153581fe..689115aa9 100755 --- a/tests/misc/uniq +++ b/tests/misc/uniq @@ -38,42 +38,42 @@ sub add_z_variants($) # skip the obsolete-syntax tests $t->[0] =~ /^obs-plus/ - and next; + and next; my @args; my @list_of_hash; foreach my $e (@$t) - { - !ref $e - and push (@args, $e), next; - - ref $e && ref $e eq 'HASH' - or (warn "$0: $t->[0]: unexpected entry type\n"), next; - my $tmp = $e; - foreach my $k (qw(IN OUT)) - { - my $val = $e->{$k}; - # skip any test whose input or output already contains a NUL byte - if (defined $val) - { - $val =~ /\0/ - and next TEST; - - # Convert each NL in input or output to \0. - $val =~ s/\n/\0/g; - $tmp = {$k => $val}; - last; - } - } - push @list_of_hash, $tmp; - } + { + !ref $e + and push (@args, $e), next; + + ref $e && ref $e eq 'HASH' + or (warn "$0: $t->[0]: unexpected entry type\n"), next; + my $tmp = $e; + foreach my $k (qw(IN OUT)) + { + my $val = $e->{$k}; + # skip any test whose input or output already contains a NUL byte + if (defined $val) + { + $val =~ /\0/ + and next TEST; + + # Convert each NL in input or output to \0. + $val =~ s/\n/\0/g; + $tmp = {$k => $val}; + last; + } + } + push @list_of_hash, $tmp; + } shift @args; # discard test name # skip any test that uses the -z option grep /z/, @args - and next; + and next; push @new, ["$t->[0]-z", '-z', @args, @list_of_hash]; } diff --git a/tests/misc/wc-files0-from b/tests/misc/wc-files0-from index b247c54c6..4dbfd7bca 100755 --- a/tests/misc/wc-files0-from +++ b/tests/misc/wc-files0-from @@ -31,8 +31,8 @@ my @Tests = # invalid extra command line argument ['f-extra-arg', '--files0-from=- no-such', {IN=>"a"}, {EXIT=>1}, {ERR => "$prog: extra operand `no-such'\n" - . "file operands cannot be combined with --files0-from\n" - . "Try `$prog --help' for more information.\n"} + . "file operands cannot be combined with --files0-from\n" + . "Try `$prog --help' for more information.\n"} ], # missing input file diff --git a/tests/mkdir/perm b/tests/mkdir/perm index 146a88e29..af2bdcd63 100755 --- a/tests/mkdir/perm +++ b/tests/mkdir/perm @@ -66,8 +66,8 @@ for p in empty -p; do # and adjust expectations accordingly. test x$p = x && \ { - mkdir -m =,u=rwx parent || fail=1 - parent_perms=drwx------ + mkdir -m =,u=rwx parent || fail=1 + parent_perms=drwx------ } mkdir $p $mode parent/sub || fail=1 diff --git a/tests/mv/part-symlink b/tests/mv/part-symlink index 78da70a39..71788b905 100755 --- a/tests/mv/part-symlink +++ b/tests/mv/part-symlink @@ -83,67 +83,67 @@ for copy in cp mv; do actual_args=`eval echo $actual_args` ( - ( - # echo 1>&2 cp $options $args - $copy $options $actual_args 2>.err - copy_status=$? - echo $copy_status $copy $options $args - - # Normalize the program name in the error output, - # remove any site-dependent part of other-partition file name, - # and put brackets around the output. - test -s .err && { - echo '[' | tr -d '\n' - sed 's/^[^:][^:]*\(..\):/\1:/;s,'$other_partition_tmpdir/,, .err - echo ']' | tr -d '\n' - } - # Strip off all but the file names. - # Remove any site-dependent part of each file name. - ls=`ls -gG --ignore=.err . \ - | sed \ - -e '/^total /d' \ - -e s,$other_partition_tmpdir/,, \ - -e "s,$pwd_tmp/,," \ - -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//'` - ls2=`cd $other_partition_tmpdir && ls -gG --ignore=.err . \ - | sed \ - -e '/^total /d' \ - -e s,$other_partition_tmpdir/,, \ - -e "s,$pwd_tmp/,," \ - -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//'` - echo "($ls) ($ls2)" - - # If the command failed, then it must not have changed the files. - if test $copy_status != 0; then - for f in $actual_args; do - test -f $f || - { echo "$copy FAILED but removed $f"; continue; } - case "`cat $f`" in - "$contents") ;; - *) echo "$copy FAILED but modified $f";; - esac - done - fi - - if test $copy = cp; then - # Make sure the original is unchanged and that - # the destination is a copy. - for f in $actual_args; do - if test -f $f; then - if test $copy_status != 0; then - test - fi - case "`cat $f`" in - "$contents") ;; - *) echo $copy FAILED;; - esac - else - echo symlink-loop - fi - done - fi - ) | tr '\n' ' ' - echo + ( + # echo 1>&2 cp $options $args + $copy $options $actual_args 2>.err + copy_status=$? + echo $copy_status $copy $options $args + + # Normalize the program name in the error output, + # remove any site-dependent part of other-partition file name, + # and put brackets around the output. + test -s .err && { + echo '[' | tr -d '\n' + sed 's/^[^:][^:]*\(..\):/\1:/;s,'$other_partition_tmpdir/,, .err + echo ']' | tr -d '\n' + } + # Strip off all but the file names. + # Remove any site-dependent part of each file name. + ls=`ls -gG --ignore=.err . \ + | sed \ + -e '/^total /d' \ + -e s,$other_partition_tmpdir/,, \ + -e "s,$pwd_tmp/,," \ + -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//'` + ls2=`cd $other_partition_tmpdir && ls -gG --ignore=.err . \ + | sed \ + -e '/^total /d' \ + -e s,$other_partition_tmpdir/,, \ + -e "s,$pwd_tmp/,," \ + -e 's/^[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *[^ ]* *//'` + echo "($ls) ($ls2)" + + # If the command failed, then it must not have changed the files. + if test $copy_status != 0; then + for f in $actual_args; do + test -f $f || + { echo "$copy FAILED but removed $f"; continue; } + case "`cat $f`" in + "$contents") ;; + *) echo "$copy FAILED but modified $f";; + esac + done + fi + + if test $copy = cp; then + # Make sure the original is unchanged and that + # the destination is a copy. + for f in $actual_args; do + if test -f $f; then + if test $copy_status != 0; then + test + fi + case "`cat $f`" in + "$contents") ;; + *) echo $copy FAILED;; + esac + else + echo symlink-loop + fi + done + fi + ) | tr '\n' ' ' + echo ) | sed 's/ *$//' cd .. done diff --git a/tests/rm/fail-eperm b/tests/rm/fail-eperm index 20ce77040..9ccb913a6 100755 --- a/tests/rm/fail-eperm +++ b/tests/rm/fail-eperm @@ -51,89 +51,89 @@ foreach my $dir (@dir_list) { if (-d $dir && -k _ && -r _ && -w _ && -x _) { - $found_dir = 1; - - # Find a non-directory there that is owned by some other user. - opendir DIR_HANDLE, $dir - or die "$ME: couldn't open $dir: $!\n"; - - foreach my $f (readdir DIR_HANDLE) - { - # Consider only names containing "safe" characters. - $f =~ /^([-\@\w.]+)$/ - or next; - $f = $1; # untaint $f - - my $target_file = "$dir/$f"; - $verbose - and warn "$ME: considering $target_file\n"; - - # Skip files owned by self, symlinks, and directories. - # It's not technically necessary to skip symlinks, but it's simpler. - # SVR4-like systems (e.g., Solaris 9) let you unlink files that - # you can write, so skip writable files too. - -l $target_file || -o _ || -d _ || -w _ - and next; - - $found_file = 1; - - # Invoke rm on this file and ensure that we get the - # expected exit code and diagnostic. - my $cmd = "$rm -f -- $target_file"; - open RM, "$cmd 2>&1 |" - or die "$ME: cannot execute `$cmd'\n"; - - my $line = <RM>; - - close RM; - my $rc = $?; - # This test opportunistically looks for files that can't - # be removed but those files may already have been removed - # by their owners by the time we get to them. It is a - # race condition. If so then the rm is successful and our - # test is thwarted. Detect this case and ignore. - if ($rc == 0) - { - next if ! -e $target_file; - die "$ME: unexpected exit status from `$cmd';\n" - . " got 0, expected 1\n"; - } - if (0x80 < $rc) - { - my $status = $rc >> 8; - $status == 1 - or die "$ME: unexpected exit status from `$cmd';\n" - . " got $status, expected 1\n"; - } - else - { - # Terminated by a signal. - my $sig_num = $rc & 0x7F; - die "$ME: command `$cmd' died with signal $sig_num\n"; - } - - my $exp = "rm: cannot remove `$target_file':"; - $line - or die "$ME: no output from `$cmd';\n" - . "expected something like `$exp ...'\n"; - - # Transform the actual diagnostic so that it starts with "rm:". - # Depending on your system, it might be "rm:" already, or - # "../../src/rm:". - $line =~ s,^\Q$rm\E:,rm:,; - - my $regex = quotemeta $exp; - $line =~ /^$regex/ - or die "$ME: unexpected diagnostic from `$cmd';\n" - . " got $line" - . " expected $exp ...\n"; - - last; - } - - closedir DIR_HANDLE; - $found_file - and last; + $found_dir = 1; + + # Find a non-directory there that is owned by some other user. + opendir DIR_HANDLE, $dir + or die "$ME: couldn't open $dir: $!\n"; + + foreach my $f (readdir DIR_HANDLE) + { + # Consider only names containing "safe" characters. + $f =~ /^([-\@\w.]+)$/ + or next; + $f = $1; # untaint $f + + my $target_file = "$dir/$f"; + $verbose + and warn "$ME: considering $target_file\n"; + + # Skip files owned by self, symlinks, and directories. + # It's not technically necessary to skip symlinks, but it's simpler. + # SVR4-like systems (e.g., Solaris 9) let you unlink files that + # you can write, so skip writable files too. + -l $target_file || -o _ || -d _ || -w _ + and next; + + $found_file = 1; + + # Invoke rm on this file and ensure that we get the + # expected exit code and diagnostic. + my $cmd = "$rm -f -- $target_file"; + open RM, "$cmd 2>&1 |" + or die "$ME: cannot execute `$cmd'\n"; + + my $line = <RM>; + + close RM; + my $rc = $?; + # This test opportunistically looks for files that can't + # be removed but those files may already have been removed + # by their owners by the time we get to them. It is a + # race condition. If so then the rm is successful and our + # test is thwarted. Detect this case and ignore. + if ($rc == 0) + { + next if ! -e $target_file; + die "$ME: unexpected exit status from `$cmd';\n" + . " got 0, expected 1\n"; + } + if (0x80 < $rc) + { + my $status = $rc >> 8; + $status == 1 + or die "$ME: unexpected exit status from `$cmd';\n" + . " got $status, expected 1\n"; + } + else + { + # Terminated by a signal. + my $sig_num = $rc & 0x7F; + die "$ME: command `$cmd' died with signal $sig_num\n"; + } + + my $exp = "rm: cannot remove `$target_file':"; + $line + or die "$ME: no output from `$cmd';\n" + . "expected something like `$exp ...'\n"; + + # Transform the actual diagnostic so that it starts with "rm:". + # Depending on your system, it might be "rm:" already, or + # "../../src/rm:". + $line =~ s,^\Q$rm\E:,rm:,; + + my $regex = quotemeta $exp; + $line =~ /^$regex/ + or die "$ME: unexpected diagnostic from `$cmd';\n" + . " got $line" + . " expected $exp ...\n"; + + last; + } + + closedir DIR_HANDLE; + $found_file + and last; } } diff --git a/tests/touch/dangling-symlink b/tests/touch/dangling-symlink index 1c4d73c13..f3ea29a7f 100755 --- a/tests/touch/dangling-symlink +++ b/tests/touch/dangling-symlink @@ -39,13 +39,13 @@ if test $fail = 1; then *linux-gnu*) case "`uname -r`" in 2.3.9[0-9]*) - skip_test_ \ + skip_test_ \ '**************************************************** WARNING!!! This version of the Linux kernel causes touch to fail when operating on dangling symlinks. ****************************************************' - ;; + ;; esac ;; esac |