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