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/cdefs.h>
28 
29 #include <sys/param.h>		/* to pick up __FreeBSD_version */
30 #include <string.h>
31 #include <stand.h>
32 #include "bootstrap.h"
33 #include "ficl.h"
34 
35 extern unsigned bootprog_rev;
36 
37 /* #define BFORTH_DEBUG */
38 
39 #ifdef BFORTH_DEBUG
40 #define	DPRINTF(fmt, args...)	printf("%s: " fmt "\n", __func__, ## args)
41 #else
42 #define	DPRINTF(fmt, args...)	((void)0)
43 #endif
44 
45 /*
46  * Eventually, all builtin commands throw codes must be defined
47  * elsewhere, possibly bootstrap.h. For now, just this code, used
48  * just in this file, it is getting defined.
49  */
50 #define	BF_PARSE 100
51 
52 /*
53  * FreeBSD loader default dictionary cells
54  */
55 #ifndef	BF_DICTSIZE
56 #define	BF_DICTSIZE	30000
57 #endif
58 
59 /*
60  * BootForth   Interface to Ficl Forth interpreter.
61  */
62 
63 ficlSystemInformation *fsi;
64 ficlSystem *bf_sys;
65 ficlVm	*bf_vm;
66 
67 /*
68  * Shim for taking commands from BF and passing them out to 'standard'
69  * argv/argc command functions.
70  */
71 static void
bf_command(ficlVm * vm)72 bf_command(ficlVm *vm)
73 {
74 	char			*name, *line, *tail, *cp;
75 	size_t			len;
76 	struct bootblk_command	**cmdp;
77 	bootblk_cmd_t		*cmd;
78 	int			nstrings, i;
79 	int			argc, result;
80 	char			**argv;
81 
82 	/* Get the name of the current word */
83 	name = vm->runningWord->name;
84 
85 	/* Find our command structure */
86 	cmd = NULL;
87 	SET_FOREACH(cmdp, Xcommand_set) {
88 		if (((*cmdp)->c_name != NULL) &&
89 		    strcmp(name, (*cmdp)->c_name) == 0)
90 			cmd = (*cmdp)->c_fn;
91 	}
92 	if (cmd == NULL)
93 		panic("callout for unknown command '%s'", name);
94 
95 	/* Check whether we have been compiled or are being interpreted */
96 	if (ficlStackPopInteger(ficlVmGetDataStack(vm))) {
97 		/*
98 		 * Get parameters from stack, in the format:
99 		 * an un ... a2 u2 a1 u1 n --
100 		 * Where n is the number of strings, a/u are pairs of
101 		 * address/size for strings, and they will be concatenated
102 		 * in LIFO order.
103 		 */
104 		nstrings = ficlStackPopInteger(ficlVmGetDataStack(vm));
105 		for (i = 0, len = 0; i < nstrings; i++) {
106 			ficlStack *stack = ficlVmGetDataStack(vm);
107 			len += ficlStackFetch(stack, i * 2).i + 1;
108 		}
109 		line = malloc(strlen(name) + len + 1);
110 		strcpy(line, name);
111 
112 		if (nstrings)
113 			for (i = 0; i < nstrings; i++) {
114 				ficlStack *stack = ficlVmGetDataStack(vm);
115 
116 				len = ficlStackPopInteger(stack);
117 				cp = ficlStackPopPointer(stack);
118 				strcat(line, " ");
119 				strncat(line, cp, len);
120 			}
121 	} else {
122 		/* Get remainder of invocation */
123 		tail = ficlVmGetInBuf(vm);
124 
125 		len = 0;
126 		cp = tail;
127 		for (; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++)
128 			len++;
129 
130 		line = malloc(strlen(name) + len + 2);
131 		strcpy(line, name);
132 		if (len > 0) {
133 			strcat(line, " ");
134 			strncat(line, tail, len);
135 			ficlVmUpdateTib(vm, tail + len);
136 		}
137 	}
138 	DPRINTF("cmd '%s'", line);
139 
140 	command_errmsg = command_errbuf;
141 	command_errbuf[0] = 0;
142 	if (!parse(&argc, &argv, line)) {
143 		result = (cmd)(argc, argv);
144 		free(argv);
145 	} else {
146 		result = BF_PARSE;
147 	}
148 
149 	switch (result) {
150 	case CMD_CRIT:
151 		printf("%s\n", command_errmsg);
152 		command_errmsg = NULL;
153 		break;
154 	case CMD_FATAL:
155 		panic("%s", command_errmsg);
156 	}
157 
158 	free(line);
159 	/*
160 	 * If there was error during nested ficlExec(), we may no longer have
161 	 * valid environment to return.  Throw all exceptions from here.
162 	 */
163 	if (result != CMD_OK)
164 		ficlVmThrow(vm, result);
165 
166 	/* This is going to be thrown!!! */
167 	ficlStackPushInteger(ficlVmGetDataStack(vm), result);
168 }
169 
170 /*
171  * Replace a word definition (a builtin command) with another
172  * one that:
173  *
174  *        - Throw error results instead of returning them on the stack
175  *        - Pass a flag indicating whether the word was compiled or is
176  *          being interpreted.
177  *
178  * There is one major problem with builtins that cannot be overcome
179  * in anyway, except by outlawing it. We want builtins to behave
180  * differently depending on whether they have been compiled or they
181  * are being interpreted. Notice that this is *not* the interpreter's
182  * current state. For example:
183  *
184  * : example ls ; immediate
185  * : problem example ;		\ "ls" gets executed while compiling
186  * example			\ "ls" gets executed while interpreting
187  *
188  * Notice that, though the current state is different in the two
189  * invocations of "example", in both cases "ls" has been
190  * *compiled in*, which is what we really want.
191  *
192  * The problem arises when you tick the builtin. For example:
193  *
194  * : example-1 ['] ls postpone literal ; immediate
195  * : example-2 example-1 execute ; immediate
196  * : problem example-2 ;
197  * example-2
198  *
199  * We have no way, when we get EXECUTEd, of knowing what our behavior
200  * should be. Thus, our only alternative is to "outlaw" this. See RFI
201  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
202  * problem, concerning compile semantics.
203  *
204  * The problem is compounded by the fact that "' builtin CATCH" is valid
205  * and desirable. The only solution is to create an intermediary word.
206  * For example:
207  *
208  * : my-ls ls ;
209  * : example ['] my-ls catch ;
210  *
211  * So, with the below implementation, here is a summary of the behavior
212  * of builtins:
213  *
214  * ls -l				\ "interpret" behavior, ie,
215  *					\ takes parameters from TIB
216  * : ex-1 s" -l" 1 ls ;			\ "compile" behavior, ie,
217  *					\ takes parameters from the stack
218  * : ex-2 ['] ls catch ; immediate	\ undefined behavior
219  * : ex-3 ['] ls catch ;		\ undefined behavior
220  * ex-2 ex-3				\ "interpret" behavior,
221  *					\ catch works
222  * : ex-4 ex-2 ;			\ "compile" behavior,
223  *					\ catch does not work
224  * : ex-5 ex-3 ; immediate		\ same as ex-2
225  * : ex-6 ex-3 ;			\ same as ex-3
226  * : ex-7 ['] ex-1 catch ;		\ "compile" behavior,
227  *					\ catch works
228  * : ex-8 postpone ls ;	immediate	\ same as ex-2
229  * : ex-9 postpone ls ;			\ same as ex-3
230  *
231  * As the definition below is particularly tricky, and it's side effects
232  * must be well understood by those playing with it, I'll be heavy on
233  * the comments.
234  *
235  * (if you edit this definition, pay attention to trailing spaces after
236  *  each word -- I warned you! :-) )
237  */
238 #define	BUILTIN_CONSTRUCTOR \
239 ": builtin: "		\
240 	">in @ "		/* save the tib index pointer */ \
241 	"' "			/* get next word's xt */ \
242 	"swap >in ! "		/* point again to next word */ \
243 	"create "		/* create a new definition of the next word */ \
244 	", "			/* save previous definition's xt */ \
245 	"immediate "	/* make the new definition an immediate word */ \
246 			\
247 	"does> "		/* Now, the *new* definition will: */ \
248 	"state @ if "		/* if in compiling state: */ \
249 	"1 postpone literal "	/* pass 1 flag to indicate compile */ \
250 	"@ compile, "		/* compile in previous definition */ \
251 	"postpone throw "	/* throw stack-returned result */ \
252 	"else "		/* if in interpreting state: */ \
253 	"0 swap "		/* pass 0 flag to indicate interpret */ \
254 	"@ execute "		/* call previous definition */ \
255 	"throw "			/* throw stack-returned result */ \
256 	"then ; "
257 
258 /*
259  * Initialise the Forth interpreter, create all our commands as words.
260  */
261 void
bf_init(char * rc)262 bf_init(char *rc)
263 {
264 	struct bootblk_command	**cmdp;
265 	char create_buf[41];	/* 31 characters-long builtins */
266 	int fd, rv;
267 	ficlDictionary *dict;
268 	ficlDictionary *env;
269 
270 	fsi = malloc(sizeof (ficlSystemInformation));
271 	ficlSystemInformationInitialize(fsi);
272 	fsi->dictionarySize = BF_DICTSIZE;
273 
274 	bf_sys = ficlSystemCreate(fsi);
275 	bf_vm = ficlSystemCreateVm(bf_sys);
276 
277 	/* Put all private definitions in a "builtins" vocabulary */
278 	rv = ficlVmEvaluate(bf_vm,
279 	    "vocabulary builtins also builtins definitions");
280 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
281 		panic("error interpreting forth: %d", rv);
282 	}
283 
284 	/* Builtin constructor word  */
285 	rv = ficlVmEvaluate(bf_vm, BUILTIN_CONSTRUCTOR);
286 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
287 		panic("error interpreting forth: %d", rv);
288 	}
289 
290 	/* make all commands appear as Forth words */
291 	dict = ficlSystemGetDictionary(bf_sys);
292 	SET_FOREACH(cmdp, Xcommand_set) {
293 		ficlDictionaryAppendPrimitive(dict, (char *)(*cmdp)->c_name,
294 		    bf_command, FICL_WORD_DEFAULT);
295 		rv = ficlVmEvaluate(bf_vm, "forth definitions builtins");
296 		if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
297 			panic("error interpreting forth: %d", rv);
298 		}
299 		sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
300 		rv = ficlVmEvaluate(bf_vm, create_buf);
301 		if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
302 			panic("error interpreting forth: %d", rv);
303 		}
304 		rv = ficlVmEvaluate(bf_vm, "builtins definitions");
305 		if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
306 			panic("error interpreting forth: %d", rv);
307 		}
308 	}
309 	rv = ficlVmEvaluate(bf_vm, "only forth definitions");
310 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
311 		panic("error interpreting forth: %d", rv);
312 	}
313 
314 	/*
315 	 * Export some version numbers so that code can detect the loader/host
316 	 * version
317 	 */
318 	env = ficlSystemGetEnvironment(bf_sys);
319 	ficlDictionarySetConstant(env, "loader_version", bootprog_rev);
320 
321 	/* try to load and run init file if present */
322 	if (rc == NULL)
323 		rc = "/boot/forth/boot.4th";
324 	if (*rc != '\0') {
325 		fd = open(rc, O_RDONLY);
326 		if (fd != -1) {
327 			(void) ficlExecFD(bf_vm, fd);
328 			close(fd);
329 		}
330 	}
331 }
332 
333 /*
334  * Feed a line of user input to the Forth interpreter
335  */
336 int
bf_run(char * line)337 bf_run(char *line)
338 {
339 	int result;
340 	ficlString s;
341 
342 	FICL_STRING_SET_FROM_CSTRING(s, line);
343 	result = ficlVmExecuteString(bf_vm, s);
344 
345 	DPRINTF("ficlExec '%s' = %d", line, result);
346 	switch (result) {
347 	case FICL_VM_STATUS_OUT_OF_TEXT:
348 	case FICL_VM_STATUS_ABORTQ:
349 	case FICL_VM_STATUS_QUIT:
350 	case FICL_VM_STATUS_ERROR_EXIT:
351 		break;
352 	case FICL_VM_STATUS_USER_EXIT:
353 		printf("No where to leave to!\n");
354 		break;
355 	case FICL_VM_STATUS_ABORT:
356 		printf("Aborted!\n");
357 		break;
358 	case BF_PARSE:
359 		printf("Parse error!\n");
360 		break;
361 	default:
362 		if (command_errmsg != NULL) {
363 			printf("%s\n", command_errmsg);
364 			command_errmsg = NULL;
365 		}
366 	}
367 
368 	/* bye is same as reboot and will behave depending on platform */
369 	if (result == FICL_VM_STATUS_USER_EXIT)
370 		bf_run("reboot");
371 	setenv("interpret", bf_vm->state ? "" : "ok", 1);
372 
373 	return (result);
374 }
375