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;
 453
 454  if (s) for (p = s+strlen(s); 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
 522int same_file(struct stat *st1, struct stat *st2)
 523{
 524  return st1->st_ino==st2->st_ino && st1->st_dev==st2->st_dev;
 525}
 526
 527int same_dev_ino(struct stat *st, struct dev_ino *di)
 528{
 529  return st->st_ino==di->ino && st->st_dev==di->dev;
 530}
 531
 532
 533
 534// Return how long the file at fd is, if there's any way to determine it.
 535off_t fdlength(int fd)
 536{
 537  struct stat st;
 538  off_t base = 0, range = 1, expand = 1, old;
 539  unsigned long long size;
 540
 541  if (!fstat(fd, &st) && S_ISREG(st.st_mode)) return st.st_size;
 542
 543  // If the ioctl works for this, return it.
 544  if (get_block_device_size(fd, &size)) return size;
 545
 546  // If not, do a binary search for the last location we can read.  (Some
 547  // block devices don't do BLKGETSIZE right.)  This should probably have
 548  // a CONFIG option...
 549  old = lseek(fd, 0, SEEK_CUR);
 550  do {
 551    char temp;
 552    off_t pos = base + range / 2;
 553
 554    if (lseek(fd, pos, 0)>=0 && read(fd, &temp, 1)==1) {
 555      off_t delta = (pos + 1) - base;
 556
 557      base += delta;
 558      if (expand) range = (expand <<= 1) - base;
 559      else range -= delta;
 560    } else {
 561      expand = 0;
 562      range = pos - base;
 563    }
 564  } while (range > 0);
 565
 566  lseek(fd, old, SEEK_SET);
 567
 568  return base;
 569}
 570
 571char *readfd(int fd, char *ibuf, off_t *plen)
 572{
 573  off_t len, rlen;
 574  char *buf, *rbuf;
 575
 576  // Unsafe to probe for size with a supplied buffer, don't ever do that.
 577  if (CFG_TOYBOX_DEBUG && (ibuf ? !*plen : *plen)) error_exit("bad readfileat");
 578
 579  // If we dunno the length, probe it. If we can't probe, start with 1 page.
 580  if (!*plen) {
 581    if ((len = fdlength(fd))>0) *plen = len;
 582    else len = 4096;
 583  } else len = *plen-1;
 584
 585  if (!ibuf) buf = xmalloc(len+1);
 586  else buf = ibuf;
 587
 588  for (rbuf = buf;;) {
 589    rlen = readall(fd, rbuf, len);
 590    if (*plen || rlen<len) break;
 591
 592    // If reading unknown size, expand buffer by 1.5 each time we fill it up.
 593    rlen += rbuf-buf;
 594    buf = xrealloc(buf, len = (rlen*3)/2);
 595    rbuf = buf+rlen;
 596    len -= rlen;
 597  }
 598  *plen = len = rlen+(rbuf-buf);
 599
 600  if (rlen<0) {
 601    if (ibuf != buf) free(buf);
 602    buf = 0;
 603  } else buf[len] = 0;
 604
 605  return buf;
 606}
 607
 608// Read contents of file as a single nul-terminated string.
 609// measure file size if !len, allocate buffer if !buf
 610// Existing buffers need len in *plen
 611// Returns amount of data read in *plen
 612char *readfileat(int dirfd, char *name, char *ibuf, off_t *plen)
 613{
 614  if (-1 == (dirfd = openat(dirfd, name, O_RDONLY))) return 0;
 615
 616  ibuf = readfd(dirfd, ibuf, plen);
 617  close(dirfd);
 618
 619  return ibuf;
 620}
 621
 622char *readfile(char *name, char *ibuf, off_t len)
 623{
 624  return readfileat(AT_FDCWD, name, ibuf, &len);
 625}
 626
 627// Sleep for this many thousandths of a second
 628void msleep(long milliseconds)
 629{
 630  struct timespec ts;
 631
 632  ts.tv_sec = milliseconds/1000;
 633  ts.tv_nsec = (milliseconds%1000)*1000000;
 634  nanosleep(&ts, &ts);
 635}
 636
 637// Adjust timespec by nanosecond offset
 638void nanomove(struct timespec *ts, long long offset)
 639{
 640  long long nano = ts->tv_nsec + offset, secs = nano/1000000000;
 641
 642  ts->tv_sec += secs;
 643  nano %= 1000000000;
 644  if (nano<0) {
 645    ts->tv_sec--;
 646    nano += 1000000000;
 647  }
 648  ts->tv_nsec = nano;
 649}
 650
 651// return difference between two timespecs in nanosecs
 652long long nanodiff(struct timespec *old, struct timespec *new)
 653{
 654  return (new->tv_sec - old->tv_sec)*1000000000LL+(new->tv_nsec - old->tv_nsec);
 655}
 656
 657// return 1<<x of highest bit set
 658int highest_bit(unsigned long l)
 659{
 660  int i;
 661
 662  for (i = 0; l; i++) l >>= 1;
 663
 664  return i-1;
 665}
 666
 667// Inefficient, but deals with unaligned access
 668int64_t peek_le(void *ptr, unsigned size)
 669{
 670  int64_t ret = 0;
 671  char *c = ptr;
 672  int i;
 673
 674  for (i=0; i<size; i++) ret |= ((int64_t)c[i])<<(i*8);
 675  return ret;
 676}
 677
 678int64_t peek_be(void *ptr, unsigned size)
 679{
 680  int64_t ret = 0;
 681  char *c = ptr;
 682  int i;
 683
 684  for (i=0; i<size; i++) ret = (ret<<8)|(c[i]&0xff);
 685  return ret;
 686}
 687
 688int64_t peek(void *ptr, unsigned size)
 689{
 690  return (IS_BIG_ENDIAN ? peek_be : peek_le)(ptr, size);
 691}
 692
 693void poke_le(void *ptr, long long val, unsigned size)
 694{
 695  char *c = ptr;
 696
 697  while (size--) {
 698    *c++ = val&255;
 699    val >>= 8;
 700  }
 701}
 702
 703void poke_be(void *ptr, long long val, unsigned size)
 704{
 705  char *c = ptr + size;
 706
 707  while (size--) {
 708    *--c = val&255;
 709    val >>=8;
 710  }
 711}
 712
 713void poke(void *ptr, long long val, unsigned size)
 714{
 715  (IS_BIG_ENDIAN ? poke_be : poke_le)(ptr, val, size);
 716}
 717
 718// Iterate through an array of files, opening each one and calling a function
 719// on that filehandle and name. The special filename "-" means stdin if
 720// flags is O_RDONLY, stdout otherwise. An empty argument list calls
 721// function() on just stdin/stdout.
 722//
 723// Note: pass O_CLOEXEC to automatically close filehandles when function()
 724// returns, otherwise filehandles must be closed by function().
 725// pass WARN_ONLY to produce warning messages about files it couldn't
 726// open/create, and skip them. Otherwise function is called with fd -1.
 727void loopfiles_rw(char **argv, int flags, int permissions,
 728  void (*function)(int fd, char *name))
 729{
 730  int fd, failok = !(flags&WARN_ONLY), anyway = flags & LOOPFILES_ANYWAY;
 731
 732  flags &= ~(WARN_ONLY|LOOPFILES_ANYWAY);
 733
 734  // If no arguments, read from stdin.
 735  if (!*argv) function((flags & O_ACCMODE) != O_RDONLY ? 1 : 0, "-");
 736  else do {
 737    // Filename "-" means read from stdin.
 738    // Inability to open a file prints a warning, but doesn't exit.
 739
 740    if (!strcmp(*argv, "-")) fd = 0;
 741    else if (0>(fd = notstdio(open(*argv, flags, permissions))) && !failok) {
 742      perror_msg_raw(*argv);
 743      if (!anyway) continue;
 744    }
 745    function(fd, *argv);
 746    if ((flags & O_CLOEXEC) && fd>0) close(fd);
 747  } while (*++argv);
 748}
 749
 750// Call loopfiles_rw with O_RDONLY|O_CLOEXEC|WARN_ONLY (common case)
 751void loopfiles(char **argv, void (*function)(int fd, char *name))
 752{
 753  loopfiles_rw(argv, O_RDONLY|O_CLOEXEC|WARN_ONLY, 0, function);
 754}
 755
 756// glue to call do_lines() from loopfiles
 757static void (*do_lines_bridge)(char **pline, long len);
 758static void loopfile_lines_bridge(int fd, char *name)
 759{
 760  do_lines(fd, '\n', do_lines_bridge);
 761}
 762
 763void loopfiles_lines(char **argv, void (*function)(char **pline, long len))
 764{
 765  do_lines_bridge = function;
 766  // No O_CLOEXEC because we need to call fclose.
 767  loopfiles_rw(argv, O_RDONLY|WARN_ONLY, 0, loopfile_lines_bridge);
 768}
 769
 770int wfchmodat(int fd, char *name, mode_t mode)
 771{
 772  int rc = fchmodat(fd, name, mode, 0);
 773
 774  if (rc) {
 775    perror_msg("chmod '%s' to %04o", name, mode);
 776    toys.exitval=1;
 777  }
 778  return rc;
 779}
 780
 781static char *tempfile2zap;
 782static void tempfile_handler(void)
 783{
 784  if (1 < (long)tempfile2zap) unlink(tempfile2zap);
 785}
 786
 787// Open a temporary file to copy an existing file into.
 788int copy_tempfile(int fdin, char *name, char **tempname)
 789{
 790  struct stat statbuf;
 791  int fd = xtempfile(name, tempname), ignored __attribute__((__unused__));
 792
 793  // Record tempfile for exit cleanup if interrupted
 794  if (!tempfile2zap) sigatexit(tempfile_handler);
 795  tempfile2zap = *tempname;
 796
 797  // Set permissions of output file.
 798  if (!fstat(fdin, &statbuf)) fchmod(fd, statbuf.st_mode);
 799
 800  // We chmod before chown, which strips the suid bit. Caller has to explicitly
 801  // switch it back on if they want to keep suid.
 802
 803  // Suppress warn-unused-result. Both gcc and clang clutch their pearls about
 804  // this but it's _supposed_ to fail when we're not root.
 805  ignored = fchown(fd, statbuf.st_uid, statbuf.st_gid);
 806
 807  return fd;
 808}
 809
 810// Abort the copy and delete the temporary file.
 811void delete_tempfile(int fdin, int fdout, char **tempname)
 812{
 813  close(fdin);
 814  close(fdout);
 815  if (*tempname) unlink(*tempname);
 816  tempfile2zap = (char *)1;
 817  free(*tempname);
 818  *tempname = NULL;
 819}
 820
 821// Copy the rest of the data and replace the original with the copy.
 822void replace_tempfile(int fdin, int fdout, char **tempname)
 823{
 824  char *temp = xstrdup(*tempname);
 825
 826  temp[strlen(temp)-6]=0;
 827  if (fdin != -1) {
 828    xsendfile(fdin, fdout);
 829    xclose(fdin);
 830  }
 831  xclose(fdout);
 832  xrename(*tempname, temp);
 833  tempfile2zap = (char *)1;
 834  free(*tempname);
 835  free(temp);
 836  *tempname = NULL;
 837}
 838
 839// Create a 256 entry CRC32 lookup table.
 840
 841void crc_init(unsigned *crc_table, int little_endian)
 842{
 843  unsigned int i;
 844
 845  // Init the CRC32 table (big endian)
 846  for (i=0; i<256; i++) {
 847    unsigned int j, c = little_endian ? i : i<<24;
 848    for (j=8; j; j--)
 849      if (little_endian) c = (c&1) ? (c>>1)^0xEDB88320 : c>>1;
 850      else c=c&0x80000000 ? (c<<1)^0x04c11db7 : (c<<1);
 851    crc_table[i] = c;
 852  }
 853}
 854
 855// Init base64 table
 856
 857void base64_init(char *p)
 858{
 859  int i;
 860
 861  for (i = 'A'; i != ':'; i++) {
 862    if (i == 'Z'+1) i = 'a';
 863    if (i == 'z'+1) i = '0';
 864    *(p++) = i;
 865  }
 866  *(p++) = '+';
 867  *(p++) = '/';
 868}
 869
 870int yesno(int def)
 871{
 872  return fyesno(stdin, def);
 873}
 874
 875int fyesno(FILE *in, int def)
 876{
 877  char buf;
 878
 879  fprintf(stderr, " (%c/%c):", def ? 'Y' : 'y', def ? 'n' : 'N');
 880  fflush(stderr);
 881  while (fread(&buf, 1, 1, in)) {
 882    int new;
 883
 884    // The letter changes the value, the newline (or space) returns it.
 885    if (isspace(buf)) break;
 886    if (-1 != (new = stridx("ny", tolower(buf)))) def = new;
 887  }
 888
 889  return def;
 890}
 891
 892// Handler that sets toys.signal, and writes to toys.signalfd if set
 893void generic_signal(int sig)
 894{
 895  if (toys.signalfd) {
 896    char c = sig;
 897
 898    writeall(toys.signalfd, &c, 1);
 899  }
 900  toys.signal = sig;
 901}
 902
 903// More or less SIG_DFL that runs our atexit list and can siglongjmp.
 904void exit_signal(int sig)
 905{
 906  sigset_t sigset;
 907
 908  if (sig) toys.exitval = sig|128;
 909  sigfillset(&sigset);
 910  sigprocmask(SIG_BLOCK, &sigset, 0);
 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 = 1, 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, ABS_FILE), *s2 = xabspath(file, 0), *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, 0))) return 0;
