File:  [gforth] / gforth / engine / main.c
Revision 1.62: download - view: text, annotated - select for diffs
Mon Apr 1 15:34:35 2002 UTC (22 years ago) by anton
Branches: MAIN
CVS tags: HEAD
added regression test for signal on broken execute (not working on Linux-PPC)
new error message and code for ticking compile-only words
bug workaround for gforth binary (dynamic superinsts produced wrong code for
    ?dup-0=-branch)

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

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