OSDN Git Service

Make "LC_ALL=C ls -Cs --color" produce the same output on toybox and ubuntu.
[android-x86/external-toybox.git] / toys / posix / ls.c
index e46a576..a336ba1 100644 (file)
@@ -5,33 +5,35 @@
  *
  * See http://opengroup.org/onlinepubs/9699919799/utilities/ls.html
 
-USE_LS(NEWTOY(ls, USE_LS_COLOR("(color):;")"ZgoACFHLRSacdfiklmnpqrstux1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL]", TOYFLAG_BIN|TOYFLAG_LOCALE))
+USE_LS(NEWTOY(ls, USE_LS_COLOR("(color):;")"ZgoACFHLRSabcdfhiklmnpqrstux1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL][!qb]", TOYFLAG_BIN|TOYFLAG_LOCALE))
 
 config LS
   bool "ls"
   default y
   help
-    usage: ls [-ACFHLRSZacdfiklmnpqrstux1] [directory...]
+    usage: ls [-ACFHLRSZacdfhiklmnpqrstux1] [directory...]
+
     list files
 
     what to show:
-    -a all files including .hidden             -c  use ctime for timestamps
-    -d directory, not contents                 -i  inode number
-    -k block sizes in kilobytes                -p  put a '/' after dir names
-    -q unprintable chars as '?'                -s  size (in blocks)
-    -u use access time for timestamps          -A  list all files but . and ..
-    -H follow command line symlinks            -L  follow symlinks
-    -R recursively list files in subdirs       -F  append /dir *exe @sym |FIFO
-    -Z security context
+    -a  all files including .hidden    -b  escape nongraphic chars
+    -c  use ctime for timestamps       -d  directory, not contents
+    -i  inode number                   -p  put a '/' after dir names
+    -q  unprintable chars as '?'       -s  storage used (1024 byte units)
+    -u  use access time for timestamps -A  list all files but . and ..
+    -H  follow command line symlinks   -L  follow symlinks
+    -R  recursively list in subdirs    -F  append /dir *exe @sym |FIFO
+    -Z  security context
 
     output formats:
-    -1 list one file per line                  -C  columns (sorted vertically)
-    -g like -l but no owner                    -l  long (show full details)
-    -m comma separated                         -n  like -l but numeric uid/gid
-    -o like -l but no group                    -x  columns (horizontal sort)
+    -1  list one file per line         -C  columns (sorted vertically)
+    -g  like -l but no owner           -h  human readable sizes
+    -l  long (show full details)       -m  comma separated
+    -n  like -l but numeric uid/gid    -o  like -l but no group
+    -x  columns (horizontal sort)
 
     sorting (default is alphabetical):
-    -f unsorted        -r  reverse     -t  timestamp   -S  size
+    -f  unsorted    -r  reverse    -t  timestamp    -S  size
 
 config LS_COLOR
   bool "ls --color"
@@ -59,34 +61,53 @@ GLOBALS(
 
   unsigned screen_width;
   int nl_title;
-  char uid_buf[12], gid_buf[12];
+  char *escmore;
 )
 
