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