toybox/lib/lib.c
<<
>>
Prefs
   1/* lib.c - various reusable stuff.
   2 *
   3 * Copyright 2006 Rob Landley <rob@landley.net>
   4 */
   5
   6#define SYSLOG_NAMES
   7#include "toys.h"
   8
   9void verror_msg(char *msg, int err, va_list va)
  10{
  11  char *s = ": %s";
  12
  13  fprintf(stderr, "%s: ", toys.which->name);
  14  if (msg) vfprintf(stderr, msg, va);
  15  else s+=2;
  16  if (err>0) fprintf(stderr, s, strerror(err));
  17  if (err<0 && CFG_TOYBOX_HELP)
  18    fprintf(stderr, " (see \"%s --help\")", toys.which->name);
  19  if (msg || err) putc('\n', stderr);
  20  if (!toys.exitval) toys.exitval++;
  21}
  22
  23// These functions don't collapse together because of the va_stuff.
  24
  25void error_msg(char *msg, ...)
  26{
  27  va_list va;
  28
  29  va_start(va, msg);
  30  verror_msg(msg, 0, va);
  31  va_end(va);
  32}
  33
  34void perror_msg(char *msg, ...)
  35{
  36  va_list va;
  37
  38  va_start(va, msg);
  39  verror_msg(msg, errno, va);
  40  va_end(va);
  41}
  42
  43// Die with an error message.
  44void error_exit(char *msg, ...)
  45{
  46  va_list va;
  47
  48  va_start(va, msg);
  49  verror_msg(msg, 0, va);
  50  va_end(va);
  51
  52  xexit();
  53}
  54
  55// Die with an error message and strerror(errno)
  56void perror_exit(char *msg, ...)
  57{
  58  // Die silently if our pipeline exited.
  59  if (errno != EPIPE) {
  60    va_list va;
  61
  62    va_start(va, msg);
  63    verror_msg(msg, errno, va);
  64    va_end(va);
  65  }
  66
  67  xexit();
  68}
  69
  70// Exit with an error message after showing help text.
  71void help_exit(char *msg, ...)
  72{
  73  va_list va;
  74
  75  if (!msg) show_help(stdout, 1);
  76  else {
  77    va_start(va, msg);
  78    verror_msg(msg, -1, va);
  79    va_end(va);
  80  }
  81
  82  xexit();
  83}
  84
  85// If you want to explicitly disable the printf() behavior (because you're
  86// printing user-supplied data, or because android's static checker produces
  87// false positives for 'char *s = x ? "blah1" : "blah2"; printf(s);' and it's
  88// -Werror there for policy reasons).
  89void error_msg_raw(char *msg)
  90{
  91  error_msg("%s", msg);
  92}
  93
  94void perror_msg_raw(char *msg)
  95{
  96  perror_msg("%s", msg);
  97}
  98
  99void error_exit_raw(char *msg)
 100{
 101  error_exit("%s", msg);
 102}
 103
 104void perror_exit_raw(char *msg)
 105{
 106  perror_exit("%s", msg);
 107}
 108
 109// Keep reading until full or EOF
 110ssize_t readall(int fd, void *buf, size_t len)
 111{
 112  size_t count = 0;
 113
 114  while (count<len) {
 115    int i = read(fd, (char *)buf+count, len-count);
 116    if (!i) break;
 117    if (i<0) return i;
 118    count += i;
 119  }
 120
 121  return count;
 122}
 123
 124// Keep writing until done or EOF
 125ssize_t writeall(int fd, void *buf, size_t len)
 126{
 127  size_t count = 0;
 128
 129  while (count<len) {
 130    int i = write(fd, count+(char *)buf, len-count);
 131    if (i<1) return i;
 132    count += i;
 133  }
 134
 135  return count;
 136}
 137
 138// skip this many bytes of input. Return 0 for success, >0 means this much
 139// left after input skipped.
 140off_t lskip(int fd, off_t offset)
 141{
 142  off_t cur = lseek(fd, 0, SEEK_CUR);
 143
 144  if (cur != -1) {
 145    off_t end = lseek(fd, 0, SEEK_END) - cur;
 146
 147    if (end > 0 && end < offset) return offset - end;
 148    end = offset+cur;
 149    if (end == lseek(fd, end, SEEK_SET)) return 0;
 150    perror_exit("lseek");
 151  }
 152
 153  while (offset>0) {
 154    int try = offset>sizeof(libbuf) ? sizeof(libbuf) : offset, or;
 155
 156    or = readall(fd, libbuf, try);
 157    if (or < 0) perror_exit("lskip to %lld", (long long)offset);
 158    else offset -= or;
 159    if (or < try) break;
 160  }
 161
 162  return offset;
 163}
 164
 165// flags:
 166// MKPATHAT_MKLAST  make last dir (with mode lastmode, else skips last part)
 167// MKPATHAT_MAKE    make leading dirs (it's ok if they already exist)
 168// MKPATHAT_VERBOSE Print what got created to stderr
 169// returns 0 = path ok, 1 = error
 170int mkpathat(int atfd, char *dir, mode_t lastmode, int flags)
 171{
 172  struct stat buf;
 173  char *s;
 174
 175  // mkdir -p one/two/three is not an error if the path already exists,
 176  // but is if "three" is a file. The others we dereference and catch
 177  // not-a-directory along the way, but the last one we must explicitly
 178  // test for. Might as well do it up front.
 179
 180  if (!fstatat(atfd, dir, &buf, 0)) {
 181    if ((flags&MKPATHAT_MKLAST) && !S_ISDIR(buf.st_mode)) {
 182      errno = EEXIST;
 183      return 1;
 184    } else return 0;
 185  }
 186
 187  for (s = dir; ;s++) {
 188    char save = 0;
 189    mode_t mode = (0777&~toys.old_umask)|0300;
 190
 191    // find next '/', but don't try to mkdir "" at start of absolute path
 192    if (*s == '/' && (flags&MKPATHAT_MAKE) && s != dir) {
 193      save = *s;
 194      *s = 0;
 195    } else if (*s) continue;
 196
 197    // Use the mode from the -m option only for the last directory.
 198    if (!save) {
 199      if (flags&MKPATHAT_MKLAST) mode = lastmode;
 200      else break;
 201    }
 202
 203    if (mkdirat(atfd, dir, mode)) {
 204      if (!(flags&MKPATHAT_MAKE) || errno != EEXIST) return 1;
 205    } else if (flags&MKPATHAT_VERBOSE)
 206      fprintf(stderr, "%s: created directory '%s'\n", toys.which->name, dir);
 207
 208    if (!(*s = save)) break;
 209  }
 210
 211  return 0;
 212}
 213
 214// The common case
 215int mkpath(char *dir)
 216{
 217  return mkpathat(AT_FDCWD, dir, 0, MKPATHAT_MAKE);
 218}
 219
 220// Split a path into linked list of components, tracking head and tail of list.
 221// Assigns head of list to *list, returns address of ->next entry to extend list
 222// Filters out // entries with no contents.
 223struct string_list **splitpath(char *path, struct string_list **list)
 224{
 225  char *new = path;
 226
 227  *list = 0;
 228  do {
 229    int len;
 230
 231    if (*path && *path != '/') continue;
 232    len = path-new;
 233    if (len > 0) {
 234      *list = xmalloc(sizeof(struct string_list) + len + 1);
 235      (*list)->next = 0;
 236      memcpy((*list)->str, new, len);
 237      (*list)->str[len] = 0;
 238      list = &(*list)->next;
 239    }
 240    new = path+1;
 241  } while (*path++);
 242
 243  return list;
 244}
 245
 246// Find all file in a colon-separated path with access type "type" (generally
 247// X_OK or R_OK).  Returns a list of absolute paths to each file found, in
 248// order.
 249
 250struct string_list *find_in_path(char *path, char *filename)
 251{
 252  struct string_list *rlist = NULL, **prlist=&rlist;
 253  char *cwd;
 254
 255  if (!path) return 0;
 256
 257  cwd = xgetcwd();
 258  for (;;) {
 259    char *res, *next = strchr(path, ':');
 260    int len = next ? next-path : strlen(path);
 261    struct string_list *rnext;
 262    struct stat st;
 263
 264    rnext = xmalloc(sizeof(void *) + strlen(filename)
 265      + (len ? len : strlen(cwd)) + 2);
 266    if (!len) sprintf(rnext->str, "%s/%s", cwd, filename);
 267    else {
 268      memcpy(res = rnext->str, path, len);
 269      res += len;
 270      *(res++) = '/';
 271      strcpy(res, filename);
 272    }
 273
 274    // Confirm it's not a directory.
 275    if (!stat(rnext->str, &st) && S_ISREG(st.st_mode)) {
 276      *prlist = rnext;
 277      rnext->next = NULL;
 278      prlist = &(rnext->next);
 279    } else free(rnext);
 280
 281    if (!next) break;
 282    path += len;
 283    path++;
 284  }
 285  free(cwd);
 286
 287  return rlist;
 288}
 289
 290long long estrtol(char *str, char **end, int base)
 291{
 292  errno = 0;
 293
 294  return strtoll(str, end, base);
 295}
 296
 297long long xstrtol(char *str, char **end, int base)
 298{
 299  long long l = estrtol(str, end, base);
 300
 301  if (errno) perror_exit_raw(str);
 302
 303  return l;
 304}
 305
 306// atol() with the kilo/mega/giga/tera/peta/exa extensions, plus word and block.
 307// (zetta and yotta don't fit in 64 bits.)
 308long long atolx(char *numstr)
 309{
 310  char *c = numstr, *suffixes="cwbkmgtpe", *end;
 311  long long val;
 312
 313  val = xstrtol(numstr, &c, 0);
 314  if (c != numstr && *c && (end = strchr(suffixes, tolower(*c)))) {
 315    int shift = end-suffixes-2;
 316    ++c;
 317    if (shift==-1) val *= 2;
 318    else if (!shift) val *= 512;
 319    else if (shift>0) {
 320      if (*c && tolower(*c++)=='d') while (shift--) val *= 1000;
 321      else val *= 1LL<<(shift*10);
 322    }
 323  }
 324  while (isspace(*c)) c++;
 325  if (c==numstr || *c) error_exit("not integer: %s", numstr);
 326
 327  return val;
 328}
 329
 330long long atolx_range(char *numstr, long long low, long long high)
 331{
 332  long long val = atolx(numstr);
 333
 334  if (val < low) error_exit("%lld < %lld", val, low);
 335  if (val > high) error_exit("%lld > %lld", val, high);
 336
 337  return val;
 338}
 339
 340int stridx(char *haystack, char needle)
 341{
 342  char *off;
 343
 344  if (!needle) return -1;
 345  off = strchr(haystack, needle);
 346  if (!off) return -1;
 347
 348  return off-haystack;
 349}
 350
 351// Convert wc to utf8, returning bytes written. Does not null terminate.
 352int wctoutf8(char *s, unsigned wc)
 353{
 354  int len = (wc>0x7ff)+(wc>0xffff), i;
 355
 356  if (wc<128) {
 357    *s = wc;
 358    return 1;
 359  } else {
 360    i = len;
 361    do {
 362      s[1+i] = 0x80+(wc&0x3f);
 363      wc >>= 6;
 364    } while (i--);
 365    *s = (((signed char) 0x80) >> (len+1)) | wc;
 366  }
 367
 368  return 2+len;
 369}
 370
 371// Convert utf8 sequence to a unicode wide character
 372// returns bytes consumed, or -1 if err, or -2 if need more data.
 373int utf8towc(unsigned *wc, char *str, unsigned len)
 374{
 375  unsigned result, mask, first;
 376  char *s, c;
 377
 378  // fast path ASCII
 379  if (len && *str<128) return !!(*wc = *str);
 380
 381  result = first = *(s = str++);
 382  if (result<0xc2 || result>0xf4) return -1;
 383  for (mask = 6; (first&0xc0)==0xc0; mask += 5, first <<= 1) {
 384    if (!--len) return -2;
 385    if (((c = *(str++))&0xc0) != 0x80) return -1;
 386    result = (result<<6)|(c&0x3f);
 387  }
 388  result &= (1<<mask)-1;
 389  c = str-s;
 390
 391  // Avoid overlong encodings
 392  if (result<(unsigned []){0x80,0x800,0x10000}[c-2]) return -1;
 393
 394  // Limit unicode so it can't encode anything UTF-16 can't.
 395  if (result>0x10ffff || (result>=0xd800 && result<=0xdfff)) return -1;
 396  *wc = result;
 397
 398  return str-s;
 399}
 400
 401// Convert string to lower case, utf8 aware.
 402char *strlower(char *s)
 403{
 404  char *try, *new;
 405  int len, mlen = (strlen(s)|7)+9;
 406  unsigned c;
 407
 408  try = new = xmalloc(mlen);
 409
 410  while (*s) {
 411
 412    if (1>(len = utf8towc(&c, s, MB_CUR_MAX))) {
 413      *(new++) = *(s++);
 414
 415      continue;
 416    }
 417
 418    s += len;
 419    // squash title case too
 420    c = towlower(c);
 421
 422    // if we had a valid utf8 sequence, convert it to lower case, and can't
 423    // encode back to utf8, something is wrong with your libc. But just
 424    // in case somebody finds an exploit...
 425    len = wcrtomb(new, c, 0);
 426    if (len < 1) error_exit("bad utf8 %x", (int)c);
 427    new += len;
 428
 429    // Case conversion can expand utf8 representation, but with extra mlen
 430    // space above we should basically never need to realloc
 431    if (mlen+4 > (len = new-try)) continue;
 432    try = xrealloc(try, mlen = len+16);
 433    new = try+len;
 434  }
 435  *new = 0;
 436
 437  return try;
 438}
 439
 440// strstr but returns pointer after match
 441char *strafter(char *haystack, char *needle)
 442{
 443  char *s = strstr(haystack, needle);
 444
 445  return s ? s+strlen(needle) : s;
 446}
 447
 448// Remove trailing \n
 449char *chomp(char *s)
 450{
 451  char *p = strrchr(s, '\n');
 452
 453  if (p && !p[1]) *p = 0;
 454  return s;
 455}
 456
 457int unescape(char c)
 458{
 459  char *from = "\\abefnrtv", *to = "\\\a\b\033\f\n\r\t\v";
 460  int idx = stridx(from, c);
 461
 462  return (idx == -1) ? 0 : to[idx];
 463}
 464
 465// parse next character advancing pointer. echo requires leading 0 in octal esc
 466int unescape2(char **c, int echo)
 467{
 468  int idx = *((*c)++), i, off;
 469
 470  if (idx != '\\' || !**c) return idx;
 471  if (**c == 'c') return 31&*(++*c);
 472  for (i = 0; i<4; i++) {
 473    if (sscanf(*c, (char *[]){"0%3o%n"+!echo, "x%2x%n", "u%4x%n", "U%6x%n"}[i],
 474        &idx, &off) > 0)
 475    {
 476      *c += off;
 477
 478      return idx;
 479    }
 480  }
 481
 482  if (-1 == (idx = stridx("\\abeEfnrtv'\"?0", **c))) return '\\';
 483  ++*c;
 484
 485  return "\\\a\b\033\033\f\n\r\t\v'\"?"[idx];
 486}
 487
 488// If string ends with suffix return pointer to start of suffix in string,
 489// else NULL
 490char *strend(char *str, char *suffix)
 491{
 492  long a = strlen(str), b = strlen(suffix);
 493
 494  if (a>b && !strcmp(str += a-b, suffix)) return str;
 495
 496  return 0;
 497}
 498
 499// If *a starts with b, advance *a past it and return 1, else return 0;
 500int strstart(char **a, char *b)
 501{
 502  char *c = *a;
 503
 504  while (*b && *c == *b) b++, c++;
 505  if (!*b) *a = c;
 506
 507  return !*b;
 508}
 509
 510// If *a starts with b, advance *a past it and return 1, else return 0;
 511int strcasestart(char **a, char *b)
 512{
 513  int len = strlen(b), i = !strncasecmp(*a, b, len);
 514
 515  if (i) *a += len;
 516
 517  return i;
 518}
 519
 520// Return how long the file at fd is, if there's any way to determine it.
 521off_t fdlength(int fd)
 522{
 523  struct stat st;
 524  off_t base = 0, range = 1, expand = 1, old;
 525  unsigned long long size;
 526
 527  if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
 528
 529  // If the ioctl works for this, return it.
 530  if (get_block_device_size(fd, &size)) return size;
 531
 532  // If not, do a binary search for the last location we can read.  (Some
 533  // block devices don't do BLKGETSIZE right.)  This should probably have
 534  // a CONFIG option...
 535  old = lseek(fd, 0, SEEK_CUR);
 536  do {
 537    char temp;
 538    off_t pos = base + range / 2;
 539
 540    if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
 541      off_t delta = (pos + 1) - base;
 542
 543      base += delta;
 544      if (expand) range = (expand <<= 1) - base;
 545      else range -= delta;
 546    } else {
 547      expand = 0;
 548      range = pos - base;
 549    }
 550  } while (range > 0);
 551
 552  lseek(fd, old, SEEK_SET);
 553
 554  return base;
 555}
 556
 557char *readfd(int fd, char *ibuf, off_t *plen)
 558{
 559  off_t len, rlen;
 560  char *buf, *rbuf;
 561
 562  // Unsafe to probe for size with a supplied buffer, don't ever do that.
 563  if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
 564
 565  // If we dunno the length, probe it. If we can't probe, start with 1 page.
 566  if (!*plen) {
 567    if ((len = fdlength(fd))>0) *plen = len;
 568    else len = 4096;
 569  } else len = *plen-1;
 570
 571  if (!ibuf) buf = xmalloc(len+1);
 572  else buf = ibuf;
 573
 574  for (rbuf = buf;;) {
 575    rlen = readall(fd, rbuf, len);
 576    if (*plen || rlen<len) break;
 577
 578    // If reading unknown size, expand buffer by 1.5 each time we fill it up.
 579    rlen += rbuf-buf;
 580    buf = xrealloc(buf, len = (rlen*3)/2);
 581    rbuf = buf+rlen;
 582    len -= rlen;
 583  }
 584  *plen = len = rlen+(rbuf-buf);
 585
 586  if (rlen<0) {
 587    if (ibuf != buf) free(buf);
 588    buf = 0;
 589  } else buf[len] = 0;
 590
 591  return buf;
 592}
 593
 594// Read contents of file as a single nul-terminated string.
 595// measure file size if !len, allocate buffer if !buf
 596// Existing buffers need len in *plen
 597// Returns amount of data read in *plen
 598char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
 599{
 600  if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0;
 601
 602  ibuf = readfd(dirfd, ibuf, plen);
 603  close(dirfd);
 604
 605  return ibuf;
 606}
 607
 608char *readfile(char *name, char *ibuf, off_t len)
 609{
 610  return readfileat(AT_FDCWD, name, ibuf, &len);
 611}
 612
 613// Sleep for this many thousandths of a second
 614void msleep(long milliseconds)
 615{
 616  struct timespec ts;
 617
 618  ts.tv_sec = milliseconds/1000;
 619  ts.tv_nsec = (milliseconds%1000)*1000000;
 620  nanosleep(&ts, &ts);
 621}
 622
 623// Adjust timespec by nanosecond offset
 624void nanomove(struct timespec *ts, long long offset)
 625{
 626  long long nano = ts->tv_nsec + offset, secs = nano/1000000000;
 627
 628  ts->tv_sec += secs;
 629  nano %= 1000000000;
 630  if (nano<0) {
 631    ts->tv_sec--;
 632    nano += 1000000000;
 633  }
 634  ts->tv_nsec = nano;
 635}
 636
 637// return difference between two timespecs in nanosecs
 638long long nanodiff(struct timespec *old, struct timespec *new)
 639{
 640  return (new->tv_sec - old->tv_sec)*1000000000LL+(new->tv_nsec - old->tv_nsec);
 641}
 642
 643// return 1<<x of highest bit set
 644int highest_bit(unsigned long l)
 645{
 646  int i;
 647
 648  for (i = 0; l; i++) l >>= 1;
 649
 650  return i-1;
 651}
 652
 653// Inefficient, but deals with unaligned access
 654int64_t peek_le(void *ptr, unsigned size)
 655{
 656  int64_t ret = 0;
 657  char *c = ptr;
 658  int i;
 659
 660  for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
 661  return ret;
 662}
 663
 664int64_t peek_be(void *ptr, unsigned size)
 665{
 666  int64_t ret = 0;
 667  char *c = ptr;
 668  int i;
 669
 670  for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
 671  return ret;
 672}
 673
 674int64_t peek(void *ptr, unsigned size)
 675{
 676  return (IS_BIG_ENDIAN ? peek_be : peek_le)(ptr, size);
 677}
 678
 679void poke_le(void *ptr, long long val, unsigned size)
 680{
 681  char *c = ptr;
 682
 683  while (size--) {
 684    *c++ = val&255;
 685    val >>= 8;
 686  }
 687}
 688
 689void poke_be(void *ptr, long long val, unsigned size)
 690{
 691  char *c = ptr + size;
 692
 693  while (size--) {
 694    *--c = val&255;
 695    val >>=8;
 696  }
 697}
 698
 699void poke(void *ptr, long long val, unsigned size)
 700{
 701  (IS_BIG_ENDIAN ? poke_be : poke_le)(ptr, val, size);
 702}
 703
 704// Iterate through an array of files, opening each one and calling a function
 705// on that filehandle and name. The special filename "-" means stdin if
 706// flags is O_RDONLY, stdout otherwise. An empty argument list calls
 707// function() on just stdin/stdout.
 708//
 709// Note: pass O_CLOEXEC to automatically close filehandles when function()
 710// returns, otherwise filehandles must be closed by function().
 711// pass WARN_ONLY to produce warning messages about files it couldn't
 712// open/create, and skip them. Otherwise function is called with fd -1.
 713void loopfiles_rw(char **argv, int flags, int permissions,
 714  void (*function)(int fd, char *name))
 715{
 716  int fd, failok = !(flags&WARN_ONLY);
 717
 718  flags &= ~WARN_ONLY;
 719
 720  // If no arguments, read from stdin.
 721  if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
 722  else do {
 723    // Filename "-" means read from stdin.
 724    // Inability to open a file prints a warning, but doesn't exit.
 725
 726    if (!strcmp(*argv, "-")) fd = 0;
 727    else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
 728      perror_msg_raw(*argv);
 729      continue;
 730    }
 731    function(fd, *argv);
 732    if ((flags & O_CLOEXEC) && fd) close(fd);
 733  } while (*++argv);
 734}
 735
 736// Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
 737void loopfiles(char **argv, void (*function)(int fd, char *name))
 738{
 739  loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
 740}
 741
 742// glue to call do_lines() from loopfiles
 743static void (*do_lines_bridge)(char **pline, long len);
 744static void loopfile_lines_bridge(int fd, char *name)
 745{
 746  do_lines(fd, '\n', do_lines_bridge);
 747}
 748
 749void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
 750{
 751  do_lines_bridge = function;
 752  // No O_CLOEXEC because we need to call fclose.
 753  loopfiles_rw(argv, O_RDONLY|WARN_ONLY, 0, loopfile_lines_bridge);
 754}
 755
 756// Slow, but small.
 757char *get_line(int fd)
 758{
 759  char c, *buf = NULL;
 760  long len = 0;
 761
 762  for (;;) {
 763    if (1>read(fd, &c, 1)) break;
 764    if (!(len & 63)) buf=xrealloc(buf, len+65);
 765    if ((buf[len++]=c) == '\n') break;
 766  }
 767  if (buf) {
 768    buf[len]=0;
 769    if (buf[--len]=='\n') buf[len]=0;
 770  }
 771
 772  return buf;
 773}
 774
 775int wfchmodat(int fd, char *name, mode_t mode)
 776{
 777  int rc = fchmodat(fd, name, mode, 0);
 778
 779  if (rc) {
 780    perror_msg("chmod '%s' to %04o", name, mode);
 781    toys.exitval=1;
 782  }
 783  return rc;
 784}
 785
 786static char *tempfile2zap;
 787static void tempfile_handler(void)
 788{
 789  if (1 < (long)tempfile2zap) unlink(tempfile2zap);
 790}
 791
 792// Open a temporary file to copy an existing file into.
 793int copy_tempfile(int fdin, char *name, char **tempname)
 794{
 795  struct stat statbuf;
 796  int fd = xtempfile(name, tempname), ignored __attribute__((__unused__));
 797
 798  // Record tempfile for exit cleanup if interrupted
 799  if (!tempfile2zap) sigatexit(tempfile_handler);
 800  tempfile2zap = *tempname;
 801
 802  // Set permissions of output file.
 803  if (!fstat(fdin, &statbuf)) fchmod(fd, statbuf.st_mode);
 804
 805  // We chmod before chown, which strips the suid bit. Caller has to explicitly
 806  // switch it back on if they want to keep suid.
 807
 808  // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
 809  // this but it's _supposed_ to fail when we're not root.
 810  ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
 811
 812  return fd;
 813}
 814
 815// Abort the copy and delete the temporary file.
 816void delete_tempfile(int fdin, int fdout, char **tempname)
 817{
 818  close(fdin);
 819  close(fdout);
 820  if (*tempname) unlink(*tempname);
 821  tempfile2zap = (char *)1;
 822  free(*tempname);
 823  *tempname = NULL;
 824}
 825
 826// Copy the rest of the data and replace the original with the copy.
 827void replace_tempfile(int fdin, int fdout, char **tempname)
 828{
 829  char *temp = xstrdup(*tempname);
 830
 831  temp[strlen(temp)-6]=0;
 832  if (fdin != -1) {
 833    xsendfile(fdin, fdout);
 834    xclose(fdin);
 835  }
 836  xclose(fdout);
 837  xrename(*tempname, temp);
 838  tempfile2zap = (char *)1;
 839  free(*tempname);
 840  free(temp);
 841  *tempname = NULL;
 842}
 843
 844// Create a 256 entry CRC32 lookup table.
 845
 846void crc_init(unsigned int *crc_table, int little_endian)
 847{
 848  unsigned int i;
 849
 850  // Init the CRC32 table (big endian)
 851  for (i=0; i<256; i++) {
 852    unsigned int j, c = little_endian ? i : i<<24;
 853    for (j=8; j; j--)
 854      if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
 855      else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
 856    crc_table[i] = c;
 857  }
 858}
 859
 860// Init base64 table
 861
 862void base64_init(char *p)
 863{
 864  int i;
 865
 866  for (i = 'A'; i != ':'; i++) {
 867    if (i == 'Z'+1) i = 'a';
 868    if (i == 'z'+1) i = '0';
 869    *(p++) = i;
 870  }
 871  *(p++) = '+';
 872  *(p++) = '/';
 873}
 874
 875int yesno(int def)
 876{
 877  return fyesno(stdin, def);
 878}
 879
 880int fyesno(FILE *in, int def)
 881{
 882  char buf;
 883
 884  fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
 885  fflush(stderr);
 886  while (fread(&buf, 1, 1, in)) {
 887    int new;
 888
 889    // The letter changes the value, the newline (or space) returns it.
 890    if (isspace(buf)) break;
 891    if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
 892  }
 893
 894  return def;
 895}
 896
 897// Handler that sets toys.signal, and writes to toys.signalfd if set
 898void generic_signal(int sig)
 899{
 900  if (toys.signalfd) {
 901    char c = sig;
 902
 903    writeall(toys.signalfd, &c, 1);
 904  }
 905  toys.signal = sig;
 906}
 907
 908void exit_signal(int sig)
 909{
 910  if (sig) toys.exitval = sig|128;
 911  xexit();
 912}
 913
 914// Install an atexit handler. Also install the same handler on every signal
 915// that defaults to killing the process, calling the handler on the way out.
 916// Calling multiple times adds the handlers to a list, to be called in LIFO
 917// order.
 918void sigatexit(void *handler)
 919{
 920  struct arg_list *al = 0;
 921
 922  xsignal_all_killers(handler ? exit_signal : SIG_DFL);
 923  if (handler) {
 924    al = xmalloc(sizeof(struct arg_list));
 925    al->next = toys.xexit;
 926    al->arg = handler;
 927  } else llist_traverse(toys.xexit, free);
 928  toys.xexit = al;
 929}
 930
 931// Output a nicely formatted table of all the signals.
 932void list_signals(void)
 933{
 934  int i = 0, count = 0;
 935  unsigned cols = 80;
 936  char *name;
 937
 938  terminal_size(&cols, 0);
 939  cols /= 16;
 940  for (; i<=NSIG; i++) {
 941    if ((name = num_to_sig(i))) {
 942      printf("%2d) SIG%-9s", i, name);
 943      if (++count % cols == 0) putchar('\n');
 944    }
 945  }
 946  putchar('\n');
 947}
 948
 949// premute mode bits based on posix mode strings.
 950mode_t string_to_mode(char *modestr, mode_t mode)
 951{
 952  char *whos = "ogua", *hows = "=+-", *whats = "xwrstX", *whys = "ogu",
 953       *s, *str = modestr;
 954  mode_t extrabits = mode & ~(07777);
 955
 956  // Handle octal mode
 957  if (isdigit(*str)) {
 958    mode = estrtol(str, &s, 8);
 959    if (errno || *s || (mode & ~(07777))) goto barf;
 960
 961    return mode | extrabits;
 962  }
 963
 964  // Gaze into the bin of permission...
 965  for (;;) {
 966    int i, j, dowho, dohow, dowhat, amask;
 967
 968    dowho = dohow = dowhat = amask = 0;
 969
 970    // Find the who, how, and what stanzas, in that order
 971    while (*str && (s = strchr(whos, *str))) {
 972      dowho |= 1<<(s-whos);
 973      str++;
 974    }
 975    // If who isn't specified, like "a" but honoring umask.
 976    if (!dowho) {
 977      dowho = 8;
 978      umask(amask = umask(0));
 979    }
 980
 981    // Repeated "hows" are allowed; something like "a=r+w+s" is valid.
 982    for (;;) {
 983      if (-1 == stridx(hows, dohow = *str)) goto barf;
 984      while (*++str && (s = strchr(whats, *str))) dowhat |= 1<<(s-whats);
 985
 986      // Convert X to x for directory or if already executable somewhere
 987      if ((dowhat&32) && (S_ISDIR(mode) || (mode&0111))) dowhat |= 1;
 988
 989      // Copy mode from another category?
 990      if (!dowhat && -1 != (i = stridx(whys, *str))) {
 991        dowhat = (mode>>(3*i))&7;
 992        str++;
 993      }
 994
 995      // Loop through what=xwrs and who=ogu to apply bits to the mode.
 996      for (i=0; i<4; i++) {
 997        for (j=0; j<3; j++) {
 998          mode_t bit = 0;
 999          int where = 1<<((3*i)+j);
1000
1001          if (amask & where) continue;
1002
1003          // Figure out new value at this location
1004          if (i == 3) {
1005            // suid and sticky
1006            if (!j) bit = dowhat&16; // o+s = t but a+s doesn't set t, hence t
1007            else if ((dowhat&8) && (dowho&(8|(1<<j)))) bit++;
1008          } else {
1009            if (!(dowho&(8|(1<<i)))) continue;
1010            else if (dowhat&(1<<j)) bit++;
1011          }
1012
1013          // When selection active, modify bit
1014          if (dohow == '=' || (bit && dohow == '-')) mode &= ~where;
1015          if (bit && dohow != '-') mode |= where;
1016        }
1017      }
1018      if (!*str) return mode|extrabits;
1019      if (*str == ',') {
1020        str++;
1021        break;
1022      }
1023    }
1024  }
1025
1026barf:
1027  error_exit("bad mode '%s'", modestr);
1028}
1029
1030// Format access mode into a drwxrwxrwx string
1031void mode_to_string(mode_t mode, char *buf)
1032{
1033  char c, d;
1034  int i, bit;
1035
1036  buf[10]=0;
1037  for (i=0; i<9; i++) {
1038    bit = mode & (1<<i);
1039    c = i%3;
1040    if (!c && (mode & (1<<((d=i/3)+9)))) {
1041      c = "tss"[d];
1042      if (!bit) c &= ~0x20;
1043    } else c = bit ? "xwr"[c] : '-';
1044    buf[9-i] = c;
1045  }
1046
1047  if (S_ISDIR(mode)) c = 'd';
1048  else if (S_ISBLK(mode)) c = 'b';
1049  else if (S_ISCHR(mode)) c = 'c';
1050  else if (S_ISLNK(mode)) c = 'l';
1051  else if (S_ISFIFO(mode)) c = 'p';
1052  else if (S_ISSOCK(mode)) c = 's';
1053  else c = '-';
1054  *buf = c;
1055}
1056
1057// basename() can modify its argument or return a pointer to a constant string
1058// This just gives after the last '/' or the whole stirng if no /
1059char *getbasename(char *name)
1060{
1061  char *s = strrchr(name, '/');
1062
1063  if (s) return s+1;
1064
1065  return name;
1066}
1067
1068// Return pointer to xabspath(file) if file is under dir, else 0
1069char *fileunderdir(char *file, char *dir)
1070{
1071  char *s1 = xabspath(dir, 1), *s2 = xabspath(file, -1), *ss = s2;
1072  int rc = s1 && s2 && strstart(&ss, s1) && (!s1[1] || s2[strlen(s1)] == '/');
1073
1074  free(s1);
1075  if (!rc) free(s2);
1076
1077  return rc ? s2 : 0;
1078}
1079
1080// return (malloced) relative path to get from "from" to "to"
1081char *relative_path(char *from, char *to)
1082{
1083  char *s, *ret = 0;
1084  int i, j, k;
1085
1086  if (!(from = xabspath(from, -1))) return 0;
1087  if (!(to = xabspath(to, -1))) goto error;
1088
1089  // skip common directories from root
1090  for (i = j = 0; from[i] && from[i] == to[i]; i++) if (to[i] == '/') j = i+1;
1091
1092  // count remaining destination directories
1093  for (i = j, k = 0; from[i]; i++) if (from[i] == '/') k++;
1094
1095  if (!k) ret = xstrdup(to+j);
1096  else {
1097    s = ret = xmprintf("%*c%s", 3*k, ' ', to+j);
1098    while (k--) memcpy(s+3*k, "../", 3);
1099  }
1100
1101error:
1102  free(from);
1103  free(to);
1104
1105  return ret;
1106}
1107
1108// Execute a callback for each PID that matches a process name from a list.
1109void names_to_pid(char **names, int (*callback)(pid_t pid, char *name),
1110    int scripts)
1111{
1112  DIR *dp;
1113  struct dirent *entry;
1114
1115  if (!(dp = opendir("/proc"))) perror_exit("no /proc");
1116
1117  while ((entry = readdir(dp))) {
1118    unsigned u = atoi(entry->d_name);
1119    char *cmd = 0, *comm = 0, **cur;
1120    off_t len;
1121
1122    if (!u) continue;
1123
1124    // Comm is original name of executable (argv[0] could be #! interpreter)
1125    // but it's limited to 15 characters
1126    if (scripts) {
1127      sprintf(libbuf, "/proc/%u/comm", u);
1128      len = sizeof(libbuf);
1129      if (!(comm = readfileat(AT_FDCWD, libbuf, libbuf, &len)) || !len)
1130        continue;
1131      if (libbuf[len-1] == '\n') libbuf[--len] = 0;
1132    }
1133
1134    for (cur = names; *cur; cur++) {
1135      struct stat st1, st2;
1136      char *bb = getbasename(*cur);
1137      off_t len = strlen(bb);
1138
1139      // Fast path: only matching a filename (no path) that fits in comm.
1140      // `len` must be 14 or less because with a full 15 bytes we don't
1141      // know whether the name fit or was truncated.
1142      if (scripts && len<=14 && bb==*cur && !strcmp(comm, bb)) goto match;
1143
1144      // If we have a path to existing file only match if same inode
1145      if (bb!=*cur && !stat(*cur, &st1)) {
1146        char buf[32];
1147
1148        sprintf(buf, "/proc/%u/exe", u);
1149        if (stat(buf, &st2)) continue;
1150        if (st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) continue;
1151        goto match;
1152      }
1153
1154      // Nope, gotta read command line to confirm
1155      if (!cmd) {
1156        sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1157        len = sizeof(libbuf)-17;
1158        if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1159        // readfile only guarantees one null terminator and we need two
1160        // (yes the kernel should do this for us, don't care)
1161        cmd[len] = 0;
1162      }
1163      if (!strcmp(bb, getbasename(cmd))) goto match;
1164      if (scripts && !strcmp(bb, getbasename(cmd+strlen(cmd)+1))) goto match;
1165      continue;
1166match:
1167      if (callback(u, *cur)) break;
1168    }
1169  }
1170  closedir(dp);
1171}
1172
1173// display first "dgt" many digits of number plus unit (kilo-exabytes)
1174int human_readable_long(char *buf, unsigned long long num, int dgt, int unit,
1175  int style)
1176{
1177  unsigned long long snap = 0;
1178  int len, divisor = (style&HR_1000) ? 1000 : 1024;
1179
1180  // Divide rounding up until we have 3 or fewer digits. Since the part we
1181  // print is decimal, the test is 999 even when we divide by 1024.
1182  // The largest unit we can detect is 1<<64 = 18 Exabytes, but we added
1183  // Zettabyte and Yottabyte in case "unit" starts above zero.
1184  for (;;unit++) {
1185    if ((len = snprintf(0, 0, "%llu", num))<=dgt) break;
1186    num = ((snap = num)+(divisor/2))/divisor;
1187  }
1188  if (CFG_TOYBOX_DEBUG && unit>8) return sprintf(buf, "%.*s", dgt, "TILT");
1189
1190  len = sprintf(buf, "%llu", num);
1191  if (!(style & HR_NODOT) && unit && len == 1) {
1192    // Redo rounding for 1.2M case, this works with and without HR_1000.
1193    num = snap/divisor;
1194    snap -= num*divisor;
1195    snap = ((snap*100)+50)/divisor;
1196    snap /= 10;
1197    len = sprintf(buf, "%llu.%llu", num, snap);
1198  }
1199  if (style & HR_SPACE) buf[len++] = ' ';
1200  if (unit) {
1201    unit = " kMGTPEZY"[unit];
1202
1203    if (!(style&HR_1000)) unit = toupper(unit);
1204    buf[len++] = unit;
1205  } else if (style & HR_B) buf[len++] = 'B';
1206  buf[len] = 0;
1207
1208  return len;
1209}
1210
1211// Give 3 digit estimate + units ala 999M or 1.7T
1212int human_readable(char *buf, unsigned long long num, int style)
1213{
1214  return human_readable_long(buf, num, 3, 0, style);
1215}
1216
1217// The qsort man page says you can use alphasort, the posix committee
1218// disagreed, and doubled down: http://austingroupbugs.net/view.php?id=142
1219// So just do our own. (The const is entirely to humor the stupid compiler.)
1220int qstrcmp(const void *a, const void *b)
1221{
1222  return strcmp(*(char **)a, *(char **)b);
1223}
1224
1225// See https://tools.ietf.org/html/rfc4122, specifically section 4.4
1226// "Algorithms for Creating a UUID from Truly Random or Pseudo-Random
1227// Numbers".
1228void create_uuid(char *uuid)
1229{
1230  // "Set all the ... bits to randomly (or pseudo-randomly) chosen values".
1231  xgetrandom(uuid, 16, 0);
1232
1233  // "Set the four most significant bits ... of the time_hi_and_version
1234  // field to the 4-bit version number [4]".
1235  uuid[6] = (uuid[6] & 0x0F) | 0x40;
1236  // "Set the two most significant bits (bits 6 and 7) of
1237  // clock_seq_hi_and_reserved to zero and one, respectively".
1238  uuid[8] = (uuid[8] & 0x3F) | 0x80;
1239}
1240
1241char *show_uuid(char *uuid)
1242{
1243  char *out = libbuf;
1244  int i;
1245
1246  for (i=0; i<16; i++) out+=sprintf(out, "-%02x"+!(0x550&(1<<i)), uuid[i]);
1247  *out = 0;
1248
1249  return libbuf;
1250}
1251
1252// Returns pointer to letter at end, 0 if none. *start = initial %
1253char *next_printf(char *s, char **start)
1254{
1255  for (; *s; s++) {
1256    if (*s != '%') continue;
1257    if (*++s == '%') continue;
1258    if (start) *start = s-1;
1259    while (0 <= stridx("0'#-+ ", *s)) s++;
1260    while (isdigit(*s)) s++;
1261    if (*s == '.') s++;
1262    while (isdigit(*s)) s++;
1263
1264    return s;
1265  }
1266
1267  return 0;
1268}
1269
1270// Return cached passwd entries.
1271struct passwd *bufgetpwuid(uid_t uid)
1272{
1273  struct pwuidbuf_list {
1274    struct pwuidbuf_list *next;
1275    struct passwd pw;
1276  } *list = 0;
1277  struct passwd *temp;
1278  static struct pwuidbuf_list *pwuidbuf;
1279  unsigned size = 256;
1280
1281  // If we already have this one, return it.
1282  for (list = pwuidbuf; list; list = list->next)
1283    if (list->pw.pw_uid == uid) return &(list->pw);
1284
1285  for (;;) {
1286    list = xrealloc(list, size *= 2);
1287    errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1288      size-sizeof(*list), &temp);
1289    if (errno != ERANGE) break;
1290  }
1291
1292  if (!temp) {
1293    free(list);
1294
1295    return 0;
1296  }
1297  list->next = pwuidbuf;
1298  pwuidbuf = list;
1299
1300  return &list->pw;
1301}
1302
1303// Return cached group entries.
1304struct group *bufgetgrgid(gid_t gid)
1305{
1306  struct grgidbuf_list {
1307    struct grgidbuf_list *next;
1308    struct group gr;
1309  } *list = 0;
1310  struct group *temp;
1311  static struct grgidbuf_list *grgidbuf;
1312  unsigned size = 256;
1313
1314  for (list = grgidbuf; list; list = list->next)
1315    if (list->gr.gr_gid == gid) return &(list->gr);
1316
1317  for (;;) {
1318    list = xrealloc(list, size *= 2);
1319    errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1320      size-sizeof(*list), &temp);
1321    if (errno != ERANGE) break;
1322  }
1323  if (!temp) {
1324    free(list);
1325
1326    return 0;
1327  }
1328  list->next = grgidbuf;
1329  grgidbuf = list;
1330
1331  return &list->gr;
1332}
1333
1334// Always null terminates, returns 0 for failure, len for success
1335int readlinkat0(int dirfd, char *path, char *buf, int len)
1336{
1337  if (!len) return 0;
1338
1339  len = readlinkat(dirfd, path, buf, len-1);
1340  if (len<0) len = 0;
1341  buf[len] = 0;
1342
1343  return len;
1344}
1345
1346int readlink0(char *path, char *buf, int len)
1347{
1348  return readlinkat0(AT_FDCWD, path, buf, len);
1349}
1350
1351// Do regex matching with len argument to handle embedded NUL bytes in string
1352int regexec0(regex_t *preg, char *string, long len, int nmatch,
1353  regmatch_t *pmatch, int eflags)
1354{
1355  regmatch_t backup;
1356
1357  if (!nmatch) pmatch = &backup;
1358  pmatch->rm_so = 0;
1359  pmatch->rm_eo = len;
1360  return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
1361}
1362
1363// Return user name or string representation of number, returned buffer
1364// lasts until next call.
1365char *getusername(uid_t uid)
1366{
1367  struct passwd *pw = bufgetpwuid(uid);
1368  static char unum[12];
1369
1370  sprintf(unum, "%u", (unsigned)uid);
1371  return pw ? pw->pw_name : unum;
1372}
1373
1374// Return group name or string representation of number, returned buffer
1375// lasts until next call.
1376char *getgroupname(gid_t gid)
1377{
1378  struct group *gr = bufgetgrgid(gid);
1379  static char gnum[12];
1380
1381  sprintf(gnum, "%u", (unsigned)gid);
1382  return gr ? gr->gr_name : gnum;
1383}
1384
1385// Iterate over lines in file, calling function. Function can write 0 to
1386// the line pointer if they want to keep it, or 1 to terminate processing,
1387// otherwise line is freed. Passed file descriptor is closed at the end.
1388// At EOF calls function(0, 0)
1389void do_lines(int fd, char delim, void (*call)(char **pline, long len))
1390{
1391  FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1392
1393  for (;;) {
1394    char *line = 0;
1395    ssize_t len;
1396
1397    len = getdelim(&line, (void *)&len, delim, fp);
1398    if (len > 0) {
1399      call(&line, len);
1400      if (line == (void *)1) break;
1401      free(line);
1402    } else break;
1403  }
1404  call(0, 0);
1405
1406  if (fd) fclose(fp);
1407}
1408
1409// Return unix time in milliseconds
1410long long millitime(void)
1411{
1412  struct timespec ts;
1413
1414  clock_gettime(CLOCK_MONOTONIC, &ts);
1415  return ts.tv_sec*1000+ts.tv_nsec/1000000;
1416}
1417
1418// Formats `ts` in ISO format ("2018-06-28 15:08:58.846386216 -0700").
1419char *format_iso_time(char *buf, size_t len, struct timespec *ts)
1420{
1421  char *s = buf;
1422
1423  s += strftime(s, len, "%F %T", localtime(&(ts->tv_sec)));
1424  s += sprintf(s, ".%09ld ", ts->tv_nsec);
1425  s += strftime(s, len-strlen(buf), "%z", localtime(&(ts->tv_sec)));
1426
1427  return buf;
1428}
1429
1430// Syslog with the openlog/closelog, autodetecting daemon status via no tty
1431
1432void loggit(int priority, char *format, ...)
1433{
1434  int i, facility = LOG_DAEMON;
1435  va_list va;
1436
1437  for (i = 0; i<3; i++) if (isatty(i)) facility = LOG_AUTH;
1438  openlog(toys.which->name, LOG_PID, facility);
1439  va_start(va, format);
1440  vsyslog(priority, format, va);
1441  va_end(va);
1442  closelog();
1443}
1444
1445// Calculate tar packet checksum, with cksum field treated as 8 spaces
1446unsigned tar_cksum(void *data)
1447{
1448  unsigned i, cksum = 8*' ';
1449
1450  for (i = 0; i<500; i += (i==147) ? 9 : 1) cksum += ((char *)data)[i];
1451
1452  return cksum;
1453}
1454
1455// is this a valid tar header?
1456int is_tar_header(void *pkt)
1457{
1458  char *p = pkt;
1459  int i = 0;
1460
1461  if (p[257] && memcmp("ustar", p+257, 5)) return 0;
1462  if (p[148] != '0' && p[148] != ' ') return 0;
1463  sscanf(p+148, "%8o", &i);
1464
1465  return i && tar_cksum(pkt) == i;
1466}
1467
1468char *elf_arch_name(int type)
1469{
1470  int i;
1471  // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
1472  // Names are linux/arch/ directory (sometimes before 32/64 bit merges)
1473  struct {int val; char *name;} types[] = {{0x9026, "alpha"}, {93, "arc"},
1474    {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
1475    {247, "bpf"}, {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
1476    {252, "csky"}, {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"},
1477    {50, "ia64"}, {88, "m32r"}, {0x9041, "m32r"}, {4, "m68k"}, {174, "metag"},
1478    {189, "microblaze"}, {0xbaab, "microblaze-old"}, {8, "mips"},
1479    {10, "mips-old"}, {89, "mn10300"}, {0xbeef, "mn10300-old"}, {113, "nios2"},
1480    {92, "openrisc"}, {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"},
1481    {21, "ppc64"}, {243, "riscv"}, {22, "s390"}, {0xa390, "s390-old"},
1482    {135, "score"}, {42, "sh"}, {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"},
1483    {188, "tile"}, {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"},
1484    {94, "xtensa"}, {0xabc7, "xtensa-old"}
1485  };
1486
1487  for (i = 0; i<ARRAY_LEN(types); i++) {
1488    if (type==types[i].val) return types[i].name;
1489  }
1490  sprintf(libbuf, "unknown arch %d", type);
1491  return libbuf;
1492}
1493