1 /*
   2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
   3  * All rights reserved.
   4  *
   5  * Redistribution and use in source and binary forms, with or without
   6  * modification, are permitted provided that the following conditions
   7  * are met:
   8  * 1. Redistributions of source code must retain the above copyright
   9  *    notice, this list of conditions and the following disclaimer.
  10  * 2. Redistributions in binary form must reproduce the above copyright
  11  *    notice, this list of conditions and the following disclaimer in the
  12  *    documentation and/or other materials provided with the distribution.
  13  *
  14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  24  * SUCH DAMAGE.
  25  */
  26 
  27 #include <sys/types.h>
  28 #include <sys/stat.h>
  29 #include <fcntl.h>
  30 #include <errno.h>
  31 #include <stdlib.h>
  32 #include <stdio.h>
  33 #include <string.h>
  34 #include <strings.h>
  35 #include <limits.h>
  36 #include <unistd.h>
  37 #include <dirent.h>
  38 #include <macros.h>
  39 #include <sys/systeminfo.h>
  40 #include <sys/queue.h>
  41 #include <sys/mnttab.h>
  42 #include "gfx_fb.h"
  43 #include "ficl.h"
  44 
  45 /* Commands and return values; nonzero return sets command_errmsg != NULL */
  46 typedef int (bootblk_cmd_t)(int argc, char *argv[]);
  47 #define CMD_OK          0
  48 #define CMD_ERROR       1
  49 
  50 /*
  51  * Support for commands
  52  */
  53 struct bootblk_command
  54 {
  55         const char *c_name;
  56         const char *c_desc;
  57         bootblk_cmd_t *c_fn;
  58         STAILQ_ENTRY(bootblk_command) next;
  59 };
  60 
  61 #define MDIR_REMOVED    0x0001
  62 #define MDIR_NOHINTS    0x0002
  63 
  64 struct moduledir {
  65         char    *d_path;        /* path of modules directory */
  66         uchar_t *d_hints;       /* content of linker.hints file */
  67         int     d_hintsz;       /* size of hints data */
  68         int     d_flags;
  69         STAILQ_ENTRY(moduledir) d_link;
  70 };
  71 static STAILQ_HEAD(, moduledir) moduledir_list =
  72     STAILQ_HEAD_INITIALIZER(moduledir_list);
  73 
  74 static const char *default_searchpath = "/platform/i86pc";
  75 
  76 static char typestr[] = "?fc?d?b? ?l?s?w";
  77 static int      ls_getdir(char **pathp);
  78 extern char **_environ;
  79 
  80 char    *command_errmsg;
  81 char    command_errbuf[256];
  82 
  83 extern void pager_open(void);
  84 extern void pager_close(void);
  85 extern int pager_output(const char *);
  86 extern int pager_file(const char *);
  87 static int page_file(char *);
  88 static int include(const char *);
  89 
  90 static int command_help(int argc, char *argv[]);
  91 static int command_commandlist(int argc, char *argv[]);
  92 static int command_show(int argc, char *argv[]);
  93 static int command_set(int argc, char *argv[]);
  94 static int command_setprop(int argc, char *argv[]);
  95 static int command_unset(int argc, char *argv[]);
  96 static int command_echo(int argc, char *argv[]);
  97 static int command_read(int argc, char *argv[]);
  98 static int command_more(int argc, char *argv[]);
  99 static int command_ls(int argc, char *argv[]);
 100 static int command_include(int argc, char *argv[]);
 101 static int command_autoboot(int argc, char *argv[]);
 102 static int command_boot(int argc, char *argv[]);
 103 static int command_unload(int argc, char *argv[]);
 104 static int command_load(int argc, char *argv[]);
 105 static int command_reboot(int argc, char *argv[]);
 106 static int command_framebuffer(int argc, char *argv[]);
 107 
 108 #define BF_PARSE        100
 109 #define BF_DICTSIZE     30000
 110 
 111 /* update when loader version will change */
 112 static const char bootprog_rev[] = "1.1";
 113 STAILQ_HEAD(cmdh, bootblk_command) commands;
 114 
 115 /*
 116  * BootForth   Interface to Ficl Forth interpreter.
 117  */
 118 
 119 ficlSystem *bf_sys;
 120 ficlVm  *bf_vm;
 121 
 122 /*
 123  * Redistribution and use in source and binary forms, with or without
 124  * modification, are permitted provided that the following conditions
 125  * are met:
 126  * 1. Redistributions of source code must retain the above copyright
 127  *    notice, this list of conditions and the following disclaimer.
 128  * 2. Redistributions in binary form must reproduce the above copyright
 129  *    notice, this list of conditions and the following disclaimer in the
 130  *    documentation and/or other materials provided with the distribution.
 131  *
 132  * Jordan K. Hubbard
 133  * 29 August 1998
 134  *
 135  * The meat of the simple parser.
 136  */
 137 
 138 static void      clean(void);
 139 static int       insert(int *argcp, char *buf);
 140 
 141 #define PARSE_BUFSIZE   1024    /* maximum size of one element */
 142 #define MAXARGS         20      /* maximum number of elements */
 143 static  char            *args[MAXARGS];
 144 
 145 #define DIGIT(x)        \
 146         (isdigit(x) ? (x) - '0' : islower(x) ? (x) + 10 - 'a' : (x) + 10 - 'A')
 147 
 148 /*
 149  * backslash: Return malloc'd copy of str with all standard "backslash
 150  * processing" done on it.  Original can be free'd if desired.
 151  */
 152 char *
 153 backslash(char *str)
 154 {
 155         /*
 156          * Remove backslashes from the strings. Turn \040 etc. into a single
 157          * character (we allow eight bit values). Currently NUL is not
 158          * allowed.
 159          *
 160          * Turn "\n" and "\t" into '\n' and '\t' characters. Etc.
 161          */
 162         char *new_str;
 163         int seenbs = 0;
 164         int i = 0;
 165 
 166         if ((new_str = strdup(str)) == NULL)
 167                 return (NULL);
 168 
 169         while (*str) {
 170                 if (seenbs) {
 171                         seenbs = 0;
 172                         switch (*str) {
 173                         case '\\':
 174                                 new_str[i++] = '\\';
 175                                 str++;
 176                         break;
 177 
 178                         /* preserve backslashed quotes, dollar signs */
 179                         case '\'':
 180                         case '"':
 181                         case '$':
 182                                 new_str[i++] = '\\';
 183                                 new_str[i++] = *str++;
 184                         break;
 185 
 186                         case 'b':
 187                                 new_str[i++] = '\b';
 188                                 str++;
 189                         break;
 190 
 191                         case 'f':
 192                                 new_str[i++] = '\f';
 193                                 str++;
 194                         break;
 195 
 196                         case 'r':
 197                                 new_str[i++] = '\r';
 198                                 str++;
 199                         break;
 200 
 201                         case 'n':
 202                                 new_str[i++] = '\n';
 203                                 str++;
 204                         break;
 205 
 206                         case 's':
 207                                 new_str[i++] = ' ';
 208                                 str++;
 209                         break;
 210 
 211                         case 't':
 212                                 new_str[i++] = '\t';
 213                                 str++;
 214                         break;
 215 
 216                         case 'v':
 217                                 new_str[i++] = '\13';
 218                                 str++;
 219                         break;
 220 
 221                         case 'z':
 222                                 str++;
 223                         break;
 224 
 225                         case '0': case '1': case '2': case '3': case '4':
 226                         case '5': case '6': case '7': case '8': case '9': {
 227                                 char val;
 228 
 229                                 /* Three digit octal constant? */
 230                                 if (*str >= '0' && *str <= '3' &&
 231                                     *(str + 1) >= '0' && *(str + 1) <= '7' &&
 232                                     *(str + 2) >= '0' && *(str + 2) <= '7') {
 233 
 234                                         val = (DIGIT(*str) << 6) +
 235                                             (DIGIT(*(str + 1)) << 3) +
 236                                             DIGIT(*(str + 2));
 237 
 238                                         /*
 239                                          * Allow null value if user really
 240                                          * wants to shoot at feet, but beware!
 241                                          */
 242                                         new_str[i++] = val;
 243                                         str += 3;
 244                                         break;
 245                                 }
 246 
 247                                 /*
 248                                  * One or two digit hex constant?
 249                                  * If two are there they will both be taken.
 250                                  * Use \z to split them up if this is not
 251                                  * wanted.
 252                                  */
 253                                 if (*str == '0' &&
 254                                     (*(str + 1) == 'x' || *(str + 1) == 'X') &&
 255                                     isxdigit(*(str + 2))) {
 256                                         val = DIGIT(*(str + 2));
 257                                         if (isxdigit(*(str + 3))) {
 258                                                 val = (val << 4) +
 259                                                     DIGIT(*(str + 3));
 260                                                 str += 4;
 261                                         } else
 262                                                 str += 3;
 263                                         /* Yep, allow null value here too */
 264                                         new_str[i++] = val;
 265                                         break;
 266                                 }
 267                         }
 268                         break;
 269 
 270                         default:
 271                                 new_str[i++] = *str++;
 272                         break;
 273                         }
 274                 } else {
 275                         if (*str == '\\') {
 276                                 seenbs = 1;
 277                                 str++;
 278                         } else
 279                                 new_str[i++] = *str++;
 280                 }
 281         }
 282 
 283         if (seenbs) {
 284                 /*
 285                  * The final character was a '\'.
 286                  * Put it in as a single backslash.
 287                  */
 288                 new_str[i++] = '\\';
 289         }
 290         new_str[i] = '\0';
 291         return (new_str);
 292 }
 293 
 294 /*
 295  * parse: accept a string of input and "parse" it for backslash
 296  * substitutions and environment variable expansions (${var}),
 297  * returning an argc/argv style vector of whitespace separated
 298  * arguments.  Returns 0 on success, 1 on failure (ok, ok, so I
 299  * wimped-out on the error codes! :).
 300  *
 301  * Note that the argv array returned must be freed by the caller, but
 302  * we own the space allocated for arguments and will free that on next
 303  * invocation.  This allows argv consumers to modify the array if
 304  * required.
 305  *
 306  * NB: environment variables that expand to more than one whitespace
 307  * separated token will be returned as a single argv[] element, not
 308  * split in turn.  Expanded text is also immune to further backslash
 309  * elimination or expansion since this is a one-pass, non-recursive
 310  * parser.  You didn't specify more than this so if you want more, ask
 311  * me. - jkh
 312  */
 313 
 314 #define PARSE_FAIL(expr)        \
 315 if (expr) { \
 316     printf("fail at line %d\n", __LINE__); \
 317     clean(); \
 318     free(copy); \
 319     free(buf); \
 320     return (1); \
 321 }
 322 
 323 /* Accept the usual delimiters for a variable, returning counterpart */
 324 static char
 325 isdelim(int ch)
 326 {
 327         if (ch == '{')
 328                 return ('}');
 329         else if (ch == '(')
 330                 return (')');
 331         return ('\0');
 332 }
 333 
 334 static int
 335 isquote(int ch)
 336 {
 337         return (ch == '\'');
 338 }
 339 
 340 static int
 341 isdquote(int ch)
 342 {
 343         return (ch == '"');
 344 }
 345 
 346 int
 347 parse(int *argc, char ***argv, char *str)
 348 {
 349         int ac;
 350         char *val, *p, *q, *copy = NULL;
 351         size_t i = 0;
 352         char token, tmp, quote, dquote, *buf;
 353         enum { STR, VAR, WHITE } state;
 354 
 355         ac = *argc = 0;
 356         dquote = quote = 0;
 357         if (!str || (p = copy = backslash(str)) == NULL)
 358                 return (1);
 359 
 360         /* Initialize vector and state */
 361         clean();
 362         state = STR;
 363         buf = (char *)malloc(PARSE_BUFSIZE);
 364         token = 0;
 365 
 366         /* And awaaaaaaaaay we go! */
 367         while (*p) {
 368                 switch (state) {
 369                 case STR:
 370                         if ((*p == '\\') && p[1]) {
 371                                 p++;
 372                                 PARSE_FAIL(i == (PARSE_BUFSIZE - 1));
 373                                 buf[i++] = *p++;
 374                         } else if (isquote(*p)) {
 375                                 quote = quote ? 0 : *p;
 376                                 if (dquote) { /* keep quote */
 377                                         PARSE_FAIL(i == (PARSE_BUFSIZE - 1));
 378                                         buf[i++] = *p++;
 379                                 } else
 380                                         ++p;
 381                         } else if (isdquote(*p)) {
 382                                 dquote = dquote ? 0 : *p;
 383                                 if (quote) { /* keep dquote */
 384                                         PARSE_FAIL(i == (PARSE_BUFSIZE - 1));
 385                                         buf[i++] = *p++;
 386                                 } else
 387                                         ++p;
 388                         } else if (isspace(*p) && !quote && !dquote) {
 389                                 state = WHITE;
 390                                 if (i) {
 391                                         buf[i] = '\0';
 392                                         PARSE_FAIL(insert(&ac, buf));
 393                                         i = 0;
 394                                 }
 395                                 ++p;
 396                         } else if (*p == '$' && !quote) {
 397                                 token = isdelim(*(p + 1));
 398                                 if (token)
 399                                         p += 2;
 400                                 else
 401                                         ++p;
 402                                 state = VAR;
 403                         } else {
 404                                 PARSE_FAIL(i == (PARSE_BUFSIZE - 1));
 405                                 buf[i++] = *p++;
 406                         }
 407                 break;
 408 
 409                 case WHITE:
 410                         if (isspace(*p))
 411                                 ++p;
 412                         else
 413                                 state = STR;
 414                 break;
 415 
 416                 case VAR:
 417                         if (token) {
 418                                 PARSE_FAIL((q = strchr(p, token)) == NULL);
 419                         } else {
 420                                 q = p;
 421                                 while (*q && !isspace(*q))
 422                                 ++q;
 423                         }
 424                         tmp = *q;
 425                         *q = '\0';
 426                         if ((val = getenv(p)) != NULL) {
 427                                 size_t len = strlen(val);
 428 
 429                                 strncpy(buf + i, val, PARSE_BUFSIZE - (i + 1));
 430                                 i += min(len, PARSE_BUFSIZE - 1);
 431                         }
 432                         *q = tmp;       /* restore value */
 433                         p = q + (token ? 1 : 0);
 434                         state = STR;
 435                 break;
 436                 }
 437         }
 438         /* missing terminating ' or " */
 439         PARSE_FAIL(quote || dquote);
 440         /* If at end of token, add it */
 441         if (i && state == STR) {
 442                 buf[i] = '\0';
 443                 PARSE_FAIL(insert(&ac, buf));
 444         }
 445         args[ac] = NULL;
 446         *argc = ac;
 447         *argv = (char **)malloc((sizeof (char *) * ac + 1));
 448         bcopy(args, *argv, sizeof (char *) * ac + 1);
 449         free(buf);
 450         free(copy);
 451         return (0);
 452 }
 453 
 454 #define MAXARGS 20
 455 
 456 /* Clean vector space */
 457 static void
 458 clean(void)
 459 {
 460         int i;
 461 
 462         for (i = 0; i < MAXARGS; i++) {
 463                 if (args[i] != NULL) {
 464                         free(args[i]);
 465                         args[i] = NULL;
 466                 }
 467         }
 468 }
 469 
 470 static int
 471 insert(int *argcp, char *buf)
 472 {
 473         if (*argcp >= MAXARGS)
 474                 return (1);
 475         args[(*argcp)++] = strdup(buf);
 476         return (0);
 477 }
 478 
 479 static char *
 480 isadir(void)
 481 {
 482         char *buf;
 483         size_t bufsize = 20;
 484         int ret;
 485 
 486         if ((buf = malloc(bufsize)) == NULL)
 487                 return (NULL);
 488         ret = sysinfo(SI_ARCHITECTURE_K, buf, bufsize);
 489         if (ret == -1) {
 490                 free(buf);
 491                 return (NULL);
 492         }
 493         return (buf);
 494 }
 495 
 496 /*
 497  * Shim for taking commands from BF and passing them out to 'standard'
 498  * argv/argc command functions.
 499  */
 500 static void
 501 bf_command(ficlVm *vm)
 502 {
 503         char *name, *line, *tail, *cp;
 504         size_t len;
 505         struct bootblk_command *cmdp;
 506         bootblk_cmd_t *cmd;
 507         int nstrings, i;
 508         int argc, result;
 509         char **argv;
 510 
 511         /* Get the name of the current word */
 512         name = vm->runningWord->name;
 513 
 514         /* Find our command structure */
 515         cmd = NULL;
 516         STAILQ_FOREACH(cmdp, &commands, next) {
 517                 if ((cmdp->c_name != NULL) && strcmp(name, cmdp->c_name) == 0)
 518                         cmd = cmdp->c_fn;
 519         }
 520         if (cmd == NULL)
 521                 printf("callout for unknown command '%s'\n", name);
 522 
 523         /* Check whether we have been compiled or are being interpreted */
 524         if (ficlStackPopInteger(ficlVmGetDataStack(vm))) {
 525                 /*
 526                  * Get parameters from stack, in the format:
 527                  * an un ... a2 u2 a1 u1 n --
 528                  * Where n is the number of strings, a/u are pairs of
 529                  * address/size for strings, and they will be concatenated
 530                  * in LIFO order.
 531                  */
 532                 nstrings = ficlStackPopInteger(ficlVmGetDataStack(vm));
 533                 for (i = 0, len = 0; i < nstrings; i++)
 534                 len += ficlStackFetch(ficlVmGetDataStack(vm), i * 2).i + 1;
 535                 line = malloc(strlen(name) + len + 1);
 536                 strcpy(line, name);
 537 
 538                 if (nstrings)
 539                         for (i = 0; i < nstrings; i++) {
 540                                 len = ficlStackPopInteger(
 541                                     ficlVmGetDataStack(vm));
 542                                 cp = ficlStackPopPointer(
 543                                     ficlVmGetDataStack(vm));
 544                                 strcat(line, " ");
 545                                 strncat(line, cp, len);
 546                         }
 547         } else {
 548                 /* Get remainder of invocation */
 549                 tail = ficlVmGetInBuf(vm);
 550                 for (cp = tail, len = 0;
 551                     cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++, len++)
 552                         ;
 553 
 554                 line = malloc(strlen(name) + len + 2);
 555                 strcpy(line, name);
 556                 if (len > 0) {
 557                         strcat(line, " ");
 558                         strncat(line, tail, len);
 559                         ficlVmUpdateTib(vm, tail + len);
 560                 }
 561         }
 562 
 563         command_errmsg = command_errbuf;
 564         command_errbuf[0] = 0;
 565         if (!parse(&argc, &argv, line)) {
 566                 result = (cmd)(argc, argv);
 567                 free(argv);
 568         } else {
 569                 result = BF_PARSE;
 570         }
 571         free(line);
 572         /*
 573          * If there was error during nested ficlExec(), we may no longer have
 574          * valid environment to return.  Throw all exceptions from here.
 575          */
 576         if (result != 0)
 577                 ficlVmThrow(vm, result);
 578         /* This is going to be thrown!!! */
 579         ficlStackPushInteger(ficlVmGetDataStack(vm), result);
 580 }
 581 
 582 static char *
 583 get_currdev(void)
 584 {
 585         int ret;
 586         char *currdev;
 587         FILE *fp;
 588         struct mnttab mpref = {0};
 589         struct mnttab mp = {0};
 590 
 591         mpref.mnt_mountp = "/";
 592         fp = fopen(MNTTAB, "r");
 593 
 594         /* do the best we can to return something... */
 595         if (fp == NULL)
 596                 return (strdup(":"));
 597 
 598         ret = getmntany(fp, &mp, &mpref);
 599         (void) fclose(fp);
 600         if (ret == 0)
 601                 (void) asprintf(&currdev, "zfs:%s:", mp.mnt_special);
 602         else
 603                 return (strdup(":"));
 604 
 605         return (currdev);
 606 }
 607 
 608 /*
 609  * Replace a word definition (a builtin command) with another
 610  * one that:
 611  *
 612  *        - Throw error results instead of returning them on the stack
 613  *        - Pass a flag indicating whether the word was compiled or is
 614  *          being interpreted.
 615  *
 616  * There is one major problem with builtins that cannot be overcome
 617  * in anyway, except by outlawing it. We want builtins to behave
 618  * differently depending on whether they have been compiled or they
 619  * are being interpreted. Notice that this is *not* the interpreter's
 620  * current state. For example:
 621  *
 622  * : example ls ; immediate
 623  * : problem example ;          \ "ls" gets executed while compiling
 624  * example                      \ "ls" gets executed while interpreting
 625  *
 626  * Notice that, though the current state is different in the two
 627  * invocations of "example", in both cases "ls" has been
 628  * *compiled in*, which is what we really want.
 629  *
 630  * The problem arises when you tick the builtin. For example:
 631  *
 632  * : example-1 ['] ls postpone literal ; immediate
 633  * : example-2 example-1 execute ; immediate
 634  * : problem example-2 ;
 635  * example-2
 636  *
 637  * We have no way, when we get EXECUTEd, of knowing what our behavior
 638  * should be. Thus, our only alternative is to "outlaw" this. See RFI
 639  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
 640  * problem, concerning compile semantics.
 641  *
 642  * The problem is compounded by the fact that "' builtin CATCH" is valid
 643  * and desirable. The only solution is to create an intermediary word.
 644  * For example:
 645  *
 646  * : my-ls ls ;
 647  * : example ['] my-ls catch ;
 648  *
 649  * So, with the below implementation, here is a summary of the behavior
 650  * of builtins:
 651  *
 652  * ls -l                                \ "interpret" behavior, ie,
 653  *                                      \ takes parameters from TIB
 654  * : ex-1 s" -l" 1 ls ;                 \ "compile" behavior, ie,
 655  *                                      \ takes parameters from the stack
 656  * : ex-2 ['] ls catch ; immediate      \ undefined behavior
 657  * : ex-3 ['] ls catch ;                \ undefined behavior
 658  * ex-2 ex-3                            \ "interpret" behavior,
 659  *                                      \ catch works
 660  * : ex-4 ex-2 ;                        \ "compile" behavior,
 661  *                                      \ catch does not work
 662  * : ex-5 ex-3 ; immediate              \ same as ex-2
 663  * : ex-6 ex-3 ;                        \ same as ex-3
 664  * : ex-7 ['] ex-1 catch ;              \ "compile" behavior,
 665  *                                      \ catch works
 666  * : ex-8 postpone ls ; immediate       \ same as ex-2
 667  * : ex-9 postpone ls ;                 \ same as ex-3
 668  *
 669  * As the definition below is particularly tricky, and it's side effects
 670  * must be well understood by those playing with it, I'll be heavy on
 671  * the comments.
 672  *
 673  * (if you edit this definition, pay attention to trailing spaces after
 674  *  each word -- I warned you! :-) )
 675  */
 676 #define BUILTIN_CONSTRUCTOR \
 677 ": builtin: "           \
 678 ">in @ "             /* save the tib index pointer */ \
 679 "' "                    /* get next word's xt */ \
 680 "swap >in ! "                /* point again to next word */ \
 681 "create "               /* create a new definition of the next word */ \
 682 ", "                    /* save previous definition's xt */ \
 683 "immediate "            /* make the new definition an immediate word */ \
 684                         \
 685 "does> "             /* Now, the *new* definition will: */ \
 686 "state @ if "           /* if in compiling state: */ \
 687 "1 postpone literal "   /* pass 1 flag to indicate compile */ \
 688 "@ compile, "           /* compile in previous definition */ \
 689 "postpone throw "               /* throw stack-returned result */ \
 690 "else "         /* if in interpreting state: */ \
 691 "0 swap "                       /* pass 0 flag to indicate interpret */ \
 692 "@ execute "            /* call previous definition */ \
 693 "throw "                        /* throw stack-returned result */ \
 694 "then ; "
 695 
 696 extern int ficlExecFD(ficlVm *, int);
 697 #define COMMAND_SET(ptr, name, desc, fn)                \
 698         ptr = malloc(sizeof (struct bootblk_command));  \
 699         ptr->c_name = (name);                                \
 700         ptr->c_desc = (desc);                                \
 701         ptr->c_fn = (fn);
 702 
 703 /*
 704  * Initialise the Forth interpreter, create all our commands as words.
 705  */
 706 ficlVm *
 707 bf_init(const char *rc, ficlOutputFunction out)
 708 {
 709         struct bootblk_command *cmdp;
 710         char create_buf[41];    /* 31 characters-long builtins */
 711         char *buf;
 712         int fd, rv;
 713         ficlSystemInformation *fsi;
 714         ficlDictionary *dict;
 715         ficlDictionary *env;
 716 
 717         /* set up commands list */
 718         STAILQ_INIT(&commands);
 719         COMMAND_SET(cmdp, "help", "detailed help", command_help);
 720         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 721         COMMAND_SET(cmdp, "?", "list commands", command_commandlist);
 722         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 723         COMMAND_SET(cmdp, "show", "show variable(s)", command_show);
 724         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 725         COMMAND_SET(cmdp, "printenv", "show variable(s)", command_show);
 726         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 727         COMMAND_SET(cmdp, "set", "set a variable", command_set);
 728         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 729         COMMAND_SET(cmdp, "setprop", "set a variable", command_setprop);
 730         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 731         COMMAND_SET(cmdp, "unset", "unset a variable", command_unset);
 732         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 733         COMMAND_SET(cmdp, "echo", "echo arguments", command_echo);
 734         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 735         COMMAND_SET(cmdp, "read", "read input from the terminal", command_read);
 736         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 737         COMMAND_SET(cmdp, "more", "show contents of a file", command_more);
 738         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 739         COMMAND_SET(cmdp, "ls", "list files", command_ls);
 740         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 741         COMMAND_SET(cmdp, "include", "read commands from a file",
 742             command_include);
 743         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 744         COMMAND_SET(cmdp, "boot", "boot a file or loaded kernel", command_boot);
 745         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 746         COMMAND_SET(cmdp, "autoboot", "boot automatically after a delay",
 747             command_autoboot);
 748         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 749         COMMAND_SET(cmdp, "load", "load a kernel or module", command_load);
 750         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 751         COMMAND_SET(cmdp, "unload", "unload all modules", command_unload);
 752         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 753         COMMAND_SET(cmdp, "reboot", "reboot the system", command_reboot);
 754         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 755         COMMAND_SET(cmdp, "framebuffer", "framebuffer mode management",
 756             command_framebuffer);
 757         STAILQ_INSERT_TAIL(&commands, cmdp, next);
 758 
 759         fsi = malloc(sizeof (ficlSystemInformation));
 760         ficlSystemInformationInitialize(fsi);
 761         fsi->textOut = out;
 762         fsi->dictionarySize = BF_DICTSIZE;
 763 
 764         bf_sys = ficlSystemCreate(fsi);
 765         free(fsi);
 766         ficlSystemCompileExtras(bf_sys);
 767         bf_vm = ficlSystemCreateVm(bf_sys);
 768 
 769         buf = isadir();
 770         if (buf == NULL || strcmp(buf, "amd64") != 0) {
 771                 (void) setenv("ISADIR", "", 1);
 772         } else {
 773                 (void) setenv("ISADIR", buf, 1);
 774         }
 775         if (buf != NULL)
 776                 free(buf);
 777         buf = get_currdev();
 778         (void) setenv("currdev", buf, 1);
 779         free(buf);
 780 
 781         /* Put all private definitions in a "builtins" vocabulary */
 782         rv = ficlVmEvaluate(bf_vm,
 783             "vocabulary builtins also builtins definitions");
 784         if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
 785                 printf("error interpreting forth: %d\n", rv);
 786                 exit(1);
 787         }
 788 
 789         /* Builtin constructor word  */
 790         rv = ficlVmEvaluate(bf_vm, BUILTIN_CONSTRUCTOR);
 791         if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
 792                 printf("error interpreting forth: %d\n", rv);
 793                 exit(1);
 794         }
 795 
 796         /* make all commands appear as Forth words */
 797         dict = ficlSystemGetDictionary(bf_sys);
 798         cmdp = NULL;
 799         STAILQ_FOREACH(cmdp, &commands, next) {
 800                 ficlDictionaryAppendPrimitive(dict, (char *)cmdp->c_name,
 801                     bf_command, FICL_WORD_DEFAULT);
 802                 rv = ficlVmEvaluate(bf_vm, "forth definitions builtins");
 803                 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
 804                         printf("error interpreting forth: %d\n", rv);
 805                         exit(1);
 806                 }
 807                 sprintf(create_buf, "builtin: %s", cmdp->c_name);
 808                 rv = ficlVmEvaluate(bf_vm, create_buf);
 809                 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
 810                         printf("error interpreting forth: %d\n", rv);
 811                         exit(1);
 812                 }
 813                 rv = ficlVmEvaluate(bf_vm, "builtins definitions");
 814                 if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
 815                         printf("error interpreting forth: %d\n", rv);
 816                         exit(1);
 817                 }
 818         }
 819         rv = ficlVmEvaluate(bf_vm, "only forth definitions");
 820         if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
 821                 printf("error interpreting forth: %d\n", rv);
 822                 exit(1);
 823         }
 824 
 825         /*
 826          * Export some version numbers so that code can detect the
 827          * loader/host version
 828          */
 829         env = ficlSystemGetEnvironment(bf_sys);
 830         ficlDictionarySetConstant(env, "loader_version",
 831             (bootprog_rev[0] - '0') * 10 + (bootprog_rev[2] - '0'));
 832 
 833         /* try to load and run init file if present */
 834         if (rc == NULL)
 835                 rc = "/boot/forth/boot.4th";
 836         if (*rc != '\0') {
 837                 fd = open(rc, O_RDONLY);
 838                 if (fd != -1) {
 839                         (void) ficlExecFD(bf_vm, fd);
 840                         close(fd);
 841                 }
 842         }
 843 
 844         gfx_framework_init();
 845         return (bf_vm);
 846 }
 847 
 848 void
 849 bf_fini(void)
 850 {
 851         ficlSystemDestroy(bf_sys);
 852         gfx_framework_fini();
 853 }
 854 
 855 /*
 856  * Feed a line of user input to the Forth interpreter
 857  */
 858 int
 859 bf_run(char *line)
 860 {
 861         int result;
 862         ficlString s;
 863 
 864         FICL_STRING_SET_FROM_CSTRING(s, line);
 865         result = ficlVmExecuteString(bf_vm, s);
 866 
 867         switch (result) {
 868         case FICL_VM_STATUS_OUT_OF_TEXT:
 869         case FICL_VM_STATUS_ABORTQ:
 870         case FICL_VM_STATUS_QUIT:
 871         case FICL_VM_STATUS_ERROR_EXIT:
 872         break;
 873         case FICL_VM_STATUS_USER_EXIT:
 874         break;
 875         case FICL_VM_STATUS_ABORT:
 876                 printf("Aborted!\n");
 877         break;
 878         case BF_PARSE:
 879                 printf("Parse error!\n");
 880         break;
 881         default:
 882                 if (command_errmsg != NULL) {
 883                         printf("%s\n", command_errmsg);
 884                         command_errmsg = NULL;
 885                 }
 886         }
 887 
 888         setenv("interpret", bf_vm->state ? "" : "ok", 1);
 889 
 890         return (result);
 891 }
 892 
 893 char *
 894 get_dev(const char *path)
 895 {
 896         FILE *fp;
 897         struct mnttab mpref = {0};
 898         struct mnttab mp = {0};
 899         char *currdev;
 900         int ret;
 901         char *buf;
 902         char *tmppath;
 903         char *tmpdev;
 904         char *cwd = NULL;
 905 
 906         fp = fopen(MNTTAB, "r");
 907 
 908         /* do the best we can to return something... */
 909         if (fp == NULL)
 910                 return (strdup(path));
 911 
 912         /*
 913          * the path can have device provided, check for it
 914          * and extract it.
 915          */
 916         buf = strrchr(path, ':');
 917         if (buf != NULL) {
 918                 tmppath = buf+1;                /* real path */
 919                 buf = strchr(path, ':');        /* skip zfs: */
 920                 buf++;
 921                 tmpdev = strdup(buf);
 922                 buf = strchr(tmpdev, ':');      /* get ending : */
 923                 *buf = '\0';
 924         } else {
 925                 tmppath = (char *)path;
 926                 if (tmppath[0] != '/')
 927                         if ((cwd = getcwd(NULL, PATH_MAX)) == NULL) {
 928                                 (void) fclose(fp);
 929                                 return (strdup(path));
 930                         }
 931 
 932                 currdev = getenv("currdev");
 933                 buf = strchr(currdev, ':');     /* skip zfs: */
 934                 if (buf == NULL) {
 935                         (void) fclose(fp);
 936                         return (strdup(path));
 937                 }
 938                 buf++;
 939                 tmpdev = strdup(buf);
 940                 buf = strchr(tmpdev, ':');      /* get ending : */
 941                 *buf = '\0';
 942         }
 943 
 944         mpref.mnt_special = tmpdev;
 945         ret = getmntany(fp, &mp, &mpref);
 946         (void) fclose(fp);
 947         free(tmpdev);
 948 
 949         if (cwd == NULL)
 950                 (void) asprintf(&buf, "%s/%s", ret? "":mp.mnt_mountp, tmppath);
 951         else {
 952                 (void) asprintf(&buf, "%s/%s/%s", ret? "":mp.mnt_mountp, cwd,
 953                     tmppath);
 954                 free(cwd);
 955         }
 956         return (buf);
 957 }
 958 
 959 static void
 960 ngets(char *buf, int n)
 961 {
 962         int c;
 963         char *lp;
 964 
 965         for (lp = buf; ; )
 966                 switch (c = getchar() & 0177) {
 967                 case '\n':
 968                 case '\r':
 969                         *lp = '\0';
 970                         putchar('\n');
 971                 return;
 972                 case '\b':
 973                 case '\177':
 974                         if (lp > buf) {
 975                                 lp--;
 976                                 putchar('\b');
 977                                 putchar(' ');
 978                                 putchar('\b');
 979                         }
 980                 break;
 981                 case 'r'&037: {
 982                         char *p;
 983 
 984                         putchar('\n');
 985                         for (p = buf; p < lp; ++p)
 986                                 putchar(*p);
 987                 break;
 988                 }
 989                 case 'u'&037:
 990                 case 'w'&037:
 991                         lp = buf;
 992                         putchar('\n');
 993                 break;
 994                 default:
 995                         if ((n < 1) || ((lp - buf) < n - 1)) {
 996                                 *lp++ = c;
 997                                 putchar(c);
 998                         }
 999                 }
1000         /*NOTREACHED*/
1001 }
1002 
1003 static int
1004 fgetstr(char *buf, int size, int fd)
1005 {
1006         char c;
1007         int err, len;
1008 
1009         size--;                 /* leave space for terminator */
1010         len = 0;
1011         while (size != 0) {
1012                 err = read(fd, &c, sizeof (c));
1013                 if (err < 0)                 /* read error */
1014                         return (-1);
1015 
1016                 if (err == 0) { /* EOF */
1017                         if (len == 0)
1018                                 return (-1);    /* nothing to read */
1019                         break;
1020                 }
1021                 if ((c == '\r') || (c == '\n')) /* line terminators */
1022                         break;
1023                 *buf++ = c;                     /* keep char */
1024                 size--;
1025                 len++;
1026         }
1027         *buf = 0;
1028         return (len);
1029 }
1030 
1031 static char *
1032 unargv(int argc, char *argv[])
1033 {
1034         size_t hlong;
1035         int i;
1036         char *cp;
1037 
1038         for (i = 0, hlong = 0; i < argc; i++)
1039                 hlong += strlen(argv[i]) + 2;
1040 
1041         if (hlong == 0)
1042                 return (NULL);
1043 
1044         cp = malloc(hlong);
1045         cp[0] = 0;
1046         for (i = 0; i < argc; i++) {
1047                 strcat(cp, argv[i]);
1048                 if (i < (argc - 1))
1049                         strcat(cp, " ");
1050         }
1051 
1052         return (cp);
1053 }
1054 
1055 /*
1056  * Help is read from a formatted text file.
1057  *
1058  * Entries in the file are formatted as:
1059  * # Ttopic [Ssubtopic] Ddescription
1060  * help
1061  * text
1062  * here
1063  * #
1064  *
1065  * Note that for code simplicity's sake, the above format must be followed
1066  * exactly.
1067  *
1068  * Subtopic entries must immediately follow the topic (this is used to
1069  * produce the listing of subtopics).
1070  *
1071  * If no argument(s) are supplied by the user, the help for 'help' is displayed.
1072  */
1073 static int
1074 help_getnext(int fd, char **topic, char **subtopic, char **desc)
1075 {
1076         char line[81], *cp, *ep;
1077 
1078         for (;;) {
1079                 if (fgetstr(line, 80, fd) < 0)
1080                         return (0);
1081 
1082                 if ((strlen(line) < 3) || (line[0] != '#') || (line[1] != ' '))
1083                         continue;
1084 
1085                 *topic = *subtopic = *desc = NULL;
1086                 cp = line + 2;
1087                 while ((cp != NULL) && (*cp != 0)) {
1088                         ep = strchr(cp, ' ');
1089                         if ((*cp == 'T') && (*topic == NULL)) {
1090                                 if (ep != NULL)
1091                                         *ep++ = 0;
1092                                 *topic = strdup(cp + 1);
1093                         } else if ((*cp == 'S') && (*subtopic == NULL)) {
1094                                 if (ep != NULL)
1095                                         *ep++ = 0;
1096                                 *subtopic = strdup(cp + 1);
1097                         } else if (*cp == 'D') {
1098                                 *desc = strdup(cp + 1);
1099                                 ep = NULL;
1100                         }
1101                         cp = ep;
1102                 }
1103                 if (*topic == NULL) {
1104                         if (*subtopic != NULL)
1105                                 free(*subtopic);
1106                         if (*desc != NULL)
1107                                 free(*desc);
1108                         continue;
1109                 }
1110                 return (1);
1111         }
1112 }
1113 
1114 static int
1115 help_emitsummary(char *topic, char *subtopic, char *desc)
1116 {
1117         int i;
1118 
1119         pager_output("    ");
1120         pager_output(topic);
1121         i = strlen(topic);
1122         if (subtopic != NULL) {
1123                 pager_output(" ");
1124                 pager_output(subtopic);
1125                 i += strlen(subtopic) + 1;
1126         }
1127         if (desc != NULL) {
1128                 do {
1129                         pager_output(" ");
1130                 } while (i++ < 30);
1131                 pager_output(desc);
1132         }
1133         return (pager_output("\n"));
1134 }
1135 
1136 static int
1137 command_help(int argc, char *argv[])
1138 {
1139         char buf[81];   /* XXX buffer size? */
1140         int hfd, matched, doindex;
1141         char *topic, *subtopic, *t, *s, *d;
1142 
1143         /* page the help text from our load path */
1144         sprintf(buf, "/boot/loader.help");
1145         if ((hfd = open(buf, O_RDONLY)) < 0) {
1146                 printf("Verbose help not available, "
1147                     "use '?' to list commands\n");
1148                 return (CMD_OK);
1149         }
1150 
1151         /* pick up request from arguments */
1152         topic = subtopic = NULL;
1153         switch (argc) {
1154         case 3:
1155                 subtopic = strdup(argv[2]);
1156                 /* FALLTHROUGH */
1157         case 2:
1158                 topic = strdup(argv[1]);
1159         break;
1160         case 1:
1161                 topic = strdup("help");
1162         break;
1163         default:
1164                 command_errmsg = "usage is 'help <topic> [<subtopic>]";
1165                 close(hfd);
1166                 return (CMD_ERROR);
1167         }
1168 
1169         /* magic "index" keyword */
1170         doindex = strcmp(topic, "index") == 0;
1171         matched = doindex;
1172 
1173         /* Scan the helpfile looking for help matching the request */
1174         pager_open();
1175         while (help_getnext(hfd, &t, &s, &d)) {
1176                 if (doindex) {          /* dink around formatting */
1177                         if (help_emitsummary(t, s, d))
1178                                 break;
1179 
1180                 } else if (strcmp(topic, t)) {
1181                         /* topic mismatch */
1182                         /* nothing more on this topic, stop scanning */
1183                         if (matched)
1184                                 break;
1185                 } else {
1186                         /* topic matched */
1187                         matched = 1;
1188                         if (((subtopic == NULL) && (s == NULL)) ||
1189                             ((subtopic != NULL) && (s != NULL) &&
1190                             strcmp(subtopic, s) == 0)) {
1191                                 /* exact match, print text */
1192                                 while ((fgetstr(buf, 80, hfd) >= 0) &&
1193                                     (buf[0] != '#')) {
1194                                         if (pager_output(buf))
1195                                                 break;
1196                                         if (pager_output("\n"))
1197                                                 break;
1198                                 }
1199                         } else if ((subtopic == NULL) && (s != NULL)) {
1200                                 /* topic match, list subtopics */
1201                                 if (help_emitsummary(t, s, d))
1202                                         break;
1203                         }
1204                 }
1205                 free(t);
1206                 free(s);
1207                 free(d);
1208         }
1209         pager_close();
1210         close(hfd);
1211         if (!matched) {
1212                 snprintf(command_errbuf, sizeof (command_errbuf),
1213                     "no help available for '%s'", topic);
1214                 free(topic);
1215                 if (subtopic)
1216                         free(subtopic);
1217                 return (CMD_ERROR);
1218         }
1219         free(topic);
1220         if (subtopic)
1221                 free(subtopic);
1222         return (CMD_OK);
1223 }
1224 
1225 static int
1226 command_commandlist(int argc, char *argv[])
1227 {
1228         struct bootblk_command *cmdp;
1229         int res;
1230         char name[20];
1231 
1232         res = 0;
1233         pager_open();
1234         res = pager_output("Available commands:\n");
1235         cmdp = NULL;
1236         STAILQ_FOREACH(cmdp, &commands, next) {
1237                 if (res)
1238                         break;
1239                 if ((cmdp->c_name != NULL) && (cmdp->c_desc != NULL)) {
1240                         sprintf(name, "  %-15s  ", cmdp->c_name);
1241                         pager_output(name);
1242                         pager_output(cmdp->c_desc);
1243                         res = pager_output("\n");
1244                 }
1245         }
1246         pager_close();
1247         return (CMD_OK);
1248 }
1249 
1250 /*
1251  * XXX set/show should become set/echo if we have variable
1252  * substitution happening.
1253  */
1254 static int
1255 command_show(int argc, char *argv[])
1256 {
1257         char **ev;
1258         char *cp;
1259 
1260         if (argc < 2) {
1261                 /*
1262                  * With no arguments, print everything.
1263                  */
1264                 pager_open();
1265                 for (ev = _environ; *ev != NULL; ev++) {
1266                         pager_output(*ev);
1267                         cp = getenv(*ev);
1268                         if (cp != NULL) {
1269                                 pager_output("=");
1270                                 pager_output(cp);
1271                         }
1272                         if (pager_output("\n"))
1273                                 break;
1274                 }
1275                 pager_close();
1276         } else {
1277                 if ((cp = getenv(argv[1])) != NULL) {
1278                         printf("%s\n", cp);
1279                 } else {
1280                         snprintf(command_errbuf, sizeof (command_errbuf),
1281                             "variable '%s' not found", argv[1]);
1282                         return (CMD_ERROR);
1283                 }
1284         }
1285         return (CMD_OK);
1286 }
1287 
1288 static int
1289 command_set(int argc, char *argv[])
1290 {
1291         int     err;
1292         char    *value, *copy;
1293 
1294         if (argc != 2) {
1295                 command_errmsg = "wrong number of arguments";
1296                 return (CMD_ERROR);
1297         } else {
1298                 copy = strdup(argv[1]);
1299                 if (copy == NULL) {
1300                         command_errmsg = strerror(errno);
1301                         return (CMD_ERROR);
1302                 }
1303                 if ((value = strchr(copy, '=')) != NULL)
1304                         *(value++) = 0;
1305                 else
1306                         value = "";
1307                 if ((err = setenv(copy, value, 1)) != 0) {
1308                         free(copy);
1309                         command_errmsg = strerror(errno);
1310                         return (CMD_ERROR);
1311                 }
1312                 free(copy);
1313         }
1314         return (CMD_OK);
1315 }
1316 
1317 static int
1318 command_setprop(int argc, char *argv[])
1319 {
1320         int err;
1321 
1322         if (argc != 3) {
1323                 command_errmsg = "wrong number of arguments";
1324                 return (CMD_ERROR);
1325         } else {
1326                 if ((err = setenv(argv[1], argv[2], 1)) != 0) {
1327                         command_errmsg = strerror(err);
1328                         return (CMD_ERROR);
1329                 }
1330         }
1331         return (CMD_OK);
1332 }
1333 
1334 static int
1335 command_unset(int argc, char *argv[])
1336 {
1337         int err;
1338 
1339         if (argc != 2) {
1340                 command_errmsg = "wrong number of arguments";
1341                 return (CMD_ERROR);
1342         } else {
1343                 if ((err = unsetenv(argv[1])) != 0) {
1344                         command_errmsg = strerror(err);
1345                         return (CMD_ERROR);
1346                 }
1347         }
1348         return (CMD_OK);
1349 }
1350 
1351 static int
1352 command_echo(int argc, char *argv[])
1353 {
1354         char *s;
1355         int nl, ch;
1356 
1357         nl = 0;
1358         optind = 1;
1359         opterr = 1;
1360         while ((ch = getopt(argc, argv, "n")) != -1) {
1361                 switch (ch) {
1362                 case 'n':
1363                         nl = 1;
1364                 break;
1365                 case '?':
1366                 default:
1367                         /* getopt has already reported an error */
1368                 return (CMD_OK);
1369                 }
1370         }
1371         argv += (optind);
1372         argc -= (optind);
1373 
1374         s = unargv(argc, argv);
1375         if (s != NULL) {
1376                 printf("%s", s);
1377                 free(s);
1378         }
1379         if (!nl)
1380                 printf("\n");
1381         return (CMD_OK);
1382 }
1383 
1384 /*
1385  * A passable emulation of the sh(1) command of the same name.
1386  */
1387 static int
1388 ischar(void)
1389 {
1390         return (1);
1391 }
1392 
1393 static int
1394 command_read(int argc, char *argv[])
1395 {
1396         char *prompt;
1397         int timeout;
1398         time_t when;
1399         char *cp;
1400         char *name;
1401         char buf[256];          /* XXX size? */
1402         int c;
1403 
1404         timeout = -1;
1405         prompt = NULL;
1406         optind = 1;
1407         opterr = 1;
1408         while ((c = getopt(argc, argv, "p:t:")) != -1) {
1409                 switch (c) {
1410                 case 'p':
1411                         prompt = optarg;
1412                 break;
1413                 case 't':
1414                         timeout = strtol(optarg, &cp, 0);
1415                         if (cp == optarg) {
1416                                 snprintf(command_errbuf,
1417                                     sizeof (command_errbuf),
1418                                     "bad timeout '%s'", optarg);
1419                                 return (CMD_ERROR);
1420                         }
1421                 break;
1422                 default:
1423                 return (CMD_OK);
1424                 }
1425         }
1426 
1427         argv += (optind);
1428         argc -= (optind);
1429         name = (argc > 0) ? argv[0]: NULL;
1430 
1431         if (prompt != NULL)
1432                 printf("%s", prompt);
1433         if (timeout >= 0) {
1434                 when = time(NULL) + timeout;
1435                 while (!ischar())
1436                         if (time(NULL) >= when)
1437                                 return (CMD_OK); /* is timeout an error? */
1438         }
1439 
1440         ngets(buf, sizeof (buf));
1441 
1442         if (name != NULL)
1443                 setenv(name, buf, 1);
1444         return (CMD_OK);
1445 }
1446 
1447 /*
1448  * File pager
1449  */
1450 static int
1451 command_more(int argc, char *argv[])
1452 {
1453         int i;
1454         int res;
1455         char line[80];
1456         char *name;
1457 
1458         res = 0;
1459         pager_open();
1460         for (i = 1; (i < argc) && (res == 0); i++) {
1461                 sprintf(line, "*** FILE %s BEGIN ***\n", argv[i]);
1462                 if (pager_output(line))
1463                         break;
1464                 name = get_dev(argv[i]);
1465                 res = page_file(name);
1466                 free(name);
1467                 if (!res) {
1468                         sprintf(line, "*** FILE %s END ***\n", argv[i]);
1469                         res = pager_output(line);
1470                 }
1471         }
1472         pager_close();
1473 
1474         if (res == 0)
1475                 return (CMD_OK);
1476         return (CMD_ERROR);
1477 }
1478 
1479 static int
1480 page_file(char *filename)
1481 {
1482         int result;
1483 
1484         result = pager_file(filename);
1485 
1486         if (result == -1) {
1487                 snprintf(command_errbuf, sizeof (command_errbuf),
1488                     "error showing %s", filename);
1489         }
1490 
1491         return (result);
1492 }
1493 
1494 static int
1495 command_ls(int argc, char *argv[])
1496 {
1497         DIR *dir;
1498         int fd;
1499         struct stat sb;
1500         struct dirent *d;
1501         char *buf, *path;
1502         char lbuf[128]; /* one line */
1503         int result, ch;
1504         int verbose;
1505 
1506         result = CMD_OK;
1507         fd = -1;
1508         verbose = 0;
1509         optind = 1;
1510         opterr = 1;
1511         while ((ch = getopt(argc, argv, "l")) != -1) {
1512                 switch (ch) {
1513                 case 'l':
1514                         verbose = 1;
1515                 break;
1516                 case '?':
1517                 default:
1518                         /* getopt has already reported an error */
1519                 return (CMD_OK);
1520                 }
1521         }
1522         argv += (optind - 1);
1523         argc -= (optind - 1);
1524 
1525         if (argc < 2) {
1526                 path = "";
1527         } else {
1528                 path = argv[1];
1529         }
1530 
1531         fd = ls_getdir(&path);
1532         if (fd == -1) {
1533                 result = CMD_ERROR;
1534                 goto out;
1535         }
1536         dir = fdopendir(fd);
1537         pager_open();
1538         pager_output(path);
1539         pager_output("\n");
1540 
1541         while ((d = readdir(dir)) != NULL) {
1542                 if (strcmp(d->d_name, ".") && strcmp(d->d_name, "..")) {
1543                         /* stat the file, if possible */
1544                         sb.st_size = 0;
1545                         sb.st_mode = 0;
1546                         buf = malloc(strlen(path) + strlen(d->d_name) + 2);
1547                         if (path[0] == '\0')
1548                                 sprintf(buf, "%s", d->d_name);
1549                         else
1550                                 sprintf(buf, "%s/%s", path, d->d_name);
1551                         /* ignore return, could be symlink, etc. */
1552                         if (stat(buf, &sb))
1553                                 sb.st_size = 0;
1554                         free(buf);
1555                         if (verbose) {
1556                                 sprintf(lbuf, " %c %8d %s\n",
1557                                     typestr[sb.st_mode >> 12],
1558                                     (int)sb.st_size, d->d_name);
1559                         } else {
1560                                 sprintf(lbuf, " %c  %s\n",
1561                                     typestr[sb.st_mode >> 12], d->d_name);
1562                         }
1563                         if (pager_output(lbuf))
1564                                 goto out;
1565                 }
1566         }
1567 out:
1568         pager_close();
1569         if (fd != -1)
1570                 closedir(dir);
1571         if (path != NULL)
1572                 free(path);
1573         return (result);
1574 }
1575 
1576 /*
1577  * Given (path) containing a vaguely reasonable path specification, return an fd
1578  * on the directory, and an allocated copy of the path to the directory.
1579  */
1580 static int
1581 ls_getdir(char **pathp)
1582 {
1583         struct stat sb;
1584         int fd;
1585         char *cp, *path;
1586 
1587         fd = -1;
1588 
1589         /* one extra byte for a possible trailing slash required */
1590         path = malloc(strlen(*pathp) + 2);
1591         strcpy(path, *pathp);
1592 
1593         /* Make sure the path is respectable to begin with */
1594         if ((cp = get_dev(path)) == NULL) {
1595                 snprintf(command_errbuf, sizeof (command_errbuf),
1596                     "bad path '%s'", path);
1597                 goto out;
1598         }
1599 
1600         /* If there's no path on the device, assume '/' */
1601         if (*cp == 0)
1602                 strcat(path, "/");
1603 
1604         fd = open(cp, O_RDONLY);
1605         if (fd < 0) {
1606                 snprintf(command_errbuf, sizeof (command_errbuf),
1607                     "open '%s' failed: %s", path, strerror(errno));
1608                 goto out;
1609         }
1610         if (fstat(fd, &sb) < 0) {
1611                 snprintf(command_errbuf, sizeof (command_errbuf),
1612                     "stat failed: %s", strerror(errno));
1613                 goto out;
1614         }
1615         if (!S_ISDIR(sb.st_mode)) {
1616                 snprintf(command_errbuf, sizeof (command_errbuf),
1617                     "%s: %s", path, strerror(ENOTDIR));
1618                 goto out;
1619         }
1620 
1621         free(cp);
1622         *pathp = path;
1623         return (fd);
1624 
1625 out:
1626         free(cp);
1627         free(path);
1628         *pathp = NULL;
1629         if (fd != -1)
1630                 close(fd);
1631         return (-1);
1632 }
1633 
1634 static int
1635 command_include(int argc, char *argv[])
1636 {
1637         int i;
1638         int res;
1639         char **argvbuf;
1640 
1641         /*
1642          * Since argv is static, we need to save it here.
1643          */
1644         argvbuf = (char **)calloc(argc, sizeof (char *));
1645         for (i = 0; i < argc; i++)
1646                 argvbuf[i] = strdup(argv[i]);
1647 
1648         res = CMD_OK;
1649         for (i = 1; (i < argc) && (res == CMD_OK); i++)
1650                 res = include(argvbuf[i]);
1651 
1652         for (i = 0; i < argc; i++)
1653                 free(argvbuf[i]);
1654         free(argvbuf);
1655 
1656         return (res);
1657 }
1658 
1659 /*
1660  * Header prepended to each line. The text immediately follows the header.
1661  * We try to make this short in order to save memory -- the loader has
1662  * limited memory available, and some of the forth files are very long.
1663  */
1664 struct includeline
1665 {
1666         struct includeline *next;
1667         int line;
1668         char text[];
1669 };
1670 
1671 int
1672 include(const char *filename)
1673 {
1674         struct includeline *script, *se, *sp;
1675         int res = CMD_OK;
1676         int prevsrcid, fd, line;
1677         char *cp, input[256]; /* big enough? */
1678         char *path;
1679 
1680         path = get_dev(filename);
1681         if (((fd = open(path, O_RDONLY)) == -1)) {
1682                 snprintf(command_errbuf, sizeof (command_errbuf),
1683                     "can't open '%s': %s", filename,
1684                     strerror(errno));
1685                 free(path);
1686                 return (CMD_ERROR);
1687         }
1688 
1689         free(path);
1690         /*
1691          * Read the script into memory.
1692          */
1693         script = se = NULL;
1694         line = 0;
1695 
1696         while (fgetstr(input, sizeof (input), fd) >= 0) {
1697                 line++;
1698                 cp = input;
1699                 /* Allocate script line structure and copy line, flags */
1700                 if (*cp == '\0')
1701                         continue;       /* ignore empty line, save memory */
1702                 if (cp[0] == '\\' && cp[1] == ' ')
1703                         continue;       /* ignore comment */
1704 
1705                 sp = malloc(sizeof (struct includeline) + strlen(cp) + 1);
1706                 /*
1707                  * On malloc failure (it happens!), free as much as possible
1708                  * and exit
1709                  */
1710                 if (sp == NULL) {
1711                         while (script != NULL) {
1712                                 se = script;
1713                                 script = script->next;
1714                                 free(se);
1715                         }
1716                         snprintf(command_errbuf, sizeof (command_errbuf),
1717                             "file '%s' line %d: memory allocation "
1718                             "failure - aborting", filename, line);
1719                         return (CMD_ERROR);
1720                 }
1721                 strcpy(sp->text, cp);
1722                 sp->line = line;
1723                 sp->next = NULL;
1724 
1725                 if (script == NULL) {
1726                         script = sp;
1727                 } else {
1728                         se->next = sp;
1729                 }
1730                 se = sp;
1731         }
1732         close(fd);
1733 
1734         /*
1735          * Execute the script
1736          */
1737 
1738         prevsrcid = bf_vm->sourceId.i;
1739         bf_vm->sourceId.i = fd+1;    /* 0 is user input device */
1740 
1741         res = CMD_OK;
1742 
1743         for (sp = script; sp != NULL; sp = sp->next) {
1744                 res = bf_run(sp->text);
1745                 if (res != FICL_VM_STATUS_OUT_OF_TEXT) {
1746                         snprintf(command_errbuf, sizeof (command_errbuf),
1747                             "Error while including %s, in the line %d:\n%s",
1748                             filename, sp->line, sp->text);
1749                         res = CMD_ERROR;
1750                         break;
1751                 } else
1752                         res = CMD_OK;
1753         }
1754 
1755         bf_vm->sourceId.i = -1;
1756         (void) bf_run("");
1757         bf_vm->sourceId.i = prevsrcid;
1758 
1759         while (script != NULL) {
1760                 se = script;
1761                 script = script->next;
1762                 free(se);
1763         }
1764 
1765         return (res);
1766 }
1767 
1768 static int
1769 command_boot(int argc, char *argv[])
1770 {
1771         return (CMD_OK);
1772 }
1773 
1774 static int
1775 command_autoboot(int argc, char *argv[])
1776 {
1777         return (CMD_OK);
1778 }
1779 
1780 static void
1781 moduledir_rebuild(void)
1782 {
1783         struct moduledir *mdp, *mtmp;
1784         const char *path, *cp, *ep;
1785         int cplen;
1786 
1787         path = getenv("module_path");
1788         if (path == NULL)
1789                 path = default_searchpath;
1790         /*
1791          * Rebuild list of module directories if it changed
1792          */
1793         STAILQ_FOREACH(mdp, &moduledir_list, d_link)
1794                 mdp->d_flags |= MDIR_REMOVED;
1795 
1796         for (ep = path; *ep != 0;  ep++) {
1797                 cp = ep;
1798                 for (; *ep != 0 && *ep != ';'; ep++)
1799                         ;
1800                 /*
1801                  * Ignore trailing slashes
1802                  */
1803                 for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/';
1804                     cplen--)
1805                         ;
1806                 STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1807                         if (strlen(mdp->d_path) != cplen ||
1808                             bcmp(cp, mdp->d_path, cplen) != 0)
1809                                 continue;
1810                         mdp->d_flags &= ~MDIR_REMOVED;
1811                         break;
1812                 }
1813                 if (mdp == NULL) {
1814                         mdp = malloc(sizeof (*mdp) + cplen + 1);
1815                         if (mdp == NULL)
1816                                 return;
1817                         mdp->d_path = (char *)(mdp + 1);
1818                         bcopy(cp, mdp->d_path, cplen);
1819                         mdp->d_path[cplen] = 0;
1820                         mdp->d_hints = NULL;
1821                         mdp->d_flags = 0;
1822                         STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1823                 }
1824                 if (*ep == 0)
1825                         break;
1826         }
1827         /*
1828          * Delete unused directories if any
1829          */
1830         mdp = STAILQ_FIRST(&moduledir_list);
1831         while (mdp) {
1832                 if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1833                         mdp = STAILQ_NEXT(mdp, d_link);
1834                 } else {
1835                         if (mdp->d_hints)
1836                                 free(mdp->d_hints);
1837                         mtmp = mdp;
1838                         mdp = STAILQ_NEXT(mdp, d_link);
1839                         STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1840                         free(mtmp);
1841                 }
1842         }
1843 }
1844 
1845 static char *
1846 file_lookup(const char *path, const char *name, int namelen)
1847 {
1848         struct stat st;
1849         char *result, *cp, *gz;
1850         int pathlen;
1851 
1852         pathlen = strlen(path);
1853         result = malloc(pathlen + namelen + 2);
1854         if (result == NULL)
1855                 return (NULL);
1856         bcopy(path, result, pathlen);
1857         if (pathlen > 0 && result[pathlen - 1] != '/')
1858                 result[pathlen++] = '/';
1859         cp = result + pathlen;
1860         bcopy(name, cp, namelen);
1861         cp += namelen;
1862         *cp = '\0';
1863         if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
1864                 return (result);
1865         /* also check for gz file */
1866         (void) asprintf(&gz, "%s.gz", result);
1867         if (gz != NULL) {
1868                 int res = stat(gz, &st);
1869                 free(gz);
1870                 if (res == 0)
1871                         return (result);
1872         }
1873         free(result);
1874         return (NULL);
1875 }
1876 
1877 static char *
1878 file_search(const char *name)
1879 {
1880         struct moduledir *mdp;
1881         struct stat sb;
1882         char *result;
1883         int namelen;
1884 
1885         if (name == NULL)
1886                 return (NULL);
1887         if (*name == 0)
1888                 return (strdup(name));
1889 
1890         if (strchr(name, '/') != NULL) {
1891                 char *gz;
1892                 if (stat(name, &sb) == 0)
1893                         return (strdup(name));
1894                 /* also check for gz file */
1895                 (void) asprintf(&gz, "%s.gz", name);
1896                 if (gz != NULL) {
1897                         int res = stat(gz, &sb);
1898                         free(gz);
1899                         if (res == 0)
1900                                 return (strdup(name));
1901                 }
1902                 return (NULL);
1903         }
1904 
1905         moduledir_rebuild();
1906         result = NULL;
1907         namelen = strlen(name);
1908         STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1909                 result = file_lookup(mdp->d_path, name, namelen);
1910                 if (result)
1911                         break;
1912         }
1913         return (result);
1914 }
1915 
1916 static int
1917 command_load(int argc, char *argv[])
1918 {
1919         int dofile, ch;
1920         char *typestr = NULL;
1921         char *filename;
1922         dofile = 0;
1923         optind = 1;
1924 
1925         if (argc == 1) {
1926                 command_errmsg = "no filename specified";
1927                 return (CMD_ERROR);
1928         }
1929 
1930         while ((ch = getopt(argc, argv, "kt:")) != -1) {
1931                 switch (ch) {
1932                 case 'k':
1933                         break;
1934                 case 't':
1935                         typestr = optarg;
1936                         dofile = 1;
1937                         break;
1938                 case '?':
1939                 default:
1940                         return (CMD_OK);
1941                 }
1942         }
1943         argv += (optind - 1);
1944         argc -= (optind - 1);
1945         if (dofile) {
1946                 if ((typestr == NULL) || (*typestr == 0)) {
1947                         command_errmsg = "invalid load type";
1948                         return (CMD_ERROR);
1949                 }
1950 #if 0
1951                 return (file_loadraw(argv[1], typestr, argc - 2, argv + 2, 1)
1952                     ? CMD_OK : CMD_ERROR);
1953 #endif
1954                 return (CMD_OK);
1955         }
1956 
1957         filename = file_search(argv[1]);
1958         if (filename == NULL) {
1959                 snprintf(command_errbuf, sizeof (command_errbuf),
1960                     "can't find '%s'", argv[1]);
1961                 return (CMD_ERROR);
1962         }
1963         setenv("kernelname", filename, 1);
1964 
1965         return (CMD_OK);
1966 }
1967 
1968 static int
1969 command_unload(int argc, char *argv[])
1970 {
1971         unsetenv("kernelname");
1972         return (CMD_OK);
1973 }
1974 
1975 static int
1976 command_reboot(int argc, char *argv[])
1977 {
1978         exit(0);
1979         return (CMD_OK);
1980 }
1981 
1982 /* Only implement get, ignore other arguments */
1983 static int
1984 command_framebuffer(int argc, char *argv[])
1985 {
1986         if (fb.fd < 0) {
1987                 printf("Framebuffer is not available.\n");
1988                 return (CMD_OK);
1989         }
1990 
1991         if (argc == 2 && strcmp(argv[1], "get") == 0) {
1992                 printf("\nSystem frame buffer: %s\n", fb.ident.name);
1993                 printf("%dx%dx%d, stride=%d\n", fb.fb_width, fb.fb_height,
1994                     fb.fb_depth, (fb.fb_pitch << 3) / fb.fb_depth);
1995                 return (CMD_OK);
1996         }
1997         if (argc == 2 && strcmp(argv[1], "list") == 0) {
1998                 printf("0: %dx%dx%d\n", fb.fb_width, fb.fb_height, fb.fb_depth);
1999                 return (CMD_OK);
2000         }
2001         return (CMD_OK);
2002 }