xref: /titanic_52/usr/src/boot/sys/boot/common/interp_forth.c (revision c8951589222ca4706bf8bfc6df387c3d4b569ad4)
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 DEBUG(fmt, args...)	printf("%s: " fmt "\n" , __func__ , ## args)
41 #else
42 # define DEBUG(fmt, args...)
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
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) && !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 (ficlStackPopInteger(ficlVmGetDataStack(vm))) {
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 = ficlStackPopInteger(ficlVmGetDataStack(vm));
104 	for (i = 0, len = 0; i < nstrings; i++)
105 	    len += ficlStackFetch(ficlVmGetDataStack(vm), 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 = ficlStackPopInteger(ficlVmGetDataStack(vm));
112 		cp = ficlStackPopPointer(ficlVmGetDataStack(vm));
113 		strcat(line, " ");
114 		strncat(line, cp, len);
115 	    }
116     } else {
117 	/* Get remainder of invocation */
118 	tail = ficlVmGetInBuf(vm);
119 
120 	for (cp = tail, len = 0; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++, len++)
121 	    ;
122 
123 	line = malloc(strlen(name) + len + 2);
124 	strcpy(line, name);
125 	if (len > 0) {
126 	    strcat(line, " ");
127 	    strncat(line, tail, len);
128 	    ficlVmUpdateTib(vm, tail + len);
129 	}
130     }
131     DEBUG("cmd '%s'", line);
132 
133     command_errmsg = command_errbuf;
134     command_errbuf[0] = 0;
135     if (!parse(&argc, &argv, line)) {
136 	result = (cmd)(argc, argv);
137 	free(argv);
138     } else {
139 	result=BF_PARSE;
140     }
141 
142     switch (result) {
143     case CMD_CRIT:
144 	printf("%s\n", command_errmsg);
145 	break;
146     case CMD_FATAL:
147 	panic("%s\n", command_errmsg);
148     }
149 
150     free(line);
151     /*
152      * If there was error during nested ficlExec(), we may no longer have
153      * valid environment to return.  Throw all exceptions from here.
154      */
155     if (result != CMD_OK)
156 	ficlVmThrow(vm, result);
157 
158     /* This is going to be thrown!!! */
159     ficlStackPushInteger(ficlVmGetDataStack(vm),result);
160 }
161 
162 /*
163  * Replace a word definition (a builtin command) with another
164  * one that:
165  *
166  *        - Throw error results instead of returning them on the stack
167  *        - Pass a flag indicating whether the word was compiled or is
168  *          being interpreted.
169  *
170  * There is one major problem with builtins that cannot be overcome
171  * in anyway, except by outlawing it. We want builtins to behave
172  * differently depending on whether they have been compiled or they
173  * are being interpreted. Notice that this is *not* the interpreter's
174  * current state. For example:
175  *
176  * : example ls ; immediate
177  * : problem example ;		\ "ls" gets executed while compiling
178  * example			\ "ls" gets executed while interpreting
179  *
180  * Notice that, though the current state is different in the two
181  * invocations of "example", in both cases "ls" has been
182  * *compiled in*, which is what we really want.
183  *
184  * The problem arises when you tick the builtin. For example:
185  *
186  * : example-1 ['] ls postpone literal ; immediate
187  * : example-2 example-1 execute ; immediate
188  * : problem example-2 ;
189  * example-2
190  *
191  * We have no way, when we get EXECUTEd, of knowing what our behavior
192  * should be. Thus, our only alternative is to "outlaw" this. See RFI
193  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
194  * problem, concerning compile semantics.
195  *
196  * The problem is compounded by the fact that "' builtin CATCH" is valid
197  * and desirable. The only solution is to create an intermediary word.
198  * For example:
199  *
200  * : my-ls ls ;
201  * : example ['] my-ls catch ;
202  *
203  * So, with the below implementation, here is a summary of the behavior
204  * of builtins:
205  *
206  * ls -l				\ "interpret" behavior, ie,
207  *					\ takes parameters from TIB
208  * : ex-1 s" -l" 1 ls ;			\ "compile" behavior, ie,
209  *					\ takes parameters from the stack
210  * : ex-2 ['] ls catch ; immediate	\ undefined behavior
211  * : ex-3 ['] ls catch ;		\ undefined behavior
212  * ex-2 ex-3				\ "interpret" behavior,
213  *					\ catch works
214  * : ex-4 ex-2 ;			\ "compile" behavior,
215  *					\ catch does not work
216  * : ex-5 ex-3 ; immediate		\ same as ex-2
217  * : ex-6 ex-3 ;			\ same as ex-3
218  * : ex-7 ['] ex-1 catch ;		\ "compile" behavior,
219  *					\ catch works
220  * : ex-8 postpone ls ;	immediate	\ same as ex-2
221  * : ex-9 postpone ls ;			\ same as ex-3
222  *
223  * As the definition below is particularly tricky, and it's side effects
224  * must be well understood by those playing with it, I'll be heavy on
225  * the comments.
226  *
227  * (if you edit this definition, pay attention to trailing spaces after
228  *  each word -- I warned you! :-) )
229  */
230 #define BUILTIN_CONSTRUCTOR \
231 ": builtin: "		\
232   ">in @ "		/* save the tib index pointer */ \
233   "' "			/* get next word's xt */ \
234   "swap >in ! "		/* point again to next word */ \
235   "create "		/* create a new definition of the next word */ \
236   ", "			/* save previous definition's xt */ \
237   "immediate "		/* make the new definition an immediate word */ \
238 			\
239   "does> "		/* Now, the *new* definition will: */ \
240   "state @ if "		/* if in compiling state: */ \
241     "1 postpone literal "	/* pass 1 flag to indicate compile */ \
242     "@ compile, "		/* compile in previous definition */ \
243     "postpone throw "		/* throw stack-returned result */ \
244   "else "		/* if in interpreting state: */ \
245     "0 swap "			/* pass 0 flag to indicate interpret */ \
246     "@ execute "		/* call previous definition */ \
247     "throw "			/* throw stack-returned result */ \
248   "then ; "
249 
250 /*
251  * Initialise the Forth interpreter, create all our commands as words.
252  */
253 void
254 bf_init(char *rc)
255 {
256     struct bootblk_command	**cmdp;
257     char create_buf[41];	/* 31 characters-long builtins */
258     int fd, rv;
259     ficlDictionary *dict;
260     ficlDictionary *env;
261 
262     fsi = malloc(sizeof(ficlSystemInformation));
263     ficlSystemInformationInitialize(fsi);
264     fsi->dictionarySize = BF_DICTSIZE;
265 
266     bf_sys = ficlSystemCreate(fsi);
267     bf_vm = ficlSystemCreateVm(bf_sys);
268 
269     /* Put all private definitions in a "builtins" vocabulary */
270     rv = ficlVmEvaluate(bf_vm, "vocabulary builtins also builtins definitions");
271     if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
272 	panic("error interpreting forth: %d\n", rv);
273     }
274 
275     /* Builtin constructor word  */
276     rv = ficlVmEvaluate(bf_vm, BUILTIN_CONSTRUCTOR);
277     if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
278 	panic("error interpreting forth: %d\n", rv);
279     }
280 
281     /* make all commands appear as Forth words */
282     dict = ficlSystemGetDictionary(bf_sys);
283     SET_FOREACH(cmdp, Xcommand_set) {
284 	ficlDictionaryAppendPrimitive(dict, (char *)(*cmdp)->c_name,
285 		bf_command, FICL_WORD_DEFAULT);
286 	rv = ficlVmEvaluate(bf_vm, "forth definitions builtins");
287 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
288 		panic("error interpreting forth: %d\n", rv);
289 	}
290 	sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
291 	rv = ficlVmEvaluate(bf_vm, create_buf);
292 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
293 		panic("error interpreting forth: %d\n", rv);
294 	}
295 	rv = ficlVmEvaluate(bf_vm, "builtins definitions");
296 	if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
297 		panic("error interpreting forth: %d\n", rv);
298 	}
299     }
300     rv = ficlVmEvaluate(bf_vm, "only forth definitions");
301     if (rv != FICL_VM_STATUS_OUT_OF_TEXT) {
302 	panic("error interpreting forth: %d\n", rv);
303     }
304 
305     /*
306      * Export some version numbers so that code can detect the loader/host
307      * version
308      */
309     env = ficlSystemGetEnvironment(bf_sys);
310     ficlDictionarySetConstant(env, "loader_version", bootprog_rev);
311 
312     /* try to load and run init file if present */
313     if (rc == NULL)
314 	rc = "/boot/forth/boot.4th";
315     if (*rc != '\0') {
316 	fd = open(rc, O_RDONLY);
317 	if (fd != -1) {
318 	    (void)ficlExecFD(bf_vm, fd);
319 	    close(fd);
320 	}
321     }
322 }
323 
324 /*
325  * Feed a line of user input to the Forth interpreter
326  */
327 int
328 bf_run(char *line)
329 {
330     int		result;
331     ficlString s;
332 
333     FICL_STRING_SET_FROM_CSTRING(s, line);
334     result = ficlVmExecuteString(bf_vm, s);
335 
336     DEBUG("ficlExec '%s' = %d", line, result);
337     switch (result) {
338     case FICL_VM_STATUS_OUT_OF_TEXT:
339     case FICL_VM_STATUS_ABORTQ:
340     case FICL_VM_STATUS_QUIT:
341     case FICL_VM_STATUS_ERROR_EXIT:
342 	break;
343     case FICL_VM_STATUS_USER_EXIT:
344 	printf("No where to leave to!\n");
345 	break;
346     case FICL_VM_STATUS_ABORT:
347 	printf("Aborted!\n");
348 	break;
349     case BF_PARSE:
350 	printf("Parse error!\n");
351 	break;
352     default:
353 	if (command_errmsg != NULL) {
354 	    printf("%s\n", command_errmsg);
355 	    command_errmsg = NULL;
356 	}
357     }
358 
359     /* bye is same as reboot and will behave depending on platform */
360     if (result == FICL_VM_STATUS_USER_EXIT)
361 	bf_run("reboot");
362     setenv("interpret", bf_vm->state ? "" : "ok", 1);
363 
364     return (result);
365 }
366