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