1087  if (!(to = xabspath(to, 0))) 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) || !same_file(&st1, &st2)) continue;
1150        goto match;
1151      }
1152
1153      // Nope, gotta read command line to confirm
1154      if (!cmd) {
1155        sprintf(cmd = libbuf+16, "/proc/%u/cmdline", u);
1156        len = sizeof(libbuf)-17;
1157        if (!(cmd = readfileat(AT_FDCWD, cmd, cmd, &len))) continue;
1158        // readfile only guarantees one null terminator and we need two
1159        // (yes the kernel should do this for us, don't care)
1160        cmd[len] = 0;
1161      }
1162      if (!strcmp(bb, getbasename(cmd))) goto match;
1163      if (scripts && !strcmp(bb, getbasename(cmd+strlen(cmd)+1))) goto match;
1164      continue;
1165match:
1166      if (callback(u, *cur)) goto done;
1167    }
1168  }
1169done:
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 *bufgetpwnamuid(char *name, 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 (name ? !strcmp(name, list->pw.pw_name) : list->pw.pw_uid==uid)
1284      return &(list->pw);
1285
1286  for (;;) {
1287    list = xrealloc(list, size *= 2);
1288    if (name) errno = getpwnam_r(name, &list->pw, sizeof(*list)+(char *)list,
1289      size-sizeof(*list), &temp);
1290    else errno = getpwuid_r(uid, &list->pw, sizeof(*list)+(char *)list,
1291      size-sizeof(*list), &temp);
1292    if (errno != ERANGE) break;
1293  }
1294
1295  if (!temp) {
1296    free(list);
1297
1298    return 0;
1299  }
1300  list->next = pwuidbuf;
1301  pwuidbuf = list;
1302
1303  return &list->pw;
1304}
1305
1306struct passwd *bufgetpwuid(uid_t uid)
1307{
1308  return bufgetpwnamuid(0, uid);
1309}
1310
1311// Return cached group entries.
1312struct group *bufgetgrnamgid(char *name, gid_t gid)
1313{
1314  struct grgidbuf_list {
1315    struct grgidbuf_list *next;
1316    struct group gr;
1317  } *list = 0;
1318  struct group *temp;
1319  static struct grgidbuf_list *grgidbuf;
1320  unsigned size = 256;
1321
1322  for (list = grgidbuf; list; list = list->next)
1323    if (name ? !strcmp(name, list->gr.gr_name) : list->gr.gr_gid==gid)
1324      return &(list->gr);
1325
1326  for (;;) {
1327    list = xrealloc(list, size *= 2);
1328    if (name) errno = getgrnam_r(name, &list->gr, sizeof(*list)+(char *)list,
1329      size-sizeof(*list), &temp);
1330    else errno = getgrgid_r(gid, &list->gr, sizeof(*list)+(char *)list,
1331      size-sizeof(*list), &temp);
1332    if (errno != ERANGE) break;
1333  }
1334  if (!temp) {
1335    free(list);
1336
1337    return 0;
1338  }
1339  list->next = grgidbuf;
1340  grgidbuf = list;
1341
1342  return &list->gr;
1343}
1344
1345struct group *bufgetgrgid(gid_t gid)
1346{
1347  return bufgetgrnamgid(0, gid);
1348}
1349
1350
1351// Always null terminates, returns 0 for failure, len for success
1352int readlinkat0(int dirfd, char *path, char *buf, int len)
1353{
1354  if (!len) return 0;
1355
1356  len = readlinkat(dirfd, path, buf, len-1);
1357  if (len<0) len = 0;
1358  buf[len] = 0;
1359
1360  return len;
1361}
1362
1363int readlink0(char *path, char *buf, int len)
1364{
1365  return readlinkat0(AT_FDCWD, path, buf, len);
1366}
1367
1368// Do regex matching with len argument to handle embedded NUL bytes in string
1369int regexec0(regex_t *preg, char *string, long len, int nmatch,
1370  regmatch_t *pmatch, int eflags)
1371{
1372  regmatch_t backup;
1373
1374  if (!nmatch) pmatch = &backup;
1375  pmatch->rm_so = 0;
1376  pmatch->rm_eo = len;
1377  return regexec(preg, string, nmatch, pmatch, eflags|REG_STARTEND);
1378}
1379
1380// Return user name or string representation of number, returned buffer
1381// lasts until next call.
1382char *getusername(uid_t uid)
1383{
1384  struct passwd *pw = bufgetpwuid(uid);
1385  static char unum[12];
1386
1387  sprintf(unum, "%u", (unsigned)uid);
1388  return pw ? pw->pw_name : unum;
1389}
1390
1391// Return group name or string representation of number, returned buffer
1392// lasts until next call.
1393char *getgroupname(gid_t gid)
1394{
1395  struct group *gr = bufgetgrgid(gid);
1396  static char gnum[12];
1397
1398  sprintf(gnum, "%u", (unsigned)gid);
1399  return gr ? gr->gr_name : gnum;
1400}
1401
1402// Iterate over lines in file, calling function. Function can write 0 to
1403// the line pointer if they want to keep it, or 1 to terminate processing,
1404// otherwise line is freed. Passed file descriptor is closed at the end.
1405// At EOF calls function(0, 0)
1406void do_lines(int fd, char delim, void (*call)(char **pline, long len))
1407{
1408  FILE *fp = fd ? xfdopen(fd, "r") : stdin;
1409
1410  for (;;) {
1411    char *line = 0;
1412    ssize_t len;
1413
1414    len = getdelim(&line, (void *)&len, delim, fp);
1415    if (len > 0) {
1416      call(&line, len);
1417      if (line == (void *)1) break;
1418      free(line);
1419    } else break;
1420  }
1421  call(0, 0);
1422
1423  if (fd) fclose(fp);
1424}
1425
1426// Return unix time in milliseconds
1427long long millitime(void)
1428{
1429  struct timespec ts;
1430
1431  clock_gettime(CLOCK_MONOTONIC, &ts);
1432  return ts.tv_sec*1000+ts.tv_nsec/1000000;
1433}
1434
1435// Formats `ts` in ISO format ("2018-06-28 15:08:58.846386216 -0700").
1436char *format_iso_time(char *buf, size_t len, struct timespec *ts)
1437{
1438  char *s = buf;
1439
1440  s += strftime(s, len, "%F %T", localtime(&(ts->tv_sec)));
1441  s += sprintf(s, ".%09ld ", ts->tv_nsec);
1442  s += strftime(s, len-strlen(buf), "%z", localtime(&(ts->tv_sec)));
1443
1444  return buf;
1445}
1446
1447// Syslog with the openlog/closelog, autodetecting daemon status via no tty
1448
1449void loggit(int priority, char *format, ...)
1450{
1451  int i, facility = LOG_DAEMON;
1452  va_list va;
1453
1454  for (i = 0; i<3; i++) if (isatty(i)) facility = LOG_AUTH;
1455  openlog(toys.which->name, LOG_PID, facility);
1456  va_start(va, format);
1457  vsyslog(priority, format, va);
1458  va_end(va);
1459  closelog();
1460}
1461
1462// Calculate tar packet checksum, with cksum field treated as 8 spaces
1463unsigned tar_cksum(void *data)
1464{
1465  unsigned i, cksum = 8*' ';
1466
1467  for (i = 0; i<500; i += (i==147) ? 9 : 1) cksum += ((char *)data)[i];
1468
1469  return cksum;
1470}
1471
1472// is this a valid tar header?
1473int is_tar_header(void *pkt)
1474{
1475  char *p = pkt;
1476  int i = 0;
1477
1478  if (p[257] && memcmp("ustar", p+257, 5)) return 0;
1479  if (p[148] != '0' && p[148] != ' ') return 0;
1480  sscanf(p+148, "%8o", &i);
1481
1482  return i && tar_cksum(pkt) == i;
1483}
1484
1485char *elf_arch_name(int type)
1486{
1487  int i;
1488  // Values from include/linux/elf-em.h (plus arch/*/include/asm/elf.h)
1489  // Names are linux/arch/ directory (sometimes before 32/64 bit merges)
1490  struct {int val; char *name;} types[] = {{0x9026, "alpha"}, {93, "arc"},
1491    {195, "arcv2"}, {40, "arm"}, {183, "arm64"}, {0x18ad, "avr32"},
1492    {247, "bpf"}, {106, "blackfin"}, {140, "c6x"}, {23, "cell"}, {76, "cris"},
1493    {252, "csky"}, {0x5441, "frv"}, {46, "h8300"}, {164, "hexagon"},
1494    {50, "ia64"}, {258, "loongarch"}, {88, "m32r"}, {0x9041, "m32r"},
1495    {4, "m68k"}, {174, "metag"}, {189, "microblaze"},
1496    {0xbaab, "microblaze-old"}, {8, "mips"}, {10, "mips-old"}, {89, "mn10300"},
1497    {0xbeef, "mn10300-old"}, {113, "nios2"}, {92, "openrisc"},
1498    {0x8472, "openrisc-old"}, {15, "parisc"}, {20, "ppc"}, {21, "ppc64"},
1499    {243, "riscv"}, {22, "s390"}, {0xa390, "s390-old"}, {135, "score"},
1500    {42, "sh"}, {2, "sparc"}, {18, "sparc8+"}, {43, "sparc9"}, {188, "tile"},
1501    {191, "tilegx"}, {3, "386"}, {6, "486"}, {62, "x86-64"}, {94, "xtensa"},
1502    {0xabc7, "xtensa-old"}
1503  };
1504
1505  for (i = 0; i<ARRAY_LEN(types); i++) {
1506    if (type==types[i].val) return types[i].name;
1507  }
1508  sprintf(libbuf, "unknown arch %d", type);
1509  return libbuf;
1510}
1511