OSDN Git Service

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