Annotation of gforth/main.c, revision 1.48

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.47      anton      43: /* Define FUZZ for better image positioning */
                     44: #define FUZZ 0x4000
                     45: 
1.10      anton      46: #ifndef DEFAULTPATH
1.16      pazsan     47: #  define DEFAULTPATH "/usr/local/lib/gforth:."
1.10      anton      48: #endif
                     49: 
1.1       anton      50: #ifdef DIRECT_THREADED
1.16      pazsan     51: #  define CA(n)        (symbols[(n)])
1.1       anton      52: #else
1.21      pazsan     53: #  define CA(n)        ((Cell)(symbols+(n)))
1.1       anton      54: #endif
                     55: 
1.23      pazsan     56: #define maxaligned(n)  (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
1.10      anton      57: 
1.21      pazsan     58: static Cell dictsize=0;
                     59: static Cell dsize=0;
                     60: static Cell rsize=0;
                     61: static Cell fsize=0;
                     62: static Cell lsize=0;
1.48    ! anton      63: static int image_offset=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.48    ! anton     228:   image=malloc(((wholesize>imagesize?wholesize:imagesize)+image_offset)
1.46      pazsan    229: #ifdef FUZZ
1.42      anton     230:               +FUZZ
                    231: #endif
1.48    ! anton     232:               )+image_offset;
1.35      anton     233:   /*image = maxaligned(image);*/
1.42      anton     234:   /* memset(image,0,wholesize); */
                    235: 
1.46      pazsan    236: #ifdef FUZZ
1.42      anton     237:   if(header.base==0) image += FUZZ/2;
                    238:   else if((UCell)(header.base - (Cell)image + preamblesize) < FUZZ)
                    239:     image = header.base - preamblesize;
                    240: #endif  
1.35      anton     241:   rewind(imagefile);  /* fseek(imagefile,0L,SEEK_SET); */
                    242:   fread(image,1,imagesize,imagefile);
1.16      pazsan    243:   fclose(imagefile);
1.35      anton     244:   imp=image+preamblesize;
1.16      pazsan    245:   
1.35      anton     246:   if(header.base==0) {
                    247:     relocate((Cell *)imp,imp+header.image_size,header.image_size,symbols);
1.48    ! anton     248: #if 0
        !           249:     { /* let's see what the relocator did */
        !           250:       FILE *snapshot=fopen("snapshot.fi","wb");
        !           251:       fwrite(image,1,imagesize,snapshot);
        !           252:       fclose(snapshot);
        !           253:     }
        !           254: #endif
1.16      pazsan    255:   }
1.35      anton     256:   else if(header.base!=imp) {
1.36      anton     257:     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     258:            progname, (unsigned long)header.base, (unsigned long)imp);
                    259:     exit(1);
1.48    ! anton     260:   }
        !           261:   if (header.checksum==0)
        !           262:     ((ImageHeader *)imp)->checksum=check_sum;
        !           263:   else if (header.checksum != check_sum) {
1.36      anton     264:     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     265:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
1.16      pazsan    266:     exit(1);
                    267:   }
1.1       anton     268: 
1.35      anton     269:   ((ImageHeader *)imp)->dict_size=dictsize;
                    270:   ((ImageHeader *)imp)->data_stack_size=dsize;
                    271:   ((ImageHeader *)imp)->return_stack_size=rsize;
                    272:   ((ImageHeader *)imp)->fp_stack_size=fsize;
                    273:   ((ImageHeader *)imp)->locals_stack_size=lsize;
                    274: 
1.38      anton     275:   CACHE_FLUSH(imp, header.image_size);
1.35      anton     276: 
                    277:   return imp;
1.1       anton     278: }
                    279: 
