]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - sys/boot/common/interp_forth.c
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / sys / boot / common / interp_forth.c
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 char 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 FICL_WORD *pInterp;
67
68 /*
69  * Shim for taking commands from BF and passing them out to 'standard'
70  * argv/argc command functions.
71  */
72 static void
73 bf_command(FICL_VM *vm)
74 {
75     char                        *name, *line, *tail, *cp;
76     size_t                      len;
77     struct bootblk_command      **cmdp;
78     bootblk_cmd_t               *cmd;
79     int                         nstrings, i;
80     int                         argc, result;
81     char                        **argv;
82
83     /* Get the name of the current word */
84     name = vm->runningWord->name;
85     
86     /* Find our command structure */
87     cmd = NULL;
88     SET_FOREACH(cmdp, Xcommand_set) {
89         if (((*cmdp)->c_name != NULL) && !strcmp(name, (*cmdp)->c_name))
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 (stackPopINT(vm->pStack)) {
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 = stackPopINT(vm->pStack);
105         for (i = 0, len = 0; i < nstrings; i++)
106             len += stackFetch(vm->pStack, i * 2).i + 1;
107         line = malloc(strlen(name) + len + 1);
108         strcpy(line, name);
109
110         if (nstrings)
111             for (i = 0; i < nstrings; i++) {
112                 len = stackPopINT(vm->pStack);
113                 cp = stackPopPtr(vm->pStack);
114                 strcat(line, " ");
115                 strncat(line, cp, len);
116             }
117     } else {
118         /* Get remainder of invocation */
119         tail = vmGetInBuf(vm);
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             vmUpdateTib(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     free(line);
142     /*
143      * If there was error during nested ficlExec(), we may no longer have
144      * valid environment to return.  Throw all exceptions from here.
145      */
146     if (result != 0)
147         vmThrow(vm, result);
148     /* This is going to be thrown!!! */
149     stackPushINT(vm->pStack,result);
150 }
151
152 /*
153  * Replace a word definition (a builtin command) with another
154  * one that:
155  *
156  *        - Throw error results instead of returning them on the stack
157  *        - Pass a flag indicating whether the word was compiled or is
158  *          being interpreted.
159  *
160  * There is one major problem with builtins that cannot be overcome
161  * in anyway, except by outlawing it. We want builtins to behave
162  * differently depending on whether they have been compiled or they
163  * are being interpreted. Notice that this is *not* the interpreter's
164  * current state. For example:
165  *
166  * : example ls ; immediate
167  * : problem example ;          \ "ls" gets executed while compiling
168  * example                      \ "ls" gets executed while interpreting
169  *
170  * Notice that, though the current state is different in the two
171  * invocations of "example", in both cases "ls" has been
172  * *compiled in*, which is what we really want.
173  *
174  * The problem arises when you tick the builtin. For example:
175  *
176  * : example-1 ['] ls postpone literal ; immediate
177  * : example-2 example-1 execute ; immediate
178  * : problem example-2 ;
179  * example-2
180  *
181  * We have no way, when we get EXECUTEd, of knowing what our behavior
182  * should be. Thus, our only alternative is to "outlaw" this. See RFI
183  * 0007, and ANS Forth Standard's appendix D, item 6.7 for a related
184  * problem, concerning compile semantics.
185  *
186  * The problem is compounded by the fact that "' builtin CATCH" is valid
187  * and desirable. The only solution is to create an intermediary word.
188  * For example:
189  *
190  * : my-ls ls ;
191  * : example ['] my-ls catch ;
192  *
193  * So, with the below implementation, here is a summary of the behavior
194  * of builtins:
195  *
196  * ls -l                                \ "interpret" behavior, ie,
197  *                                      \ takes parameters from TIB
198  * : ex-1 s" -l" 1 ls ;                 \ "compile" behavior, ie,
199  *                                      \ takes parameters from the stack
200  * : ex-2 ['] ls catch ; immediate      \ undefined behavior
201  * : ex-3 ['] ls catch ;                \ undefined behavior
202  * ex-2 ex-3                            \ "interpret" behavior,
203  *                                      \ catch works
204  * : ex-4 ex-2 ;                        \ "compile" behavior,
205  *                                      \ catch does not work
206  * : ex-5 ex-3 ; immediate              \ same as ex-2
207  * : ex-6 ex-3 ;                        \ same as ex-3
208  * : ex-7 ['] ex-1 catch ;              \ "compile" behavior,
209  *                                      \ catch works
210  * : ex-8 postpone ls ; immediate       \ same as ex-2
211  * : ex-9 postpone ls ;                 \ same as ex-3
212  *
213  * As the definition below is particularly tricky, and it's side effects
214  * must be well understood by those playing with it, I'll be heavy on
215  * the comments.
216  *
217  * (if you edit this definition, pay attention to trailing spaces after
218  *  each word -- I warned you! :-) )
219  */
220 #define BUILTIN_CONSTRUCTOR \
221 ": builtin: "           \
222   ">in @ "              /* save the tib index pointer */ \
223   "' "                  /* get next word's xt */ \
224   "swap >in ! "         /* point again to next word */ \
225   "create "             /* create a new definition of the next word */ \
226   ", "                  /* save previous definition's xt */ \
227   "immediate "          /* make the new definition an immediate word */ \
228                         \
229   "does> "              /* Now, the *new* definition will: */ \
230   "state @ if "         /* if in compiling state: */ \
231     "1 postpone literal "       /* pass 1 flag to indicate compile */ \
232     "@ compile, "               /* compile in previous definition */ \
233     "postpone throw "           /* throw stack-returned result */ \
234   "else "               /* if in interpreting state: */ \
235     "0 swap "                   /* pass 0 flag to indicate interpret */ \
236     "@ execute "                /* call previous definition */ \
237     "throw "                    /* throw stack-returned result */ \
238   "then ; "
239
240 /*
241  * Initialise the Forth interpreter, create all our commands as words.
242  */
243 void
244 bf_init(void)
245 {
246     struct bootblk_command      **cmdp;
247     char create_buf[41];        /* 31 characters-long builtins */
248     int fd;
249
250     bf_sys = ficlInitSystem(BF_DICTSIZE);
251     bf_vm = ficlNewVM(bf_sys);
252
253     /* Put all private definitions in a "builtins" vocabulary */
254     ficlExec(bf_vm, "vocabulary builtins also builtins definitions");
255
256     /* Builtin constructor word  */
257     ficlExec(bf_vm, BUILTIN_CONSTRUCTOR);
258
259     /* make all commands appear as Forth words */
260     SET_FOREACH(cmdp, Xcommand_set) {
261         ficlBuild(bf_sys, (char *)(*cmdp)->c_name, bf_command, FW_DEFAULT);
262         ficlExec(bf_vm, "forth definitions builtins");
263         sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);
264         ficlExec(bf_vm, create_buf);
265         ficlExec(bf_vm, "builtins definitions");
266     }
267     ficlExec(bf_vm, "only forth definitions");
268
269     /* Export some version numbers so that code can detect the loader/host version */
270     ficlSetEnv(bf_sys, "FreeBSD_version", __FreeBSD_version);
271     ficlSetEnv(bf_sys, "loader_version", 
272                (bootprog_rev[0] - '0') * 10 + (bootprog_rev[2] - '0'));
273
274     /* try to load and run init file if present */
275     if ((fd = open("/boot/boot.4th", O_RDONLY)) != -1) {
276         (void)ficlExecFD(bf_vm, fd);
277         close(fd);
278     }
279
280     /* Do this last, so /boot/boot.4th can change it */
281     pInterp = ficlLookup(bf_sys, "interpret");
282 }
283
284 /*
285  * Feed a line of user input to the Forth interpreter
286  */
287 int
288 bf_run(char *line)
289 {
290     int         result;
291
292     result = ficlExec(bf_vm, line);
293
294     DEBUG("ficlExec '%s' = %d", line, result);
295     switch (result) {
296     case VM_OUTOFTEXT:
297     case VM_ABORTQ:
298     case VM_QUIT:
299     case VM_ERREXIT:
300         break;
301     case VM_USEREXIT:
302         printf("No where to leave to!\n");
303         break;
304     case VM_ABORT:
305         printf("Aborted!\n");
306         break;
307     case BF_PARSE:
308         printf("Parse error!\n");
309         break;
310     default:
311         /* Hopefully, all other codes filled this buffer */
312         printf("%s\n", command_errmsg);
313     }
314     
315     if (result == VM_USEREXIT)
316         panic("interpreter exit");
317     setenv("interpret", bf_vm->state ? "" : "OK", 1);
318
319     return result;
320 }