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