Annotation of gforth/main.c, revision 1.45

1.30      anton       1: /* command line interpretation, image loading etc. for Gforth
                      2: 
                      3: 
                      4:   Copyright (C) 1995 Free Software Foundation, Inc.
                      5: 
                      6:   This file is part of Gforth.
                      7: 
                      8:   Gforth is free software; you can redistribute it and/or
                      9:   modify it under the terms of the GNU General Public License
                     10:   as published by the Free Software Foundation; either version 2
                     11:   of the License, or (at your option) any later version.
                     12: 
                     13:   This program is distributed in the hope that it will be useful,
                     14:   but WITHOUT ANY WARRANTY; without even the implied warranty of
                     15:   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     16:   GNU General Public License for more details.
                     17: 
                     18:   You should have received a copy of the GNU General Public License
                     19:   along with this program; if not, write to the Free Software
                     20:   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
1.1       anton      21: */
                     22: 
1.32      anton      23: #include "config.h"
1.35      anton      24: #include <errno.h>
1.1       anton      25: #include <ctype.h>
                     26: #include <stdio.h>
                     27: #include <string.h>
                     28: #include <math.h>
                     29: #include <sys/types.h>
                     30: #include <sys/stat.h>
                     31: #include <fcntl.h>
                     32: #include <assert.h>
                     33: #include <stdlib.h>
                     34: #include "forth.h"
1.5       pazsan     35: #include "io.h"
1.20      anton      36: #include "getopt.h"
1.45    ! anton      37: #include "version.h"
1.2       pazsan     38: 
1.22      pazsan     39: #ifdef MSDOS
                     40: jmp_buf throw_jmp_buf;
                     41: #endif
                     42: 
1.42      anton      43: #ifndef FUZZ
                     44: #  define FUZZ 0x4000
                     45: #endif
                     46: 
1.10      anton      47: #ifndef DEFAULTPATH
1.16      pazsan     48: #  define DEFAULTPATH "/usr/local/lib/gforth:."
1.10      anton      49: #endif
                     50: 
1.1       anton      51: #ifdef DIRECT_THREADED
1.16      pazsan     52: #  define CA(n)        (symbols[(n)])
1.1       anton      53: #else
1.21      pazsan     54: #  define CA(n)        ((Cell)(symbols+(n)))
1.1       anton      55: #endif
                     56: 
1.23      pazsan     57: #define maxaligned(n)  (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
1.10      anton      58: 
1.21      pazsan     59: static Cell dictsize=0;
                     60: static Cell dsize=0;
                     61: static Cell rsize=0;
                     62: static Cell fsize=0;
                     63: static Cell lsize=0;
1.10      anton      64: char *progname;
                     65: 
1.1       anton      66: /* image file format:
1.35      anton      67:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.2.0 -i\n")
                     68:  *   padding to a multiple of 8
1.36      anton      69:  *   magic: "Gforth1x" means format 0.2,
1.35      anton      70:  *              where x is even for big endian and odd for little endian
                     71:  *              and x & ~1 is the size of the cell in bytes.
                     72:  *  padding to max alignment (no padding necessary on current machines)
                     73:  *  ImageHeader structure (see below)
                     74:  *  data (size in ImageHeader.image_size)
                     75:  *  tags ((if relocatable, 1 bit/data cell)
1.1       anton      76:  *
1.35      anton      77:  * tag==1 means that the corresponding word is an address;
1.1       anton      78:  * If the word is >=0, the address is within the image;
                     79:  * addresses within the image are given relative to the start of the image.
1.35      anton      80:  * If the word =-1 (CF_NIL), the address is NIL,
                     81:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
                     82:  * If the word =CF(DODOES), it's a DOES> CFA
                     83:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
                     84:  *                                     possibly containing a jump to dodoes)
                     85:  * If the word is <CF(DOESJUMP), it's a primitive
1.1       anton      86:  */
                     87: 
1.35      anton      88: typedef struct {
                     89:   Address base;                /* base address of image (0 if relocatable) */
                     90:   UCell checksum;      /* checksum of ca's to protect against some
                     91:                           incompatible binary/executable combinations
                     92:                           (0 if relocatable) */
                     93:   UCell image_size;    /* all sizes in bytes */
                     94:   UCell dict_size;
                     95:   UCell data_stack_size;
                     96:   UCell fp_stack_size;
                     97:   UCell return_stack_size;
                     98:   UCell locals_stack_size;
                     99:   Xt *boot_entry;      /* initial ip for booting (in BOOT) */
                    100:   Xt *throw_entry;     /* ip after signal (in THROW) */
                    101: } ImageHeader;
                    102: /* the image-header is created in main.fs */
                    103: 
