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