-// Does two things: 1) Returns wcwidth(utf8) version of strlen,
-// 2) replaces unprintable characters input string with '?' wildcard char.
-int strwidth(char *s)
+// Callback from crunch_str to represent unprintable chars
+int crunch_qb(FILE *out, int cols, int wc)
 {
-  int total = 0, width, len;
-  wchar_t c;
-
-  if (!CFG_TOYBOX_I18N) {
-    total = strlen(s);
-    if (toys.optflags & FLAG_q) for (; *s; s++) if (!isprint(*s)) *s = '?';
-  } else while (*s) {
-    len = mbrtowc(&c, s, MB_CUR_MAX, 0);
-    if (len < 1 || (width = wcwidth(c)) < 0) {
-      total++;
-      if (toys.optflags & FLAG_q) *s = '?';
-      s++;
-    } else {
-      s += len;
-      total += width;
+  unsigned len = 1;
+  char buf[32];
+
+  if (toys.optflags&FLAG_q) *buf = '?';
+  else {
+    if (wc<256) *buf = wc;
+    // scrute the inscrutable, eff the ineffable, print the unprintable
+    else len = wcrtomb(buf, wc, 0);
+    if (toys.optflags&FLAG_b) {
+      char *to = buf, *from = buf+24;
+      int i, j;
+
+      memcpy(from, to, 8);
+      for (i = 0; i<len; i++) {
+        *to++ = '\\';
+        if (strchr(TT.escmore, from[i])) *to++ = from[i];
+        else if (-1 != (j = stridx("\\\a\b\033\f\n\r\t\v", from[i])))
+          *to++ = "\\abefnrtv"[j];
+        else to += sprintf(to, "%03o", from[i]);
+      }
+      len = to-buf;
     }
   }
 
-  return total;
+  if (cols<len) len = cols;
+  if (out) fwrite(buf, len, 1, out);
+
+  return len;
+}
+
+// Returns wcwidth(utf8) version of strlen with -qb escapes
+int strwidth(char *s)
+{
+  return crunch_str(&s, INT_MAX, 0, TT.escmore, crunch_qb);
 }
 
+void qbstr(char *s, int width)
+{
+  draw_trim_esc(s, width, abs(width), TT.escmore, crunch_qb);
+} 
+
 static char endtype(struct stat *st)
 {
   mode_t mode = st->st_mode;
@@ -100,25 +121,15 @@ static char endtype(struct stat *st)
   return 0;
 }
 
-static char *getusername(uid_t uid)
-{
-  struct passwd *pw = getpwuid(uid);
-
-  sprintf(TT.uid_buf, "%u", (unsigned)uid);
-  return pw ? pw->pw_name : TT.uid_buf;
-}
-
-static char *getgroupname(gid_t gid)
+static int numlen(long long ll)
 {
-  struct group *gr = getgrgid(gid);
-
-  sprintf(TT.gid_buf, "%u", (unsigned)gid);
-  return gr ? gr->gr_name : TT.gid_buf;
+  return snprintf(0, 0, "%llu", ll);
 }
 
-static int numlen(long long ll)
+static int print_with_h(char *s, long long value, int units)
 {
-  return snprintf(0, 0, "%llu", ll);
+  if (toys.optflags&FLAG_h) return human_readable(s, value*units, 0);
+  else return sprintf(s, "%lld", value);
 }
 
 // Figure out size of printable entry fields for display indent/wrap
@@ -127,6 +138,7 @@ static void entrylen(struct dirtree *dt, unsigned *len)
 {
   struct stat *st = &(dt->st);
   unsigned flags = toys.optflags;
+  char tmp[64];
 
   *len = strwidth(dt->name);
   if (endtype(st)) ++*len;
@@ -141,11 +153,11 @@ static void entrylen(struct dirtree *dt, unsigned *len)
     if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
       // cheating slightly here: assuming minor is always 3 digits to avoid
       // tracking another column
-      len[5] = numlen(major(st->st_rdev))+5;
-    } else len[5] = numlen(st->st_size);
+      len[5] = numlen(dev_major(st->st_rdev))+5;
+    } else len[5] = print_with_h(tmp, st->st_size, 1);
   }
 
-  len[6] = (flags & FLAG_s) ? numlen(st->st_blocks) : 0;
+  len[6] = (flags & FLAG_s) ? print_with_h(tmp, st->st_blocks, 512) : 0;
   len[7] = (flags & FLAG_Z) ? strwidth((char *)dt->extra) : 0;
 }
 
