xref: /illumos-gate/usr/src/common/ficl/emu/loader_emu.c (revision 2a1fd0ffe121888d44fdec321c25b53dcfaa9118)
1 /*
2  * Copyright (c) 1998 Michael Smith <msmith@freebsd.org>
3  * Copyright 2019 OmniOS Community Edition (OmniOSce) Association.
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #include <fcntl.h>
31 #include <errno.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <strings.h>
36 #include <limits.h>
37 #include <unistd.h>
38 #include <dirent.h>
39 #include <macros.h>
40 #include <sys/systeminfo.h>
41 #include <sys/queue.h>
42 #include <sys/mnttab.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_sifting(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, "sifting", "find words", command_sifting);
756 	STAILQ_INSERT_TAIL(&commands, cmdp, next);
757 
758 	fsi = malloc(sizeof (ficlSystemInformation));
759 	ficlSystemInformationInitialize(fsi);
760 	fsi->textOut = out;
761 	fsi->dictionarySize = BF_DICTSIZE;
762 
763 	bf_sys = ficlSystemCreate(fsi);
764 	free(fsi);
765 	ficlSystemCompileExtras(bf_sys);
766 	bf_vm = ficlSystemCreateVm(bf_sys);
767 
768 	buf = isadir();
769 	if (buf == NULL || strcmp(buf, "amd64") != 0) {
770 		(void) setenv("ISADIR", "", 1);
771 	} else {
772 		(void) setenv("ISADIR", buf, 1);
773 	}
774 	if (buf != NULL)
775 		free(buf);
776 	buf = get_currdev();
777 	(void) setenv("currdev", buf, 1);
778 	free(buf);
779 
780 	/* Put all private definitions in a "builtins" vocabulary */
781 	rv = ficlVmEvaluate(bf_vm,
782 	    "vocabulary builtins also builtins definitions");
783 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
784 		printf("error interpreting forth: %d\n", rv);
785 		exit(1);
786 	}
787 
788 	/* Builtin constructor word  */
789 	rv = ficlVmEvaluate(bf_vm, BUILTIN_CONSTRUCTOR);
790 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
791 		printf("error interpreting forth: %d\n", rv);
792 		exit(1);
793 	}
794 
795 	/* make all commands appear as Forth words */
796 	dict = ficlSystemGetDictionary(bf_sys);
797 	cmdp = NULL;
798 	STAILQ_FOREACH(cmdp, &commands, next) {
799 		ficlDictionaryAppendPrimitive(dict, (char *)cmdp->c_name,
800 		    bf_command, FICL_WORD_DEFAULT);
801 		rv = ficlVmEvaluate(bf_vm, "forth definitions builtins");
802 		if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
803 			printf("error interpreting forth: %d\n", rv);
804 			exit(1);
805 		}
806 		snprintf(create_buf, sizeof (create_buf), "builtin: %s",
807 		    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 	return (bf_vm);
845 }
846 
847 void
848 bf_fini(void)
849 {
850 	ficlSystemDestroy(bf_sys);
851 }
852 
853 /*
854  * Feed a line of user input to the Forth interpreter
855  */
856 int
857 bf_run(char *line)
858 {
859 	int result;
860 	ficlString s;
861 
862 	FICL_STRING_SET_FROM_CSTRING(s, line);
863 	result = ficlVmExecuteString(bf_vm, s);
864 
865 	switch (result) {
866 	case FICL_VM_STATUS_OUT_OF_TEXT:
867 	case FICL_VM_STATUS_ABORTQ:
868 	case FICL_VM_STATUS_QUIT:
869 	case FICL_VM_STATUS_ERROR_EXIT:
870 	break;
871 	case FICL_VM_STATUS_USER_EXIT:
872 	break;
873 	case FICL_VM_STATUS_ABORT:
874 		printf("Aborted!\n");
875 	break;
876 	case BF_PARSE:
877 		printf("Parse error!\n");
878 	break;
879 	default:
880 		if (command_errmsg != NULL) {
881 			printf("%s\n", command_errmsg);
882 			command_errmsg = NULL;
883 		}
884 	}
885 
886 	setenv("interpret", bf_vm->state ? "" : "ok", 1);
887 
888 	return (result);
889 }
890 
891 char *
892 get_dev(const char *path)
893 {
894 	FILE *fp;
895 	struct mnttab mpref = {0};
896 	struct mnttab mp = {0};
897 	char *currdev;
898 	int ret;
899 	char *buf;
900 	char *tmppath;
901 	char *tmpdev;
902 	char *cwd = NULL;
903 
904 	fp = fopen(MNTTAB, "r");
905 
906 	/* do the best we can to return something... */
907 	if (fp == NULL)
908 		return (strdup(path));
909 
910 	/*
911 	 * the path can have device provided, check for it
912 	 * and extract it.
913 	 */
914 	buf = strrchr(path, ':');
915 	if (buf != NULL) {
916 		tmppath = buf+1;		/* real path */
917 		buf = strchr(path, ':');	/* skip zfs: */
918 		buf++;
919 		tmpdev = strdup(buf);
920 		buf = strchr(tmpdev, ':');	/* get ending : */
921 		*buf = '\0';
922 	} else {
923 		tmppath = (char *)path;
924 		if (tmppath[0] != '/')
925 			if ((cwd = getcwd(NULL, PATH_MAX)) == NULL) {
926 				(void) fclose(fp);
927 				return (strdup(path));
928 			}
929 
930 		currdev = getenv("currdev");
931 		buf = strchr(currdev, ':');	/* skip zfs: */
932 		if (buf == NULL) {
933 			(void) fclose(fp);
934 			return (strdup(path));
935 		}
936 		buf++;
937 		tmpdev = strdup(buf);
938 		buf = strchr(tmpdev, ':');	/* get ending : */
939 		*buf = '\0';
940 	}
941 
942 	mpref.mnt_special = tmpdev;
943 	ret = getmntany(fp, &mp, &mpref);
944 	(void) fclose(fp);
945 	free(tmpdev);
946 
947 	if (cwd == NULL)
948 		(void) asprintf(&buf, "%s/%s", ret? "":mp.mnt_mountp, tmppath);
949 	else {
950 		(void) asprintf(&buf, "%s/%s/%s", ret? "":mp.mnt_mountp, cwd,
951 		    tmppath);
952 		free(cwd);
953 	}
954 	return (buf);
955 }
956 
957 static void
958 ngets(char *buf, int n)
959 {
960 	int c;
961 	char *lp;
962 
963 	for (lp = buf; ; )
964 		switch (c = getchar() & 0177) {
965 		case '\n':
966 		case '\r':
967 			*lp = '\0';
968 			putchar('\n');
969 		return;
970 		case '\b':
971 		case '\177':
972 			if (lp > buf) {
973 				lp--;
974 				putchar('\b');
975 				putchar(' ');
976 				putchar('\b');
977 			}
978 		break;
979 		case 'r'&037: {
980 			char *p;
981 
982 			putchar('\n');
983 			for (p = buf; p < lp; ++p)
984 				putchar(*p);
985 		break;
986 		}
987 		case 'u'&037:
988 		case 'w'&037:
989 			lp = buf;
990 			putchar('\n');
991 		break;
992 		default:
993 			if ((n < 1) || ((lp - buf) < n - 1)) {
994 				*lp++ = c;
995 				putchar(c);
996 			}
997 		}
998 	/*NOTREACHED*/
999 }
1000 
1001 static int
1002 fgetstr(char *buf, int size, int fd)
1003 {
1004 	char c;
1005 	int err, len;
1006 
1007 	size--;			/* leave space for terminator */
1008 	len = 0;
1009 	while (size != 0) {
1010 		err = read(fd, &c, sizeof (c));
1011 		if (err < 0)			/* read error */
1012 			return (-1);
1013 
1014 		if (err == 0) {	/* EOF */
1015 			if (len == 0)
1016 				return (-1);	/* nothing to read */
1017 			break;
1018 		}
1019 		if ((c == '\r') || (c == '\n'))	/* line terminators */
1020 			break;
1021 		*buf++ = c;			/* keep char */
1022 		size--;
1023 		len++;
1024 	}
1025 	*buf = 0;
1026 	return (len);
1027 }
1028 
1029 static char *
1030 unargv(int argc, char *argv[])
1031 {
1032 	size_t hlong;
1033 	int i;
1034 	char *cp;
1035 
1036 	for (i = 0, hlong = 0; i < argc; i++)
1037 		hlong += strlen(argv[i]) + 2;
1038 
1039 	if (hlong == 0)
1040 		return (NULL);
1041 
1042 	cp = malloc(hlong);
1043 	cp[0] = 0;
1044 	for (i = 0; i < argc; i++) {
1045 		strcat(cp, argv[i]);
1046 		if (i < (argc - 1))
1047 			strcat(cp, " ");
1048 	}
1049 
1050 	return (cp);
1051 }
1052 
1053 /*
1054  * Help is read from a formatted text file.
1055  *
1056  * Entries in the file are formatted as:
1057  * # Ttopic [Ssubtopic] Ddescription
1058  * help
1059  * text
1060  * here
1061  * #
1062  *
1063  * Note that for code simplicity's sake, the above format must be followed
1064  * exactly.
1065  *
1066  * Subtopic entries must immediately follow the topic (this is used to
1067  * produce the listing of subtopics).
1068  *
1069  * If no argument(s) are supplied by the user, the help for 'help' is displayed.
1070  */
1071 static int
1072 help_getnext(int fd, char **topic, char **subtopic, char **desc)
1073 {
1074 	char line[81], *cp, *ep;
1075 
1076 	*topic = *subtopic = *desc = NULL;
1077 	for (;;) {
1078 		if (fgetstr(line, 80, fd) < 0)
1079 			return (0);
1080 
1081 		if (strlen(line) < 3 || line[0] != '#' || line[1] != ' ')
1082 			continue;
1083 
1084 		*topic = *subtopic = *desc = NULL;
1085 		cp = line + 2;
1086 		while (cp != NULL && *cp != 0) {
1087 			ep = strchr(cp, ' ');
1088 			if (*cp == 'T' && *topic == NULL) {
1089 				if (ep != NULL)
1090 					*ep++ = 0;
1091 				*topic = strdup(cp + 1);
1092 			} else if (*cp == 'S' && *subtopic == NULL) {
1093 				if (ep != NULL)
1094 					*ep++ = 0;
1095 				*subtopic = strdup(cp + 1);
1096 			} else if (*cp == 'D') {
1097 				*desc = strdup(cp + 1);
1098 				ep = NULL;
1099 			}
1100 			cp = ep;
1101 		}
1102 		if (*topic == NULL) {
1103 			free(*subtopic);
1104 			free(*desc);
1105 			continue;
1106 		}
1107 		return (1);
1108 	}
1109 }
1110 
1111 static int
1112 help_emitsummary(char *topic, char *subtopic, char *desc)
1113 {
1114 	int i;
1115 
1116 	pager_output("    ");
1117 	pager_output(topic);
1118 	i = strlen(topic);
1119 	if (subtopic != NULL) {
1120 		pager_output(" ");
1121 		pager_output(subtopic);
1122 		i += strlen(subtopic) + 1;
1123 	}
1124 	if (desc != NULL) {
1125 		do {
1126 			pager_output(" ");
1127 		} while (i++ < 30);
1128 		pager_output(desc);
1129 	}
1130 	return (pager_output("\n"));
1131 }
1132 
1133 static int
1134 command_help(int argc, char *argv[])
1135 {
1136 	char buf[81];	/* XXX buffer size? */
1137 	int hfd, matched, doindex;
1138 	char *topic, *subtopic, *t, *s, *d;
1139 
1140 	/* page the help text from our load path */
1141 	snprintf(buf, sizeof (buf), "/boot/loader.help");
1142 	if ((hfd = open(buf, O_RDONLY)) < 0) {
1143 		printf("Verbose help not available, "
1144 		    "use '?' to list commands\n");
1145 		return (CMD_OK);
1146 	}
1147 
1148 	/* pick up request from arguments */
1149 	topic = subtopic = NULL;
1150 	switch (argc) {
1151 	case 3:
1152 		subtopic = strdup(argv[2]);
1153 		/* FALLTHROUGH */
1154 	case 2:
1155 		topic = strdup(argv[1]);
1156 	break;
1157 	case 1:
1158 		topic = strdup("help");
1159 	break;
1160 	default:
1161 		command_errmsg = "usage is 'help <topic> [<subtopic>]";
1162 		close(hfd);
1163 		return (CMD_ERROR);
1164 	}
1165 
1166 	/* magic "index" keyword */
1167 	doindex = strcmp(topic, "index") == 0;
1168 	matched = doindex;
1169 
1170 	/* Scan the helpfile looking for help matching the request */
1171 	pager_open();
1172 	while (help_getnext(hfd, &t, &s, &d)) {
1173 		if (doindex) {		/* dink around formatting */
1174 			if (help_emitsummary(t, s, d))
1175 				break;
1176 
1177 		} else if (strcmp(topic, t)) {
1178 			/* topic mismatch */
1179 			/* nothing more on this topic, stop scanning */
1180 			if (matched)
1181 				break;
1182 		} else {
1183 			/* topic matched */
1184 			matched = 1;
1185 			if ((subtopic == NULL && s == NULL) ||
1186 			    (subtopic != NULL && s != NULL &&
1187 			    strcmp(subtopic, s) == 0)) {
1188 				/* exact match, print text */
1189 				while (fgetstr(buf, 80, hfd) >= 0 &&
1190 				    buf[0] != '#') {
1191 					if (pager_output(buf))
1192 						break;
1193 					if (pager_output("\n"))
1194 						break;
1195 				}
1196 			} else if (subtopic == NULL && s != NULL) {
1197 				/* topic match, list subtopics */
1198 				if (help_emitsummary(t, s, d))
1199 					break;
1200 			}
1201 		}
1202 		free(t);
1203 		free(s);
1204 		free(d);
1205 		t = s = d = NULL;
1206 	}
1207 	free(t);
1208 	free(s);
1209 	free(d);
1210 	pager_close();
1211 	close(hfd);
1212 	if (!matched) {
1213 		snprintf(command_errbuf, sizeof (command_errbuf),
1214 		    "no help available for '%s'", topic);
1215 		free(topic);
1216 		free(subtopic);
1217 		return (CMD_ERROR);
1218 	}
1219 	free(topic);
1220 	free(subtopic);
1221 	return (CMD_OK);
1222 }
1223 
1224 static int
1225 command_commandlist(int argc __unused, char *argv[] __unused)
1226 {
1227 	struct bootblk_command *cmdp;
1228 	int res;
1229 	char name[20];
1230 
1231 	res = 0;
1232 	pager_open();
1233 	res = pager_output("Available commands:\n");
1234 	cmdp = NULL;
1235 	STAILQ_FOREACH(cmdp, &commands, next) {
1236 		if (res)
1237 			break;
1238 		if (cmdp->c_name != NULL && cmdp->c_desc != NULL) {
1239 			snprintf(name, sizeof (name), "  %-15s  ",
1240 			    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 		snprintf(line, sizeof (line), "*** FILE %s BEGIN ***\n",
1462 		    argv[i]);
1463 		if (pager_output(line))
1464 			break;
1465 		name = get_dev(argv[i]);
1466 		res = page_file(name);
1467 		free(name);
1468 		if (!res) {
1469 			snprintf(line, sizeof (line), "*** FILE %s END ***\n",
1470 			    argv[i]);
1471 			res = pager_output(line);
1472 		}
1473 	}
1474 	pager_close();
1475 
1476 	if (res == 0)
1477 		return (CMD_OK);
1478 	return (CMD_ERROR);
1479 }
1480 
1481 static int
1482 page_file(char *filename)
1483 {
1484 	int result;
1485 
1486 	result = pager_file(filename);
1487 
1488 	if (result == -1) {
1489 		snprintf(command_errbuf, sizeof (command_errbuf),
1490 		    "error showing %s", filename);
1491 	}
1492 
1493 	return (result);
1494 }
1495 
1496 static int
1497 command_ls(int argc, char *argv[])
1498 {
1499 	DIR *dir;
1500 	int fd;
1501 	struct stat sb;
1502 	struct dirent *d;
1503 	char *buf, *path;
1504 	char lbuf[128];	/* one line */
1505 	int result, ch;
1506 	int verbose;
1507 
1508 	result = CMD_OK;
1509 	fd = -1;
1510 	verbose = 0;
1511 	optind = 1;
1512 	opterr = 1;
1513 	while ((ch = getopt(argc, argv, "l")) != -1) {
1514 		switch (ch) {
1515 		case 'l':
1516 			verbose = 1;
1517 		break;
1518 		case '?':
1519 		default:
1520 			/* getopt has already reported an error */
1521 		return (CMD_OK);
1522 		}
1523 	}
1524 	argv += (optind - 1);
1525 	argc -= (optind - 1);
1526 
1527 	if (argc < 2) {
1528 		path = "";
1529 	} else {
1530 		path = argv[1];
1531 	}
1532 
1533 	fd = ls_getdir(&path);
1534 	if (fd == -1) {
1535 		result = CMD_ERROR;
1536 		goto out;
1537 	}
1538 	dir = fdopendir(fd);
1539 	pager_open();
1540 	pager_output(path);
1541 	pager_output("\n");
1542 
1543 	while ((d = readdir(dir)) != NULL) {
1544 		if (strcmp(d->d_name, ".") && strcmp(d->d_name, "..")) {
1545 			/* stat the file, if possible */
1546 			sb.st_size = 0;
1547 			sb.st_mode = 0;
1548 			buf = malloc(strlen(path) + strlen(d->d_name) + 2);
1549 			if (path[0] == '\0') {
1550 				snprintf(buf, sizeof (buf), "%s", d->d_name);
1551 			} else {
1552 				snprintf(buf, sizeof (buf), "%s/%s", path,
1553 				    d->d_name);
1554 			}
1555 			/* ignore return, could be symlink, etc. */
1556 			if (stat(buf, &sb))
1557 				sb.st_size = 0;
1558 			free(buf);
1559 			if (verbose) {
1560 				snprintf(lbuf, sizeof (lbuf), " %c %8d %s\n",
1561 				    typestr[sb.st_mode >> 12],
1562 				    (int)sb.st_size, d->d_name);
1563 			} else {
1564 				snprintf(lbuf, sizeof (lbuf), " %c  %s\n",
1565 				    typestr[sb.st_mode >> 12], d->d_name);
1566 			}
1567 			if (pager_output(lbuf))
1568 				goto out;
1569 		}
1570 	}
1571 out:
1572 	pager_close();
1573 	if (fd != -1)
1574 		closedir(dir);
1575 	if (path != NULL)
1576 		free(path);
1577 	return (result);
1578 }
1579 
1580 /*
1581  * Given (path) containing a vaguely reasonable path specification, return an fd
1582  * on the directory, and an allocated copy of the path to the directory.
1583  */
1584 static int
1585 ls_getdir(char **pathp)
1586 {
1587 	struct stat sb;
1588 	int fd;
1589 	char *cp, *path;
1590 
1591 	fd = -1;
1592 
1593 	/* one extra byte for a possible trailing slash required */
1594 	path = malloc(strlen(*pathp) + 2);
1595 	strcpy(path, *pathp);
1596 
1597 	/* Make sure the path is respectable to begin with */
1598 	if ((cp = get_dev(path)) == NULL) {
1599 		snprintf(command_errbuf, sizeof (command_errbuf),
1600 		    "bad path '%s'", path);
1601 		goto out;
1602 	}
1603 
1604 	/* If there's no path on the device, assume '/' */
1605 	if (*cp == 0)
1606 		strcat(path, "/");
1607 
1608 	fd = open(cp, O_RDONLY);
1609 	if (fd < 0) {
1610 		snprintf(command_errbuf, sizeof (command_errbuf),
1611 		    "open '%s' failed: %s", path, strerror(errno));
1612 		goto out;
1613 	}
1614 	if (fstat(fd, &sb) < 0) {
1615 		snprintf(command_errbuf, sizeof (command_errbuf),
1616 		    "stat failed: %s", strerror(errno));
1617 		goto out;
1618 	}
1619 	if (!S_ISDIR(sb.st_mode)) {
1620 		snprintf(command_errbuf, sizeof (command_errbuf),
1621 		    "%s: %s", path, strerror(ENOTDIR));
1622 		goto out;
1623 	}
1624 
1625 	free(cp);
1626 	*pathp = path;
1627 	return (fd);
1628 
1629 out:
1630 	free(cp);
1631 	free(path);
1632 	*pathp = NULL;
1633 	if (fd != -1)
1634 		close(fd);
1635 	return (-1);
1636 }
1637 
1638 static int
1639 command_include(int argc, char *argv[])
1640 {
1641 	int i;
1642 	int res;
1643 	char **argvbuf;
1644 
1645 	/*
1646 	 * Since argv is static, we need to save it here.
1647 	 */
1648 	argvbuf = (char **)calloc(argc, sizeof (char *));
1649 	for (i = 0; i < argc; i++)
1650 		argvbuf[i] = strdup(argv[i]);
1651 
1652 	res = CMD_OK;
1653 	for (i = 1; (i < argc) && (res == CMD_OK); i++)
1654 		res = include(argvbuf[i]);
1655 
1656 	for (i = 0; i < argc; i++)
1657 		free(argvbuf[i]);
1658 	free(argvbuf);
1659 
1660 	return (res);
1661 }
1662 
1663 /*
1664  * Header prepended to each line. The text immediately follows the header.
1665  * We try to make this short in order to save memory -- the loader has
1666  * limited memory available, and some of the forth files are very long.
1667  */
1668 struct includeline
1669 {
1670 	struct includeline *next;
1671 	int line;
1672 	char text[];
1673 };
1674 
1675 int
1676 include(const char *filename)
1677 {
1678 	struct includeline *script, *se, *sp;
1679 	int res = CMD_OK;
1680 	int prevsrcid, fd, line;
1681 	char *cp, input[256]; /* big enough? */
1682 	char *path;
1683 
1684 	path = get_dev(filename);
1685 	if (((fd = open(path, O_RDONLY)) == -1)) {
1686 		snprintf(command_errbuf, sizeof (command_errbuf),
1687 		    "can't open '%s': %s", filename,
1688 		    strerror(errno));
1689 		free(path);
1690 		return (CMD_ERROR);
1691 	}
1692 
1693 	free(path);
1694 	/*
1695 	 * Read the script into memory.
1696 	 */
1697 	script = se = NULL;
1698 	line = 0;
1699 
1700 	while (fgetstr(input, sizeof (input), fd) >= 0) {
1701 		line++;
1702 		cp = input;
1703 		/* Allocate script line structure and copy line, flags */
1704 		if (*cp == '\0')
1705 			continue;	/* ignore empty line, save memory */
1706 		if (cp[0] == '\\' && cp[1] == ' ')
1707 			continue;	/* ignore comment */
1708 
1709 		sp = malloc(sizeof (struct includeline) + strlen(cp) + 1);
1710 		/*
1711 		 * On malloc failure (it happens!), free as much as possible
1712 		 * and exit
1713 		 */
1714 		if (sp == NULL) {
1715 			while (script != NULL) {
1716 				se = script;
1717 				script = script->next;
1718 				free(se);
1719 			}
1720 			snprintf(command_errbuf, sizeof (command_errbuf),
1721 			    "file '%s' line %d: memory allocation "
1722 			    "failure - aborting", filename, line);
1723 			return (CMD_ERROR);
1724 		}
1725 		strcpy(sp->text, cp);
1726 		sp->line = line;
1727 		sp->next = NULL;
1728 
1729 		if (script == NULL) {
1730 			script = sp;
1731 		} else {
1732 			se->next = sp;
1733 		}
1734 		se = sp;
1735 	}
1736 	close(fd);
1737 
1738 	/*
1739 	 * Execute the script
1740 	 */
1741 
1742 	prevsrcid = bf_vm->sourceId.i;
1743 	bf_vm->sourceId.i = fd+1;	/* 0 is user input device */
1744 
1745 	res = CMD_OK;
1746 
1747 	for (sp = script; sp != NULL; sp = sp->next) {
1748 		res = bf_run(sp->text);
1749 		if (res != FICL_VM_STATUS_OUT_OF_TEXT) {
1750 			snprintf(command_errbuf, sizeof (command_errbuf),
1751 			    "Error while including %s, in the line %d:\n%s",
1752 			    filename, sp->line, sp->text);
1753 			res = CMD_ERROR;
1754 			break;
1755 		} else
1756 			res = CMD_OK;
1757 	}
1758 
1759 	bf_vm->sourceId.i = -1;
1760 	(void) bf_run("");
1761 	bf_vm->sourceId.i = prevsrcid;
1762 
1763 	while (script != NULL) {
1764 		se = script;
1765 		script = script->next;
1766 		free(se);
1767 	}
1768 
1769 	return (res);
1770 }
1771 
1772 static int
1773 command_boot(int argc, char *argv[])
1774 {
1775 	return (CMD_OK);
1776 }
1777 
1778 static int
1779 command_autoboot(int argc, char *argv[])
1780 {
1781 	return (CMD_OK);
1782 }
1783 
1784 static void
1785 moduledir_rebuild(void)
1786 {
1787 	struct moduledir *mdp, *mtmp;
1788 	const char *path, *cp, *ep;
1789 	int cplen;
1790 
1791 	path = getenv("module_path");
1792 	if (path == NULL)
1793 		path = default_searchpath;
1794 	/*
1795 	 * Rebuild list of module directories if it changed
1796 	 */
1797 	STAILQ_FOREACH(mdp, &moduledir_list, d_link)
1798 		mdp->d_flags |= MDIR_REMOVED;
1799 
1800 	for (ep = path; *ep != 0;  ep++) {
1801 		cp = ep;
1802 		for (; *ep != 0 && *ep != ';'; ep++)
1803 			;
1804 		/*
1805 		 * Ignore trailing slashes
1806 		 */
1807 		for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/';
1808 		    cplen--)
1809 			;
1810 		STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1811 			if (strlen(mdp->d_path) != cplen ||
1812 			    bcmp(cp, mdp->d_path, cplen) != 0)
1813 				continue;
1814 			mdp->d_flags &= ~MDIR_REMOVED;
1815 			break;
1816 		}
1817 		if (mdp == NULL) {
1818 			mdp = malloc(sizeof (*mdp) + cplen + 1);
1819 			if (mdp == NULL)
1820 				return;
1821 			mdp->d_path = (char *)(mdp + 1);
1822 			bcopy(cp, mdp->d_path, cplen);
1823 			mdp->d_path[cplen] = 0;
1824 			mdp->d_hints = NULL;
1825 			mdp->d_flags = 0;
1826 			STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1827 		}
1828 		if (*ep == 0)
1829 			break;
1830 	}
1831 	/*
1832 	 * Delete unused directories if any
1833 	 */
1834 	mdp = STAILQ_FIRST(&moduledir_list);
1835 	while (mdp) {
1836 		if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1837 			mdp = STAILQ_NEXT(mdp, d_link);
1838 		} else {
1839 			if (mdp->d_hints)
1840 				free(mdp->d_hints);
1841 			mtmp = mdp;
1842 			mdp = STAILQ_NEXT(mdp, d_link);
1843 			STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1844 			free(mtmp);
1845 		}
1846 	}
1847 }
1848 
1849 static char *
1850 file_lookup(const char *path, const char *name, int namelen)
1851 {
1852 	struct stat st;
1853 	char *result, *cp, *gz;
1854 	int pathlen;
1855 
1856 	pathlen = strlen(path);
1857 	result = malloc(pathlen + namelen + 2);
1858 	if (result == NULL)
1859 		return (NULL);
1860 	bcopy(path, result, pathlen);
1861 	if (pathlen > 0 && result[pathlen - 1] != '/')
1862 		result[pathlen++] = '/';
1863 	cp = result + pathlen;
1864 	bcopy(name, cp, namelen);
1865 	cp += namelen;
1866 	*cp = '\0';
1867 	if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
1868 		return (result);
1869 	/* also check for gz file */
1870 	(void) asprintf(&gz, "%s.gz", result);
1871 	if (gz != NULL) {
1872 		int res = stat(gz, &st);
1873 		free(gz);
1874 		if (res == 0)
1875 			return (result);
1876 	}
1877 	free(result);
1878 	return (NULL);
1879 }
1880 
1881 static char *
1882 file_search(const char *name)
1883 {
1884 	struct moduledir *mdp;
1885 	struct stat sb;
1886 	char *result;
1887 	int namelen;
1888 
1889 	if (name == NULL)
1890 		return (NULL);
1891 	if (*name == 0)
1892 		return (strdup(name));
1893 
1894 	if (strchr(name, '/') != NULL) {
1895 		char *gz;
1896 		if (stat(name, &sb) == 0)
1897 			return (strdup(name));
1898 		/* also check for gz file */
1899 		(void) asprintf(&gz, "%s.gz", name);
1900 		if (gz != NULL) {
1901 			int res = stat(gz, &sb);
1902 			free(gz);
1903 			if (res == 0)
1904 				return (strdup(name));
1905 		}
1906 		return (NULL);
1907 	}
1908 
1909 	moduledir_rebuild();
1910 	result = NULL;
1911 	namelen = strlen(name);
1912 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1913 		result = file_lookup(mdp->d_path, name, namelen);
1914 		if (result)
1915 			break;
1916 	}
1917 	return (result);
1918 }
1919 
1920 static int
1921 command_load(int argc, char *argv[])
1922 {
1923 	int dofile, ch;
1924 	char *typestr = NULL;
1925 	char *filename;
1926 	dofile = 0;
1927 	optind = 1;
1928 
1929 	if (argc == 1) {
1930 		command_errmsg = "no filename specified";
1931 		return (CMD_ERROR);
1932 	}
1933 
1934 	while ((ch = getopt(argc, argv, "kt:")) != -1) {
1935 		switch (ch) {
1936 		case 'k':
1937 			break;
1938 		case 't':
1939 			typestr = optarg;
1940 			dofile = 1;
1941 			break;
1942 		case '?':
1943 		default:
1944 			return (CMD_OK);
1945 		}
1946 	}
1947 	argv += (optind - 1);
1948 	argc -= (optind - 1);
1949 	if (dofile) {
1950 		if ((typestr == NULL) || (*typestr == 0)) {
1951 			command_errmsg = "invalid load type";
1952 			return (CMD_ERROR);
1953 		}
1954 #if 0
1955 		return (file_loadraw(argv[1], typestr, argc - 2, argv + 2, 1)
1956 		    ? CMD_OK : CMD_ERROR);
1957 #endif
1958 		return (CMD_OK);
1959 	}
1960 
1961 	filename = file_search(argv[1]);
1962 	if (filename == NULL) {
1963 		snprintf(command_errbuf, sizeof (command_errbuf),
1964 		    "can't find '%s'", argv[1]);
1965 		return (CMD_ERROR);
1966 	}
1967 	setenv("kernelname", filename, 1);
1968 
1969 	return (CMD_OK);
1970 }
1971 
1972 static int
1973 command_unload(int argc, char *argv[])
1974 {
1975 	unsetenv("kernelname");
1976 	return (CMD_OK);
1977 }
1978 
1979 static int
1980 command_reboot(int argc, char *argv[])
1981 {
1982 	exit(0);
1983 	return (CMD_OK);
1984 }
1985 
1986 static int
1987 command_sifting(int argc, char *argv[])
1988 {
1989 	if (argc != 2) {
1990 		command_errmsg = "wrong number of arguments";
1991 		return (CMD_ERROR);
1992 	}
1993 	ficlPrimitiveSiftingImpl(bf_vm, argv[1]);
1994 	return (CMD_OK);
1995 }
1996