File:  [gforth] / gforth / engine / main.c
Revision 1.46: download - view: text, annotated - select for diffs
Sun Sep 16 08:59:48 2001 UTC (22 years, 7 months ago) by jwilke
Branches: MAIN
CVS tags: HEAD
Non-relocatable images with fixed base work again.
Base address of $100 and 0 are now special cases that indicate
a relocatable image.

    1: /* command line interpretation, image loading etc. for Gforth
    2: 
    3: 
    4:   Copyright (C) 1995,1996,1997,1998,2000 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., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
   21: */
   22: 
   23: #include "config.h"
   24: #include <errno.h>
   25: #include <ctype.h>
   26: #include <stdio.h>
   27: #include <unistd.h>
   28: #include <string.h>
   29: #include <math.h>
   30: #include <sys/types.h>
   31: #ifndef STANDALONE
   32: #include <sys/stat.h>
   33: #endif
   34: #include <fcntl.h>
   35: #include <assert.h>
   36: #include <stdlib.h>
   37: #ifndef STANDALONE
   38: #if HAVE_SYS_MMAN_H
   39: #include <sys/mman.h>
   40: #endif
   41: #endif
   42: #include "forth.h"
   43: #include "io.h"
   44: #include "getopt.h"
   45: #ifdef STANDALONE
   46: #include <systypes.h>
   47: #endif
   48: 
   49: #define PRIM_VERSION 1
   50: /* increment this whenever the primitives change in an incompatible way */
   51: 
   52: #ifndef DEFAULTPATH
   53: #  define DEFAULTPATH "."
   54: #endif
   55: 
   56: #ifdef MSDOS
   57: jmp_buf throw_jmp_buf;
   58: #endif
   59: 
   60: #if defined(DIRECT_THREADED) 
   61: #  define CA(n)	(symbols[(n)])
   62: #else
   63: #  define CA(n)	((Cell)(symbols+(n)))
   64: #endif
   65: 
   66: #define maxaligned(n)	(typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
   67: 
   68: static UCell dictsize=0;
   69: static UCell dsize=0;
   70: static UCell rsize=0;
   71: static UCell fsize=0;
   72: static UCell lsize=0;
   73: int offset_image=0;
   74: int die_on_signal=0;
   75: #ifndef INCLUDE_IMAGE
   76: static int clear_dictionary=0;
   77: UCell pagesize=1;
   78: char *progname;
   79: #else
   80: char *progname = "gforth";
   81: int optind = 1;
   82: #endif
   83: 
   84: #ifdef HAS_DEBUG
   85: static int debug=0;
   86: #else
   87: # define debug 0
   88: # define perror(x...)
   89: # define fprintf(x...)
   90: #endif
   91: 
   92: ImageHeader *gforth_header;
   93: Label *vm_prims;
   94: 
   95: #ifdef MEMCMP_AS_SUBROUTINE
   96: int gforth_memcmp(const char * s1, const char * s2, size_t n)
   97: {
   98:   return memcmp(s1, s2, n);
   99: }
  100: #endif
  101: 
  102: /* image file format:
  103:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
  104:  *   padding to a multiple of 8
  105:  *   magic: "Gforth2x" means format 0.4,
  106:  *              where x is a byte with
  107:  *              bit 7:   reserved = 0
  108:  *              bit 6:5: address unit size 2^n octets
  109:  *              bit 4:3: character size 2^n octets
  110:  *              bit 2:1: cell size 2^n octets
  111:  *              bit 0:   endian, big=0, little=1.
  112:  *  The magic are always 8 octets, no matter what the native AU/character size is
  113:  *  padding to max alignment (no padding necessary on current machines)
  114:  *  ImageHeader structure (see forth.h)
  115:  *  data (size in ImageHeader.image_size)
  116:  *  tags ((if relocatable, 1 bit/data cell)
  117:  *
  118:  * tag==1 means that the corresponding word is an address;
  119:  * If the word is >=0, the address is within the image;
  120:  * addresses within the image are given relative to the start of the image.
  121:  * If the word =-1 (CF_NIL), the address is NIL,
  122:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
  123:  * If the word =CF(DODOES), it's a DOES> CFA
  124:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
  125:  *					possibly containing a jump to dodoes)
  126:  * If the word is <CF(DOESJUMP), it's a primitive
  127:  */
  128: 
  129: void relocate(Cell *image, const char *bitstring, 
  130:               int size, int base, Label symbols[])
  131: {
  132:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
  133:   Cell token;
  134:   char bits;
  135:   Cell max_symbols;
  136:   /* 
  137:    * A virtial start address that's the real start address minus 
  138:    * the one in the image 
  139:    */
  140:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
  141: 
  142:   
  143: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
  144:   
  145:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
  146:     ;
  147:   size/=sizeof(Cell);
  148: 
  149:   for(k=0; k<=steps; k++) {
  150:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  151:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
  152:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
  153: 	/* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
  154:         token=image[i];
  155: 	if(token<0)
  156: 	  switch(token)
  157: 	    {
  158: 	    case CF_NIL      : image[i]=0; break;
  159: #if !defined(DOUBLY_INDIRECT)
  160: 	    case CF(DOCOL)   :
  161: 	    case CF(DOVAR)   :
  162: 	    case CF(DOCON)   :
  163: 	    case CF(DOUSER)  : 
  164: 	    case CF(DODEFER) : 
  165: 	    case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
  166: 	    case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
  167: #endif /* !defined(DOUBLY_INDIRECT) */
  168: 	    case CF(DODOES)  :
  169: 	      MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
  170: 	      break;
  171: 	    default          :
  172: /*	      printf("Code field generation image[%x]:=CA(%x)\n",
  173: 		     i, CF(image[i])); */
  174: 	      if (CF(token)<max_symbols)
  175: 		image[i]=(Cell)CA(CF(token));
  176: 	      else
  177: 		fprintf(stderr,"Primitive %d used in this image at $%lx is not implemented by this\n engine (%s); executing this code will crash.\n",CF(token),(long)&image[i],VERSION);
  178: 	    }
  179: 	else {
  180:           // if base is > 0: 0 is a null reference so don't adjust
  181:           if (token>=base) {
  182:             image[i]+=(Cell)start;
  183:           }
  184:         }
  185:       }
  186:     }
  187:   }
  188:   ((ImageHeader*)(image))->base = (Address) image;
  189: }
  190: 
  191: UCell checksum(Label symbols[])
  192: {
  193:   UCell r=PRIM_VERSION;
  194:   Cell i;
  195: 
  196:   for (i=DOCOL; i<=DOESJUMP; i++) {
  197:     r ^= (UCell)(symbols[i]);
  198:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  199:   }
  200: #ifdef DIRECT_THREADED
  201:   /* we have to consider all the primitives */
  202:   for (; symbols[i]!=(Label)0; i++) {
  203:     r ^= (UCell)(symbols[i]);
  204:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  205:   }
  206: #else
  207:   /* in indirect threaded code all primitives are accessed through the
  208:      symbols table, so we just have to put the base address of symbols
  209:      in the checksum */
  210:   r ^= (UCell)symbols;
  211: #endif
  212:   return r;
  213: }
  214: 
  215: Address verbose_malloc(Cell size)
  216: {
  217:   Address r;
  218:   /* leave a little room (64B) for stack underflows */
  219:   if ((r = malloc(size+64))==NULL) {
  220:     perror(progname);
  221:     exit(1);
  222:   }
  223:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
  224:   if (debug)
  225:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
  226:   return r;
  227: }
  228: 
  229: static Address next_address=0;
  230: void after_alloc(Address r, Cell size)
  231: {
  232:   if (r != (Address)-1) {
  233:     if (debug)
  234:       fprintf(stderr, "success, address=$%lx\n", (long) r);
  235:     if (pagesize != 1)
  236:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
  237:   } else {
  238:     if (debug)
  239:       fprintf(stderr, "failed: %s\n", strerror(errno));
  240:   }
  241: }
  242: 
  243: #ifndef MAP_FAILED
  244: #define MAP_FAILED ((Address) -1)
  245: #endif
  246: #ifndef MAP_FILE
  247: # define MAP_FILE 0
  248: #endif
  249: #ifndef MAP_PRIVATE
  250: # define MAP_PRIVATE 0
  251: #endif
  252: 
  253: #if defined(HAVE_MMAP)
  254: static Address alloc_mmap(Cell size)
  255: {
  256:   Address r;
  257: 
  258: #if defined(MAP_ANON)
  259:   if (debug)
  260:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
  261:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
  262: #else /* !defined(MAP_ANON) */
  263:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
  264:      apparently defaults) */
  265:   static int dev_zero=-1;
  266: 
  267:   if (dev_zero == -1)
  268:     dev_zero = open("/dev/zero", O_RDONLY);
  269:   if (dev_zero == -1) {
  270:     r = MAP_FAILED;
  271:     if (debug)
  272:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
  273: 	      strerror(errno));
  274:   } else {
  275:     if (debug)
  276:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
  277:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
  278:   }
  279: #endif /* !defined(MAP_ANON) */
  280:   after_alloc(r, size);
  281:   return r;  
  282: }
  283: #endif
  284: 
  285: Address my_alloc(Cell size)
  286: {
  287: #if HAVE_MMAP
  288:   Address r;
  289: 
  290:   r=alloc_mmap(size);
  291:   if (r!=MAP_FAILED)
  292:     return r;
  293: #endif /* HAVE_MMAP */
  294:   /* use malloc as fallback */
  295:   return verbose_malloc(size);
  296: }
  297: 
  298: #if (defined(mips) && !defined(INDIRECT_THREADED))
  299: /* the 256MB jump restriction on the MIPS architecture makes the
  300:    combination of direct threading and mmap unsafe. */
  301: #define mips_dict_alloc 1
  302: #define dict_alloc(size) verbose_malloc(size)
  303: #else
  304: #define dict_alloc(size) my_alloc(size)
  305: #endif
  306: 
  307: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
  308: {
  309:   Address image = MAP_FAILED;
  310: 
  311: #if defined(HAVE_MMAP) && !defined(mips_dict_alloc)
  312:   if (offset==0) {
  313:     image=alloc_mmap(dictsize);
  314:     if (debug)
  315:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
  316:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
  317:     after_alloc(image,dictsize);
  318:   }
  319: #endif /* defined(MAP_ANON) && !defined(mips_dict_alloc) */
  320:   if (image == MAP_FAILED) {
  321:     image = dict_alloc(dictsize+offset)+offset;
  322:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
  323:     fread(image, 1, imagesize, file);
  324:   }
  325:   return image;
  326: }
  327: 
  328: void set_stack_sizes(ImageHeader * header)
  329: {
  330:   if (dictsize==0)
  331:     dictsize = header->dict_size;
  332:   if (dsize==0)
  333:     dsize = header->data_stack_size;
  334:   if (rsize==0)
  335:     rsize = header->return_stack_size;
  336:   if (fsize==0)
  337:     fsize = header->fp_stack_size;
  338:   if (lsize==0)
  339:     lsize = header->locals_stack_size;
  340:   dictsize=maxaligned(dictsize);
  341:   dsize=maxaligned(dsize);
  342:   rsize=maxaligned(rsize);
  343:   lsize=maxaligned(lsize);
  344:   fsize=maxaligned(fsize);
  345: }
  346: 
  347: void alloc_stacks(ImageHeader * header)
  348: {
  349:   header->dict_size=dictsize;
  350:   header->data_stack_size=dsize;
  351:   header->fp_stack_size=fsize;
  352:   header->return_stack_size=rsize;
  353:   header->locals_stack_size=lsize;
  354: 
  355:   header->data_stack_base=my_alloc(dsize);
  356:   header->fp_stack_base=my_alloc(fsize);
  357:   header->return_stack_base=my_alloc(rsize);
  358:   header->locals_stack_base=my_alloc(lsize);
  359: }
  360: 
  361: #warning You can ignore the warnings about clobbered variables in go_forth
  362: int go_forth(Address image, int stack, Cell *entries)
  363: {
  364:   volatile ImageHeader *image_header = (ImageHeader *)image;
  365:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
  366:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
  367:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
  368: #ifdef GFORTH_DEBUGGING
  369:   volatile Cell *orig_rp0=rp0;
  370: #endif
  371:   Address lp0=image_header->locals_stack_base + lsize;
  372:   Xt *ip0=(Xt *)(image_header->boot_entry);
  373: #ifdef SYSSIGNALS
  374:   int throw_code;
  375: #endif
  376: 
  377:   /* ensure that the cached elements (if any) are accessible */
  378:   IF_spTOS(sp0--);
  379:   IF_fpTOS(fp0--);
  380:   
  381:   for(;stack>0;stack--)
  382:     *--sp0=entries[stack-1];
  383: 
  384: #ifdef SYSSIGNALS
  385:   get_winsize();
  386:    
  387:   install_signal_handlers(); /* right place? */
  388:   
  389:   if ((throw_code=setjmp(throw_jmp_buf))) {
  390:     static Cell signal_data_stack[8];
  391:     static Cell signal_return_stack[8];
  392:     static Float signal_fp_stack[1];
  393: 
  394:     signal_data_stack[7]=throw_code;
  395: 
  396: #ifdef GFORTH_DEBUGGING
  397:     /* fprintf(stderr,"\nrp=%ld\n",(long)rp); */
  398:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
  399:       /* no rstack overflow or underflow */
  400:       rp0 = rp;
  401:       *--rp0 = (Cell)ip;
  402:     }
  403:     else /* I love non-syntactic ifdefs :-) */
  404: #endif
  405:     rp0 = signal_return_stack+8;
  406:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
  407:     
  408:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
  409: 		       rp0, signal_fp_stack, 0));
  410:   }
  411: #endif
  412: 
  413:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
  414: }
  415: 
  416: 
  417: #ifndef INCLUDE_IMAGE
  418: void print_sizes(Cell sizebyte)
  419:      /* print size information */
  420: {
  421:   static char* endianstring[]= { "   big","little" };
  422:   
  423:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
  424: 	  endianstring[sizebyte & 1],
  425: 	  1 << ((sizebyte >> 1) & 3),
  426: 	  1 << ((sizebyte >> 3) & 3),
  427: 	  1 << ((sizebyte >> 5) & 3));
  428: }
  429: 
  430: Address loader(FILE *imagefile, char* filename)
  431: /* returns the address of the image proper (after the preamble) */
  432: {
  433:   ImageHeader header;
  434:   Address image;
  435:   Address imp; /* image+preamble */
  436:   Char magic[8];
  437:   char magic7; /* size byte of magic number */
  438:   Cell preamblesize=0;
  439:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
  440:   UCell check_sum;
  441:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
  442: 		 (RELINFOBITS == 16) ? 1 :
  443: 		 (RELINFOBITS == 32) ? 2 : 3);
  444:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
  445: 		   (sizeof(Char) == 2) ? 1 :
  446: 		   (sizeof(Char) == 4) ? 2 : 3) + ausize;
  447:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
  448: 		   (sizeof(Cell) == 2) ? 1 :
  449: 		   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
  450:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
  451: #ifdef WORDS_BIGENDIAN
  452:        0
  453: #else
  454:        1
  455: #endif
  456:     ;
  457: 
  458:   vm_prims = engine(0,0,0,0,0);
  459: #ifndef DOUBLY_INDIRECT
  460:   check_sum = checksum(vm_prims);
  461: #else /* defined(DOUBLY_INDIRECT) */
  462:   check_sum = (UCell)vm_prims;
  463: #endif /* defined(DOUBLY_INDIRECT) */
  464:   
  465:   do {
  466:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
  467:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.4) image.\n",
  468: 	      progname, filename);
  469:       exit(1);
  470:     }
  471:     preamblesize+=8;
  472:   } while(memcmp(magic,"Gforth2",7));
  473:   magic7 = magic[7];
  474:   if (debug) {
  475:     magic[7]='\0';
  476:     fprintf(stderr,"Magic found: %s ", magic);
  477:     print_sizes(magic7);
  478:   }
  479: 
  480:   if (magic7 != sizebyte)
  481:     {
  482:       fprintf(stderr,"This image is:         ");
  483:       print_sizes(magic7);
  484:       fprintf(stderr,"whereas the machine is ");
  485:       print_sizes(sizebyte);
  486:       exit(-2);
  487:     };
  488: 
  489:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
  490: 
  491:   set_stack_sizes(&header);
  492:   
  493: #if HAVE_GETPAGESIZE
  494:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
  495: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
  496:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
  497: #elif PAGESIZE
  498:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
  499: #endif
  500:   if (debug)
  501:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
  502: 
  503:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
  504: 			  preamblesize+dictsize, data_offset);
  505:   imp=image+preamblesize;
  506:   if (clear_dictionary)
  507:     memset(imp+header.image_size, 0, dictsize-header.image_size);
  508:   if(header.base==0 || header.base  == 0x100) {
  509:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
  510:     char reloc_bits[reloc_size];
  511:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
  512:     fread(reloc_bits, 1, reloc_size, imagefile);
  513:     relocate((Cell *)imp, reloc_bits, header.image_size, header.base, vm_prims);
  514: #if 0
  515:     { /* let's see what the relocator did */
  516:       FILE *snapshot=fopen("snapshot.fi","wb");
  517:       fwrite(image,1,imagesize,snapshot);
  518:       fclose(snapshot);
  519:     }
  520: #endif
  521:   }
  522:   else if(header.base!=imp) {
  523:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
  524: 	    progname, (unsigned long)header.base, (unsigned long)imp);
  525:     exit(1);
  526:   }
  527:   if (header.checksum==0)
  528:     ((ImageHeader *)imp)->checksum=check_sum;
  529:   else if (header.checksum != check_sum) {
  530:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
  531: 	    progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
  532:     exit(1);
  533:   }
  534:   fclose(imagefile);
  535: 
  536:   alloc_stacks((ImageHeader *)imp);
  537: 
  538:   CACHE_FLUSH(imp, header.image_size);
  539: 
  540:   return imp;
  541: }
  542: 
  543: /* index of last '/' or '\' in file, 0 if there is none. !! Hmm, could
  544:    be implemented with strrchr and the separator should be
  545:    OS-dependent */
  546: int onlypath(char *file)
  547: {
  548:   int i;
  549:   i=strlen(file);
  550:   while (i) {
  551:     if (file[i]=='\\' || file[i]=='/') break;
  552:     i--;
  553:   }
  554:   return i;
  555: }
  556: 
  557: FILE *openimage(char *fullfilename)
  558: {
  559:   FILE *image_file;
  560:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
  561: 
  562:   image_file=fopen(expfilename,"rb");
  563:   if (image_file!=NULL && debug)
  564:     fprintf(stderr, "Opened image file: %s\n", expfilename);
  565:   return image_file;
  566: }
  567: 
  568: /* try to open image file concat(path[0:len],imagename) */
  569: FILE *checkimage(char *path, int len, char *imagename)
  570: {
  571:   int dirlen=len;
  572:   char fullfilename[dirlen+strlen(imagename)+2];
  573: 
  574:   memcpy(fullfilename, path, dirlen);
  575:   if (fullfilename[dirlen-1]!='/')
  576:     fullfilename[dirlen++]='/';
  577:   strcpy(fullfilename+dirlen,imagename);
  578:   return openimage(fullfilename);
  579: }
  580: 
  581: FILE * open_image_file(char * imagename, char * path)
  582: {
  583:   FILE * image_file=NULL;
  584:   char *origpath=path;
  585:   
  586:   if(strchr(imagename, '/')==NULL) {
  587:     /* first check the directory where the exe file is in !! 01may97jaw */
  588:     if (onlypath(progname))
  589:       image_file=checkimage(progname, onlypath(progname), imagename);
  590:     if (!image_file)
  591:       do {
  592: 	char *pend=strchr(path, PATHSEP);
  593: 	if (pend==NULL)
  594: 	  pend=path+strlen(path);
  595: 	if (strlen(path)==0) break;
  596: 	image_file=checkimage(path, pend-path, imagename);
  597: 	path=pend+(*pend==PATHSEP);
  598:       } while (image_file==NULL);
  599:   } else {
  600:     image_file=openimage(imagename);
  601:   }
  602: 
  603:   if (!image_file) {
  604:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
  605: 	    progname, imagename, origpath);
  606:     exit(1);
  607:   }
  608: 
  609:   return image_file;
  610: }
  611: #endif
  612: 
  613: #ifdef HAS_OS
  614: UCell convsize(char *s, UCell elemsize)
  615: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
  616:    of bytes.  the letter at the end indicates the unit, where e stands
  617:    for the element size. default is e */
  618: {
  619:   char *endp;
  620:   UCell n,m;
  621: 
  622:   m = elemsize;
  623:   n = strtoul(s,&endp,0);
  624:   if (endp!=NULL) {
  625:     if (strcmp(endp,"b")==0)
  626:       m=1;
  627:     else if (strcmp(endp,"k")==0)
  628:       m=1024;
  629:     else if (strcmp(endp,"M")==0)
  630:       m=1024*1024;
  631:     else if (strcmp(endp,"G")==0)
  632:       m=1024*1024*1024;
  633:     else if (strcmp(endp,"T")==0) {
  634: #if (SIZEOF_CHAR_P > 4)
  635:       m=1024L*1024*1024*1024;
  636: #else
  637:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
  638:       exit(1);
  639: #endif
  640:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
  641:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
  642:       exit(1);
  643:     }
  644:   }
  645:   return n*m;
  646: }
  647: 
  648: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
  649: {
  650:   int c;
  651: 
  652:   opterr=0;
  653:   while (1) {
  654:     int option_index=0;
  655:     static struct option opts[] = {
  656:       {"appl-image", required_argument, NULL, 'a'},
  657:       {"image-file", required_argument, NULL, 'i'},
  658:       {"dictionary-size", required_argument, NULL, 'm'},
  659:       {"data-stack-size", required_argument, NULL, 'd'},
  660:       {"return-stack-size", required_argument, NULL, 'r'},
  661:       {"fp-stack-size", required_argument, NULL, 'f'},
  662:       {"locals-stack-size", required_argument, NULL, 'l'},
  663:       {"path", required_argument, NULL, 'p'},
  664:       {"version", no_argument, NULL, 'v'},
  665:       {"help", no_argument, NULL, 'h'},
  666:       /* put something != 0 into offset_image */
  667:       {"offset-image", no_argument, &offset_image, 1},
  668:       {"no-offset-im", no_argument, &offset_image, 0},
  669:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
  670:       {"die-on-signal", no_argument, &die_on_signal, 1},
  671:       {"debug", no_argument, &debug, 1},
  672:       {0,0,0,0}
  673:       /* no-init-file, no-rc? */
  674:     };
  675:     
  676:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
  677:     
  678:     switch (c) {
  679:     case EOF: return;
  680:     case '?': optind--; return;
  681:     case 'a': *imagename = optarg; return;
  682:     case 'i': *imagename = optarg; break;
  683:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
  684:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
  685:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
  686:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
  687:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
  688:     case 'p': *path = optarg; break;
  689:     case 'o': offset_image = 1; break;
  690:     case 'n': offset_image = 0; break;
  691:     case 'c': clear_dictionary = 1; break;
  692:     case 's': die_on_signal = 1; break;
  693:     case 'x': debug = 1; break;
  694:     case 'v': fprintf(stderr, "gforth %s\n", VERSION); exit(0);
  695:     case 'h': 
  696:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
  697: Engine Options:\n\
  698:   --appl-image FILE		    equivalent to '--image-file=FILE --'\n\
  699:   --clear-dictionary		    Initialize the dictionary with 0 bytes\n\
  700:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
  701:   --debug			    Print debugging information during startup\n\
  702:   --die-on-signal		    exit instead of CATCHing some signals\n\
  703:   -f SIZE, --fp-stack-size=SIZE	    Specify floating point stack size\n\
  704:   -h, --help			    Print this message and exit\n\
  705:   -i FILE, --image-file=FILE	    Use image FILE instead of `gforth.fi'\n\
  706:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
  707:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
  708:   --no-offset-im		    Load image at normal position\n\
  709:   --offset-image		    Load image at a different position\n\
  710:   -p PATH, --path=PATH		    Search path for finding image and sources\n\
  711:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
  712:   -v, --version			    Print version and exit\n\
  713: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
  714:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
  715: 	      argv[0]);
  716:       optind--;
  717:       return;
  718:     }
  719:   }
  720: }
  721: #endif
  722: 
  723: #ifdef INCLUDE_IMAGE
  724: extern Cell image[];
  725: extern const char reloc_bits[];
  726: #endif
  727: 
  728: int main(int argc, char **argv, char **env)
  729: {
  730: #ifdef HAS_OS
  731:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
  732: #else
  733:   char *path = DEFAULTPATH;
  734: #endif
  735: #ifndef INCLUDE_IMAGE
  736:   char *imagename="gforth.fi";
  737:   FILE *image_file;
  738:   Address image;
  739: #endif
  740:   int retvalue;
  741: 	  
  742: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
  743:   /* turn on alignment checks on the 486.
  744:    * on the 386 this should have no effect. */
  745:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
  746:   /* this is unusable with Linux' libc.4.6.27, because this library is
  747:      not alignment-clean; we would have to replace some library
  748:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
  749:      the stack FP-aligned. */
  750: #endif
  751: 
  752:   /* buffering of the user output device */
  753: #ifdef _IONBF
  754:   if (isatty(fileno(stdout))) {
  755:     fflush(stdout);
  756:     setvbuf(stdout,NULL,_IONBF,0);
  757:   }
  758: #endif
  759: 
  760:   progname = argv[0];
  761: 
  762: #ifdef HAS_OS
  763:   gforth_args(argc, argv, &path, &imagename);
  764: #endif
  765: 
  766: #ifdef INCLUDE_IMAGE
  767:   set_stack_sizes((ImageHeader *)image);
  768:   if(((ImageHeader *)image)->base != image)
  769:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
  770: 	     (Label*)engine(0, 0, 0, 0, 0));
  771:   alloc_stacks((ImageHeader *)image);
  772: #else
  773:   image_file = open_image_file(imagename, path);
  774:   image = loader(image_file, imagename);
  775: #endif
  776:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
  777: 
  778:   {
  779:     char path2[strlen(path)+1];
  780:     char *p1, *p2;
  781:     Cell environ[]= {
  782:       (Cell)argc-(optind-1),
  783:       (Cell)(argv+(optind-1)),
  784:       (Cell)strlen(path),
  785:       (Cell)path2};
  786:     argv[optind-1] = progname;
  787:     /*
  788:        for (i=0; i<environ[0]; i++)
  789:        printf("%s\n", ((char **)(environ[1]))[i]);
  790:        */
  791:     /* make path OS-independent by replacing path separators with NUL */
  792:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
  793:       if (*p1==PATHSEP)
  794: 	*p2 = '\0';
  795:       else
  796: 	*p2 = *p1;
  797:     *p2='\0';
  798:     retvalue = go_forth(image, 4, environ);
  799: #ifdef VM_PROFILING
  800:     vm_print_profile(stderr);
  801: #endif
  802:     deprep_terminal();
  803:   }
  804:   return retvalue;
  805: }

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