/*-1* Copyright (c) 1998 Michael Smith <[email protected]>2* All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7* 1. Redistributions of source code must retain the above copyright8* notice, this list of conditions and the following disclaimer.9* 2. Redistributions in binary form must reproduce the above copyright10* notice, this list of conditions and the following disclaimer in the11* documentation and/or other materials provided with the distribution.12*13* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND14* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE15* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE16* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE17* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL18* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS19* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)20* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT21* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY22* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF23* SUCH DAMAGE.24*/2526#include <sys/param.h> /* to pick up __FreeBSD_version */27#include <string.h>28#include <stand.h>29#include "bootstrap.h"30#include "ficl.h"3132INTERP_DEFINE("4th");3334/* #define BFORTH_DEBUG */3536#ifdef BFORTH_DEBUG37#define DPRINTF(fmt, args...) printf("%s: " fmt "\n" , __func__ , ## args)38#else39#define DPRINTF(fmt, args...) ((void)0)40#endif4142/*43* Eventually, all builtin commands throw codes must be defined44* elsewhere, possibly bootstrap.h. For now, just this code, used45* just in this file, it is getting defined.46*/47#define BF_PARSE 1004849/*50* FreeBSD loader default dictionary cells51*/52#ifndef BF_DICTSIZE53#define BF_DICTSIZE 1000054#endif5556/*57* BootForth Interface to Ficl Forth interpreter.58*/5960FICL_SYSTEM *bf_sys;61FICL_VM *bf_vm;6263/*64* Shim for taking commands from BF and passing them out to 'standard'65* argv/argc command functions.66*/67static void68bf_command(FICL_VM *vm)69{70char *name, *line, *tail, *cp;71size_t len;72struct bootblk_command **cmdp;73bootblk_cmd_t *cmd;74int nstrings, i;75int argc, result;76char **argv;7778/* Get the name of the current word */79name = vm->runningWord->name;8081/* Find our command structure */82cmd = NULL;83SET_FOREACH(cmdp, Xcommand_set) {84if (((*cmdp)->c_name != NULL) && !strcmp(name, (*cmdp)->c_name))85cmd = (*cmdp)->c_fn;86}87if (cmd == NULL)88panic("callout for unknown command '%s'", name);8990/* Check whether we have been compiled or are being interpreted */91if (stackPopINT(vm->pStack)) {92/*93* Get parameters from stack, in the format:94* an un ... a2 u2 a1 u1 n --95* Where n is the number of strings, a/u are pairs of96* address/size for strings, and they will be concatenated97* in LIFO order.98*/99nstrings = stackPopINT(vm->pStack);100for (i = 0, len = 0; i < nstrings; i++)101len += stackFetch(vm->pStack, i * 2).i + 1;102line = malloc(strlen(name) + len + 1);103strcpy(line, name);104105if (nstrings)106for (i = 0; i < nstrings; i++) {107len = stackPopINT(vm->pStack);108cp = stackPopPtr(vm->pStack);109strcat(line, " ");110strncat(line, cp, len);111}112} else {113/* Get remainder of invocation */114tail = vmGetInBuf(vm);115for (cp = tail, len = 0; cp != vm->tib.end && *cp != 0 && *cp != '\n'; cp++, len++)116;117118line = malloc(strlen(name) + len + 2);119strcpy(line, name);120if (len > 0) {121strcat(line, " ");122strncat(line, tail, len);123vmUpdateTib(vm, tail + len);124}125}126DPRINTF("cmd '%s'", line);127128command_errmsg = command_errbuf;129command_errbuf[0] = 0;130if (!parse(&argc, &argv, line)) {131result = (cmd)(argc, argv);132free(argv);133} else {134result=BF_PARSE;135}136137switch (result) {138case CMD_CRIT:139printf("%s\n", command_errmsg);140command_errmsg = NULL;141break;142case CMD_FATAL:143panic("%s", command_errmsg);144}145146free(line);147/*148* If there was error during nested ficlExec(), we may no longer have149* valid environment to return. Throw all exceptions from here.150*/151if (result != CMD_OK)152vmThrow(vm, result);153154/* This is going to be thrown!!! */155stackPushINT(vm->pStack,result);156}157158/*159* Replace a word definition (a builtin command) with another160* one that:161*162* - Throw error results instead of returning them on the stack163* - Pass a flag indicating whether the word was compiled or is164* being interpreted.165*166* There is one major problem with builtins that cannot be overcome167* in anyway, except by outlawing it. We want builtins to behave168* differently depending on whether they have been compiled or they169* are being interpreted. Notice that this is *not* the interpreter's170* current state. For example:171*172* : example ls ; immediate173* : problem example ; \ "ls" gets executed while compiling174* example \ "ls" gets executed while interpreting175*176* Notice that, though the current state is different in the two177* invocations of "example", in both cases "ls" has been178* *compiled in*, which is what we really want.179*180* The problem arises when you tick the builtin. For example:181*182* : example-1 ['] ls postpone literal ; immediate183* : example-2 example-1 execute ; immediate184* : problem example-2 ;185* example-2186*187* We have no way, when we get EXECUTEd, of knowing what our behavior188* should be. Thus, our only alternative is to "outlaw" this. See RFI189* 0007, and ANS Forth Standard's appendix D, item 6.7 for a related190* problem, concerning compile semantics.191*192* The problem is compounded by the fact that "' builtin CATCH" is valid193* and desirable. The only solution is to create an intermediary word.194* For example:195*196* : my-ls ls ;197* : example ['] my-ls catch ;198*199* So, with the below implementation, here is a summary of the behavior200* of builtins:201*202* ls -l \ "interpret" behavior, ie,203* \ takes parameters from TIB204* : ex-1 s" -l" 1 ls ; \ "compile" behavior, ie,205* \ takes parameters from the stack206* : ex-2 ['] ls catch ; immediate \ undefined behavior207* : ex-3 ['] ls catch ; \ undefined behavior208* ex-2 ex-3 \ "interpret" behavior,209* \ catch works210* : ex-4 ex-2 ; \ "compile" behavior,211* \ catch does not work212* : ex-5 ex-3 ; immediate \ same as ex-2213* : ex-6 ex-3 ; \ same as ex-3214* : ex-7 ['] ex-1 catch ; \ "compile" behavior,215* \ catch works216* : ex-8 postpone ls ; immediate \ same as ex-2217* : ex-9 postpone ls ; \ same as ex-3218*219* As the definition below is particularly tricky, and it's side effects220* must be well understood by those playing with it, I'll be heavy on221* the comments.222*223* (if you edit this definition, pay attention to trailing spaces after224* each word -- I warned you! :-) )225*/226#define BUILTIN_CONSTRUCTOR \227": builtin: " \228">in @ " /* save the tib index pointer */ \229"' " /* get next word's xt */ \230"swap >in ! " /* point again to next word */ \231"create " /* create a new definition of the next word */ \232", " /* save previous definition's xt */ \233"immediate " /* make the new definition an immediate word */ \234\235"does> " /* Now, the *new* definition will: */ \236"state @ if " /* if in compiling state: */ \237"1 postpone literal " /* pass 1 flag to indicate compile */ \238"@ compile, " /* compile in previous definition */ \239"postpone throw " /* throw stack-returned result */ \240"else " /* if in interpreting state: */ \241"0 swap " /* pass 0 flag to indicate interpret */ \242"@ execute " /* call previous definition */ \243"throw " /* throw stack-returned result */ \244"then ; "245246/*247* Initialise the Forth interpreter, create all our commands as words.248*/249void250bf_init(void)251{252struct bootblk_command **cmdp;253char create_buf[41]; /* 31 characters-long builtins */254int fd;255256bf_sys = ficlInitSystem(BF_DICTSIZE);257bf_vm = ficlNewVM(bf_sys);258259/* Put all private definitions in a "builtins" vocabulary */260ficlExec(bf_vm, "vocabulary builtins also builtins definitions");261262/* Builtin constructor word */263ficlExec(bf_vm, BUILTIN_CONSTRUCTOR);264265/* make all commands appear as Forth words */266SET_FOREACH(cmdp, Xcommand_set) {267ficlBuild(bf_sys, (char *)(*cmdp)->c_name, bf_command, FW_DEFAULT);268ficlExec(bf_vm, "forth definitions builtins");269sprintf(create_buf, "builtin: %s", (*cmdp)->c_name);270ficlExec(bf_vm, create_buf);271ficlExec(bf_vm, "builtins definitions");272}273ficlExec(bf_vm, "only forth definitions");274275/* Export some version numbers so that code can detect the loader/host version */276ficlSetEnv(bf_sys, "FreeBSD_version", __FreeBSD_version);277ficlSetEnv(bf_sys, "loader_version", bootprog_rev);278279/* try to load and run init file if present */280if ((fd = open("/boot/boot.4th", O_RDONLY)) != -1) {281#ifdef LOADER_VERIEXEC282if (verify_file(fd, "/boot/boot.4th", 0, VE_GUESS, __func__) < 0) {283close(fd);284return;285}286#endif287(void)ficlExecFD(bf_vm, fd);288close(fd);289}290}291292/*293* Feed a line of user input to the Forth interpreter294*/295static int296bf_run(const char *line)297{298int result;299300/*301* ficl would require extensive changes to accept a const char *302* interface. Instead, cast it away here and hope for the best.303* We know at the present time the caller for us in the boot304* forth loader can tolerate the string being modified because305* the string is passed in here and then not touched again.306*/307result = ficlExec(bf_vm, __DECONST(char *, line));308309DPRINTF("ficlExec '%s' = %d", line, result);310switch (result) {311case VM_OUTOFTEXT:312case VM_ABORTQ:313case VM_QUIT:314case VM_ERREXIT:315break;316case VM_USEREXIT:317printf("No where to leave to!\n");318break;319case VM_ABORT:320printf("Aborted!\n");321break;322case BF_PARSE:323printf("Parse error!\n");324break;325default:326if (command_errmsg != NULL) {327printf("%s\n", command_errmsg);328command_errmsg = NULL;329}330}331332if (result == VM_USEREXIT)333panic("interpreter exit");334setenv("interpret", bf_vm->state ? "" : "OK", 1);335336return (result);337}338339static bool preinit_run = false;340341void342interp_preinit(void)343{344if (preinit_run)345return;346setenv("script.lang", "forth", 1);347bf_init();348preinit_run = true;349}350351void352interp_init(void)353{354/* Read our default configuration. */355interp_include("/boot/loader.rc");356}357358int359interp_run(const char *input)360{361362bf_vm->sourceID.i = 0;363return bf_run(input);364}365366/*367* Header prepended to each line. The text immediately follows the header.368* We try to make this short in order to save memory -- the loader has369* limited memory available, and some of the forth files are very long.370*/371struct includeline372{373struct includeline *next;374char text[0];375};376377int378interp_include(const char *filename)379{380struct includeline *script, *se, *sp;381char input[256]; /* big enough? */382int res;383char *cp;384int prevsrcid, fd, line;385386if (((fd = open(filename, O_RDONLY)) == -1)) {387snprintf(command_errbuf, sizeof(command_errbuf),388"can't open '%s': %s", filename, strerror(errno));389return(CMD_ERROR);390}391392#ifdef LOADER_VERIEXEC393if (verify_file(fd, filename, 0, VE_GUESS, __func__) < 0) {394close(fd);395sprintf(command_errbuf,"can't verify '%s'", filename);396return(CMD_ERROR);397}398#endif399/*400* Read the script into memory.401*/402script = se = NULL;403line = 0;404405while (fgetstr(input, sizeof(input), fd) >= 0) {406line++;407cp = input;408/* Allocate script line structure and copy line, flags */409if (*cp == '\0')410continue; /* ignore empty line, save memory */411sp = malloc(sizeof(struct includeline) + strlen(cp) + 1);412/* On malloc failure (it happens!), free as much as possible and exit */413if (sp == NULL) {414while (script != NULL) {415se = script;416script = script->next;417free(se);418}419snprintf(command_errbuf, sizeof(command_errbuf),420"file '%s' line %d: memory allocation failure - aborting",421filename, line);422close(fd);423return (CMD_ERROR);424}425strcpy(sp->text, cp);426sp->next = NULL;427428if (script == NULL) {429script = sp;430} else {431se->next = sp;432}433se = sp;434}435close(fd);436437/*438* Execute the script439*/440prevsrcid = bf_vm->sourceID.i;441bf_vm->sourceID.i = fd;442res = CMD_OK;443for (sp = script; sp != NULL; sp = sp->next) {444res = bf_run(sp->text);445if (res != VM_OUTOFTEXT) {446snprintf(command_errbuf, sizeof(command_errbuf),447"Error while including %s, in the line:\n%s",448filename, sp->text);449res = CMD_ERROR;450break;451} else452res = CMD_OK;453}454bf_vm->sourceID.i = prevsrcid;455456while (script != NULL) {457se = script;458script = script->next;459free(se);460}461return(res);462}463464465