1.10      anton     104: void relocate(Cell *image, char *bitstring, int size, Label symbols[])
1.1       anton     105: {
1.16      pazsan    106:   int i=0, j, k, steps=(size/sizeof(Cell))/8;
                    107:   char bits;
1.5       pazsan    108: /*   static char bits[8]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};*/
1.37      pazsan    109: 
                    110: /*  printf("relocating %x[%x]\n", image, size); */
1.5       pazsan    111:    
1.16      pazsan    112:   for(k=0; k<=steps; k++)
                    113:     for(j=0, bits=bitstring[k]; j<8; j++, i++, bits<<=1)
                    114:       if(bits & 0x80)
                    115:        if(image[i]<0)
                    116:          switch(image[i])
                    117:            {
                    118:            case CF_NIL      : image[i]=0; break;
                    119:            case CF(DOCOL)   :
                    120:            case CF(DOVAR)   :
                    121:            case CF(DOCON)   :
                    122:            case CF(DOUSER)  : 
1.24      pazsan    123:            case CF(DODEFER) : 
1.28      anton     124:            case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(image[i])]); break;
1.21      pazsan    125:            case CF(DODOES)  : MAKE_DOES_CF(image+i,image[i+1]+((Cell)image));
1.16      pazsan    126:              break;
                    127:            case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
1.37      pazsan    128:            default          :
                    129: /*           printf("Code field generation image[%x]:=CA(%x)\n",
                    130:                     i, CF(image[i]));
                    131: */           image[i]=(Cell)CA(CF(image[i]));
1.16      pazsan    132:            }
                    133:        else
                    134:          image[i]+=(Cell)image;
1.1       anton     135: }
                    136: 
1.35      anton     137: UCell checksum(Label symbols[])
                    138: {
                    139:   UCell r=0;
                    140:   Cell i;
                    141: 
                    142:   for (i=DOCOL; i<=DOESJUMP; i++) {
                    143:     r ^= (UCell)(symbols[i]);
                    144:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    145:   }
                    146: #ifdef DIRECT_THREADED
                    147:   /* we have to consider all the primitives */
                    148:   for (; symbols[i]!=(Label)0; i++) {
                    149:     r ^= (UCell)(symbols[i]);
                    150:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    151:   }
                    152: #else
                    153:   /* in indirect threaded code all primitives are accessed through the
                    154:      symbols table, so we just have to put the base address of symbols
                    155:      in the checksum */
                    156:   r ^= (UCell)symbols;
                    157: #endif
                    158:   return r;
                    159: }
                    160: 
1.39      pazsan    161: Address loader(FILE *imagefile, char* filename)
1.35      anton     162: /* returns the address of the image proper (after the preamble) */
1.10      anton     163: {
1.35      anton     164:   ImageHeader header;
                    165:   Address image;
                    166:   Address imp; /* image+preamble */
1.18      pazsan    167:   Char magic[8];
1.35      anton     168:   Cell wholesize;
                    169:   Cell imagesize; /* everything needed by the image */
                    170:   Cell preamblesize=0;
                    171:   Label *symbols=engine(0,0,0,0,0);
                    172:   UCell check_sum=checksum(symbols);
1.18      pazsan    173: 
1.35      anton     174:   static char* endianstring[]= { "big","little" };
1.25      pazsan    175: 
1.18      pazsan    176:   do
                    177:     {
                    178:       if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1.39      pazsan    179:        fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.2) image.\n",
                    180:                progname, filename);
1.18      pazsan    181:        exit(1);
                    182:       }
1.35      anton     183:       preamblesize+=8;
1.18      pazsan    184: #ifdef DEBUG
1.35      anton     185:       fprintf(stderr,"Magic found: %-8s\n",magic);
1.18      pazsan    186: #endif
                    187:     }
