OSDN Git Service

If chomp() needs to test it found \n, should also test it's at end of string.
[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 // malloc new one if buf=len=0
415 char *readfileat(int dirfd, char *name, char *ibuf, off_t len)
416 {
417   int fd;
418   char *buf;
419
420   if (-1 == (fd = openat(dirfd, name, O_RDONLY))) return 0;
421   if (len<1) {
422     len = fdlength(fd);
423     // proc files don't report a length, so try 1 page minimum.
424     if (len<4096) len = 4096;
425   }
426   if (!ibuf) buf = xmalloc(len+1);
427   else buf = ibuf;
428
429   len = readall(fd, buf, len-1);
430   close(fd);
431   if (len<0) {
432     if (ibuf != buf) free(buf);
433     buf = 0;
434   } else buf[len] = 0;
435
436   return buf;
437 }
438
439 char *readfile(char *name, char *ibuf, off_t len)
440 {
441   return readfileat(AT_FDCWD, name, ibuf, len);
442 }
443
444 // Sleep for this many thousandths of a second
445 void msleep(long miliseconds)
446 {
447   struct timespec ts;
448
449   ts.tv_sec = miliseconds/1000;
450   ts.tv_nsec = (miliseconds%1000)*1000000;
451   nanosleep(&ts, &ts);
452 }
453
454 // Inefficient, but deals with unaligned access
455 int64_t peek_le(void *ptr, unsigned size)
456 {
457   int64_t ret = 0;
458   char *c = ptr;
459   int i;
460
461   for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<i;
462
463   return ret;
464 }
465
466 int64_t peek_be(void *ptr, unsigned size)
467 {
468   int64_t ret = 0;
469   char *c = ptr;
470
471   while (size--) ret = (ret<<8)|c[size];
472
473   return ret;
474 }
475
476 int64_t peek(void *ptr, unsigned size)
477 {
478   return IS_BIG_ENDIAN ? peek_be(ptr, size) : peek_le(ptr, size);
479 }
480
481 void poke(void *ptr, uint64_t val, int size)
482 {
483   if (size & 8) {
484     volatile uint64_t *p = (uint64_t *)ptr;
485     *p = val;
486   } else if (size & 4) {
487     volatile int *p = (int *)ptr;
488     *p = val;
489   } else if (size & 2) {
490     volatile short *p = (short *)ptr;
491     *p = val;
492   } else {
493     volatile char *p = (char *)ptr;
494     *p = val;
495   }
496 }
497
498 // Iterate through an array of files, opening each one and calling a function
499 // on that filehandle and name.  The special filename "-" means stdin if
500 // flags is O_RDONLY, stdout otherwise.  An empty argument list calls
501 // function() on just stdin/stdout.
502 //
503 // Note: pass O_CLOEXEC to automatically close filehandles when function()
504 // returns, otherwise filehandles must be closed by function()
505 void loopfiles_rw(char **argv, int flags, int permissions, int failok,
506   void (*function)(int fd, char *name))
507 {
508   int fd;
509
510   // If no arguments, read from stdin.
511   if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
512   else do {
513     // Filename "-" means read from stdin.
514     // Inability to open a file prints a warning, but doesn't exit.
515
516     if (!strcmp(*argv, "-")) fd=0;
517     else if (0>(fd = open(*argv, flags, permissions)) && !failok) {
518       perror_msg("%s", *argv);
519       toys.exitval = 1;
520       continue;
521     }
522     function(fd, *argv);
523     if (flags & O_CLOEXEC) close(fd);
524   } while (*++argv);
525 }
526
527 // Call loopfiles_rw with O_RDONLY|O_CLOEXEC and !failok (common case).
528 void loopfiles(char **argv, void (*function)(int fd, char *name))
529 {
530   loopfiles_rw(argv, O_RDONLY|O_CLOEXEC, 0, 0, function);
531 }
532
533 // Slow, but small.
534
535 char *get_rawline(int fd, long *plen, char end)
536 {
537   char c, *buf = NULL;
538   long len = 0;
539
540   for (;;) {
541     if (1>read(fd, &c, 1)) break;
542     if (!(len & 63)) buf=xrealloc(buf, len+65);
543     if ((buf[len++]=c) == end) break;
544   }
545   if (buf) buf[len]=0;
546   if (plen) *plen = len;
547
548   return buf;
549 }
550
551 char *get_line(int fd)
552 {
553   long len;
554   char *buf = get_rawline(fd, &len, '\n');
555
556   if (buf && buf[--len]=='\n') buf[len]=0;
557
558   return buf;
559 }
560
561 int wfchmodat(int fd, char *name, mode_t mode)
562 {
563   int rc = fchmodat(fd, name, mode, 0);
564
565   if (rc) {
566     perror_msg("chmod '%s' to %04o", name, mode);
567     toys.exitval=1;
568   }
569   return rc;
570 }
571
572 static char *tempfile2zap;
573 static void tempfile_handler(int i)
574 {
575   if (1 < (long)tempfile2zap) unlink(tempfile2zap);
576   _exit(1);
577 }
578
579 // Open a temporary file to copy an existing file into.
580 int copy_tempfile(int fdin, char *name, char **tempname)
581 {
582   struct stat statbuf;
583   int fd;
584
585   *tempname = xmprintf("%s%s", name, "XXXXXX");
586   if(-1 == (fd = mkstemp(*tempname))) error_exit("no temp file");
587   if (!tempfile2zap) sigatexit(tempfile_handler);
588   tempfile2zap = *tempname;
589
590   // Set permissions of output file
591
592   fstat(fdin, &statbuf);
593   fchmod(fd, statbuf.st_mode);
594
595   return fd;
596 }
597
598 // Abort the copy and delete the temporary file.
599 void delete_tempfile(int fdin, int fdout, char **tempname)
600 {
601   close(fdin);
602   close(fdout);
603   if (*tempname) unlink(*tempname);
604   tempfile2zap = (char *)1;
605   free(*tempname);
606   *tempname = NULL;
607 }
608
609 // Copy the rest of the data and replace the original with the copy.
610 void replace_tempfile(int fdin, int fdout, char **tempname)
611 {
612   char *temp = xstrdup(*tempname);
613
614   temp[strlen(temp)-6]=0;
615   if (fdin != -1) {
616     xsendfile(fdin, fdout);
617     xclose(fdin);
618   }
619   xclose(fdout);
620   rename(*tempname, temp);
621   tempfile2zap = (char *)1;
622   free(*tempname);
623   free(temp);
624   *tempname = NULL;
625 }
626
627 // Create a 256 entry CRC32 lookup table.
628
629 void crc_init(unsigned int *crc_table, int little_endian)
630 {
631   unsigned int i;
632
633   // Init the CRC32 table (big endian)
634   for (i=0; i<256; i++) {
635     unsigned int j, c = little_endian ? i : i<<24;
636     for (j=8; j; j--)
637       if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
638       else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
639     crc_table[i] = c;
640   }
641 }
642
643 // Init base64 table
644
645 void base64_init(char *p)
646 {
647   int i;
648
649   for (i = 'A'; i != ':'; i++) {
650     if (i == 'Z'+1) i = 'a';
651     if (i == 'z'+1) i = '0';
652     *(p++) = i;
653   }
654   *(p++) = '+';
655   *(p++) = '/';
656 }
657
658 int yesno(int def)
659 {
660   char buf;
661
662   fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
663   fflush(stderr);
664   while (fread(&buf, 1, 1, stdin)) {
665     int new;
666
667     // The letter changes the value, the newline (or space) returns it.
668     if (isspace(buf)) break;
669     if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
670   }
671
672   return def;
673 }
674
675 struct signame {
676   int num;
677   char *name;
678 };
679
680 // Signals required by POSIX 2008:
681 // http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html
682
683 #define SIGNIFY(x) {SIG##x, #x}
684
685 static struct signame signames[] = {
686   SIGNIFY(ABRT), SIGNIFY(ALRM), SIGNIFY(BUS),
687   SIGNIFY(FPE), SIGNIFY(HUP), SIGNIFY(ILL), SIGNIFY(INT), SIGNIFY(KILL),
688   SIGNIFY(PIPE), SIGNIFY(QUIT), SIGNIFY(SEGV), SIGNIFY(TERM),
689   SIGNIFY(USR1), SIGNIFY(USR2), SIGNIFY(SYS), SIGNIFY(TRAP),
690   SIGNIFY(VTALRM), SIGNIFY(XCPU), SIGNIFY(XFSZ),
691
692   // Start of non-terminal signals
693
694   SIGNIFY(CHLD), SIGNIFY(CONT), SIGNIFY(STOP), SIGNIFY(TSTP),
695   SIGNIFY(TTIN), SIGNIFY(TTOU), SIGNIFY(URG)
696 };
697
698 // not in posix: SIGNIFY(STKFLT), SIGNIFY(WINCH), SIGNIFY(IO), SIGNIFY(PWR)
699 // obsolete: SIGNIFY(PROF) SIGNIFY(POLL)
700
701 // Handler that sets toys.signal, and writes to toys.signalfd if set
702 void generic_signal(int sig)
703 {
704   if (toys.signalfd) {
705     char c = sig;
706
707     writeall(toys.signalfd, &c, 1);
708   }
709   toys.signal = sig;
710 }
711
712 // Install the same handler on every signal that defaults to killing the process
713 void sigatexit(void *handler)
714 {
715   int i;
716   for (i=0; signames[i].num != SIGCHLD; i++) signal(signames[i].num, handler);
717 }
718
719 // Convert name to signal number.  If name == NULL print names.
720 int sig_to_num(char *pidstr)
721 {
722   int i;
723
724   if (pidstr) {
725     char *s;
726
727     i = estrtol(pidstr, &s, 10);
728     if (!errno && !*s) return i;
729
730     if (!strncasecmp(pidstr, "sig", 3)) pidstr+=3;
731   }
732   for (i = 0; i < sizeof(signames)/sizeof(struct signame); i++)
733     if (!pidstr) xputs(signames[i].name);
734     else if (!strcasecmp(pidstr, signames[i].name)) return signames[i].num;
735
736   return -1;
737 }
738
739 char *num_to_sig(int sig)
740 {
741   int i;
742
743   for (i=0; i<sizeof(signames)/sizeof(struct signame); i++)
744     if (signames[i].num == sig) return signames[i].name;
745   return NULL;
746 }
747
748 // premute mode bits based on posix mode strings.
749 mode_t string_to_mode(char *modestr, mode_t mode)
750 {
751   char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
752        *s, *str = modestr;
753   mode_t extrabits = mode & ~(07777);
754
755   // Handle octal mode
756   if (isdigit(*str)) {
757     mode = estrtol(str, &s, 8);
758     if (errno || *s || (mode & ~(07777))) goto barf;
759
760     return mode | extrabits;
761   }
762
763   // Gaze into the bin of permission...
764   for (;;) {
765     int i, j, dowho, dohow, dowhat, amask;
766
767     dowho = dohow = dowhat = amask = 0;
768
769     // Find the who, how, and what stanzas, in that order
770     while (*str && (s = strchr(whos, *str))) {
771       dowho |= 1<<(s-whos);
772       str++;
773     }
774     // If who isn't specified, like "a" but honoring umask.
775     if (!dowho) {
776       dowho = 8;
777       umask(amask=umask(0));
778     }
779     if (!*str || !(s = strchr(hows, *str))) goto barf;
780     dohow = *(str++);
781
782     if (!dohow) goto barf;
783     while (*str && (s = strchr(whats, *str))) {
784       dowhat |= 1<<(s-whats);
785       str++;
786     }
787
788     // Convert X to x for directory or if already executable somewhere
789     if ((dowhat&32) &&  (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
790
791     // Copy mode from another category?
792     if (!dowhat && *str && (s = strchr(whys, *str))) {
793       dowhat = (mode>>(3*(s-whys)))&7;
794       str++;
795     }
796
797     // Are we ready to do a thing yet?
798     if (*str && *(str++) != ',') goto barf;
799
800     // Ok, apply the bits to the mode.
801     for (i=0; i<4; i++) {
802       for (j=0; j<3; j++) {
803         mode_t bit = 0;
804         int where = 1<<((3*i)+j);
805
806         if (amask & where) continue;
807
808         // Figure out new value at this location
809         if (i == 3) {
810           // suid/sticky bit.
811           if (j) {
812             if ((dowhat & 8) && (dowho&(8|(1<<i)))) bit++;
813           } else if (dowhat & 16) bit++;
814         } else {
815           if (!(dowho&(8|(1<<i)))) continue;
816           if (dowhat&(1<<j)) bit++;
817         }
818
819         // When selection active, modify bit
820
821         if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
822         if (bit && dohow != '-') mode |= where;
823       }
824     }
825
826     if (!*str) break;
827   }
828
829   return mode|extrabits;
830 barf:
831   error_exit("bad mode '%s'", modestr);
832 }
833
834 // Format access mode into a drwxrwxrwx string
835 void mode_to_string(mode_t mode, char *buf)
836 {
837   char c, d;
838   int i, bit;
839
840   buf[10]=0;
841   for (i=0; i<9; i++) {
842     bit = mode & (1<<i);
843     c = i%3;
844     if (!c && (mode & (1<<((d=i/3)+9)))) {
845       c = "tss"[d];
846       if (!bit) c &= ~0x20;
847     } else c = bit ? "xwr"[c] : '-';
848     buf[9-i] = c;
849   }
850
851   if (S_ISDIR(mode)) c = 'd';
852   else if (S_ISBLK(mode)) c = 'b';
853   else if (S_ISCHR(mode)) c = 'c';
854   else if (S_ISLNK(mode)) c = 'l';
855   else if (S_ISFIFO(mode)) c = 'p';
856   else if (S_ISSOCK(mode)) c = 's';
857   else c = '-';
858   *buf = c;
859 }
860
861 char *basename_r(char *name)
862 {
863   char *s = strrchr(name, '/');
864
865   if (s) return s+1;
866   return name;
867 }
868
869 // Execute a callback for each PID that matches a process name from a list.
870 void names_to_pid(char **names, int (*callback)(pid_t pid, char *name))
871 {
872   DIR *dp;
873   struct dirent *entry;
874
875   if (!(dp = opendir("/proc"))) perror_exit("opendir");
876
877   while ((entry = readdir(dp))) {
878     unsigned u;
879     char *cmd, **curname;
880
881     if (!(u = atoi(entry->d_name))) continue;
882     sprintf(libbuf, "/proc/%u/cmdline", u);
883     if (!(cmd = readfile(libbuf, libbuf, sizeof(libbuf)))) continue;
884
885     for (curname = names; *curname; curname++)
886       if (**curname == '/' ? !strcmp(cmd, *curname)
887           : !strcmp(basename_r(cmd), basename_r(*curname)))
888         if (callback(u, *curname)) break;
889     if (*curname) break;
890   }
891   closedir(dp);
892 }
893
894 // display first few digits of number with power of two units
895 int human_readable(char *buf, unsigned long long num, int style)
896 {
897   unsigned long long snap = 0;
898   int len, unit, divisor = (style&HR_1000) ? 1000 : 1024;
899
900   // Divide rounding up until we have 3 or fewer digits. Since the part we
901   // print is decimal, the test is 999 even when we divide by 1024.
902   // We can't run out of units because 2<<64 is 18 exabytes.
903   // test 5675 is 5.5k not 5.6k.
904   for (unit = 0; num > 999; unit++) num = ((snap = num)+(divisor/2))/divisor;
905   len = sprintf(buf, "%llu", num);
906   if (unit && len == 1) {
907     // Redo rounding for 1.2M case, this works with and without HR_1000.
908     num = snap/divisor;
909     snap -= num*divisor;
910     snap = ((snap*100)+50)/divisor;
911     snap /= 10;
912     len = sprintf(buf, "%llu.%llu", num, snap);
913   }
914   if (style & HR_SPACE) buf[len++] = ' ';
915   if (unit) {
916     unit = " kMGTPE"[unit];
917
918     if (!(style&HR_1000)) unit = toupper(unit);
919     buf[len++] = unit;
920   } else if (style & HR_B) buf[len++] = 'B';
921   buf[len] = 0;
922
923   return len;
924 }
925
926 // The qsort man page says you can use alphasort, the posix committee
927 // disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
928 // So just do our own. (The const is entirely to humor the stupid compiler.)
929 int qstrcmp(const void *a, const void *b)
930 {
931   return strcmp(*(char **)a, *(char **)b);
932 }
933
934 int xpoll(struct pollfd *fds, int nfds, int timeout)
935 {
936   int i;
937
938   for (;;) {
939     if (0>(i = poll(fds, nfds, timeout))) {
940       if (errno != EINTR && errno != ENOMEM) perror_exit("xpoll");
941       else if (timeout>0) timeout--;
942     } else return i;
943   }
944 }