1.35      anton     280: int go_forth(Address image, int stack, Cell *entries)
1.1       anton     281: {
1.35      anton     282:   Cell *sp=(Cell*)(image+dictsize+dsize);
1.15      anton     283:   Address lp=(Address)((void *)sp+lsize);
                    284:   Float *fp=(Float *)((void *)lp+fsize);
                    285:   Cell *rp=(Cell*)((void *)fp+rsize);
1.35      anton     286:   Xt *ip=(Xt *)(((ImageHeader *)image)->boot_entry);
1.15      anton     287:   int throw_code;
                    288:   
                    289:   for(;stack>0;stack--)
                    290:     *--sp=entries[stack-1];
1.39      pazsan    291: 
1.44      pazsan    292: #if !defined(MSDOS) && !defined(_WIN32) && !defined(__EMX__)
1.33      anton     293:   get_winsize();
1.39      pazsan    294: #endif
                    295:    
1.15      anton     296:   install_signal_handlers(); /* right place? */
                    297:   
                    298:   if ((throw_code=setjmp(throw_jmp_buf))) {
                    299:     static Cell signal_data_stack[8];
                    300:     static Cell signal_return_stack[8];
                    301:     static Float signal_fp_stack[1];
                    302:     
                    303:     signal_data_stack[7]=throw_code;
                    304:     
1.35      anton     305:     return((int)engine(((ImageHeader *)image)->throw_entry,signal_data_stack+7,
1.15      anton     306:                       signal_return_stack+8,signal_fp_stack,0));
                    307:   }
1.35      anton     308: 
1.15      anton     309:   return((int)engine(ip,sp,rp,fp,lp));
1.1       anton     310: }
                    311: 
1.10      anton     312: int convsize(char *s, int elemsize)
                    313: /* converts s of the format #+u (e.g. 25k) into the number of bytes.
                    314:    the unit u can be one of bekM, where e stands for the element
                    315:    size. default is e */
                    316: {
                    317:   char *endp;
                    318:   int n,m;
                    319: 
                    320:   m = elemsize;
                    321:   n = strtoul(s,&endp,0);
                    322:   if (endp!=NULL) {
                    323:     if (strcmp(endp,"b")==0)
                    324:       m=1;
                    325:     else if (strcmp(endp,"k")==0)
                    326:       m=1024;
                    327:     else if (strcmp(endp,"M")==0)
                    328:       m=1024*1024;
1.31      anton     329:     else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                    330:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
1.10      anton     331:       exit(1);
                    332:     }
                    333:   }
                    334:   return n*m;
                    335: }
                    336: 