1.35      anton     188:   while(memcmp(magic,"Gforth1",7));
1.25      pazsan    189:   
1.35      anton     190:   if(magic[7] != sizeof(Cell) +
1.25      pazsan    191: #ifdef WORDS_BIGENDIAN
                    192:        '0'
                    193: #else
                    194:        '1'
                    195: #endif
1.35      anton     196:        )
                    197:     { fprintf(stderr,"This image is %d bit %s-endian, whereas the machine is %d bit %s-endian.\n", 
                    198:              ((magic[7]-'0')&~1)*8, endianstring[magic[7]&1],
                    199:              sizeof(Cell)*8, endianstring[
1.25      pazsan    200: #ifdef WORDS_BIGENDIAN
                    201:                      0
                    202: #else
                    203:                      1
                    204: #endif
                    205:                      ]);
                    206:       exit(-2);
                    207:     };
1.18      pazsan    208: 
1.35      anton     209:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1.16      pazsan    210:   if (dictsize==0)
1.35      anton     211:     dictsize = header.dict_size;
1.16      pazsan    212:   if (dsize==0)
1.35      anton     213:     dsize=header.data_stack_size;
1.16      pazsan    214:   if (rsize==0)
1.35      anton     215:     rsize=header.return_stack_size;
1.16      pazsan    216:   if (fsize==0)
1.35      anton     217:     fsize=header.fp_stack_size;
1.16      pazsan    218:   if (lsize==0)
1.35      anton     219:     lsize=header.locals_stack_size;
1.16      pazsan    220:   dictsize=maxaligned(dictsize);
                    221:   dsize=maxaligned(dsize);
                    222:   rsize=maxaligned(rsize);
                    223:   lsize=maxaligned(lsize);
                    224:   fsize=maxaligned(fsize);
                    225:   
1.35      anton     226:   wholesize = preamblesize+dictsize+dsize+rsize+fsize+lsize;
                    227:   imagesize = preamblesize+header.image_size+((header.image_size-1)/sizeof(Cell))/8+1;
1.42      anton     228:   image=malloc((wholesize>imagesize?wholesize:imagesize)
                    229: #ifndef __unix__
                    230:               +FUZZ
                    231: #endif
                    232:               );
1.35      anton     233:   /*image = maxaligned(image);*/
1.42      anton     234:   /* memset(image,0,wholesize); */
                    235: 
                    236: #ifndef __unix__
1.44      pazsan    237: #warning Non-Unix machine, trying to help relocate with FUZZ
1.42      anton     238:   if(header.base==0) image += FUZZ/2;
                    239:   else if((UCell)(header.base - (Cell)image + preamblesize) < FUZZ)
                    240:     image = header.base - preamblesize;
                    241: #endif  
1.35      anton     242:   rewind(imagefile);  /* fseek(imagefile,0L,SEEK_SET); */
                    243:   fread(image,1,imagesize,imagefile);
1.16      pazsan    244:   fclose(imagefile);
1.35      anton     245:   imp=image+preamblesize;
1.16      pazsan    246:   
1.35      anton     247:   if(header.base==0) {
                    248:     relocate((Cell *)imp,imp+header.image_size,header.image_size,symbols);
                    249:     ((ImageHeader *)imp)->checksum=check_sum;
1.16      pazsan    250:   }
1.35      anton     251:   else if(header.base!=imp) {
1.36      anton     252:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\nThe Gforth installer should look into the INSTALL file\n",
1.35      anton     253:            progname, (unsigned long)header.base, (unsigned long)imp);
                    254:     exit(1);
                    255:   } else if (header.checksum != check_sum) {
1.36      anton     256:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\nThe Gforth installer should look into the INSTALL file\n",
1.35      anton     257:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
1.16      pazsan    258:     exit(1);
                    259:   }
1.1       anton     260: 
1.35      anton     261:   ((ImageHeader *)imp)->dict_size=dictsize;
                    262:   ((ImageHeader *)imp)->data_stack_size=dsize;
                    263:   ((ImageHeader *)imp)->return_stack_size=rsize;
                    264:   ((ImageHeader *)imp)->fp_stack_size=fsize;
                    265:   ((ImageHeader *)imp)->locals_stack_size=lsize;
                    266: 
1.38      anton     267:   CACHE_FLUSH(imp, header.image_size);
1.35      anton     268: 
                    269:   return imp;
1.1       anton     270: }
                    271: 