@@ -181,34 +193,27 @@ static int filter(struct dirtree *new)
 
   if (flags & FLAG_Z) {
     if (!CFG_TOYBOX_LSM_NONE) {
-      int fd;
-
-      // Why not just openat(O_PATH|(O_NOFOLLOW*!!(toys.optflags&FLAG_L))) and
-      // lsm_fget_context() on that filehandle? Because the kernel is broken,
-      // and won't let us read this "metadata" from the filehandle unless we
-      // have permission to read the data. We _can_ read the same data in
-      // by path, we just can't do it through an O_PATH filehandle, because
-      // reasons. So as a bug workaround for the broken kernel, we do it
-      // both ways.
-      //
-      // The O_NONBLOCK is there to avoid triggering automounting (there's
-      // a rush of nostalgia for you) on directories we don't descend into,
-      // which O_PATH would have done for us but see "the kernel is broken".
-      if (S_ISSOCK(new->st.st_mode) ||
-          (S_ISLNK(new->st.st_mode) && !(toys.optflags & FLAG_L)) ||
-          -1 == (fd = openat(dirtree_parentfd(new), new->name,
-                             O_RDONLY|O_NONBLOCK|O_NOATIME)))
-      {
-        char *path;
-
-        // Wouldn't it be nice if the lsm functions worked like openat(),
-        // fchmodat(), mknodat(), readlinkat() so we could do this without
-        // even O_PATH? But no, this is 1990's tech.
-        path = dirtree_path(new, 0);
-        lsm_lget_context(path, (char **)&new->extra);
-        free(path);
-      } else {
-        lsm_fget_context(fd, (char **)&new->extra);
+
+      // (Wouldn't it be nice if the lsm functions worked like openat(),
+      // fchmodat(), mknodat(), readlinkat() so we could do this without
+      // even O_PATH? But no, this is 1990's tech.)
+      int fd = openat(dirtree_parentfd(new), new->name,
+        O_PATH|(O_NOFOLLOW*!(toys.optflags&FLAG_L)));
+
+      if (fd != -1) {
+        if (-1 == lsm_fget_context(fd, (char **)&new->extra) && errno == EBADF)
+        {
+          char hack[32];
+
+          // Work around kernel bug that won't let us read this "metadata" from
+          // the filehandle unless we have permission to read the data. (We can
+          // query the same data in by path, but can't do it through an O_PATH
+          // filehandle, because reasons. But for some reason, THIS is ok? If
+          // they ever fix the kernel, this should stop triggering.)
+
+          sprintf(hack, "/proc/self/fd/%d", fd);
+          lsm_lget_context(hack, (char **)&new->extra);
+        }
         close(fd);
       }
     }
@@ -217,7 +222,7 @@ static int filter(struct dirtree *new)
 
   if (flags & FLAG_u) new->st.st_mtime = new->st.st_atime;
   if (flags & FLAG_c) new->st.st_mtime = new->st.st_ctime;
-  if (flags & FLAG_k) new->st.st_blocks = (new->st.st_blocks + 1) / 2;
+  new->st.st_blocks >>= 1;
 
   if (flags & (FLAG_a|FLAG_f)) return DIRTREE_SAVE;
   if (!(flags & FLAG_A) && new->name[0]=='.') return 0;
@@ -290,8 +295,16 @@ static void listfiles(int dirfd, struct dirtree *indir)
   unsigned long dtlen, ul = 0;
   unsigned width, flags = toys.optflags, totals[8], len[8], totpad = 0,
     *colsizes = (unsigned *)(toybuf+260), columns = (sizeof(toybuf)-260)/4;
+  char tmp[64];
+
+  if (-1 == dirfd) {
+    perror_msg_raw(indir->name);
+
+    return;
+  }
 
   memset(totals, 0, sizeof(totals));
+  if (CFG_TOYBOX_DEBUG) memset(len, 0, sizeof(len));
 
   // Top level directory was already populated by main()
   if (!indir->parent) {
@@ -308,12 +321,10 @@ static void listfiles(int dirfd, struct dirtree *indir)
     // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
     for (;dt; dt = dt->next) filter(dt);
     if (flags == (FLAG_1|FLAG_f)) return;
-  } else {
-    // Read directory contents. We dup() the fd because this will close it.
-    // This reads/saves contents to display later, except for in "ls -1f" mode.
-    indir->data = dup(dirfd);
-    dirtree_recurse(indir, filter, DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
-  }
+  // Read directory contents. We dup() the fd because this will close it.
+  // This reads/saves contents to display later, except for in "ls -1f" mode.
+  } else  dirtree_recurse(indir, filter, dup(dirfd),
+      DIRTREE_SYMFOLLOW*!!(flags&FLAG_L));
 
   // Copy linked list to array and sort it. Directories go in array because
   // we visit them in sorted order too. (The nested loops let us measure and
@@ -346,8 +357,10 @@ static void listfiles(int dirfd, struct dirtree *indir)
       blocks += sort[ul]->st.st_blocks;
     }
     totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
-    if ((flags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent)
-      xprintf("total %llu\n", blocks);
+    if ((flags&(FLAG_h|FLAG_l|FLAG_o|FLAG_n|FLAG_g|FLAG_s)) && indir->parent) {
+      print_with_h(tmp, blocks, 512);
+      xprintf("total %s\n", tmp);
+    }
   }
 
   // Find largest entry in each field for display alignment
@@ -365,7 +378,7 @@ static void listfiles(int dirfd, struct dirtree *indir)
       memset(colsizes, 0, columns*sizeof(unsigned));
       for (ul=0; ul<dtlen; ul++) {
         entrylen(sort[next_column(ul, dtlen, columns, &c)], len);
-        *len += totpad;
+        *len += totpad+1;
         if (c == columns) break;
         // Expand this column if necessary, break if that puts us over budget
         if (*len > colsizes[c]) {
@@ -383,11 +396,12 @@ static void listfiles(int dirfd, struct dirtree *indir)
   memset(toybuf, ' ', 256);
   width = 0;
   for (ul = 0; ul<dtlen; ul++) {
+    int ii;
     unsigned curcol, color = 0;
     unsigned long next = next_column(ul, dtlen, columns, &curcol);
     struct stat *st = &(sort[next]->st);
     mode_t mode = st->st_mode;
-    char et = endtype(st);
+    char et = endtype(st), *ss;
 
     // Skip directories at the top of the tree when -d isn't set
     if (S_ISDIR(mode) && !indir->parent && !(flags & FLAG_d)) continue;
@@ -399,55 +413,64 @@ static void listfiles(int dirfd, struct dirtree *indir)
       if (flags & FLAG_m) xputc(',');
       if (flags & (FLAG_C|FLAG_x)) {
         if (!curcol) xputc('\n');
-      } else if ((flags & FLAG_1) || width+1+*len > TT.screen_width) {
+      } else if ((flags & FLAG_1) || width+2+*len > TT.screen_width) {
         xputc('\n');
         width = 0;
       } else {
-        xputc(' ');
-        width++;
+        printf("  ");
+        width += 2;
       }
     }
     width += *len;
 
-    if (flags & FLAG_i)
-      xprintf("%*lu ", totals[1], (unsigned long)st->st_ino);
-    if (flags & FLAG_s)
-      xprintf("%*lu ", totals[6], (unsigned long)st->st_blocks);
+    if (flags & FLAG_i) printf("%*lu ", totals[1], (unsigned long)st->st_ino);
+
+    if (flags & FLAG_s) {
+      print_with_h(tmp, st->st_blocks, 512);
+      printf("%*s ", totals[6], tmp);
+    }
 
     if (flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) {
       struct tm *tm;
-      char perm[11], thyme[64], *ss;
 
       // (long) is to coerce the st types into something we know we can print.
-      mode_to_string(mode, perm);
-      printf("%s% *ld", perm, totals[2]+1, (long)st->st_nlink);
+      mode_to_string(mode, tmp);
+      printf("%s% *ld", tmp, totals[2]+1, (long)st->st_nlink);
 
       // print user
       if (!(flags&FLAG_g)) {
-        if (flags&FLAG_n) sprintf(ss = thyme, "%u", (unsigned)st->st_uid);
-        else strwidth(ss = getusername(st->st_uid));
-        printf(" %-*s", (int)totals[3], ss);
+        putchar(' ');
+        ii = -totals[3];
+        if (flags&FLAG_n) printf("%*u", ii, (unsigned)st->st_uid);
+        else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
+                           crunch_qb);
       }
 
       // print group
       if (!(flags&FLAG_o)) {
-        if (flags&FLAG_n) sprintf(ss = thyme, "%u", (unsigned)st->st_gid);
-        else strwidth(ss = getgroupname(st->st_gid));
-        printf(" %-*s", (int)totals[4], ss);
+        putchar(' ');
+        ii = -totals[4];
+        if (flags&FLAG_n) printf("%*u", ii, (unsigned)st->st_gid);
+        else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
+                           crunch_qb);
       }
 
       if (flags & FLAG_Z)
         printf(" %-*s", -(int)totals[7], (char *)sort[next]->extra);
 
-      // print major/minor
+      // print major/minor, or size
       if (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode))
-        printf("% *d,% 4d", totals[5]-4, major(st->st_rdev),minor(st->st_rdev));
-      else printf("% *lld", totals[5]+1, (long long)st->st_size);
+        printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
+          dev_minor(st->st_rdev));
+      else {
+        print_with_h(tmp, st->st_size, 0);
+        printf("%*s", totals[5]+1, tmp);
+      }
 
       // print time, always in --time-style=long-iso
       tm = localtime(&(st->st_mtime));