1.1       anton     337: int main(int argc, char **argv, char **env)
                    338: {
1.43      anton     339:   char *path, *path1;
1.16      pazsan    340:   char *imagename="gforth.fi";
                    341:   FILE *image_file;
                    342:   int c, retvalue;
1.10      anton     343:          
1.14      anton     344: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
1.30      anton     345:   /* turn on alignment checks on the 486.
                    346:    * on the 386 this should have no effect. */
                    347:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
                    348:   /* this is unusable with Linux' libc.4.6.27, because this library is
                    349:      not alignment-clean; we would have to replace some library
                    350:      functions (e.g., memcpy) to make it work */
1.6       anton     351: #endif
1.2       pazsan    352: 
1.16      pazsan    353:   progname = argv[0];
1.44      pazsan    354:   if ((path1=getenv("GFORTHPATH"))==NULL)
                    355:     path1 = DEFAULTPATH;
                    356:   
1.16      pazsan    357:   opterr=0;
                    358:   while (1) {
                    359:     int option_index=0;
                    360:     static struct option opts[] = {
                    361:       {"image-file", required_argument, NULL, 'i'},
                    362:       {"dictionary-size", required_argument, NULL, 'm'},
                    363:       {"data-stack-size", required_argument, NULL, 'd'},
                    364:       {"return-stack-size", required_argument, NULL, 'r'},
                    365:       {"fp-stack-size", required_argument, NULL, 'f'},
                    366:       {"locals-stack-size", required_argument, NULL, 'l'},
                    367:       {"path", required_argument, NULL, 'p'},
1.45      anton     368:       {"version", no_argument, NULL, 'v'},
                    369:       {"help", no_argument, NULL, 'h'},
1.48    ! anton     370:       /* put something != 0 into image_offset; it should be a
        !           371:          not-too-large max-aligned number */
        !           372:       {"offset-image", no_argument, &image_offset, 28*sizeof(Cell)},
1.16      pazsan    373:       {0,0,0,0}
                    374:       /* no-init-file, no-rc? */
                    375:     };
1.44      pazsan    376:     
1.45      anton     377:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vh", opts, &option_index);
1.44      pazsan    378:     
1.16      pazsan    379:     if (c==EOF)
                    380:       break;
                    381:     if (c=='?') {
                    382:       optind--;
                    383:       break;
                    384:     }
                    385:     switch (c) {
                    386:     case 'i': imagename = optarg; break;
                    387:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                    388:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                    389:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                    390:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                    391:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.44      pazsan    392:     case 'p': path1 = optarg; break;
1.45      anton     393:     case 'v': fprintf(stderr, "gforth %s\n", gforth_version); exit(0);
                    394:     case 'h': 
                    395:       fprintf(stderr, "Usage: %s [engine options] [image arguments]\n\
                    396: Engine Options:\n\
                    397:  -d SIZE, --data-stack-size=SIZE    Specify data stack size\n\
                    398:  -f SIZE, --fp-stack-size=SIZE     Specify floating point stack size\n\
                    399:  -h, --help                        Print this message and exit\n\
                    400:  -i FILE, --image-file=FILE        Use image FILE instead of `gforth.fi'\n\
                    401:  -l SIZE, --locals-stack-size=SIZE  Specify locals stack size\n\
                    402:  -m SIZE, --dictionary-size=SIZE    Specify Forth dictionary size\n\
1.48    ! anton     403:  --offset-image                            load image at a different position\n\
1.45      anton     404:  -p PATH, --path=PATH              Search path for finding image and sources\n\
                    405:  -r SIZE, --return-stack-size=SIZE  Specify return stack size\n\
                    406:  -v, --version                     Print version and exit\n\
                    407: SIZE arguments consists of an integer followed by a unit. The unit can be\n\
                    408:   `b' (bytes), `e' (elements), `k' (kilobytes), or `M' (Megabytes).\n\
                    409: \n\
                    410: Arguments of default image `gforth.fi':\n\
                    411:  FILE                              load FILE (with `require')\n\
                    412:  -e STRING, --evaluate STRING       interpret STRING (with `EVALUATE')\n",
                    413:              argv[0]); exit(0);
1.16      pazsan    414:     }
                    415:   }
1.44      pazsan    416:   path=path1;
                    417:   
1.29      pazsan    418:   if(strchr(imagename, '/')==NULL)
                    419:     {
                    420:       do {
1.43      anton     421:        char *pend=strchr(path, PATHSEP);
1.29      pazsan    422:        if (pend==NULL)
                    423:          pend=path+strlen(path);
                    424:        if (strlen(path)==0) {
                    425:          fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.47      anton     426:                  progname, imagename, path1);
1.29      pazsan    427:          exit(1);
                    428:        }
                    429:        {
                    430:          int dirlen=pend-path;
                    431:          char fullfilename[dirlen+strlen(imagename)+2];
                    432:          memcpy(fullfilename, path, dirlen);
                    433:          if (fullfilename[dirlen-1]!='/')
                    434:            fullfilename[dirlen++]='/';
                    435:          strcpy(fullfilename+dirlen,imagename);
                    436:          image_file=fopen(fullfilename,"rb");
                    437:        }
1.43      anton     438:        path=pend+(*pend==PATHSEP);
1.29      pazsan    439:       } while (image_file==NULL);
1.16      pazsan    440:     }
1.29      pazsan    441:   else
1.16      pazsan    442:     {
1.29      pazsan    443:       image_file=fopen(imagename,"rb");
1.16      pazsan    444:     }
1.29      pazsan    445: 
1.16      pazsan    446:   {
1.45      anton     447:     char path2[strlen(path1)+1];
1.43      anton     448:     char *p1, *p2;
1.16      pazsan    449:     Cell environ[]= {
                    450:       (Cell)argc-(optind-1),
                    451:       (Cell)(argv+(optind-1)),
1.42      anton     452:       (Cell)strlen(path1),
1.43      anton     453:       (Cell)path2};
1.16      pazsan    454:     argv[optind-1] = progname;
                    455:     /*
                    456:        for (i=0; i<environ[0]; i++)
                    457:        printf("%s\n", ((char **)(environ[1]))[i]);
                    458:        */
1.42      anton     459:     /* make path OS-independent by replacing path separators with NUL */
1.43      anton     460:     for (p1=path1, p2=path2; *p1!='\0'; p1++, p2++)
                    461:       if (*p1==PATHSEP)
                    462:        *p2 = '\0';
                    463:       else
                    464:        *p2 = *p1;
                    465:     *p2='\0';
1.42      anton     466:     retvalue=go_forth(loader(image_file, imagename),4,environ);
1.16      pazsan    467:     deprep_terminal();
                    468:     exit(retvalue);
                    469:   }
1.1       anton     470: }

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