1.35      anton     272: int go_forth(Address image, int stack, Cell *entries)
1.1       anton     273: {
1.35      anton     274:   Cell *sp=(Cell*)(image+dictsize+dsize);
1.15      anton     275:   Address lp=(Address)((void *)sp+lsize);
                    276:   Float *fp=(Float *)((void *)lp+fsize);
                    277:   Cell *rp=(Cell*)((void *)fp+rsize);
1.35      anton     278:   Xt *ip=(Xt *)(((ImageHeader *)image)->boot_entry);
1.15      anton     279:   int throw_code;
                    280:   
                    281:   for(;stack>0;stack--)
                    282:     *--sp=entries[stack-1];
1.39      pazsan    283: 
1.44      pazsan    284: #if !defined(MSDOS) && !defined(_WIN32) && !defined(__EMX__)
1.33      anton     285:   get_winsize();
1.39      pazsan    286: #endif
                    287:    
1.15      anton     288:   install_signal_handlers(); /* right place? */
                    289:   
                    290:   if ((throw_code=setjmp(throw_jmp_buf))) {
                    291:     static Cell signal_data_stack[8];
                    292:     static Cell signal_return_stack[8];
                    293:     static Float signal_fp_stack[1];
                    294:     
                    295:     signal_data_stack[7]=throw_code;
                    296:     
1.35      anton     297:     return((int)engine(((ImageHeader *)image)->throw_entry,signal_data_stack+7,
1.15      anton     298:                       signal_return_stack+8,signal_fp_stack,0));
                    299:   }
1.35      anton     300: 
1.15      anton     301:   return((int)engine(ip,sp,rp,fp,lp));
1.1       anton     302: }
                    303: 
1.10      anton     304: int convsize(char *s, int elemsize)
                    305: /* converts s of the format #+u (e.g. 25k) into the number of bytes.
                    306:    the unit u can be one of bekM, where e stands for the element
                    307:    size. default is e */
                    308: {
                    309:   char *endp;
                    310:   int n,m;
                    311: 
                    312:   m = elemsize;
                    313:   n = strtoul(s,&endp,0);
                    314:   if (endp!=NULL) {
                    315:     if (strcmp(endp,"b")==0)
                    316:       m=1;
                    317:     else if (strcmp(endp,"k")==0)
                    318:       m=1024;
                    319:     else if (strcmp(endp,"M")==0)
                    320:       m=1024*1024;
1.31      anton     321:     else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                    322:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
1.10      anton     323:       exit(1);
                    324:     }
                    325:   }
                    326:   return n*m;
                    327: }
                    328: 
