OSDN Git Service

am b1a33391: am 0d7a388b: Merge remote-tracking branch \'toybox/master\' into HEAD
[android-x86/external-toybox.git] / lib / lib.c
1 /* lib.c - various reusable stuff.
2  *
3  * Copyright 2006 Rob Landley <rob@landley.net>
4  */
5
6 #include "toys.h"
7
8 void verror_msg(char *msg, int err, va_list va)
9 {
10   char *s = ": %s";
11
12   fprintf(stderr, "%s: ", toys.which->name);
13   if (msg) vfprintf(stderr, msg, va);
14   else s+=2;
15   if (err) fprintf(stderr, s, strerror(err));
16   if (msg || err) putc('\n', stderr);
17   if (!toys.exitval) toys.exitval++;
18 }
19
20 // These functions don't collapse together because of the va_stuff.
21
22 void error_msg(char *msg, ...)
23 {
24   va_list va;
25
26   va_start(va, msg);
27   verror_msg(msg, 0, va);
28   va_end(va);
29 }
30
31 void perror_msg(char *msg, ...)
32 {
33   va_list va;
34
35   va_start(va, msg);
36   verror_msg(msg, errno, va);
37   va_end(va);
38 }
39
40 // Die with an error message.
41 void error_exit(char *msg, ...)
42 {
43   va_list va;
44
45   va_start(va, msg);
46   verror_msg(msg, 0, va);
47   va_end(va);
48
49   xexit();
50 }
51
52 // Exit with an error message after showing help text.
53 void help_exit(char *msg, ...)
54 {
55   va_list va;
56
57   if (CFG_TOYBOX_HELP) show_help(stderr);
58
59   va_start(va, msg);
60   verror_msg(msg, 0, va);
61   va_end(va);
62
63   xexit();
64 }
65
66 // Die with an error message and strerror(errno)
67 void perror_exit(char *msg, ...)
68 {
69   va_list va;
70
71   va_start(va, msg);
72   verror_msg(msg, errno, va);
73   va_end(va);
74
75   xexit();
76 }
77
78 // Keep reading until full or EOF
79 ssize_t readall(int fd, void *buf, size_t len)
80 {
81   size_t count = 0;
82
83   while (count<len) {
84     int i = read(fd, (char *)buf+count, len-count);
85     if (!i) break;
86     if (i<0) return i;
87     count += i;
88   }
89
90   return count;
91 }
92
93 // Keep writing until done or EOF
94 ssize_t writeall(int fd, void *buf, size_t len)
95 {
96   size_t count = 0;
97   while (count<len) {
98     int i = write(fd, count+(char *)buf, len-count);
99     if (i<1) return i;
100     count += i;
101   }
102
103   return count;
104 }
105
106 // skip this many bytes of input. Return 0 for success, >0 means this much
107 // left after input skipped.
108 off_t lskip(int fd, off_t offset)
109 {
110   off_t cur = lseek(fd, 0, SEEK_CUR);
111
112   if (cur != -1) {
113     off_t end = lseek(fd, 0, SEEK_END) - cur;
114
115     if (end > 0 && end < offset) return offset - end;
116     end = offset+cur;
117     if (end == lseek(fd, end, SEEK_SET)) return 0;
118     perror_exit("lseek");
119   }
120
121   while (offset>0) {
122     int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
123
124     or = readall(fd, libbuf, try);
125     if (or < 0) perror_exit("lskip to %lld", (long long)offset);
126     else offset -= or;
127     if (or < try) break;
128   }
129
130   return offset;
131 }
132
133 // flags: 1=make last dir (with mode lastmode, otherwise skips last component)
134 //        2=make path (already exists is ok)
135 //        4=verbose
136 // returns 0 = path ok, 1 = error
137 int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
138 {
139   struct stat buf;
140   char *s;
141
142   // mkdir -p one/two/three is not an error if the path already exists,
143   // but is if "three" is a file. The others we dereference and catch
144   // not-a-directory along the way, but the last one we must explicitly
145   // test for. Might as well do it up front.
146
147   if (!fstatat(atfd, dir, &buf, 0) && !S_ISDIR(buf.st_mode)) {
148     errno = EEXIST;
149     return 1;
150   }
151
152   for (s = dir; ;s++) {
153     char save = 0;
154     mode_t mode = (0777&~toys.old_umask)|0300;
155
156     // find next '/', but don't try to mkdir "" at start of absolute path
157     if (*s == '/' && (flags&2) && s != dir) {
158       save = *s;
159       *s = 0;
160     } else if (*s) continue;
161
162     // Use the mode from the -m option only for the last directory.
163     if (!save) {
164       if (flags&1) mode = lastmode;
165       else break;
166     }
167
168     if (mkdirat(atfd, dir, mode)) {
169       if (!(flags&2) || errno != EEXIST) return 1;
170     } else if (flags&4)
171       fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
172
173     if (!(*s = save)) break;
174   }
175
176   return 0;
177 }
178
179 // Split a path into linked list of components, tracking head and tail of list.
180 // Filters out // entries with no contents.
181 struct string_list **splitpath(char *path, struct string_list **list)
182 {
183   char *new = path;
184
185   *list = 0;
186   do {
187     int len;
188
189     if (*path && *path != '/') continue;
190     len = path-new;
191     if (len > 0) {
192       *list = xmalloc(sizeof(struct string_list) + len + 1);
193       (*list)->next = 0;
194       memcpy((*list)->str, new, len);
195       (*list)->str[len] = 0;
196       list = &(*list)->next;
197     }
198     new = path+1;
199   } while (*path++);
200
201   return list;
202 }
203
204 // Find all file in a colon-separated path with access type "type" (generally
205 // X_OK or R_OK).  Returns a list of absolute paths to each file found, in
206 // order.
207
208 struct string_list *find_in_path(char *path, char *filename)
209 {
210   struct string_list *rlist = NULL, **prlist=&rlist;
211   char *cwd;
212
213   if (!path) return 0;
214
215   cwd = xgetcwd();
216   for (;;) {
217     char *next = strchr(path, ':');
218     int len = next ? next-path : strlen(path);
219     struct string_list *rnext;
220     struct stat st;
221
222     rnext = xmalloc(sizeof(void *) + strlen(filename)
223       + (len ? len : strlen(cwd)) + 2);
224     if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
225     else {
226       char *res = rnext->str;
227
228       memcpy(res, path, len);
229       res += len;
230       *(res++) = '/';
231       strcpy(res, filename);
232     }
233
234     // Confirm it's not a directory.
235     if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
236       *prlist = rnext;
237       rnext->next = NULL;
238       prlist = &(rnext->next);
239     } else free(rnext);
240
241     if (!next) break;
242     path += len;
243     path++;
244   }
245   free(cwd);
246
247   return rlist;
248 }
249
250 long estrtol(char *str, char **end, int base)
251 {
252   errno = 0;
253
254   return strtol(str, end, base);
255 }
256
257 long xstrtol(char *str, char **end, int base)
258 {
259   long l = estrtol(str, end, base);
260
261   if (errno) perror_exit("%s", str);
262
263   return l;
264 }
265
266 // atol() with the kilo/mega/giga/tera/peta/exa extensions.
267 // (zetta and yotta don't fit in 64 bits.)
268 long atolx(char *numstr)
269 {
270   char *c, *suffixes="cbkmgtpe", *end;
271   long val;
272
273   val = xstrtol(numstr, &c, 0);
274   if (*c) {
275     if (c != numstr && (end = strchr(suffixes, tolower(*c)))) {
276       int shift = end-suffixes-2;
277       if (shift >= 0) val *= 1024L<<(shift*10);
278     } else {
279       while (isspace(*c)) c++;
280       if (*c) error_exit("not integer: %s", numstr);
281     }
282   }
283
284   return val;
285 }
286
287 long atolx_range(char *numstr, long low, long high)
288 {
289   long val = atolx(numstr);
290
291   if (val < low) error_exit("%ld < %ld", val, low);
292   if (val > high) error_exit("%ld > %ld", val, high);
293
294   return val;
295 }
296
297 int stridx(char *haystack, char needle)
298 {
299   char *off;
300
301   if (!needle) return -1;
302   off = strchr(haystack, needle);
303   if (!off) return -1;
304
305   return off-haystack;
306 }
307
308 char *strlower(char *s)
309 {
310   char *try, *new;
311
312   if (!CFG_TOYBOX_I18N) {
313     try = new = xstrdup(s);
314     for (; *s; s++) *(new++) = tolower(*s);
315   } else {
316     // I can't guarantee the string _won't_ expand during reencoding, so...?
317     try = new = xmalloc(strlen(s)*2+1);
318
319     while (*s) {
320       wchar_t c;
321       int len = mbrtowc(&c, s, MB_CUR_MAX, 0);
322
323       if (len < 1) *(new++) = *(s++);
324       else {
325         s += len;
326         // squash title case too
327         c = towlower(c);
328
329         // if we had a valid utf8 sequence, convert it to lower case, and can't
330         // encode back to utf8, something is wrong with your libc. But just
331         // in case somebody finds an exploit...
332         len = wcrtomb(new, c, 0);
333         if (len < 1) error_exit("bad utf8 %x", (int)c);
334         new += len;
335       }
336     }
337     *new = 0;
338   }
339
340   return try;
341 }
342
343 int unescape(char c)
344 {
345   char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
346   int idx = stridx(from, c);
347
348   return (idx == -1) ? 0 : to[idx];
349 }
350
351 // If *a starts with b, advance *a past it and return 1, else return 0;
352 int strstart(char **a, char *b)
353 {
354   int len = strlen(b), i = !strncmp(*a, b, len);
355
356   if (i) *a += len;
357
358   return i;
359 }
360
361 // Return how long the file at fd is, if there's any way to determine it.
362 off_t fdlength(int fd)
363 {
364   struct stat st;
365   off_t base = 0, range = 1, expand = 1, old;
366
367   if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
368
369   // If the ioctl works for this, return it.
370   // TODO: is blocksize still always 512, or do we stat for it?
371   // unsigned int size;
372   // if (ioctl(fd, BLKGETSIZE, &size) >= 0) return size*512L;
373
374   // If not, do a binary search for the last location we can read.  (Some
375   // block devices don't do BLKGETSIZE right.)  This should probably have
376   // a CONFIG option...
377
378   // If not, do a binary search for the last location we can read.
379
380   old = lseek(fd, 0, SEEK_CUR);
381   do {
382     char temp;
383     off_t pos = base + range / 2;
384
385     if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
386       off_t delta = (pos + 1) - base;
387
388       base += delta;
389       if (expand) range = (expand <<= 1) - base;
390       else range -= delta;
391     } else {
392       expand = 0;
393       range = pos - base;
394     }
395   } while (range > 0);
396
397   lseek(fd, old, SEEK_SET);
398
399   return base;
400 }
401
402 // Read contents of file as a single nul-terminated string.
403 // malloc new one if buf=len=0
404 char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
405 {
406   int fd;
407   char *buf;
408
409   if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
410   if (len<1) {
411     len = fdlength(fd);
412     // proc files don't report a length, so try 1 page minimum.
413     if (len<4096) len = 4096;
414   }
415   if (!ibuf) buf = xmalloc(len+1);
416   else buf = ibuf;
417
418   len = readall(fd, buf, len-1);
419   close(fd);
420   if (len<0) {
421     if (ibuf != buf) free(buf);
422     buf = 0;
423   } else buf[len] = 0;
424
425   return buf;
426 }
427
428 char *readfile(char *name, char *ibuf, off_t len)
429 {
430   return readfileat(AT_FDCWD, name, ibuf, len);
431 }
432
433 // Sleep for this many thousandths of a second
434 void msleep(long miliseconds)
435 {
436   struct timespec ts;
437
438   ts.tv_sec = miliseconds/1000;
439   ts.tv_nsec = (miliseconds%1000)*1000000;
440   nanosleep(&ts, &ts);
441 }
442
443 // Inefficient, but deals with unaligned access
444 int64_t peek_le(void *ptr, unsigned size)
445 {
446   int64_t ret = 0;
447   char *c = ptr;
448   int i;
449
450   for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
451
452   return ret;
453 }
454
455 int64_t peek_be(void *ptr, unsigned size)
456 {
457   int64_t ret = 0;
458   char *c = ptr;
459
460   while (size--) ret = (ret<<8)|c[size];
461
462   return ret;
463 }
464
465 int64_t peek(void *ptr, unsigned size)
466 {
467   return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
468 }
469
470 void poke(void *ptr, uint64_t val, int size)
471 {
472   if (size & 8) {
473     volatile uint64_t *p = (uint64_t *)ptr;
474     *p = val;
475   } else if (size & 4) {
476     volatile int *p = (int *)ptr;
477     *p = val;
478   } else if (size & 2) {
479     volatile short *p = (short *)ptr;
480     *p = val;
481   } else {
482     volatile char *p = (char *)ptr;
483     *p = val;
484   }
485 }
486
487 // Iterate through an array of files, opening each one and calling a function
488 // on that filehandle and name.  The special filename "-" means stdin if
489 // flags is O_RDONLY, stdout otherwise.  An empty argument list calls
490 // function() on just stdin/stdout.
491 //
492 // Note: pass O_CLOEXEC to automatically close filehandles when function()
493 // returns, otherwise filehandles must be closed by function()
494 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
495   void (*function)(int fd, char *name))
496 {
497   int fd;
498
499   // If no arguments, read from stdin.
500   if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
501   else do {
502     // Filename "-" means read from stdin.
503     // Inability to open a file prints a warning, but doesn't exit.
504
505     if (!strcmp(*argv, "-")) fd=0;
506     else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
507       perror_msg("%s", *argv);
508       toys.exitval = 1;
509       continue;
510     }
511     function(fd, *argv);
512     if (flags & O_CLOEXEC) close(fd);
513   } while (*++argv);
514 }
515
516 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
517 void loopfiles(char **argv, void (*function)(int fd, char *name))
518 {
519   loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
520 }
521
522 // Slow, but small.
523
524 char *get_rawline(int fd, long *plen, char end)
525 {
526   char c, *buf = NULL;
527   long len = 0;
528
529   for (;;) {
530     if (1>read(fd, &c, 1)) break;
531     if (!(len & 63)) buf=xrealloc(buf, len+65);
532     if ((buf[len++]=c) == end) break;
533   }
534   if (buf) buf[len]=0;
535   if (plen) *plen = len;
536
537   return buf;
538 }
539
540 char *get_line(int fd)
541 {
542   long len;
543   char *buf = get_rawline(fd, &len, '\n');
544
545   if (buf && buf[--len]=='\n') buf[len]=0;
546
547   return buf;
548 }
549
550 int wfchmodat(int fd, char *name, mode_t mode)
551 {
552   int rc = fchmodat(fd, name, mode, 0);
553
554   if (rc) {
555     perror_msg("chmod '%s' to %04o", name, mode);
556     toys.exitval=1;
557   }
558   return rc;
559 }
560
561 static char *tempfile2zap;
562 static void tempfile_handler(int i)
563 {
564   if (1 < (long)tempfile2zap) unlink(tempfile2zap);
565   _exit(1);
566 }
567
568 // Open a temporary file to copy an existing file into.
569 int copy_tempfile(int fdin, char *name, char **tempname)
570 {
571   struct stat statbuf;
572   int fd;
573
574   *tempname = xmprintf("%s%s", name, "XXXXXX");
575   if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
576   if (!tempfile2zap) sigatexit(tempfile_handler);
577   tempfile2zap = *tempname;
578
579   // Set permissions of output file
580
581   fstat(fdin, &statbuf);
582   fchmod(fd, statbuf.st_mode);
583
584   return fd;
585 }
586
587 // Abort the copy and delete the temporary file.
588 void delete_tempfile(int fdin, int fdout, char **tempname)
589 {
590   close(fdin);
591   close(fdout);
592   if (*tempname) unlink(*tempname);
593   tempfile2zap = (char *)1;
594   free(*tempname);
595   *tempname = NULL;
596 }
597
598 // Copy the rest of the data and replace the original with the copy.
599 void replace_tempfile(int fdin, int fdout, char **tempname)
600 {
601   char *temp = xstrdup(*tempname);
602
603   temp[strlen(temp)-6]=0;
604   if (fdin != -1) {
605     xsendfile(fdin, fdout);
606     xclose(fdin);
607   }
608   xclose(fdout);
609   rename(*tempname, temp);
610   tempfile2zap = (char *)1;
611   free(*tempname);
612   free(temp);
613   *tempname = NULL;
614 }
615
616 // Create a 256 entry CRC32 lookup table.
617
618 void crc_init(unsigned int *crc_table, int little_endian)
619 {
620   unsigned int i;
621
622   // Init the CRC32 table (big endian)
623   for (i=0; i<256; i++) {
624     unsigned int j, c = little_endian ? i : i<<24;
625     for (j=8; j; j--)
626       if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
627       else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
628     crc_table[i] = c;
629   }
630 }
631
632 // Init base64 table
633
634 void base64_init(char *p)
635 {
636   int i;
637
638   for (i = 'A'; i != ':'; i++) {
639     if (i == 'Z'+1) i = 'a';
640     if (i == 'z'+1) i = '0';
641     *(p++) = i;
642   }
643   *(p++) = '+';
644   *(p++) = '/';
645 }
646
647 int yesno(int def)
648 {
649   char buf;
650
651   fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
652   fflush(stderr);
653   while (fread(&buf, 1, 1, stdin)) {
654     int new;
655
656     // The letter changes the value, the newline (or space) returns it.
657     if (isspace(buf)) break;
658     if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
659   }
660
661   return def;
662 }
663
664 struct signame {
665   int num;
666   char *name;
667 };
668
669 // Signals required by POSIX 2008:
670 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
671
672 #define SIGNIFY(x) {SIG##x, #x}
673
674 static struct signame signames[] = {
675   SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
676   SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
677   SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
678   SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
679   SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
680
681   // Start of non-terminal signals
682
683   SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
684   SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
685 };
686
687 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
688 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
689
690 // Handler that sets toys.signal, and writes to toys.signalfd if set
691 void generic_signal(int sig)
692 {
693   if (toys.signalfd) {
694     char c = sig;
695
696     writeall(toys.signalfd, &c, 1);
697   }
698   toys.signal = sig;
699 }
700
701 // Install the same handler on every signal that defaults to killing the process
702 void sigatexit(void *handler)
703 {
704   int i;
705   for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
706 }
707
708 // Convert name to signal number.  If name == NULL print names.
709 int sig_to_num(char *pidstr)
710 {
711   int i;
712
713   if (pidstr) {
714     char *s;
715
716     i = estrtol(pidstr, &s, 10);
717     if (!errno && !*s) return i;
718
719     if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
720   }
721   for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
722     if (!pidstr) xputs(signames[i].name);
723     else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
724
725   return -1;
726 }
727
728 char *num_to_sig(int sig)
729 {
730   int i;
731
732   for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
733     if (signames[i].num == sig) return signames[i].name;
734   return NULL;
735 }
736
737 // premute mode bits based on posix mode strings.
738 mode_t string_to_mode(char *modestr, mode_t mode)
739 {
740   char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
741        *s, *str = modestr;
742   mode_t extrabits = mode & ~(07777);
743
744   // Handle octal mode
745   if (isdigit(*str)) {
746     mode = estrtol(str, &s, 8);
747     if (errno || *s || (mode & ~(07777))) goto barf;
748
749     return mode | extrabits;
750   }
751
752   // Gaze into the bin of permission...
753   for (;;) {
754     int i, j, dowho, dohow, dowhat, amask;
755
756     dowho = dohow = dowhat = amask = 0;
757
758     // Find the who, how, and what stanzas, in that order
759     while (*str && (s = strchr(whos, *str))) {
760       dowho |= 1<<(s-whos);
761       str++;
762     }
763     // If who isn't specified, like "a" but honoring umask.
764     if (!dowho) {
765       dowho = 8;
766       umask(amask=umask(0));
767     }
768     if (!*str || !(s = strchr(hows, *str))) goto barf;
769     dohow = *(str++);
770
771     if (!dohow) goto barf;
772     while (*str && (s = strchr(whats, *str))) {
773       dowhat |= 1<<(s-whats);
774       str++;
775     }
776
777     // Convert X to x for directory or if already executable somewhere
778     if ((dowhat&32) &&  (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
779
780     // Copy mode from another category?
781     if (!dowhat && *str && (s = strchr(whys, *str))) {
782       dowhat = (mode>>(3*(s-whys)))&7;
783       str++;
784     }
785
786     // Are we ready to do a thing yet?
787     if (*str && *(str++) != ',') goto barf;
788
789     // Ok, apply the bits to the mode.
790     for (i=0; i<4; i++) {
791       for (j=0; j<3; j++) {
792         mode_t bit = 0;
793         int where = 1<<((3*i)+j);
794
795         if (amask & where) continue;
796
797         // Figure out new value at this location
798         if (i == 3) {
799           // suid/sticky bit.
800           if (j) {
801             if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
802           } else if (dowhat & 16) bit++;
803         } else {
804           if (!(dowho&(8|(1<<i)))) continue;
805           if (dowhat&(1<<j)) bit++;
806         }
807
808         // When selection active, modify bit
809
810         if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
811         if (bit && dohow != '-') mode |= where;
812       }
813     }
814
815     if (!*str) break;
816   }
817
818   return mode|extrabits;
819 barf:
820   error_exit("bad mode '%s'", modestr);
821 }
822
823 // Format access mode into a drwxrwxrwx string
824 void mode_to_string(mode_t mode, char *buf)
825 {
826   char c, d;
827   int i, bit;
828
829   buf[10]=0;
830   for (i=0; i<9; i++) {
831     bit = mode & (1<<i);
832     c = i%3;
833     if (!c && (mode & (1<<((d=i/3)+9)))) {
834       c = "tss"[d];
835       if (!bit) c &= ~0x20;
836     } else c = bit ? "xwr"[c] : '-';
837     buf[9-i] = c;
838   }
839
840   if (S_ISDIR(mode)) c = 'd';
841   else if (S_ISBLK(mode)) c = 'b';
842   else if (S_ISCHR(mode)) c = 'c';
843   else if (S_ISLNK(mode)) c = 'l';
844   else if (S_ISFIFO(mode)) c = 'p';
845   else if (S_ISSOCK(mode)) c = 's';
846   else c = '-';
847   *buf = c;
848 }
849
850 char *basename_r(char *name)
851 {
852   char *s = strrchr(name, '/');
853
854   if (s) return s+1;
855   return name;
856 }
857
858 // Execute a callback for each PID that matches a process name from a list.
859 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
860 {
861   DIR *dp;
862   struct dirent *entry;
863
864   if (!(dp = opendir("/proc"))) perror_exit("opendir");
865
866   while ((entry = readdir(dp))) {
867     unsigned u;
868     char *cmd, **curname;
869
870     if (!(u = atoi(entry->d_name))) continue;
871     sprintf(libbuf, "/proc/%u/cmdline", u);
872     if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
873
874     for (curname = names; *curname; curname++)
875       if (**curname == '/' ? !strcmp(cmd, *curname)
876           : !strcmp(basename_r(cmd), basename_r(*curname)))
877         if (callback(u, *curname)) break;
878     if (*curname) break;
879   }
880   closedir(dp);
881 }
882
883 // display first few digits of number with power of two units
884 int human_readable(char *buf, unsigned long long num, int style)
885 {
886   unsigned long long snap = 0;
887   int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
888
889   // Divide rounding up until we have 3 or fewer digits. Since the part we
890   // print is decimal, the test is 999 even when we divide by 1024.
891   // We can't run out of units because 2<<64 is 18 exabytes.
892   // test 5675 is 5.5k not 5.6k.
893   for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
894   len = sprintf(buf, "%llu", num);
895   if (unit && len == 1) {
896     // Redo rounding for 1.2M case, this works with and without HR_1000.
897     num = snap/divisor;
898     snap -= num*divisor;
899     snap = ((snap*100)+50)/divisor;
900     snap /= 10;
901     len = sprintf(buf, "%llu.%llu", num, snap);
902   }
903   if (style & HR_SPACE) buf[len++] = ' ';
904   if (unit) {
905     unit = " kMGTPE"[unit];
906
907     if (!(style&HR_1000)) unit = toupper(unit);
908     buf[len++] = unit;
909   } else if (style & HR_B) buf[len++] = 'B';
910   buf[len] = 0;
911
912   return len;
913 }
914
915 // The qsort man page says you can use alphasort, the posix committee
916 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
917 // So just do our own. (The const is entirely to humor the stupid compiler.)
918 int qstrcmp(const void *a, const void *b)
919 {
920   return strcmp(*(char **)a, *(char **)b);
921 }
922
923 int xpoll(struct pollfd *fds, int nfds, int timeout)
924 {
925   int i;
926
927   for (;;) {
928     if (0>(i = poll(fds, nfds, timeout))) {
929       if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
930       else if (timeout>0) timeout--;
931     } else return i;
932   }
933 }