-      strftime(thyme, sizeof(thyme), "%F %H:%M", tm);
-      xprintf(" %s ", thyme);
+      strftime(tmp, sizeof(tmp), "%F %H:%M", tm);
+      printf(" %s ", tmp);
     } else if (flags & FLAG_Z)
       printf("%-*s ", (int)totals[7], (char *)sort[next]->extra);
 
@@ -456,11 +479,9 @@ static void listfiles(int dirfd, struct dirtree *indir)
       if (color) printf("\033[%d;%dm", color>>8, color&255);
     }
 
-    if (flags & FLAG_q) {
-      char *p;
-      for (p=sort[next]->name; *p; p++) fputc(isprint(*p) ? *p : '?', stdout);
-    } else xprintf("%s", sort[next]->name);
-    if (color) xprintf("\033[0m");
+    ss = sort[next]->name;
+    crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
+    if (color) printf("\033[0m");
 
     if ((flags & (FLAG_l|FLAG_o|FLAG_n|FLAG_g)) && S_ISLNK(mode)) {
       printf(" -> ");
@@ -482,7 +503,7 @@ static void listfiles(int dirfd, struct dirtree *indir)
     // Pad columns
     if (flags & (FLAG_C|FLAG_x)) {
       curcol = colsizes[curcol]-(*len)-totpad;
-      if (curcol < 255) xprintf("%s", toybuf+255-curcol);
+      if (curcol < 255) printf("%s", toybuf+255-curcol);
     }
   }
 