1.1       anton     329: int main(int argc, char **argv, char **env)
                    330: {
1.43      anton     331:   char *path, *path1;
1.16      pazsan    332:   char *imagename="gforth.fi";
                    333:   FILE *image_file;
                    334:   int c, retvalue;
1.10      anton     335:          
1.14      anton     336: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
1.30      anton     337:   /* turn on alignment checks on the 486.
                    338:    * on the 386 this should have no effect. */
                    339:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
                    340:   /* this is unusable with Linux' libc.4.6.27, because this library is
                    341:      not alignment-clean; we would have to replace some library
                    342:      functions (e.g., memcpy) to make it work */
1.6       anton     343: #endif
1.2       pazsan    344: 
1.16      pazsan    345:   progname = argv[0];
1.44      pazsan    346:   if ((path1=getenv("GFORTHPATH"))==NULL)
                    347:     path1 = DEFAULTPATH;
                    348:   
1.16      pazsan    349:   opterr=0;
                    350:   while (1) {
                    351:     int option_index=0;
                    352:     static struct option opts[] = {
                    353:       {"image-file", required_argument, NULL, 'i'},
                    354:       {"dictionary-size", required_argument, NULL, 'm'},
                    355:       {"data-stack-size", required_argument, NULL, 'd'},
                    356:       {"return-stack-size", required_argument, NULL, 'r'},
                    357:       {"fp-stack-size", required_argument, NULL, 'f'},
                    358:       {"locals-stack-size", required_argument, NULL, 'l'},
                    359:       {"path", required_argument, NULL, 'p'},
1.45    ! anton     360:       {"version", no_argument, NULL, 'v'},
        !           361:       {"help", no_argument, NULL, 'h'},
1.16      pazsan    362:       {0,0,0,0}
                    363:       /* no-init-file, no-rc? */
                    364:     };
1.44      pazsan    365:     
1.45    ! anton     366:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vh", opts, &option_index);
1.44      pazsan    367:     
1.16      pazsan    368:     if (c==EOF)
                    369:       break;
                    370:     if (c=='?') {
                    371:       optind--;
                    372:       break;
                    373:     }
                    374:     switch (c) {
                    375:     case 'i': imagename = optarg; break;
                    376:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                    377:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                    378:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                    379:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                    380:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.44      pazsan    381:     case 'p': path1 = optarg; break;
1.45    ! anton     382:     case 'v': fprintf(stderr, "gforth %s\n", gforth_version); exit(0);
        !           383:     case 'h': 
        !           384:       fprintf(stderr, "Usage: %s [engine options] [image arguments]\n\
        !           385: Engine Options:\n\
        !           386:  -d SIZE, --data-stack-size=SIZE    Specify data stack size\n\
        !           387:  -f SIZE, --fp-stack-size=SIZE     Specify floating point stack size\n\
        !           388:  -h, --help                        Print this message and exit\n\
        !           389:  -i FILE, --image-file=FILE        Use image FILE instead of `gforth.fi'\n\
        !           390:  -l SIZE, --locals-stack-size=SIZE  Specify locals stack size\n\
        !           391:  -m SIZE, --dictionary-size=SIZE    Specify Forth dictionary size\n\
        !           392:  -p PATH, --path=PATH              Search path for finding image and sources\n\
        !           393:  -r SIZE, --return-stack-size=SIZE  Specify return stack size\n\
        !           394:  -v, --version                     Print version and exit\n\
        !           395: SIZE arguments consists of an integer followed by a unit. The unit can be\n\
        !           396:   `b' (bytes), `e' (elements), `k' (kilobytes), or `M' (Megabytes).\n\
        !           397: \n\
        !           398: Arguments of default image `gforth.fi':\n\
        !           399:  FILE                              load FILE (with `require')\n\
        !           400:  -e STRING, --evaluate STRING       interpret STRING (with `EVALUATE')\n",
        !           401:              argv[0]); exit(0);
1.16      pazsan    402:     }
                    403:   }
1.44      pazsan    404:   path=path1;
                    405:   
1.29      pazsan    406:   if(strchr(imagename, '/')==NULL)
                    407:     {
                    408:       do {
1.43      anton     409:        char *pend=strchr(path, PATHSEP);
1.29      pazsan    410:        if (pend==NULL)
                    411:          pend=path+strlen(path);
                    412:        if (strlen(path)==0) {
                    413:          fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.44      pazsan    414:                  progname, imagename, path);
1.29      pazsan    415:          exit(1);
                    416:        }
                    417:        {
                    418:          int dirlen=pend-path;
                    419:          char fullfilename[dirlen+strlen(imagename)+2];
                    420:          memcpy(fullfilename, path, dirlen);
                    421:          if (fullfilename[dirlen-1]!='/')
                    422:            fullfilename[dirlen++]='/';
                    423:          strcpy(fullfilename+dirlen,imagename);
                    424:          image_file=fopen(fullfilename,"rb");
                    425:        }
1.43      anton     426:        path=pend+(*pend==PATHSEP);
1.29      pazsan    427:       } while (image_file==NULL);
1.16      pazsan    428:     }
1.29      pazsan    429:   else
1.16      pazsan    430:     {
1.29      pazsan    431:       image_file=fopen(imagename,"rb");
1.16      pazsan    432:     }
1.29      pazsan    433: 
1.16      pazsan    434:   {
1.45    ! anton     435:     char path2[strlen(path1)+1];
1.43      anton     436:     char *p1, *p2;
1.16      pazsan    437:     Cell environ[]= {
                    438:       (Cell)argc-(optind-1),
                    439:       (Cell)(argv+(optind-1)),
1.42      anton     440:       (Cell)strlen(path1),
1.43      anton     441:       (Cell)path2};
1.16      pazsan    442:     argv[optind-1] = progname;
                    443:     /*
                    444:        for (i=0; i<environ[0]; i++)
                    445:        printf("%s\n", ((char **)(environ[1]))[i]);
                    446:        */
1.42      anton     447:     /* make path OS-independent by replacing path separators with NUL */
1.43      anton     448:     for (p1=path1, p2=path2; *p1!='\0'; p1++, p2++)
                    449:       if (*p1==PATHSEP)
                    450:        *p2 = '\0';
                    451:       else
                    452:        *p2 = *p1;
                    453:     *p2='\0';
1.42      anton     454:     retvalue=go_forth(loader(image_file, imagename),4,environ);
1.16      pazsan    455:     deprep_terminal();
                    456:     exit(retvalue);
                    457:   }
1.1       anton     458: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>