xref: /freebsd/stand/common/interp_forth.c (revision b00ab754)
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 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>		/* to pick up __FreeBSD_version */
31 #include <string.h>
32 #include <stand.h>
33 #include "bootstrap.h"
34 #include "ficl.h"
35 
36 extern unsigned bootprog_rev;
37 
38 /* #define BFORTH_DEBUG */
39 
40 #ifdef BFORTH_DEBUG
41 #define	DEBUG(fmt, args...)	printf("%s: " fmt "\n" , __func__ , ## args)
42 #else
43 #define	DEBUG(fmt, args...)
44 #endif
45 
46 /*
47  * Eventually, all builtin commands throw codes must be defined
48  * elsewhere, possibly bootstrap.h. For now, just this code, used
49  * just in this file, it is getting defined.
50  */
51 #define BF_PARSE 100
52 
53 /*
54  * FreeBSD loader default dictionary cells
55  */
56 #ifndef	BF_DICTSIZE
57 #define	BF_DICTSIZE	10000
58 #endif
59 
60 /*
61  * BootForth   Interface to Ficl Forth interpreter.
62  */
63 
64 FICL_SYSTEM *bf_sys;
65 FICL_VM	*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
72 bf_command(FICL_VM *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) && !strcmp(name, (*cmdp)->c_name))
89 			cmd = (*cmdp)->c_fn;
90 	}
91 	if (cmd == NULL)
92 		panic("callout for unknown command '%s'", name);
93 
94 	/* Check whether we have been compiled or are being interpreted */
95 	if (stackPopINT(vm->pStack)) {
96 		/*
97 		 * Get parameters from stack, in the format:
98 		 * an un ... a2 u2 a1 u1 n --
99 		 * Where n is the number of strings, a/u are pairs of
100 		 * address/size for strings, and they will be concatenated
101 		 * in LIFO order.
102 		 */
103 		nstrings = stackPopINT(vm->pStack);
104 		for (i = 0, len = 0; i < nstrings; i++)
105 			len += stackFetch(vm->pStack, i * 2).i + 1;
106 		line = malloc(strlen(name) + len + 1);
107 		strcpy(line, name);
108 
109 		if (nstrings)
110 			for (i = 0; i < nstrings; i++) {
111 				len = stackPopINT(vm->pStack);
112 				cp = stackPopPtr(vm->pStack);
113 				strcat(line, " ");
114 				strncat(line, cp, len);
115 			}
116 	} else {
117 		/* Get remainder of invocation */
118 		tail = vmGetInBuf(vm);
119 		for (cp = tail, len = 0; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++, len++)
120 			;
121 
122 		line = malloc(strlen(name) + len + 2);
123 		strcpy(line, name);
124 		if (len > 0) {
125 			strcat(line, " ");
126 			strncat(line, tail, len);
127 			vmUpdateTib(vm, tail + len);
128 		}
129 	}
130 	DEBUG("cmd '%s'", line);
131 
132 	command_errmsg = command_errbuf;
133 	command_errbuf[0] = 0;
134 	if (!parse(&argc, &argv, line)) {
135 		result = (cmd)(argc, argv);
136 		free(argv);
137 	} else {
138 		result=BF_PARSE;
139 	}
140 
141 	switch (result) {
142 	case CMD_CRIT:
143 		printf("%s\n", command_errmsg);
144 		break;
145 	case CMD_FATAL:
146 		panic("%s\n", command_errmsg);
147 	}
148 
149 	free(line);
150 	/*
151 	 * If there was error during nested ficlExec(), we may no longer have
152 	 * valid environment to return.  Throw all exceptions from here.
153 	 */
154 	if (result != CMD_OK)
155 		vmThrow(vm, result);
156 
157 	/* This is going to be thrown!!! */
158 	stackPushINT(vm->pStack,result);
159 }
160 
161 /*
162  * Replace a word definition (a builtin command) with another
163  * one that:
164  *
165  *        - Throw error results instead of returning them on the stack
166  *        - Pass a flag indicating whether the word was compiled or is
167  *          being interpreted.
168  *
169  * There is one major problem with builtins that cannot be overcome
170  * in anyway, except by outlawing it. We want builtins to behave
171  * differently depending on whether they have been compiled or they
172  * are being interpreted. Notice that this is *not* the interpreter's
173  * current state. For example:
174  *
175  * : example ls ; immediate
176  * : problem example ;		\ "ls" gets executed while compiling
177  * example			\ "ls" gets executed while interpreting
178  *
179  * Notice that, though the current state is different in the two
180  * invocations of "example", in both cases "ls" has been
181  * *compiled in*, which is what we really want.
182  *
183  * The problem arises when you tick the builtin. For example:
184  *
185  * : example-1 ['] ls postpone literal ; immediate
186  * : example-2 example-1 execute ; immediate
187  * : problem example-2 ;
188  * example-2
189  *
190  * We have no way, when we get EXECUTEd, of knowing what our behavior
191  * should be. Thus, our only alternative is to "outlaw" this. See RFI
192  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
193  * problem, concerning compile semantics.
194  *
195  * The problem is compounded by the fact that "' builtin CATCH" is valid
196  * and desirable. The only solution is to create an intermediary word.
197  * For example:
198  *
199  * : my-ls ls ;
200  * : example ['] my-ls catch ;
201  *
202  * So, with the below implementation, here is a summary of the behavior
203  * of builtins:
204  *
205  * ls -l				\ "interpret" behavior, ie,
206  *					\ takes parameters from TIB
207  * : ex-1 s" -l" 1 ls ;			\ "compile" behavior, ie,
208  *					\ takes parameters from the stack
209  * : ex-2 ['] ls catch ; immediate	\ undefined behavior
210  * : ex-3 ['] ls catch ;		\ undefined behavior
211  * ex-2 ex-3				\ "interpret" behavior,
212  *					\ catch works
213  * : ex-4 ex-2 ;			\ "compile" behavior,
214  *					\ catch does not work
215  * : ex-5 ex-3 ; immediate		\ same as ex-2
216  * : ex-6 ex-3 ;			\ same as ex-3
217  * : ex-7 ['] ex-1 catch ;		\ "compile" behavior,
218  *					\ catch works
219  * : ex-8 postpone ls ;	immediate	\ same as ex-2
220  * : ex-9 postpone ls ;			\ same as ex-3
221  *
222  * As the definition below is particularly tricky, and it's side effects
223  * must be well understood by those playing with it, I'll be heavy on
224  * the comments.
225  *
226  * (if you edit this definition, pay attention to trailing spaces after
227  *  each word -- I warned you! :-) )
228  */
229 #define BUILTIN_CONSTRUCTOR						\
230 	": builtin: "							\
231 	">in @ "		/* save the tib index pointer */	\
232 	"' "			/* get next word's xt */		\
233 	"swap >in ! "		/* point again to next word */		\
234 	"create "		/* create a new definition of the next word */ \
235 	", "			/* save previous definition's xt */	\
236 	"immediate "		/* make the new definition an immediate word */ \
237 									\
238 	"does> "		/* Now, the *new* definition will: */	\
239 	"state @ if "		/* if in compiling state: */		\
240 	"1 postpone literal "	/* pass 1 flag to indicate compile */	\
241 	"@ compile, "		/* compile in previous definition */	\
242 	"postpone throw "		/* throw stack-returned result */ \
243 	"else "		/* if in interpreting state: */			\
244 	"0 swap "			/* pass 0 flag to indicate interpret */ \
245 	"@ execute "		/* call previous definition */		\
246 	"throw "			/* throw stack-returned result */ \
247 	"then ; "
248 
249 /*
250  * Initialise the Forth interpreter, create all our commands as words.
251  */
252 void
253 bf_init(void)
254 {
255 	struct bootblk_command	**cmdp;
256 	char create_buf[41];	/* 31 characters-long builtins */
257 	int fd;
258 
259 	bf_sys = ficlInitSystem(BF_DICTSIZE);
260 	bf_vm = ficlNewVM(bf_sys);
261 
262 	/* Put all private definitions in a "builtins" vocabulary */
263 	ficlExec(bf_vm, "vocabulary builtins also builtins definitions");
264 
265 	/* Builtin constructor word  */
266 	ficlExec(bf_vm, BUILTIN_CONSTRUCTOR);
267 
268 	/* make all commands appear as Forth words */
269 	SET_FOREACH(cmdp, Xcommand_set) {
270 		ficlBuild(bf_sys, (char *)(*cmdp)->c_name, bf_command, FW_DEFAULT);
271 		ficlExec(bf_vm, "forth definitions builtins");
272 		sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
273 		ficlExec(bf_vm, create_buf);
274 		ficlExec(bf_vm, "builtins definitions");
275 	}
276 	ficlExec(bf_vm, "only forth definitions");
277 
278 	/* Export some version numbers so that code can detect the loader/host version */
279 	ficlSetEnv(bf_sys, "FreeBSD_version", __FreeBSD_version);
280 	ficlSetEnv(bf_sys, "loader_version", bootprog_rev);
281 
282 	/* try to load and run init file if present */
283 	if ((fd = open("/boot/boot.4th", O_RDONLY)) != -1) {
284 		(void)ficlExecFD(bf_vm, fd);
285 		close(fd);
286 	}
287 }
288 
289 /*
290  * Feed a line of user input to the Forth interpreter
291  */
292 static int
293 bf_run(const char *line)
294 {
295 	int		result;
296 
297 	/*
298 	 * ficl would require extensive changes to accept a const char *
299 	 * interface. Instead, cast it away here and hope for the best.
300 	 * We know at the present time the caller for us in the boot
301 	 * forth loader can tolerate the string being modified because
302 	 * the string is passed in here and then not touched again.
303 	 */
304 	result = ficlExec(bf_vm, __DECONST(char *, line));
305 
306 	DEBUG("ficlExec '%s' = %d", line, result);
307 	switch (result) {
308 	case VM_OUTOFTEXT:
309 	case VM_ABORTQ:
310 	case VM_QUIT:
311 	case VM_ERREXIT:
312 		break;
313 	case VM_USEREXIT:
314 		printf("No where to leave to!\n");
315 		break;
316 	case VM_ABORT:
317 		printf("Aborted!\n");
318 		break;
319 	case BF_PARSE:
320 		printf("Parse error!\n");
321 		break;
322 	default:
323 		if (command_errmsg != NULL) {
324 			printf("%s\n", command_errmsg);
325 			command_errmsg = NULL;
326 		}
327 	}
328 
329 	if (result == VM_USEREXIT)
330 		panic("interpreter exit");
331 	setenv("interpret", bf_vm->state ? "" : "OK", 1);
332 
333 	return (result);
334 }
335 
336 void
337 interp_init(void)
338 {
339 
340 	setenv("script.lang", "forth", 1);
341 	bf_init();
342 	/* Read our default configuration. */
343 	interp_include("/boot/loader.rc");
344 }
345 
346 int
347 interp_run(const char *input)
348 {
349 
350 	bf_vm->sourceID.i = 0;
351 	return bf_run(input);
352 }
353 
354 /*
355  * Header prepended to each line. The text immediately follows the header.
356  * We try to make this short in order to save memory -- the loader has
357  * limited memory available, and some of the forth files are very long.
358  */
359 struct includeline
360 {
361 	struct includeline	*next;
362 	char			text[0];
363 };
364 
365 int
366 interp_include(const char *filename)
367 {
368 	struct includeline	*script, *se, *sp;
369 	char			input[256];			/* big enough? */
370 	int			res;
371 	char			*cp;
372 	int			prevsrcid, fd, line;
373 
374 	if (((fd = open(filename, O_RDONLY)) == -1)) {
375 		snprintf(command_errbuf, sizeof(command_errbuf),
376 		    "can't open '%s': %s", filename, strerror(errno));
377 		return(CMD_ERROR);
378 	}
379 
380 	/*
381 	 * Read the script into memory.
382 	 */
383 	script = se = NULL;
384 	line = 0;
385 
386 	while (fgetstr(input, sizeof(input), fd) >= 0) {
387 		line++;
388 		cp = input;
389 		/* Allocate script line structure and copy line, flags */
390 		if (*cp == '\0')
391 			continue;	/* ignore empty line, save memory */
392 		sp = malloc(sizeof(struct includeline) + strlen(cp) + 1);
393 		/* On malloc failure (it happens!), free as much as possible and exit */
394 		if (sp == NULL) {
395 			while (script != NULL) {
396 				se = script;
397 				script = script->next;
398 				free(se);
399 			}
400 			snprintf(command_errbuf, sizeof(command_errbuf),
401 			    "file '%s' line %d: memory allocation failure - aborting",
402 			    filename, line);
403 			close(fd);
404 			return (CMD_ERROR);
405 		}
406 		strcpy(sp->text, cp);
407 		sp->next = NULL;
408 
409 		if (script == NULL) {
410 			script = sp;
411 		} else {
412 			se->next = sp;
413 		}
414 		se = sp;
415 	}
416 	close(fd);
417 
418 	/*
419 	 * Execute the script
420 	 */
421 	prevsrcid = bf_vm->sourceID.i;
422 	bf_vm->sourceID.i = fd;
423 	res = CMD_OK;
424 	for (sp = script; sp != NULL; sp = sp->next) {
425 		res = bf_run(sp->text);
426 		if (res != VM_OUTOFTEXT) {
427 			snprintf(command_errbuf, sizeof(command_errbuf),
428 			    "Error while including %s, in the line:\n%s",
429 			    filename, sp->text);
430 			res = CMD_ERROR;
431 			break;
432 		} else
433 			res = CMD_OK;
434 	}
435 	bf_vm->sourceID.i = prevsrcid;
436 
437 	while (script != NULL) {
438 		se = script;
439 		script = script->next;
440 		free(se);
441 	}
442 	return(res);
443 }
444