toybox/main.c
<<
>>
Prefs
   1/* Toybox infrastructure.
   2 *
   3 * Copyright 2006 Rob Landley <rob@landley.net>
   4 */
   5
   6#include "toys.h"
   7
   8#ifndef TOYBOX_VERSION
   9#ifndef TOYBOX_VENDOR
  10#define TOYBOX_VENDOR ""
  11#endif
  12#define TOYBOX_VERSION "0.8.1"TOYBOX_VENDOR
  13#endif
  14
  15// Populate toy_list[].
  16
  17#undef NEWTOY
  18#undef OLDTOY
  19#define NEWTOY(name, opts, flags) {#name, name##_main, OPTSTR_##name, flags},
  20#define OLDTOY(name, oldname, flags) \
  21  {#name, oldname##_main, OPTSTR_##oldname, flags},
  22
  23struct toy_list toy_list[] = {
  24#include "generated/newtoys.h"
  25};
  26
  27// global context for this command.
  28
  29struct toy_context toys;
  30union global_union this;
  31char toybuf[4096], libbuf[4096];
  32
  33struct toy_list *toy_find(char *name)
  34{
  35  int top, bottom, middle;
  36
  37  if (!CFG_TOYBOX || strchr(name, '/')) return 0;
  38
  39  // If the name starts with "toybox" accept that as a match.  Otherwise
  40  // skip the first entry, which is out of order.
  41
  42  if (!strncmp(name,"toybox",6)) return toy_list;
  43  bottom = 1;
  44
  45  // Binary search to find this command.
  46
  47  top = ARRAY_LEN(toy_list)-1;
  48  for (;;) {
  49    int result;
  50
  51    middle = (top+bottom)/2;
  52    if (middle<bottom || middle>top) return NULL;
  53    result = strcmp(name,toy_list[middle].name);
  54    if (!result) return toy_list+middle;
  55    if (result<0) top = --middle;
  56    else bottom = ++middle;
  57  }
  58}
  59
  60// Figure out whether or not anything is using the option parsing logic,
  61// because the compiler can't figure out whether or not to optimize it away
  62// on its' own.  NEED_OPTIONS becomes a constant allowing if() to optimize
  63// stuff out via dead code elimination.
  64
  65#undef NEWTOY
  66#undef OLDTOY
  67#define NEWTOY(name, opts, flags) opts ||
  68#define OLDTOY(name, oldname, flags) OPTSTR_##oldname ||
  69static const int NEED_OPTIONS =
  70#include "generated/newtoys.h"
  710;  // Ends the opts || opts || opts...
  72
  73static void unknown(char *name)
  74{
  75  toys.exitval = 127;
  76  toys.which = toy_list;
  77  error_exit("Unknown command %s", name);
  78}
  79
  80// Setup toybox global state for this command.
  81static void toy_singleinit(struct toy_list *which, char *argv[])
  82{
  83  toys.which = which;
  84  toys.argv = argv;
  85
  86  if (CFG_TOYBOX_I18N) setlocale(LC_CTYPE, "C.UTF-8");
  87  setlinebuf(stdout);
  88
  89  // Parse --help and --version for (almost) all commands
  90  if (CFG_TOYBOX_HELP_DASHDASH && !(which->flags & TOYFLAG_NOHELP) && argv[1]) {
  91    if (!strcmp(argv[1], "--help")) {
  92      if (CFG_TOYBOX && toys.which == toy_list && toys.argv[2])
  93        if (!(toys.which = toy_find(toys.argv[2]))) unknown(toys.argv[2]);
  94      show_help(stdout);
  95      xexit();
  96    }
  97
  98    if (!strcmp(argv[1], "--version")) {
  99      xputs("toybox "TOYBOX_VERSION);
 100      xexit();
 101    }
 102  }
 103
 104  if (NEED_OPTIONS && which->options) get_optflags();
 105  else {
 106    toys.optargs = argv+1;
 107    for (toys.optc = 0; toys.optargs[toys.optc]; toys.optc++);
 108  }
 109  toys.old_umask = umask(0);
 110  if (!(which->flags & TOYFLAG_UMASK)) umask(toys.old_umask);
 111  toys.signalfd--;
 112  toys.toycount = ARRAY_LEN(toy_list);
 113}
 114
 115// Full init needed by multiplexer or reentrant calls, calls singleinit at end
 116void toy_init(struct toy_list *which, char *argv[])
 117{
 118  void *oldwhich = toys.which;
 119
 120  // Drop permissions for non-suid commands.
 121
 122  if (CFG_TOYBOX_SUID) {
 123    if (!toys.which) toys.which = toy_list;
 124
 125    uid_t uid = getuid(), euid = geteuid();
 126
 127    if (!(which->flags & TOYFLAG_STAYROOT)) {
 128      if (uid != euid) {
 129        if (setuid(uid)) perror_exit("setuid %d->%d", euid, uid); // drop root
 130        euid = uid;
 131        toys.wasroot++;
 132      }
 133    } else if (CFG_TOYBOX_DEBUG && uid && which != toy_list)
 134      error_msg("Not installed suid root");
 135
 136    if ((which->flags & TOYFLAG_NEEDROOT) && euid) help_exit("Not root");
 137  }
 138
 139  // Free old toys contents (to be reentrant), but leave rebound if any
 140  // don't blank old optargs if our new argc lives in the old optargs.
 141  if (argv<toys.optargs || argv>toys.optargs+toys.optc) free(toys.optargs);
 142  memset(&toys, 0, offsetof(struct toy_context, rebound));
 143  if (oldwhich) memset(&this, 0, sizeof(this));
 144
 145  // Continue to portion of init needed by standalone commands
 146  toy_singleinit(which, argv);
 147}
 148
 149// Run an internal toybox command.
 150// Only returns if it can't run command internally, otherwise xexit() when done.
 151void toy_exec_which(struct toy_list *which, char *argv[])
 152{
 153  // Return if we can't find it (which includes no multiplexer case),
 154  if (!which) return;
 155
 156  // Return if stack depth getting noticeable (proxy for leaked heap, etc).
 157
 158  // Compiler writers have decided subtracting char * is undefined behavior,
 159  // so convert to integers. (LP64 says sizeof(long)==sizeof(pointer).)
 160  // Signed typecast so stack growth direction is irrelevant: we're measuring
 161  // the distance between two pointers on the same stack, hence the labs().
 162  if (!CFG_TOYBOX_NORECURSE && toys.stacktop)
 163    if (labs((long)toys.stacktop-(long)&which)>6000) return;
 164
 165  // Return if we need to re-exec to acquire root via suid bit.
 166  if (toys.which && (which->flags&TOYFLAG_ROOTONLY) && toys.wasroot) return;
 167
 168  // Run command
 169  toy_init(which, argv);
 170  if (toys.which) toys.which->toy_main();
 171  xexit();
 172}
 173
 174// Lookup internal toybox command to run via argv[0]
 175void toy_exec(char *argv[])
 176{
 177  toy_exec_which(toy_find(basename(*argv)), argv);
 178}
 179
 180// Multiplexer command, first argument is command to run, rest are args to that.
 181// If first argument starts with - output list of command install paths.
 182void toybox_main(void)
 183{
 184  static char *toy_paths[]={"usr/","bin/","sbin/",0};
 185  int i, len = 0;
 186
 187  // fast path: try to exec immediately.
 188  // (Leave toys.which null to disable suid return logic.)
 189  // Try dereferencing one layer of symlink
 190  if (toys.argv[1]) {
 191    toy_exec(toys.argv+1);
 192    if (0<readlink(toys.argv[1], libbuf, sizeof(libbuf)))
 193      toy_exec_which(toy_find(basename(libbuf)), toys.argv);
 194  }
 195
 196  // For early error reporting
 197  toys.which = toy_list;
 198
 199  if (toys.argv[1] && toys.argv[1][0] != '-') unknown(toys.argv[1]);
 200
 201  // Output list of command.
 202  for (i=1; i<ARRAY_LEN(toy_list); i++) {
 203    int fl = toy_list[i].flags;
 204    if (fl & TOYMASK_LOCATION) {
 205      if (toys.argv[1]) {
 206        int j;
 207        for (j=0; toy_paths[j]; j++)
 208          if (fl & (1<<j)) len += printf("%s", toy_paths[j]);
 209      }
 210      len += printf("%s",toy_list[i].name);
 211      if (++len > 65) len = 0;
 212      xputc(len ? ' ' : '\n');
 213    }
 214  }
 215  xputc('\n');
 216}
 217
 218int main(int argc, char *argv[])
 219{
 220  if (!*argv) return 127;
 221
 222  // Snapshot stack location so we can detect recursion depth later.
 223  // This is its own block so probe doesn't permanently consume stack.
 224  else {
 225    int stack;
 226
 227    toys.stacktop = &stack;
 228  }
 229
 230  // Up to and including Android M, bionic's dynamic linker added a handler to
 231  // cause a crash dump on SIGPIPE. That was removed in Android N, but adbd
 232  // was still setting the SIGPIPE disposition to SIG_IGN, and its children
 233  // were inheriting that. In Android O, adbd is fixed, but manually asking
 234  // for the default disposition is harmless, and it'll be a long time before
 235  // no one's using anything older than O!
 236  if (CFG_TOYBOX_ON_ANDROID) signal(SIGPIPE, SIG_DFL);
 237
 238  // If nommu can't fork, special reentry path.
 239  // Use !stacktop to signal "vfork happened", both before and after xexec()
 240  if (!CFG_TOYBOX_FORK) {
 241    if (0x80 & **argv) {
 242      **argv &= 0x7f;
 243      toys.stacktop = 0;
 244    }
 245  }
 246
 247  if (CFG_TOYBOX) {
 248    // Call the multiplexer, adjusting this argv[] to be its' argv[1].
 249    // (It will adjust it back before calling toy_exec().)
 250    toys.argv = argv-1;
 251    toybox_main();
 252  } else {
 253    // a single toybox command built standalone with no multiplexer
 254    toy_singleinit(toy_list, argv);
 255    toy_list->toy_main();
 256  }
 257
 258  xexit();
 259}
 260