xref: /aosp_15_r20/external/toybox/toys/posix/ls.c (revision cf5a6c84e2b8763fc1a7db14496fd4742913b199)
1 /* ls.c - list files
2  *
3  * Copyright 2012 Andre Renaud <[email protected]>
4  * Copyright 2012 Rob Landley <[email protected]>
5  *
6  * See http://opengroup.org/onlinepubs/9699919799/utilities/ls.html
7  *
8  * Deviations from posix:
9  *   add -b (as default instead of -q: -b is unambiguous without collisions)
10  *   add -Z -ll --color
11  *   Posix says the -l date format should vary based on how recent it is
12  *   and we do --time-style=long-iso instead
13  * Deviations from gnu: -N switches off -q (no --show-control-chars)
14  *   No --quoting-style=shell-escape, mostly because no short or long opt for it
15 
16 USE_LS(NEWTOY(ls, "(sort):(color):;(full-time)(show-control-chars)\377(block-size)#=1024<1\241(group-directories-first)\376ZgoACFHLNRSUXabcdfhikl@mnpqrstuw#=80<0x1[-Cxm1][-Cxml][-Cxmo][-Cxmg][-cu][-ftS][-HL][-Nqb][-k\377]", TOYFLAG_BIN))
17 
18 config LS
19   bool "ls"
20   default y
21   help
22     usage: ls [-1ACFHLNRSUXZabcdfghilmnopqrstuwx] [--color[=auto]] [FILE...]
23 
24     List files
25 
26     what to show:
27     -A  all files except . and ..      -a  all files including .hidden
28     -b  escape nongraphic chars        -d  directory, not contents
29     -F  append /dir *exe @sym |FIFO    -f  files (no sort/filter/format)
30     -H  follow command line symlinks   -i  inode number
31     -L  follow symlinks                -N  no escaping, even on tty
32     -p  put '/' after dir names        -q  unprintable chars as '?'
33     -R  recursively list in subdirs    -s  storage used (units of --block-size)
34     -Z  security context
35 
36     output formats:
37     -1  list one file per line         -C  columns (sorted vertically)
38     -g  like -l but no owner           -h  human readable sizes
39     -k  reset --block-size to default  -l  long (show full details)
40     -m  comma separated                -ll long with nanoseconds (--full-time)
41     -n  long with numeric uid/gid      -o  long without group column
42     -r  reverse order                  -w  set column width
43     -x  columns (horizontal sort)
44 
45     sort by:  (also --sort=longname,longname... ends with alphabetical)
46     -c  ctime      -r  reverse    -S  size     -t  time    -u  atime    -U  none
47     -X  extension  -!  dirfirst   -~  nocase
48 
49     --block-size N	block size for -s (default 1024, -k resets to 1024)
50     --color  =always (default)  =auto (when stdout is tty) =never
51         exe=green  suid=red  suidfile=redback  stickydir=greenback
52         device=yellow  symlink=turquoise/red  dir=blue  socket=purple
53 
54     Long output uses -cu for display, use -ltc/-ltu to also sort by ctime/atime.
55 */
56 
57 #define FOR_ls
58 #include "toys.h"
59 
60 // test sst output (suid/sticky in ls flaglist)
61 
62 // ls -lR starts .: then ./subdir:
63 
64 GLOBALS(
65   long w, l, block_size;
66   char *color, *sort;
67 
68   struct dirtree *files, *singledir;
69   unsigned screen_width;
70   int nl_title;
71   char *escmore;
72 )
73 
74 // Callback from crunch_str to represent unprintable chars
crunch_qb(FILE * out,int cols,int wc)75 static int crunch_qb(FILE *out, int cols, int wc)
76 {
77   int len = 1;
78   char buf[32];
79 
80   if (FLAG(q)) *buf = '?';
81   else {
82     if (wc<256) *buf = wc;
83     // scrute the inscrutable, eff the ineffable, print the unprintable
84     else if ((len = wcrtomb(buf, wc, 0) ) == -1) len = 1;
85     if (FLAG(b)) {
86       char *to = buf, *from = buf+24;
87       int i, j;
88 
89       memcpy(from, to, 8);
90       for (i = 0; i<len; i++) {
91         *to++ = '\\';
92         if (strchr(TT.escmore, from[i])) *to++ = from[i];
93         else if (-1 != (j = stridx("\\\a\b\e\f\n\r\t\v", from[i])))
94           *to++ = "\\abefnrtv"[j];
95         else to += sprintf(to, "%03o", from[i]);
96       }
97       len = to-buf;
98     }
99   }
100 
101   if (cols<len) len = cols;
102   if (out) fwrite(buf, len, 1, out);
103 
104   return len;
105 }
106 
107 // Returns wcwidth(utf8) version of strlen with -qb escapes
strwidth(char * s)108 static int strwidth(char *s)
109 {
110   return crunch_str(&s, INT_MAX, 0, TT.escmore, crunch_qb);
111 }
112 
endtype(struct stat * st)113 static char endtype(struct stat *st)
114 {
115   mode_t mode = st->st_mode;
116   if ((FLAG(F)||FLAG(p)) && S_ISDIR(mode)) return '/';
117   if (FLAG(F)) {
118     if (S_ISLNK(mode)) return '@';
119     if (S_ISREG(mode) && (mode&0111)) return '*';
120     if (S_ISFIFO(mode)) return '|';
121     if (S_ISSOCK(mode)) return '=';
122   }
123   return 0;
124 }
125 
numlen(long long ll)126 static int numlen(long long ll)
127 {
128   return snprintf(0, 0, "%llu", ll);
129 }
130 
print_with_h(char * s,long long value,int blocks)131 static int print_with_h(char *s, long long value, int blocks)
132 {
133   if (blocks) value = (value * 1024) / TT.block_size;
134   if (FLAG(h)) return human_readable(s, value, 0);
135   else return sprintf(s, "%lld", value);
136 }
137 
138 // Figure out size of printable entry fields for display indent/wrap
139 
entrylen(struct dirtree * dt,unsigned * len)140 static void entrylen(struct dirtree *dt, unsigned *len)
141 {
142   struct stat *st = &(dt->st);
143   char tmp[64];
144 
145   *len = strwidth(dt->name);
146   if (endtype(st)) ++*len;
147   if (FLAG(m)) ++*len;
148 
149   len[1] = FLAG(i) ? numlen(st->st_ino) : 0;
150   if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) {
151     len[2] = numlen(st->st_nlink);
152     len[3] = FLAG(n) ? numlen(st->st_uid) : strwidth(getusername(st->st_uid));
153     len[4] = FLAG(n) ? numlen(st->st_gid) : strwidth(getgroupname(st->st_gid));
154     if (S_ISBLK(st->st_mode) || S_ISCHR(st->st_mode)) {
155       // cheating slightly here: assuming minor is always 3 digits to avoid
156       // tracking another column
157       len[5] = numlen(dev_major(st->st_rdev))+5;
158     } else len[5] = print_with_h(tmp, st->st_size, 0);
159   }
160 
161   len[6] = FLAG(s) ? print_with_h(tmp, st->st_blocks, 1) : 0;
162   len[7] = FLAG(Z) ? strwidth((char *)dt->extra) : 0;
163 }
164 
165 // Perform one or more comparisons on a pair of files.
166 // Reused FLAG_a to mean "alphabetical"
do_compare(struct dirtree * a,struct dirtree * b,long long flags)167 static int do_compare(struct dirtree *a, struct dirtree *b, long long flags)
168 {
169   struct timespec *ts1 = 0, *ts2;
170   char *s1, *s2;
171   int ret;
172 
173 // TODO -? nocase  -! dirfirst
174 
175   if (flags&FLAG_S) {
176     if (a->st.st_size > b->st.st_size) return -1;
177     else if (a->st.st_size < b->st.st_size) return 1;
178   }
179   if (flags&FLAG_t) ts1 = &a->st.st_mtim, ts2 = &b->st.st_mtim;
180   if (flags&FLAG_u) ts1 = &a->st.st_atim, ts2 = &b->st.st_atim;
181   if (flags&FLAG_c) ts1 = &a->st.st_ctim, ts2 = &b->st.st_ctim;
182   if (ts1) {
183     // Newest is first by default, so return values are backwards
184     if (ts1->tv_sec > ts2->tv_sec) return -1;
185     else if (ts1->tv_sec < ts2->tv_sec) return 1;
186     else if (ts1->tv_nsec > ts2->tv_nsec) return -1;
187     else if (ts1->tv_nsec < ts2->tv_nsec) return 1;
188   }
189   if (flags&FLAG_X21) // dirfirst
190     if (S_ISDIR(a->st.st_mode)!=S_ISDIR(b->st.st_mode))
191       return S_ISDIR(a->st.st_mode) ? -1 : 1;
192 
193   // -X is a form of alphabetical sort, without -~ do case sensitive comparison
194   s1 = 0;
195   if (flags&FLAG_X) {
196     s1 = strrchr(a->name, '.');
197     s2 = strrchr(b->name, '.');
198     if (s2 && !s1) return -1;
199     if (s1 && !s2) return 1;
200     if (!(flags&FLAG_X7E)) flags |= FLAG_a;
201   }
202   if (!s1) {
203     s1 = a->name;
204     s2 = b->name;
205   }
206 
207   // case insensitive sort falls back to case sensitive sort when equal
208   ret = (flags&FLAG_X7E) ? strcasecmp(s1, s2) : 0;
209   if (!ret && (flags&FLAG_a)) ret = strcmp(s1, s2);
210 
211   return ret;
212 }
213 
comma_start(char ** aa,char * b)214 int comma_start(char **aa, char *b)
215 {
216   return strstart(aa, b) && (!**aa || **aa==',');
217 }
218 
219 // callback for qsort
compare(void * a,void * b)220 static int compare(void *a, void *b)
221 {
222   struct dirtree *dta = *(struct dirtree **)a;
223   struct dirtree *dtb = *(struct dirtree **)b;
224   char *ss = TT.sort;
225   long long ll = 0;
226   int ret = 0;
227 // TODO: test --sort=reverse with fallback alphabetical
228 
229   if (ss) for (;;) {
230     while (*ss==',') ss++;
231     if (!*ss) break;
232     if (comma_start(&ss, "reverse")) toys.optflags |= FLAG_r;
233     else if (comma_start(&ss, "none")) goto skip;
234     else if (comma_start(&ss, "ctime")) ll = FLAG_c;
235     else if (comma_start(&ss, "size")) ll = FLAG_S;
236     else if (comma_start(&ss, "time")) ll = FLAG_t;
237     else if (comma_start(&ss, "atime")) ll = FLAG_u;
238     else if (comma_start(&ss, "nocase")) ll = FLAG_X7E;
239     else if (comma_start(&ss, "extension")) ll = FLAG_X;
240     else if (comma_start(&ss, "dirfirst")) ll = FLAG_X21;
241     else error_exit("bad --sort %s", ss);
242 
243     if (!ret) ret = do_compare(dta, dtb, ll);
244   }
245 
246   // Alpha fallback sort, and handle short opts
247   if (!ret) {
248     ll = toys.optflags|FLAG_a;
249     // historical nonsense: -lc displays -c but doesn't sort, -ltc sorts.
250     if (FLAG(o)|FLAG(l)) {
251       if (!FLAG(t)) ll &= ~(FLAG_c|FLAG_u);
252       else if (FLAG(c)||FLAG(u)) ll &= ~FLAG_t;
253     }
254     ret = do_compare(dta, dtb, ll);
255   }
256 skip:
257   if (FLAG(r)) ret *= -1;
258 
259   return ret;
260 }
261 
262 // callback from dirtree_recurse() determining how to handle this entry.
263 
filter(struct dirtree * new)264 static int filter(struct dirtree *new)
265 {
266   // Special case to handle enormous dirs without running out of memory.
267   if (toys.optflags == (FLAG_1|FLAG_f)) {
268     xprintf("%s\n", new->name);
269     return 0;
270   }
271 
272   if (FLAG(Z)) {
273     if (!CFG_TOYBOX_LSM_NONE) {
274       // Linux doesn't support fgetxattr(2) on O_PATH file descriptors (though
275       // bionic works around that), and there are no *xattrat(2) calls, so we
276       // just use lgetxattr(2).
277       char *path = dirtree_path(new, 0);
278 
279       (FLAG(L) ? lsm_get_context : lsm_lget_context)(path,(char **)&new->extra);
280       free(path);
281     }
282     if (CFG_TOYBOX_LSM_NONE || !new->extra) new->extra = (long)xstrdup("?");
283   }
284 
285   if (FLAG(u)) new->st.st_mtime = new->st.st_atime;
286   if (FLAG(c)) new->st.st_mtime = new->st.st_ctime;
287   new->st.st_blocks >>= 1; // Use 1KiB blocks rather than 512B blocks.
288 
289   if (FLAG(a)||FLAG(f)) return DIRTREE_SAVE;
290   if (!FLAG(A) && *new->name=='.') return 0;
291 
292   return dirtree_notdotdot(new) & DIRTREE_SAVE;
293 }
294 
295 // For column view, calculate horizontal position (for padding) and return
296 // index of next entry to display.
297 
next_column(unsigned long ul,unsigned long dtlen,unsigned columns,unsigned * xpos)298 static unsigned long next_column(unsigned long ul, unsigned long dtlen,
299   unsigned columns, unsigned *xpos)
300 {
301   unsigned height, extra;
302 
303   // Horizontal sort is easy
304   if (!FLAG(C)) {
305     *xpos = ul % columns;
306     return ul;
307   }
308 
309   // vertical sort (-x), uneven rounding goes along right edge
310   height = (dtlen+columns-1)/columns; // round up
311   extra = dtlen%height; // how many rows are wider?
312   if (extra && ul >= extra*columns) ul -= extra*columns--;
313   else extra = 0;
314 
315   return (*xpos = ul % columns)*height + extra + ul/columns;
316 }
317 
color_from_mode(mode_t mode)318 static int color_from_mode(mode_t mode)
319 {
320   int color = 0;
321 
322   if (S_ISDIR(mode)) color = 256+34;
323   else if (S_ISLNK(mode)) color = 256+36;
324   else if (S_ISBLK(mode) || S_ISCHR(mode)) color = 256+33;
325   else if (S_ISREG(mode) && (mode&0111)) color = 256+32;
326   else if (S_ISFIFO(mode)) color = 33;
327   else if (S_ISSOCK(mode)) color = 256+35;
328 
329   return color;
330 }
331 
zprint(int zap,char * pat,int len,unsigned long arg)332 static void zprint(int zap, char *pat, int len, unsigned long arg)
333 {
334   char tmp[32];
335 
336   sprintf(tmp, "%%*%s", zap ? "s" : pat);
337   if (zap && pat[strlen(pat)-1]==' ') strcat(tmp, " ");
338   printf(tmp, len, zap ? (unsigned long)"?" : arg);
339 }
340 
341 // Display a list of dirtree entries, according to current format
342 // Output types -1, -l, -C, or stream
343 
listfiles(int dirfd,struct dirtree * indir)344 static void listfiles(int dirfd, struct dirtree *indir)
345 {
346   struct dirtree *dt, **sort;
347   unsigned long dtlen, ul = 0;
348   unsigned width, totals[8], len[8], totpad = 0,
349     *colsizes = (unsigned *)toybuf, columns = sizeof(toybuf)/4;
350   char tmp[64];
351 
352   if (-1 == dirfd) {
353     perror_msg_raw(indir->name);
354 
355     return;
356   }
357 
358   memset(totals, 0, sizeof(totals));
359   memset(len, 0, sizeof(len));
360 
361   // Top level directory was already populated by main()
362   if (!indir->parent) {
363     // Silently descend into single directory listed by itself on command line.
364     // In this case only show dirname/total header when given -R.
365     dt = indir->child;
366     if (dt && S_ISDIR(dt->st.st_mode) && !dt->next && !(FLAG(d)||FLAG(R))) {
367       listfiles(open(dt->name, 0), TT.singledir = dt);
368 
369       return;
370     }
371 
372     // Do preprocessing (Dirtree didn't populate, so callback wasn't called.)
373     for (;dt; dt = dt->next) filter(dt);
374     if (toys.optflags == (FLAG_1|FLAG_f)) return;
375   // Read directory contents. We dup() the fd because this will close it.
376   // This reads/saves contents to display later, except for in "ls -1f" mode.
377   } else dirtree_recurse(indir, filter, dirfd,
378       DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*FLAG(L));
379 
380   // Copy linked list to array and sort it. Directories go in array because
381   // we visit them in sorted order too. (The nested loops let us measure and
382   // fill with the same inner loop.)
383   for (sort = 0;;sort = xmalloc(dtlen*sizeof(void *))) {
384     for (dtlen = 0, dt = indir->child; dt; dt = dt->next, dtlen++)
385       if (sort) sort[dtlen] = dt;
386     if (sort || !dtlen) break;
387   }
388 
389   // Label directory if not top of tree, or if -R
390   if (indir->parent && (TT.singledir!=indir || FLAG(R))) {
391     char *path = dirtree_path(indir, 0);
392 
393     if (TT.nl_title++) xputc('\n');
394     xprintf("%s:\n", path);
395     free(path);
396   }
397 
398   // Measure each entry to work out whitespace padding and total blocks
399   if (!FLAG(f)) {
400     unsigned long long blocks = 0;
401 
402     if (!FLAG(U)) qsort(sort, dtlen, sizeof(void *), (void *)compare);
403     for (ul = 0; ul<dtlen; ul++) {
404       entrylen(sort[ul], len);
405       for (width = 0; width<8; width++)
406         if (len[width]>totals[width]) totals[width] = len[width];
407       blocks += sort[ul]->st.st_blocks;
408     }
409     totpad = totals[1]+!!totals[1]+totals[6]+!!totals[6]+totals[7]+!!totals[7];
410     if ((FLAG(h)||FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)||FLAG(s)) && indir->parent)
411     {
412       print_with_h(tmp, blocks, 1);
413       xprintf("total %s\n", tmp);
414     }
415   }
416 
417   // Find largest entry in each field for display alignment
418   if (FLAG(C)||FLAG(x)) {
419 
420     // columns can't be more than toybuf can hold, or more than files,
421     // or > 1/2 screen width (one char filename, one space).
422     if (columns > TT.screen_width/2) columns = TT.screen_width/2;
423     if (columns > dtlen) columns = dtlen;
424 
425     // Try to fit as many columns as we can, dropping down by one each time
426     for (;columns > 1; columns--) {
427       unsigned c, cc, totlen = columns;
428 
429       memset(colsizes, 0, columns*sizeof(unsigned));
430       for (ul = 0; ul<dtlen; ul++) {
431         cc = next_column(ul, dtlen, columns, &c);
432         if (cc>=dtlen) break; // tilt: remainder bigger than height
433         entrylen(sort[cc], len);
434         if (c<columns-1) *len += totpad+2;  // 2 spaces between filenames
435         // Expand this column if necessary, break if that puts us over budget
436         if (*len > colsizes[c]) {
437           totlen += (*len)-colsizes[c];
438           colsizes[c] = *len;
439           if (totlen > TT.screen_width) break;
440         }
441       }
442       // If everything fit, stop here
443       if (ul == dtlen) break;
444     }
445   }
446 
447   // Loop through again to produce output.
448   width = 0;
449   for (ul = 0; ul<dtlen; ul++) {
450     int ii, zap;
451     unsigned curcol, lastlen = *len, color = 0;
452     struct stat *st = &((dt = sort[next_column(ul,dtlen,columns,&curcol)])->st);
453     mode_t mode = st->st_mode;
454     char et = endtype(st), *ss;
455 
456     // If we couldn't stat, output ? for most fields
457     zap = !st->st_blksize && !st->st_dev && !st->st_ino;
458 
459     // Skip directories at the top of the tree when -d isn't set
460     if (S_ISDIR(mode) && !indir->parent && !FLAG(d)) continue;
461     TT.nl_title=1;
462 
463     // Handle padding and wrapping for display purposes
464     entrylen(dt, len);
465     if (ul) {
466       if (FLAG(m)) xputc(',');
467       if (FLAG(C)||FLAG(x)) {
468         if (!curcol) xputc('\n');
469         else {
470           if (ul) next_column(ul-1, dtlen, columns, &curcol);
471           printf("%*c", colsizes[ul ? curcol : 0]-lastlen-totpad, ' ');
472         }
473       } else if (FLAG(1) || width+1+*len > TT.screen_width) {
474         xputc('\n');
475         width = 0;
476       } else {
477         xputsn("  "+FLAG(m));
478         width += 2-FLAG(m);
479       }
480     }
481     width += *len;
482 
483     if (FLAG(i)) zprint(zap, "lu ", totals[1], st->st_ino);
484 
485     if (FLAG(s)) {
486       print_with_h(tmp, st->st_blocks, 1);
487       zprint(zap, "s ", totals[6], (unsigned long)tmp);
488     }
489 
490     if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) {
491       mode_to_string(mode, tmp);
492       if (zap) memset(tmp+1, '?', 9);
493       printf("%s", tmp);
494       zprint(zap, "ld", totals[2]+1, st->st_nlink);
495 
496       // print user
497       if (!FLAG(g)) {
498         putchar(' ');
499         ii = -totals[3];
500         if (zap || FLAG(n)) zprint(zap, "lu", ii, st->st_uid);
501         else draw_trim_esc(getusername(st->st_uid), ii, abs(ii), TT.escmore,
502                            crunch_qb);
503       }
504 
505       // print group
506       if (!FLAG(o)) {
507         putchar(' ');
508         ii = -totals[4];
509         if (zap || FLAG(n)) zprint(zap, "lu", ii, st->st_gid);
510         else draw_trim_esc(getgroupname(st->st_gid), ii, abs(ii), TT.escmore,
511                            crunch_qb);
512       }
513     }
514     if (FLAG(Z)) printf(" %-*s "+!FLAG(l), -(int)totals[7], (char *)dt->extra);
515 
516     if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) {
517       struct tm *tm;
518 
519       // print major/minor, or size
520       if (!zap && (S_ISCHR(st->st_mode) || S_ISBLK(st->st_mode)))
521         printf("% *d,% 4d", totals[5]-4, dev_major(st->st_rdev),
522           dev_minor(st->st_rdev));
523       else {
524         print_with_h(tmp, st->st_size, 0);
525         zprint(zap, "s", totals[5]+1, (unsigned long)tmp);
526       }
527 
528       // print time, always in --time-style=long-iso
529       tm = localtime(&(st->st_mtime));
530       strftime(tmp, sizeof(tmp), " %F %H:%M", tm);
531       if (TT.l>1) {
532         char *s = tmp+strlen(tmp);
533 
534         s += sprintf(s, ":%02d.%09d ", tm->tm_sec, (int)st->st_mtim.tv_nsec);
535         strftime(s, sizeof(tmp)-(s-tmp), "%z", tm);
536       }
537       zprint(zap, "s ", 17+(TT.l>1)*13, (unsigned long)tmp);
538     }
539 
540     if (FLAG(color)) {
541       color = color_from_mode(st->st_mode);
542       if (color) printf("\e[%d;%dm", color>>8, color&255);
543     }
544 
545     ss = dt->name;
546     crunch_str(&ss, INT_MAX, stdout, TT.escmore, crunch_qb);
547     if (color) printf("\e[0m");
548 
549     if ((FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) && S_ISLNK(mode)) {
550       printf(" -> ");
551       if (!zap && FLAG(color)) {
552         struct stat st2;
553 
554         if (fstatat(dirfd, dt->symlink, &st2, 0)) color = 256+31;
555         else color = color_from_mode(st2.st_mode);
556 
557         if (color) printf("\e[%d;%dm", color>>8, color&255);
558       }
559 
560       zprint(zap, "s", 0, (unsigned long)dt->symlink);
561       if (!zap && color) printf("\e[0m");
562     }
563 
564     if (et) xputc(et);
565   }
566 
567   if (width) xputc('\n');
568 
569   // Free directory entries, recursing first if necessary.
570 
571   for (ul = 0; ul<dtlen; free(sort[ul++])) {
572     if (FLAG(d) || !S_ISDIR(sort[ul]->st.st_mode)) continue;
573 
574     // Recurse into dirs if at top of the tree or given -R
575     if (!indir->parent || (FLAG(R) && dirtree_notdotdot(sort[ul])))
576       listfiles(openat(dirfd, sort[ul]->name, 0), sort[ul]);
577     free((void *)sort[ul]->extra);
578   }
579   free(sort);
580   if (dirfd != AT_FDCWD) close(dirfd);
581 }
582 
ls_main(void)583 void ls_main(void)
584 {
585   char **s, *noargs[] = {".", 0};
586   struct dirtree *dt;
587 
588   if (FLAG(full_time)) {
589     toys.optflags |= FLAG_l;
590     TT.l = 2;
591   }
592 
593   // Do we have an implied -1
594   if (isatty(1)) {
595     if (!FLAG(show_control_chars)) toys.optflags |= FLAG_b;
596     if (FLAG(l)||FLAG(o)||FLAG(n)||FLAG(g)) toys.optflags |= FLAG_1;
597     else if (!(FLAG(1)||FLAG(x)||FLAG(m))) toys.optflags |= FLAG_C;
598   } else {
599     if (!FLAG(m)) toys.optflags |= FLAG_1;
600     if (TT.color) toys.optflags ^= FLAG_color;
601   }
602 
603   // -N *doesn't* disable -q; you need --show-control-chars for that.
604   if (FLAG(N)) toys.optflags &= ~FLAG_b;
605 
606   TT.screen_width = 80;
607   if (FLAG(w)) TT.screen_width = TT.w+2;
608   else terminal_size(&TT.screen_width, NULL);
609   if (TT.screen_width<2) TT.screen_width = 2;
610   if (FLAG(b)) TT.escmore = " \\";
611 
612   // The optflags parsing infrastructure should really do this for us,
613   // but currently it has "switch off when this is set", so "-dR" and "-Rd"
614   // behave differently
615   if (FLAG(d)) toys.optflags &= ~FLAG_R;
616 
617   // Iterate through command line arguments, collecting directories and files.
618   // Non-absolute paths are relative to current directory. Top of tree is
619   // a dummy node to collect command line arguments into pseudo-directory.
620   TT.files = dirtree_add_node(0, 0, 0);
621   TT.files->dirfd = AT_FDCWD;
622   for (s = *toys.optargs ? toys.optargs : noargs; *s; s++) {
623     int sym = !(FLAG(l)||FLAG(d)||FLAG(F)) || FLAG(L) || FLAG(H);
624 
625     dt = dirtree_add_node(0, *s, DIRTREE_STATLESS|DIRTREE_SYMFOLLOW*sym);
626 
627     // note: double_list->prev temporarily goes in dirtree->parent
628     if (dt) {
629       if (dt->again&DIRTREE_STATLESS) {
630         perror_msg_raw(*s);
631         free(dt);
632       } else dlist_add_nomalloc((void *)&TT.files->child, (void *)dt);
633     } else toys.exitval = 1;
634   }
635 
636   // Convert double_list into dirtree.
637   dlist_terminate(TT.files->child);
638   for (dt = TT.files->child; dt; dt = dt->next) dt->parent = TT.files;
639 
640   // Display the files we collected
641   listfiles(AT_FDCWD, TT.files);
642 
643   if (CFG_TOYBOX_FREE) free(TT.files);
644 }
645