@@ -510,10 +531,11 @@ void ls_main(void)
   TT.screen_width = 80;
   terminal_size(&TT.screen_width, NULL);
   if (TT.screen_width<2) TT.screen_width = 2;
+  if (toys.optflags&FLAG_b) TT.escmore = " \\";
 
   // Do we have an implied -1
   if (!isatty(1)) {
-    toys.optflags |= FLAG_1;
+    if (!(toys.optflags & FLAG_m)) toys.optflags |= FLAG_1;
     if (TT.color) toys.optflags ^= FLAG_color;
   } else if (toys.optflags&(FLAG_l|FLAG_o|FLAG_n|FLAG_g))
     toys.optflags |= FLAG_1;
@@ -524,11 +546,15 @@ void ls_main(void)
   if (toys.optflags & FLAG_d) toys.optflags &= ~FLAG_R;
 
   // Iterate through command line arguments, collecting directories and files.
-  // Non-absolute paths are relative to current directory.
-  TT.files = dirtree_start(0, 0);
+  // Non-absolute paths are relative to current directory. Top of tree is
+  // a dummy node to collect command line arguments into pseudo-directory.
+  TT.files = dirtree_add_node(0, 0, 0);
+  TT.files->dirfd = AT_FDCWD;
   for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
-    dt = dirtree_start(*s, !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F)) ||
-                            (toys.optflags&(FLAG_L|FLAG_H)));
+    int sym = !(toys.optflags&(FLAG_l|FLAG_d|FLAG_F))
+      || (toys.optflags&(FLAG_L|FLAG_H));
+
+    dt = dirtree_add_node(0, *s, DIRTREE_SYMFOLLOW*sym);
 
     // note: double_list->prev temporarirly goes in dirtree->parent
     if (dt) dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);