Subject: bug#10016: ls -lk is wrong

From: Jim Meyering <[email-masked]>
Date: Fri, 11 Nov 2011 17:20:11 +0100

Eric Blake wrote:
> On 11/10/2011 04:35 PM, Alan Curry wrote:
>> I mentioned this already in the bug#9939 thread, but nobody replied and it's
>> really a separate issue so here's an independent report.
>>
>> This behavior:
>>
>> $ ls -l /bin/ls
>> -rwxr-xr-x 1 root root 107124 Feb  8  2011 /bin/ls
>> $ ls -lk /bin/ls
>> -rwxr-xr-x 1 root root 105 Feb  8  2011 /bin/ls
>>
>> is awful. -k should not have any effect on the ls -l field that reports
>> st_size. It is only supposed to possibly affect the reporting of st_blocks
>> by -s and the "total" line at the start of a full directory listing.
>
> I just re-read POSIX, and it looks like you are correct:
>
> http://pubs.opengroup.org/onlinepubs/9699919799/utilities/ls.html
>
> -k
>     Set the block size for the -s option and the per-directory block
> count written for the -l, -n, -s, [XSI] [Option Start] -g, and -o
> [Option End] options (see the STDOUT section) to 1024 bytes.
>
> POSIX has no mention of -k affecting the file size output, just the
> initial column for -s and the per-directory summary on "total" lines.

Thank you, Alan!

I reached the same conclusion.
It is a bug.

It was introduced 9 years ago, in coreutils-4.5.4,
probably by commit 106c3bf3:

       sprintf (p, "%8s ",
-              human_readable (size, hbuf, 1,
-                              output_block_size < 0 ? output_block_size : 1));
+              human_readable (size, hbuf, human_output_opts,
+                              1, file_output_block_size));

Per POSIX, this should print 1000000:

    $ truncate -s 1000000 k; set - $(env ls -ogk k); echo $3
    977

The following change fixes it and introduces no test failure,
so I'll write a test, NEWS, etc.

diff --git a/src/ls.c b/src/ls.c
index 0b8f512..41e9123 100644
--- a/src/ls.c
+++ b/src/ls.c
@@ -3030,9 +3030,7 @@ gobble_file (char const *name, enum filetype type, ino_t inode,
             {
               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);
+              int len = mbswidth (human_readable (size, buf, 0, 1, 1), 0);
               if (file_size_width < len)
                 file_size_width = len;
             }
@@ -3772,7 +3770,7 @@ print_long_format (const struct fileinfo *f)
         (! f->stat_ok
          ? "?"
          : human_readable (unsigned_file_size (f->stat.st_size),
-                           hbuf, human_output_opts, 1, file_output_block_size));
+                           hbuf, 0, 1, 1));
       int pad;
       for (pad = file_size_width - mbswidth (size, 0); 0 < pad; pad--)
         *p++ = ' ';