xref: /illumos-gate/usr/src/common/ficl/emu/loader_emu.c (revision afc2ba1deb75b323afde536f2dd18bcafdaa308d)
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 		/* Hopefully, all other codes filled this buffer */
881 		printf("%s\n", command_errmsg);
882 	}
883 
884 	setenv("interpret", bf_vm->state ? "" : "ok", 1);
885 
886 	return (result);
887 }
888 
889 char *
890 get_dev(const char *path)
891 {
892 	FILE *fp;
893 	struct mnttab mpref = {0};
894 	struct mnttab mp = {0};
895 	char *currdev;
896 	int ret;
897 	char *buf;
898 	char *tmppath;
899 	char *tmpdev;
900 	char *cwd = NULL;
901 
902 	fp = fopen(MNTTAB, "r");
903 
904 	/* do the best we can to return something... */
905 	if (fp == NULL)
906 		return (strdup(path));
907 
908 	/*
909 	 * the path can have device provided, check for it
910 	 * and extract it.
911 	 */
912 	buf = strrchr(path, ':');
913 	if (buf != NULL) {
914 		tmppath = buf+1;		/* real path */
915 		buf = strchr(path, ':');	/* skip zfs: */
916 		buf++;
917 		tmpdev = strdup(buf);
918 		buf = strchr(tmpdev, ':');	/* get ending : */
919 		*buf = '\0';
920 	} else {
921 		tmppath = (char *)path;
922 		if (tmppath[0] != '/')
923 			if ((cwd = getcwd(NULL, PATH_MAX)) == NULL) {
924 				(void) fclose(fp);
925 				return (strdup(path));
926 			}
927 
928 		currdev = getenv("currdev");
929 		buf = strchr(currdev, ':');	/* skip zfs: */
930 		if (buf == NULL) {
931 			(void) fclose(fp);
932 			return (strdup(path));
933 		}
934 		buf++;
935 		tmpdev = strdup(buf);
936 		buf = strchr(tmpdev, ':');	/* get ending : */
937 		*buf = '\0';
938 	}
939 
940 	mpref.mnt_special = tmpdev;
941 	ret = getmntany(fp, &mp, &mpref);
942 	(void) fclose(fp);
943 	free(tmpdev);
944 
945 	if (cwd == NULL)
946 		(void) asprintf(&buf, "%s/%s", ret? "":mp.mnt_mountp, tmppath);
947 	else {
948 		(void) asprintf(&buf, "%s/%s/%s", ret? "":mp.mnt_mountp, cwd,
949 		    tmppath);
950 		free(cwd);
951 	}
952 	return (buf);
953 }
954 
955 static void
956 ngets(char *buf, int n)
957 {
958 	int c;
959 	char *lp;
960 
961 	for (lp = buf; ; )
962 		switch (c = getchar() & 0177) {
963 		case '\n':
964 		case '\r':
965 			*lp = '\0';
966 			putchar('\n');
967 		return;
968 		case '\b':
969 		case '\177':
970 			if (lp > buf) {
971 				lp--;
972 				putchar('\b');
973 				putchar(' ');
974 				putchar('\b');
975 			}
976 		break;
977 		case 'r'&037: {
978 			char *p;
979 
980 			putchar('\n');
981 			for (p = buf; p < lp; ++p)
982 				putchar(*p);
983 		break;
984 		}
985 		case 'u'&037:
986 		case 'w'&037:
987 			lp = buf;
988 			putchar('\n');
989 		break;
990 		default:
991 			if ((n < 1) || ((lp - buf) < n - 1)) {
992 				*lp++ = c;
993 				putchar(c);
994 			}
995 		}
996 	/*NOTREACHED*/
997 }
998 
999 static int
1000 fgetstr(char *buf, int size, int fd)
1001 {
1002 	char c;
1003 	int err, len;
1004 
1005 	size--;			/* leave space for terminator */
1006 	len = 0;
1007 	while (size != 0) {
1008 		err = read(fd, &c, sizeof (c));
1009 		if (err < 0)			/* read error */
1010 			return (-1);
1011 
1012 		if (err == 0) {	/* EOF */
1013 			if (len == 0)
1014 				return (-1);	/* nothing to read */
1015 			break;
1016 		}
1017 		if ((c == '\r') || (c == '\n'))	/* line terminators */
1018 			break;
1019 		*buf++ = c;			/* keep char */
1020 		size--;
1021 		len++;
1022 	}
1023 	*buf = 0;
1024 	return (len);
1025 }
1026 
1027 static char *
1028 unargv(int argc, char *argv[])
1029 {
1030 	size_t hlong;
1031 	int i;
1032 	char *cp;
1033 
1034 	for (i = 0, hlong = 0; i < argc; i++)
1035 		hlong += strlen(argv[i]) + 2;
1036 
1037 	if (hlong == 0)
1038 		return (NULL);
1039 
1040 	cp = malloc(hlong);
1041 	cp[0] = 0;
1042 	for (i = 0; i < argc; i++) {
1043 		strcat(cp, argv[i]);
1044 		if (i < (argc - 1))
1045 			strcat(cp, " ");
1046 	}
1047 
1048 	return (cp);
1049 }
1050 
1051 /*
1052  * Help is read from a formatted text file.
1053  *
1054  * Entries in the file are formatted as:
1055  * # Ttopic [Ssubtopic] Ddescription
1056  * help
1057  * text
1058  * here
1059  * #
1060  *
1061  * Note that for code simplicity's sake, the above format must be followed
1062  * exactly.
1063  *
1064  * Subtopic entries must immediately follow the topic (this is used to
1065  * produce the listing of subtopics).
1066  *
1067  * If no argument(s) are supplied by the user, the help for 'help' is displayed.
1068  */
1069 static int
1070 help_getnext(int fd, char **topic, char **subtopic, char **desc)
1071 {
1072 	char line[81], *cp, *ep;
1073 
1074 	for (;;) {
1075 		if (fgetstr(line, 80, fd) < 0)
1076 			return (0);
1077 
1078 		if ((strlen(line) < 3) || (line[0] != '#') || (line[1] != ' '))
1079 			continue;
1080 
1081 		*topic = *subtopic = *desc = NULL;
1082 		cp = line + 2;
1083 		while ((cp != NULL) && (*cp != 0)) {
1084 			ep = strchr(cp, ' ');
1085 			if ((*cp == 'T') && (*topic == NULL)) {
1086 				if (ep != NULL)
1087 					*ep++ = 0;
1088 				*topic = strdup(cp + 1);
1089 			} else if ((*cp == 'S') && (*subtopic == NULL)) {
1090 				if (ep != NULL)
1091 					*ep++ = 0;
1092 				*subtopic = strdup(cp + 1);
1093 			} else if (*cp == 'D') {
1094 				*desc = strdup(cp + 1);
1095 				ep = NULL;
1096 			}
1097 			cp = ep;
1098 		}
1099 		if (*topic == NULL) {
1100 			if (*subtopic != NULL)
1101 				free(*subtopic);
1102 			if (*desc != NULL)
1103 				free(*desc);
1104 			continue;
1105 		}
1106 		return (1);
1107 	}
1108 }
1109 
1110 static int
1111 help_emitsummary(char *topic, char *subtopic, char *desc)
1112 {
1113 	int i;
1114 
1115 	pager_output("    ");
1116 	pager_output(topic);
1117 	i = strlen(topic);
1118 	if (subtopic != NULL) {
1119 		pager_output(" ");
1120 		pager_output(subtopic);
1121 		i += strlen(subtopic) + 1;
1122 	}
1123 	if (desc != NULL) {
1124 		do {
1125 			pager_output(" ");
1126 		} while (i++ < 30);
1127 		pager_output(desc);
1128 	}
1129 	return (pager_output("\n"));
1130 }
1131 
1132 static int
1133 command_help(int argc, char *argv[])
1134 {
1135 	char buf[81];	/* XXX buffer size? */
1136 	int hfd, matched, doindex;
1137 	char *topic, *subtopic, *t, *s, *d;
1138 
1139 	/* page the help text from our load path */
1140 	sprintf(buf, "/boot/loader.help");
1141 	if ((hfd = open(buf, O_RDONLY)) < 0) {
1142 		printf("Verbose help not available, "
1143 		    "use '?' to list commands\n");
1144 		return (CMD_OK);
1145 	}
1146 
1147 	/* pick up request from arguments */
1148 	topic = subtopic = NULL;
1149 	switch (argc) {
1150 	case 3:
1151 		subtopic = strdup(argv[2]);
1152 	case 2:
1153 		topic = strdup(argv[1]);
1154 	break;
1155 	case 1:
1156 		topic = strdup("help");
1157 	break;
1158 	default:
1159 		command_errmsg = "usage is 'help <topic> [<subtopic>]";
1160 		close(hfd);
1161 		return (CMD_ERROR);
1162 	}
1163 
1164 	/* magic "index" keyword */
1165 	doindex = strcmp(topic, "index") == 0;
1166 	matched = doindex;
1167 
1168 	/* Scan the helpfile looking for help matching the request */
1169 	pager_open();
1170 	while (help_getnext(hfd, &t, &s, &d)) {
1171 		if (doindex) {		/* dink around formatting */
1172 			if (help_emitsummary(t, s, d))
1173 				break;
1174 
1175 		} else if (strcmp(topic, t)) {
1176 			/* topic mismatch */
1177 			/* nothing more on this topic, stop scanning */
1178 			if (matched)
1179 				break;
1180 		} else {
1181 			/* topic matched */
1182 			matched = 1;
1183 			if (((subtopic == NULL) && (s == NULL)) ||
1184 			    ((subtopic != NULL) && (s != NULL) &&
1185 			    strcmp(subtopic, s) == 0)) {
1186 				/* exact match, print text */
1187 				while ((fgetstr(buf, 80, hfd) >= 0) &&
1188 				    (buf[0] != '#')) {
1189 					if (pager_output(buf))
1190 						break;
1191 					if (pager_output("\n"))
1192 						break;
1193 				}
1194 			} else if ((subtopic == NULL) && (s != NULL)) {
1195 				/* topic match, list subtopics */
1196 				if (help_emitsummary(t, s, d))
1197 					break;
1198 			}
1199 		}
1200 		free(t);
1201 		free(s);
1202 		free(d);
1203 	}
1204 	pager_close();
1205 	close(hfd);
1206 	if (!matched) {
1207 		snprintf(command_errbuf, sizeof (command_errbuf),
1208 		    "no help available for '%s'", topic);
1209 		free(topic);
1210 		if (subtopic)
1211 			free(subtopic);
1212 		return (CMD_ERROR);
1213 	}
1214 	free(topic);
1215 	if (subtopic)
1216 		free(subtopic);
1217 	return (CMD_OK);
1218 }
1219 
1220 static int
1221 command_commandlist(int argc, char *argv[])
1222 {
1223 	struct bootblk_command *cmdp;
1224 	int res;
1225 	char name[20];
1226 
1227 	res = 0;
1228 	pager_open();
1229 	res = pager_output("Available commands:\n");
1230 	cmdp = NULL;
1231 	STAILQ_FOREACH(cmdp, &commands, next) {
1232 		if (res)
1233 			break;
1234 		if ((cmdp->c_name != NULL) && (cmdp->c_desc != NULL)) {
1235 			sprintf(name, "  %-15s  ", cmdp->c_name);
1236 			pager_output(name);
1237 			pager_output(cmdp->c_desc);
1238 			res = pager_output("\n");
1239 		}
1240 	}
1241 	pager_close();
1242 	return (CMD_OK);
1243 }
1244 
1245 /*
1246  * XXX set/show should become set/echo if we have variable
1247  * substitution happening.
1248  */
1249 static int
1250 command_show(int argc, char *argv[])
1251 {
1252 	char **ev;
1253 	char *cp;
1254 
1255 	if (argc < 2) {
1256 		/*
1257 		 * With no arguments, print everything.
1258 		 */
1259 		pager_open();
1260 		for (ev = _environ; *ev != NULL; ev++) {
1261 			pager_output(*ev);
1262 			cp = getenv(*ev);
1263 			if (cp != NULL) {
1264 				pager_output("=");
1265 				pager_output(cp);
1266 			}
1267 			if (pager_output("\n"))
1268 				break;
1269 		}
1270 		pager_close();
1271 	} else {
1272 		if ((cp = getenv(argv[1])) != NULL) {
1273 			printf("%s\n", cp);
1274 		} else {
1275 			snprintf(command_errbuf, sizeof (command_errbuf),
1276 			    "variable '%s' not found", argv[1]);
1277 			return (CMD_ERROR);
1278 		}
1279 	}
1280 	return (CMD_OK);
1281 }
1282 
1283 static int
1284 command_set(int argc, char *argv[])
1285 {
1286 	int	err;
1287 	char	*value, *copy;
1288 
1289 	if (argc != 2) {
1290 		command_errmsg = "wrong number of arguments";
1291 		return (CMD_ERROR);
1292 	} else {
1293 		copy = strdup(argv[1]);
1294 		if (copy == NULL) {
1295 			command_errmsg = strerror(errno);
1296 			return (CMD_ERROR);
1297 		}
1298 		if ((value = strchr(copy, '=')) != NULL)
1299 			*(value++) = 0;
1300 		else
1301 			value = "";
1302 		if ((err = setenv(copy, value, 1)) != 0) {
1303 			free(copy);
1304 			command_errmsg = strerror(errno);
1305 			return (CMD_ERROR);
1306 		}
1307 		free(copy);
1308 	}
1309 	return (CMD_OK);
1310 }
1311 
1312 static int
1313 command_setprop(int argc, char *argv[])
1314 {
1315 	int err;
1316 
1317 	if (argc != 3) {
1318 		command_errmsg = "wrong number of arguments";
1319 		return (CMD_ERROR);
1320 	} else {
1321 		if ((err = setenv(argv[1], argv[2], 1)) != 0) {
1322 			command_errmsg = strerror(err);
1323 			return (CMD_ERROR);
1324 		}
1325 	}
1326 	return (CMD_OK);
1327 }
1328 
1329 static int
1330 command_unset(int argc, char *argv[])
1331 {
1332 	int err;
1333 
1334 	if (argc != 2) {
1335 		command_errmsg = "wrong number of arguments";
1336 		return (CMD_ERROR);
1337 	} else {
1338 		if ((err = unsetenv(argv[1])) != 0) {
1339 			command_errmsg = strerror(err);
1340 			return (CMD_ERROR);
1341 		}
1342 	}
1343 	return (CMD_OK);
1344 }
1345 
1346 static int
1347 command_echo(int argc, char *argv[])
1348 {
1349 	char *s;
1350 	int nl, ch;
1351 
1352 	nl = 0;
1353 	optind = 1;
1354 	opterr = 1;
1355 	while ((ch = getopt(argc, argv, "n")) != -1) {
1356 		switch (ch) {
1357 		case 'n':
1358 			nl = 1;
1359 		break;
1360 		case '?':
1361 		default:
1362 			/* getopt has already reported an error */
1363 		return (CMD_OK);
1364 		}
1365 	}
1366 	argv += (optind);
1367 	argc -= (optind);
1368 
1369 	s = unargv(argc, argv);
1370 	if (s != NULL) {
1371 		printf("%s", s);
1372 		free(s);
1373 	}
1374 	if (!nl)
1375 		printf("\n");
1376 	return (CMD_OK);
1377 }
1378 
1379 /*
1380  * A passable emulation of the sh(1) command of the same name.
1381  */
1382 static int
1383 ischar(void)
1384 {
1385 	return (1);
1386 }
1387 
1388 static int
1389 command_read(int argc, char *argv[])
1390 {
1391 	char *prompt;
1392 	int timeout;
1393 	time_t when;
1394 	char *cp;
1395 	char *name;
1396 	char buf[256];		/* XXX size? */
1397 	int c;
1398 
1399 	timeout = -1;
1400 	prompt = NULL;
1401 	optind = 1;
1402 	opterr = 1;
1403 	while ((c = getopt(argc, argv, "p:t:")) != -1) {
1404 		switch (c) {
1405 		case 'p':
1406 			prompt = optarg;
1407 		break;
1408 		case 't':
1409 			timeout = strtol(optarg, &cp, 0);
1410 			if (cp == optarg) {
1411 				snprintf(command_errbuf,
1412 				    sizeof (command_errbuf),
1413 				    "bad timeout '%s'", optarg);
1414 				return (CMD_ERROR);
1415 			}
1416 		break;
1417 		default:
1418 		return (CMD_OK);
1419 		}
1420 	}
1421 
1422 	argv += (optind);
1423 	argc -= (optind);
1424 	name = (argc > 0) ? argv[0]: NULL;
1425 
1426 	if (prompt != NULL)
1427 		printf("%s", prompt);
1428 	if (timeout >= 0) {
1429 		when = time(NULL) + timeout;
1430 		while (!ischar())
1431 			if (time(NULL) >= when)
1432 				return (CMD_OK); /* is timeout an error? */
1433 	}
1434 
1435 	ngets(buf, sizeof (buf));
1436 
1437 	if (name != NULL)
1438 		setenv(name, buf, 1);
1439 	return (CMD_OK);
1440 }
1441 
1442 /*
1443  * File pager
1444  */
1445 static int
1446 command_more(int argc, char *argv[])
1447 {
1448 	int i;
1449 	int res;
1450 	char line[80];
1451 	char *name;
1452 
1453 	res = 0;
1454 	pager_open();
1455 	for (i = 1; (i < argc) && (res == 0); i++) {
1456 		sprintf(line, "*** FILE %s BEGIN ***\n", argv[i]);
1457 		if (pager_output(line))
1458 			break;
1459 		name = get_dev(argv[i]);
1460 		res = page_file(name);
1461 		free(name);
1462 		if (!res) {
1463 			sprintf(line, "*** FILE %s END ***\n", argv[i]);
1464 			res = pager_output(line);
1465 		}
1466 	}
1467 	pager_close();
1468 
1469 	if (res == 0)
1470 		return (CMD_OK);
1471 	return (CMD_ERROR);
1472 }
1473 
1474 static int
1475 page_file(char *filename)
1476 {
1477 	int result;
1478 
1479 	result = pager_file(filename);
1480 
1481 	if (result == -1) {
1482 		snprintf(command_errbuf, sizeof (command_errbuf),
1483 		    "error showing %s", filename);
1484 	}
1485 
1486 	return (result);
1487 }
1488 
1489 static int
1490 command_ls(int argc, char *argv[])
1491 {
1492 	DIR *dir;
1493 	int fd;
1494 	struct stat sb;
1495 	struct dirent *d;
1496 	char *buf, *path;
1497 	char lbuf[128];	/* one line */
1498 	int result, ch;
1499 	int verbose;
1500 
1501 	result = CMD_OK;
1502 	fd = -1;
1503 	verbose = 0;
1504 	optind = 1;
1505 	opterr = 1;
1506 	while ((ch = getopt(argc, argv, "l")) != -1) {
1507 		switch (ch) {
1508 		case 'l':
1509 			verbose = 1;
1510 		break;
1511 		case '?':
1512 		default:
1513 			/* getopt has already reported an error */
1514 		return (CMD_OK);
1515 		}
1516 	}
1517 	argv += (optind - 1);
1518 	argc -= (optind - 1);
1519 
1520 	if (argc < 2) {
1521 		path = "";
1522 	} else {
1523 		path = argv[1];
1524 	}
1525 
1526 	fd = ls_getdir(&path);
1527 	if (fd == -1) {
1528 		result = CMD_ERROR;
1529 		goto out;
1530 	}
1531 	dir = fdopendir(fd);
1532 	pager_open();
1533 	pager_output(path);
1534 	pager_output("\n");
1535 
1536 	while ((d = readdir(dir)) != NULL) {
1537 		if (strcmp(d->d_name, ".") && strcmp(d->d_name, "..")) {
1538 			/* stat the file, if possible */
1539 			sb.st_size = 0;
1540 			sb.st_mode = 0;
1541 			buf = malloc(strlen(path) + strlen(d->d_name) + 2);
1542 			if (path[0] == '\0')
1543 				sprintf(buf, "%s", d->d_name);
1544 			else
1545 				sprintf(buf, "%s/%s", path, d->d_name);
1546 			/* ignore return, could be symlink, etc. */
1547 			if (stat(buf, &sb))
1548 				sb.st_size = 0;
1549 			free(buf);
1550 			if (verbose) {
1551 				sprintf(lbuf, " %c %8d %s\n",
1552 				    typestr[sb.st_mode >> 12],
1553 				    (int)sb.st_size, d->d_name);
1554 			} else {
1555 				sprintf(lbuf, " %c  %s\n",
1556 				    typestr[sb.st_mode >> 12], d->d_name);
1557 			}
1558 			if (pager_output(lbuf))
1559 				goto out;
1560 		}
1561 	}
1562 out:
1563 	pager_close();
1564 	if (fd != -1)
1565 		closedir(dir);
1566 	if (path != NULL)
1567 		free(path);
1568 	return (result);
1569 }
1570 
1571 /*
1572  * Given (path) containing a vaguely reasonable path specification, return an fd
1573  * on the directory, and an allocated copy of the path to the directory.
1574  */
1575 static int
1576 ls_getdir(char **pathp)
1577 {
1578 	struct stat sb;
1579 	int fd;
1580 	char *cp, *path;
1581 
1582 	fd = -1;
1583 
1584 	/* one extra byte for a possible trailing slash required */
1585 	path = malloc(strlen(*pathp) + 2);
1586 	strcpy(path, *pathp);
1587 
1588 	/* Make sure the path is respectable to begin with */
1589 	if ((cp = get_dev(path)) == NULL) {
1590 		snprintf(command_errbuf, sizeof (command_errbuf),
1591 		    "bad path '%s'", path);
1592 		goto out;
1593 	}
1594 
1595 	/* If there's no path on the device, assume '/' */
1596 	if (*cp == 0)
1597 		strcat(path, "/");
1598 
1599 	fd = open(cp, O_RDONLY);
1600 	if (fd < 0) {
1601 		snprintf(command_errbuf, sizeof (command_errbuf),
1602 		    "open '%s' failed: %s", path, strerror(errno));
1603 		goto out;
1604 	}
1605 	if (fstat(fd, &sb) < 0) {
1606 		snprintf(command_errbuf, sizeof (command_errbuf),
1607 		    "stat failed: %s", strerror(errno));
1608 		goto out;
1609 	}
1610 	if (!S_ISDIR(sb.st_mode)) {
1611 		snprintf(command_errbuf, sizeof (command_errbuf),
1612 		    "%s: %s", path, strerror(ENOTDIR));
1613 		goto out;
1614 	}
1615 
1616 	free(cp);
1617 	*pathp = path;
1618 	return (fd);
1619 
1620 out:
1621 	free(cp);
1622 	free(path);
1623 	*pathp = NULL;
1624 	if (fd != -1)
1625 		close(fd);
1626 	return (-1);
1627 }
1628 
1629 static int
1630 command_include(int argc, char *argv[])
1631 {
1632 	int i;
1633 	int res;
1634 	char **argvbuf;
1635 
1636 	/*
1637 	 * Since argv is static, we need to save it here.
1638 	 */
1639 	argvbuf = (char **)calloc(argc, sizeof (char *));
1640 	for (i = 0; i < argc; i++)
1641 		argvbuf[i] = strdup(argv[i]);
1642 
1643 	res = CMD_OK;
1644 	for (i = 1; (i < argc) && (res == CMD_OK); i++)
1645 		res = include(argvbuf[i]);
1646 
1647 	for (i = 0; i < argc; i++)
1648 		free(argvbuf[i]);
1649 	free(argvbuf);
1650 
1651 	return (res);
1652 }
1653 
1654 /*
1655  * Header prepended to each line. The text immediately follows the header.
1656  * We try to make this short in order to save memory -- the loader has
1657  * limited memory available, and some of the forth files are very long.
1658  */
1659 struct includeline
1660 {
1661 	struct includeline *next;
1662 	int line;
1663 	char text[];
1664 };
1665 
1666 int
1667 include(const char *filename)
1668 {
1669 	struct includeline *script, *se, *sp;
1670 	int res = CMD_OK;
1671 	int prevsrcid, fd, line;
1672 	char *cp, input[256]; /* big enough? */
1673 	char *path;
1674 
1675 	path = get_dev(filename);
1676 	if (((fd = open(path, O_RDONLY)) == -1)) {
1677 		snprintf(command_errbuf, sizeof (command_errbuf),
1678 		    "can't open '%s': %s", filename,
1679 		    strerror(errno));
1680 		free(path);
1681 		return (CMD_ERROR);
1682 	}
1683 
1684 	free(path);
1685 	/*
1686 	 * Read the script into memory.
1687 	 */
1688 	script = se = NULL;
1689 	line = 0;
1690 
1691 	while (fgetstr(input, sizeof (input), fd) >= 0) {
1692 		line++;
1693 		cp = input;
1694 		/* Allocate script line structure and copy line, flags */
1695 		if (*cp == '\0')
1696 			continue;	/* ignore empty line, save memory */
1697 		if (cp[0] == '\\' && cp[1] == ' ')
1698 			continue;	/* ignore comment */
1699 
1700 		sp = malloc(sizeof (struct includeline) + strlen(cp) + 1);
1701 		/*
1702 		 * On malloc failure (it happens!), free as much as possible
1703 		 * and exit
1704 		 */
1705 		if (sp == NULL) {
1706 			while (script != NULL) {
1707 				se = script;
1708 				script = script->next;
1709 				free(se);
1710 			}
1711 			snprintf(command_errbuf, sizeof (command_errbuf),
1712 			    "file '%s' line %d: memory allocation "
1713 			    "failure - aborting", filename, line);
1714 			return (CMD_ERROR);
1715 		}
1716 		strcpy(sp->text, cp);
1717 		sp->line = line;
1718 		sp->next = NULL;
1719 
1720 		if (script == NULL) {
1721 			script = sp;
1722 		} else {
1723 			se->next = sp;
1724 		}
1725 		se = sp;
1726 	}
1727 	close(fd);
1728 
1729 	/*
1730 	 * Execute the script
1731 	 */
1732 
1733 	prevsrcid = bf_vm->sourceId.i;
1734 	bf_vm->sourceId.i = fd+1;	/* 0 is user input device */
1735 
1736 	res = CMD_OK;
1737 
1738 	for (sp = script; sp != NULL; sp = sp->next) {
1739 		res = bf_run(sp->text);
1740 		if (res != FICL_VM_STATUS_OUT_OF_TEXT) {
1741 			snprintf(command_errbuf, sizeof (command_errbuf),
1742 			    "Error while including %s, in the line %d:\n%s",
1743 			    filename, sp->line, sp->text);
1744 			res = CMD_ERROR;
1745 			break;
1746 		} else
1747 			res = CMD_OK;
1748 	}
1749 
1750 	bf_vm->sourceId.i = -1;
1751 	(void) bf_run("");
1752 	bf_vm->sourceId.i = prevsrcid;
1753 
1754 	while (script != NULL) {
1755 		se = script;
1756 		script = script->next;
1757 		free(se);
1758 	}
1759 
1760 	return (res);
1761 }
1762 
1763 static int
1764 command_boot(int argc, char *argv[])
1765 {
1766 	return (CMD_OK);
1767 }
1768 
1769 static int
1770 command_autoboot(int argc, char *argv[])
1771 {
1772 	return (CMD_OK);
1773 }
1774 
1775 static void
1776 moduledir_rebuild(void)
1777 {
1778 	struct moduledir *mdp, *mtmp;
1779 	const char *path, *cp, *ep;
1780 	int cplen;
1781 
1782 	path = getenv("module_path");
1783 	if (path == NULL)
1784 		path = default_searchpath;
1785 	/*
1786 	 * Rebuild list of module directories if it changed
1787 	 */
1788 	STAILQ_FOREACH(mdp, &moduledir_list, d_link)
1789 		mdp->d_flags |= MDIR_REMOVED;
1790 
1791 	for (ep = path; *ep != 0;  ep++) {
1792 		cp = ep;
1793 		for (; *ep != 0 && *ep != ';'; ep++)
1794 			;
1795 		/*
1796 		 * Ignore trailing slashes
1797 		 */
1798 		for (cplen = ep - cp; cplen > 1 && cp[cplen - 1] == '/';
1799 		    cplen--)
1800 			;
1801 		STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1802 			if (strlen(mdp->d_path) != cplen ||
1803 			    bcmp(cp, mdp->d_path, cplen) != 0)
1804 				continue;
1805 			mdp->d_flags &= ~MDIR_REMOVED;
1806 			break;
1807 		}
1808 		if (mdp == NULL) {
1809 			mdp = malloc(sizeof (*mdp) + cplen + 1);
1810 			if (mdp == NULL)
1811 				return;
1812 			mdp->d_path = (char *)(mdp + 1);
1813 			bcopy(cp, mdp->d_path, cplen);
1814 			mdp->d_path[cplen] = 0;
1815 			mdp->d_hints = NULL;
1816 			mdp->d_flags = 0;
1817 			STAILQ_INSERT_TAIL(&moduledir_list, mdp, d_link);
1818 		}
1819 		if (*ep == 0)
1820 			break;
1821 	}
1822 	/*
1823 	 * Delete unused directories if any
1824 	 */
1825 	mdp = STAILQ_FIRST(&moduledir_list);
1826 	while (mdp) {
1827 		if ((mdp->d_flags & MDIR_REMOVED) == 0) {
1828 			mdp = STAILQ_NEXT(mdp, d_link);
1829 		} else {
1830 			if (mdp->d_hints)
1831 				free(mdp->d_hints);
1832 			mtmp = mdp;
1833 			mdp = STAILQ_NEXT(mdp, d_link);
1834 			STAILQ_REMOVE(&moduledir_list, mtmp, moduledir, d_link);
1835 			free(mtmp);
1836 		}
1837 	}
1838 }
1839 
1840 static char *
1841 file_lookup(const char *path, const char *name, int namelen)
1842 {
1843 	struct stat st;
1844 	char *result, *cp, *gz;
1845 	int pathlen;
1846 
1847 	pathlen = strlen(path);
1848 	result = malloc(pathlen + namelen + 2);
1849 	if (result == NULL)
1850 		return (NULL);
1851 	bcopy(path, result, pathlen);
1852 	if (pathlen > 0 && result[pathlen - 1] != '/')
1853 		result[pathlen++] = '/';
1854 	cp = result + pathlen;
1855 	bcopy(name, cp, namelen);
1856 	cp += namelen;
1857 	*cp = '\0';
1858 	if (stat(result, &st) == 0 && S_ISREG(st.st_mode))
1859 		return (result);
1860 	/* also check for gz file */
1861 	(void) asprintf(&gz, "%s.gz", result);
1862 	if (gz != NULL) {
1863 		int res = stat(gz, &st);
1864 		free(gz);
1865 		if (res == 0)
1866 			return (result);
1867 	}
1868 	free(result);
1869 	return (NULL);
1870 }
1871 
1872 static char *
1873 file_search(const char *name)
1874 {
1875 	struct moduledir *mdp;
1876 	struct stat sb;
1877 	char *result;
1878 	int namelen;
1879 
1880 	if (name == NULL)
1881 		return (NULL);
1882 	if (*name == 0)
1883 		return (strdup(name));
1884 
1885 	if (strchr(name, '/') != NULL) {
1886 		char *gz;
1887 		if (stat(name, &sb) == 0)
1888 			return (strdup(name));
1889 		/* also check for gz file */
1890 		(void) asprintf(&gz, "%s.gz", name);
1891 		if (gz != NULL) {
1892 			int res = stat(gz, &sb);
1893 			free(gz);
1894 			if (res == 0)
1895 				return (strdup(name));
1896 		}
1897 		return (NULL);
1898 	}
1899 
1900 	moduledir_rebuild();
1901 	result = NULL;
1902 	namelen = strlen(name);
1903 	STAILQ_FOREACH(mdp, &moduledir_list, d_link) {
1904 		result = file_lookup(mdp->d_path, name, namelen);
1905 		if (result)
1906 			break;
1907 	}
1908 	return (result);
1909 }
1910 
1911 static int
1912 command_load(int argc, char *argv[])
1913 {
1914 	int dofile, ch;
1915 	char *typestr = NULL;
1916 	char *filename;
1917 	dofile = 0;
1918 	optind = 1;
1919 
1920 	if (argc == 1) {
1921 		command_errmsg = "no filename specified";
1922 		return (CMD_ERROR);
1923 	}
1924 
1925 	while ((ch = getopt(argc, argv, "kt:")) != -1) {
1926 		switch (ch) {
1927 		case 'k':
1928 			break;
1929 		case 't':
1930 			typestr = optarg;
1931 			dofile = 1;
1932 			break;
1933 		case '?':
1934 		default:
1935 			return (CMD_OK);
1936 		}
1937 	}
1938 	argv += (optind - 1);
1939 	argc -= (optind - 1);
1940 	if (dofile) {
1941 		if ((typestr == NULL) || (*typestr == 0)) {
1942 			command_errmsg = "invalid load type";
1943 			return (CMD_ERROR);
1944 		}
1945 #if 0
1946 		return (file_loadraw(argv[1], typestr, argc - 2, argv + 2, 1)
1947 		    ? CMD_OK : CMD_ERROR);
1948 #endif
1949 		return (CMD_OK);
1950 	}
1951 
1952 	filename = file_search(argv[1]);
1953 	if (filename == NULL) {
1954 		snprintf(command_errbuf, sizeof (command_errbuf),
1955 		    "can't find '%s'", argv[1]);
1956 		return (CMD_ERROR);
1957 	}
1958 	setenv("kernelname", filename, 1);
1959 
1960 	return (CMD_OK);
1961 }
1962 
1963 static int
1964 command_unload(int argc, char *argv[])
1965 {
1966 	unsetenv("kernelname");
1967 	return (CMD_OK);
1968 }
1969 
1970 static int
1971 command_reboot(int argc, char *argv[])
1972 {
1973 	exit(0);
1974 	return (CMD_OK);
1975 }
1976