OSDN Git Service

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