File:  [gforth] / gforth / Attic / main.c
Revision 1.51: download - view: text, annotated - select for diffs
Sat Jan 4 16:32:31 1997 UTC (27 years, 3 months ago) by anton
Branches: MAIN
CVS tags: HEAD
reformatted errore.fs to single-column format
updated definition of UNUSED
fixed some documentation typos
removed FUZZ

    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.
   21: */
   22: 
   23: #include "config.h"
   24: #include <errno.h>
   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: #if HAVE_SYS_MMAN_H
   35: #include <sys/mman.h>
   36: #endif
   37: #include "forth.h"
   38: #include "io.h"
   39: #include "getopt.h"
   40: #include "version.h"
   41: 
   42: #ifdef MSDOS
   43: jmp_buf throw_jmp_buf;
   44: #endif
   45: 
   46: #ifndef DEFAULTPATH
   47: #  define DEFAULTPATH "/usr/local/lib/gforth:."
   48: #endif
   49: 
   50: #ifdef DIRECT_THREADED
   51: #  define CA(n)	(symbols[(n)])
   52: #else
   53: #  define CA(n)	((Cell)(symbols+(n)))
   54: #endif
   55: 
   56: #define maxaligned(n)	(typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
   57: 
   58: static UCell dictsize=0;
   59: static UCell dsize=0;
   60: static UCell rsize=0;
   61: static UCell fsize=0;
   62: static UCell lsize=0;
   63: static int image_offset=0;
   64: static int clear_dictionary=0;
   65: static int debug=0;
   66: static size_t pagesize=0;
   67: char *progname;
   68: 
   69: /* image file format:
   70:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.2.0 -i\n")
   71:  *   padding to a multiple of 8
   72:  *   magic: "Gforth1x" means format 0.2,
   73:  *              where x is even for big endian and odd for little endian
   74:  *              and x & ~1 is the size of the cell in bytes.
   75:  *  padding to max alignment (no padding necessary on current machines)
   76:  *  ImageHeader structure (see below)
   77:  *  data (size in ImageHeader.image_size)
   78:  *  tags ((if relocatable, 1 bit/data cell)
   79:  *
   80:  * tag==1 means that the corresponding word is an address;
   81:  * If the word is >=0, the address is within the image;
   82:  * addresses within the image are given relative to the start of the image.
   83:  * If the word =-1 (CF_NIL), the address is NIL,
   84:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
   85:  * If the word =CF(DODOES), it's a DOES> CFA
   86:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
   87:  *					possibly containing a jump to dodoes)
   88:  * If the word is <CF(DOESJUMP), it's a primitive
   89:  */
   90: 
   91: typedef struct {
   92:   Address base;		/* base address of image (0 if relocatable) */
   93:   UCell checksum;	/* checksum of ca's to protect against some
   94: 			   incompatible	binary/executable combinations
   95: 			   (0 if relocatable) */
   96:   UCell image_size;	/* all sizes in bytes */
   97:   UCell dict_size;
   98:   UCell data_stack_size;
   99:   UCell fp_stack_size;
  100:   UCell return_stack_size;
  101:   UCell locals_stack_size;
  102:   Xt *boot_entry;	/* initial ip for booting (in BOOT) */
  103:   Xt *throw_entry;	/* ip after signal (in THROW) */
  104:   Cell unused1;		/* possibly tib stack size */
  105:   Cell unused2;
  106:   Address data_stack_base; /* this and the following fields are initialized by the loader */
  107:   Address fp_stack_base;
  108:   Address return_stack_base;
  109:   Address locals_stack_base;
  110: } ImageHeader;
  111: /* the image-header is created in main.fs */
  112: 
  113: void relocate(Cell *image, char *bitstring, int size, Label symbols[])
  114: {
  115:   int i=0, j, k, steps=(size/sizeof(Cell))/8;
  116:   char bits;
  117: /*   static char bits[8]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};*/
  118: 
  119: /*  printf("relocating %x[%x]\n", image, size); */
  120:    
  121:   for(k=0; k<=steps; k++)
  122:     for(j=0, bits=bitstring[k]; j<8; j++, i++, bits<<=1)
  123:       if(bits & 0x80)
  124: 	if(image[i]<0)
  125: 	  switch(image[i])
  126: 	    {
  127: 	    case CF_NIL      : image[i]=0; break;
  128: 	    case CF(DOCOL)   :
  129: 	    case CF(DOVAR)   :
  130: 	    case CF(DOCON)   :
  131: 	    case CF(DOUSER)  : 
  132: 	    case CF(DODEFER) : 
  133: 	    case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(image[i])]); break;
  134: 	    case CF(DODOES)  : MAKE_DOES_CF(image+i,image[i+1]+((Cell)image));
  135: 	      break;
  136: 	    case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
  137: 	    default          :
  138: /*	      printf("Code field generation image[%x]:=CA(%x)\n",
  139: 		     i, CF(image[i]));
  140: */	      image[i]=(Cell)CA(CF(image[i]));
  141: 	    }
  142: 	else
  143: 	  image[i]+=(Cell)image;
  144: }
  145: 
  146: UCell checksum(Label symbols[])
  147: {
  148:   UCell r=0;
  149:   Cell i;
  150: 
  151:   for (i=DOCOL; i<=DOESJUMP; i++) {
  152:     r ^= (UCell)(symbols[i]);
  153:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  154:   }
  155: #ifdef DIRECT_THREADED
  156:   /* we have to consider all the primitives */
  157:   for (; symbols[i]!=(Label)0; i++) {
  158:     r ^= (UCell)(symbols[i]);
  159:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  160:   }
  161: #else
  162:   /* in indirect threaded code all primitives are accessed through the
  163:      symbols table, so we just have to put the base address of symbols
  164:      in the checksum */
  165:   r ^= (UCell)symbols;
  166: #endif
  167:   return r;
  168: }
  169: 
  170: Address my_alloc(Cell size)
  171: {
  172:   static Address next_address=0;
  173:   Address r;
  174: 
  175: #if HAVE_MMAP && defined(MAP_ANON)
  176:   if (debug)
  177:     fprintf(stderr,"try mmap($%lx, $%lx, ...); ", (long)next_address, (long)size);
  178:   r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
  179:   if (r != (Address)-1) {
  180:     if (debug)
  181:       fprintf(stderr, "success, address=$%lx\n", (long) r);
  182:     if (pagesize != 0)
  183:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
  184:     return r;
  185:   }
  186:   if (debug)
  187:     fprintf(stderr, "failed: %s\n", strerror(errno));
  188: #endif
  189:   /* use malloc as fallback, leave a little room (64B) for stack underflows */
  190:   if ((r = malloc(size+64))==NULL) {
  191:     perror(progname);
  192:     exit(1);
  193:   }
  194:   if (debug)
  195:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
  196:   return r;
  197: }
  198: 
  199: Address loader(FILE *imagefile, char* filename)
  200: /* returns the address of the image proper (after the preamble) */
  201: {
  202:   ImageHeader header;
  203:   Address image;
  204:   Address imp; /* image+preamble */
  205:   Char magic[8];
  206:   Cell preamblesize=0;
  207:   Label *symbols=engine(0,0,0,0,0);
  208:   UCell check_sum=checksum(symbols);
  209: 
  210:   static char* endianstring[]= { "big","little" };
  211: 
  212:   do
  213:     {
  214:       if(fread(magic,sizeof(Char),8,imagefile) < 8) {
  215: 	fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.2) image.\n",
  216: 		progname, filename);
  217: 	exit(1);
  218:       }
  219:       preamblesize+=8;
  220:     }
  221:   while(memcmp(magic,"Gforth1",7));
  222:   if (debug)
  223:     fprintf(stderr,"Magic found: %-8s\n",magic);
  224:   
  225:   if(magic[7] != sizeof(Cell) +
  226: #ifdef WORDS_BIGENDIAN
  227:        '0'
  228: #else
  229:        '1'
  230: #endif
  231:        )
  232:     { fprintf(stderr,"This image is %d bit %s-endian, whereas the machine is %d bit %s-endian.\n", 
  233: 	      ((magic[7]-'0')&~1)*8, endianstring[magic[7]&1],
  234: 	      sizeof(Cell)*8, endianstring[
  235: #ifdef WORDS_BIGENDIAN
  236: 		      0
  237: #else
  238: 		      1
  239: #endif
  240: 		      ]);
  241:       exit(-2);
  242:     };
  243: 
  244:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
  245:   if (dictsize==0)
  246:     dictsize = header.dict_size;
  247:   if (dsize==0)
  248:     dsize=header.data_stack_size;
  249:   if (rsize==0)
  250:     rsize=header.return_stack_size;
  251:   if (fsize==0)
  252:     fsize=header.fp_stack_size;
  253:   if (lsize==0)
  254:     lsize=header.locals_stack_size;
  255:   dictsize=maxaligned(dictsize);
  256:   dsize=maxaligned(dsize);
  257:   rsize=maxaligned(rsize);
  258:   lsize=maxaligned(lsize);
  259:   fsize=maxaligned(fsize);
  260:   
  261: #if HAVE_GETPAGESIZE
  262:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
  263: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
  264:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
  265: #elif PAGESIZE
  266:   pagesize=PAGESIZE; /* in limits.h accoring to Gallmeister's POSIX.4 book */
  267: #endif
  268:   if (debug)
  269:     fprintf(stderr,"pagesize=%d\n",pagesize);
  270: 
  271:   image = my_alloc(preamblesize+dictsize+image_offset)+image_offset;
  272:   rewind(imagefile);  /* fseek(imagefile,0L,SEEK_SET); */
  273:   if (clear_dictionary)
  274:     memset(image,0,dictsize);
  275:   fread(image,1,preamblesize+header.image_size,imagefile);
  276:   imp=image+preamblesize;
  277:   if(header.base==0) {
  278:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
  279:     char reloc_bits[reloc_size];
  280:     fread(reloc_bits,1,reloc_size,imagefile);
  281:     relocate((Cell *)imp,reloc_bits,header.image_size,symbols);
  282: #if 0
  283:     { /* let's see what the relocator did */
  284:       FILE *snapshot=fopen("snapshot.fi","wb");
  285:       fwrite(image,1,imagesize,snapshot);
  286:       fclose(snapshot);
  287:     }
  288: #endif
  289:   }
  290:   else if(header.base!=imp) {
  291:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
  292: 	    progname, (unsigned long)header.base, (unsigned long)imp);
  293:     exit(1);
  294:   }
  295:   if (header.checksum==0)
  296:     ((ImageHeader *)imp)->checksum=check_sum;
  297:   else if (header.checksum != check_sum) {
  298:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\nThe Gforth installer should look into the INSTALL file\n",
  299: 	    progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
  300:     exit(1);
  301:   }
  302:   fclose(imagefile);
  303: 
  304:   ((ImageHeader *)imp)->dict_size=dictsize;
  305:   ((ImageHeader *)imp)->data_stack_size=dsize;
  306:   ((ImageHeader *)imp)->fp_stack_size=fsize;
  307:   ((ImageHeader *)imp)->return_stack_size=rsize;
  308:   ((ImageHeader *)imp)->locals_stack_size=lsize;
  309: 
  310:   ((ImageHeader *)imp)->data_stack_base=my_alloc(dsize);
  311:   ((ImageHeader *)imp)->fp_stack_base=my_alloc(fsize);
  312:   ((ImageHeader *)imp)->return_stack_base=my_alloc(rsize);
  313:   ((ImageHeader *)imp)->locals_stack_base=my_alloc(lsize);
  314: 
  315:   CACHE_FLUSH(imp, header.image_size);
  316: 
  317:   return imp;
  318: }
  319: 
  320: int go_forth(Address image, int stack, Cell *entries)
  321: {
  322:   Cell *sp=(Cell*)(((ImageHeader *)image)->data_stack_base + dsize);
  323:   Float *fp=(Float *)(((ImageHeader *)image)->fp_stack_base + fsize);
  324:   Cell *rp=(Cell *)(((ImageHeader *)image)->return_stack_base + rsize);
  325:   Address lp=((ImageHeader *)image)->locals_stack_base + lsize;
  326:   Xt *ip=(Xt *)(((ImageHeader *)image)->boot_entry);
  327:   int throw_code;
  328: 
  329:   /* ensure that the cached elements (if any) are accessible */
  330:   IF_TOS(sp--);
  331:   IF_FTOS(fp--);
  332:   
  333:   for(;stack>0;stack--)
  334:     *--sp=entries[stack-1];
  335: 
  336: #if !defined(MSDOS) && !defined(_WIN32) && !defined(__EMX__)
  337:   get_winsize();
  338: #endif
  339:    
  340:   install_signal_handlers(); /* right place? */
  341:   
  342:   if ((throw_code=setjmp(throw_jmp_buf))) {
  343:     static Cell signal_data_stack[8];
  344:     static Cell signal_return_stack[8];
  345:     static Float signal_fp_stack[1];
  346:     
  347:     signal_data_stack[7]=throw_code;
  348:     
  349:     return((int)engine(((ImageHeader *)image)->throw_entry,signal_data_stack+7,
  350: 		       signal_return_stack+8,signal_fp_stack,0));
  351:   }
  352: 
  353:   return((int)engine(ip,sp,rp,fp,lp));
  354: }
  355: 
  356: UCell convsize(char *s, UCell elemsize)
  357: /* converts s of the format #+u (e.g. 25k) into the number of bytes.
  358:    the unit u can be one of bekM, where e stands for the element
  359:    size. default is e */
  360: {
  361:   char *endp;
  362:   UCell n,m;
  363: 
  364:   m = elemsize;
  365:   n = strtoul(s,&endp,0);
  366:   if (endp!=NULL) {
  367:     if (strcmp(endp,"b")==0)
  368:       m=1;
  369:     else if (strcmp(endp,"k")==0)
  370:       m=1024;
  371:     else if (strcmp(endp,"M")==0)
  372:       m=1024*1024;
  373:     else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
  374:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
  375:       exit(1);
  376:     }
  377:   }
  378:   return n*m;
  379: }
  380: 
  381: int main(int argc, char **argv, char **env)
  382: {
  383:   char *path, *path1;
  384:   char *imagename="gforth.fi";
  385:   FILE *image_file;
  386:   int c, retvalue;
  387: 	  
  388: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
  389:   /* turn on alignment checks on the 486.
  390:    * on the 386 this should have no effect. */
  391:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
  392:   /* this is unusable with Linux' libc.4.6.27, because this library is
  393:      not alignment-clean; we would have to replace some library
  394:      functions (e.g., memcpy) to make it work */
  395: #endif
  396: 
  397:   progname = argv[0];
  398:   if ((path1=getenv("GFORTHPATH"))==NULL)
  399:     path1 = DEFAULTPATH;
  400:   
  401:   opterr=0;
  402:   while (1) {
  403:     int option_index=0;
  404:     static struct option opts[] = {
  405:       {"image-file", required_argument, NULL, 'i'},
  406:       {"dictionary-size", required_argument, NULL, 'm'},
  407:       {"data-stack-size", required_argument, NULL, 'd'},
  408:       {"return-stack-size", required_argument, NULL, 'r'},
  409:       {"fp-stack-size", required_argument, NULL, 'f'},
  410:       {"locals-stack-size", required_argument, NULL, 'l'},
  411:       {"path", required_argument, NULL, 'p'},
  412:       {"version", no_argument, NULL, 'v'},
  413:       {"help", no_argument, NULL, 'h'},
  414:       /* put something != 0 into image_offset; it should be a
  415:          not-too-large max-aligned number */
  416:       {"offset-image", no_argument, &image_offset, 28*sizeof(Cell)},
  417:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
  418:       {"debug", no_argument, &debug, 1},
  419:       {0,0,0,0}
  420:       /* no-init-file, no-rc? */
  421:     };
  422:     
  423:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vh", opts, &option_index);
  424:     
  425:     if (c==EOF)
  426:       break;
  427:     if (c=='?') {
  428:       optind--;
  429:       break;
  430:     }
  431:     switch (c) {
  432:     case 'i': imagename = optarg; break;
  433:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
  434:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
  435:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
  436:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
  437:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
  438:     case 'p': path1 = optarg; break;
  439:     case 'v': fprintf(stderr, "gforth %s\n", gforth_version); exit(0);
  440:     case 'h': 
  441:       fprintf(stderr, "Usage: %s [engine options] [image arguments]\n\
  442: Engine Options:\n\
  443:  --clear-dictionary		    Initialize the dictionary with 0 bytes\n\
  444:  -d SIZE, --data-stack-size=SIZE    Specify data stack size\n\
  445:  --debug			    Print debugging information during startup\n\
  446:  -f SIZE, --fp-stack-size=SIZE	    Specify floating point stack size\n\
  447:  -h, --help			    Print this message and exit\n\
  448:  -i FILE, --image-file=FILE	    Use image FILE instead of `gforth.fi'\n\
  449:  -l SIZE, --locals-stack-size=SIZE  Specify locals stack size\n\
  450:  -m SIZE, --dictionary-size=SIZE    Specify Forth dictionary size\n\
  451:  --offset-image			    Load image at a different position\n\
  452:  -p PATH, --path=PATH		    Search path for finding image and sources\n\
  453:  -r SIZE, --return-stack-size=SIZE  Specify return stack size\n\
  454:  -v, --version			    Print version and exit\n\
  455: SIZE arguments consists of an integer followed by a unit. The unit can be\n\
  456:   `b' (bytes), `e' (elements), `k' (kilobytes), or `M' (Megabytes).\n\
  457: \n\
  458: Arguments of default image `gforth.fi':\n\
  459:  FILE				    load FILE (with `require')\n\
  460:  -e STRING, --evaluate STRING       interpret STRING (with `EVALUATE')\n",
  461: 	      argv[0]); exit(0);
  462:     }
  463:   }
  464:   path=path1;
  465:   
  466:   if(strchr(imagename, '/')==NULL)
  467:     {
  468:       do {
  469: 	char *pend=strchr(path, PATHSEP);
  470: 	if (pend==NULL)
  471: 	  pend=path+strlen(path);
  472: 	if (strlen(path)==0) {
  473: 	  fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
  474: 		  progname, imagename, path1);
  475: 	  exit(1);
  476: 	}
  477: 	{
  478: 	  int dirlen=pend-path;
  479: 	  char fullfilename[dirlen+strlen(imagename)+2];
  480: 	  memcpy(fullfilename, path, dirlen);
  481: 	  if (fullfilename[dirlen-1]!='/')
  482: 	    fullfilename[dirlen++]='/';
  483: 	  strcpy(fullfilename+dirlen,imagename);
  484: 	  image_file=fopen(fullfilename,"rb");
  485: 	}
  486: 	path=pend+(*pend==PATHSEP);
  487:       } while (image_file==NULL);
  488:     }
  489:   else
  490:     {
  491:       image_file=fopen(imagename,"rb");
  492:     }
  493: 
  494:   {
  495:     char path2[strlen(path1)+1];
  496:     char *p1, *p2;
  497:     Cell environ[]= {
  498:       (Cell)argc-(optind-1),
  499:       (Cell)(argv+(optind-1)),
  500:       (Cell)strlen(path1),
  501:       (Cell)path2};
  502:     argv[optind-1] = progname;
  503:     /*
  504:        for (i=0; i<environ[0]; i++)
  505:        printf("%s\n", ((char **)(environ[1]))[i]);
  506:        */
  507:     /* make path OS-independent by replacing path separators with NUL */
  508:     for (p1=path1, p2=path2; *p1!='\0'; p1++, p2++)
  509:       if (*p1==PATHSEP)
  510: 	*p2 = '\0';
  511:       else
  512: 	*p2 = *p1;
  513:     *p2='\0';
  514:     retvalue=go_forth(loader(image_file, imagename),4,environ);
  515:     deprep_terminal();
  516:     exit(retvalue);
  517:   }
  518: }

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