File:  [gforth] / gforth / engine / main.c
Revision 1.89: download - view: text, annotated - select for diffs
Fri Jan 3 20:26:19 2003 UTC (21 years, 3 months ago) by anton
Branches: MAIN
CVS tags: HEAD
undid the unnecessary/broken stuff Bernd has done
moved a change from machpc.fs to machpc.fs.in
removed machpc.fs (generated file)

    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 "forth.h"
   25: #include <errno.h>
   26: #include <ctype.h>
   27: #include <stdio.h>
   28: #include <unistd.h>
   29: #include <string.h>
   30: #include <math.h>
   31: #include <sys/types.h>
   32: #ifndef STANDALONE
   33: #include <sys/stat.h>
   34: #endif
   35: #include <fcntl.h>
   36: #include <assert.h>
   37: #include <stdlib.h>
   38: #ifndef STANDALONE
   39: #if HAVE_SYS_MMAN_H
   40: #include <sys/mman.h>
   41: #endif
   42: #endif
   43: #include "io.h"
   44: #include "getopt.h"
   45: #ifdef STANDALONE
   46: #include <systypes.h>
   47: #endif
   48: 
   49: /* global variables for engine.c 
   50:    We put them here because engine.c is compiled several times in
   51:    different ways for the same engine. */
   52: Cell *SP;
   53: Float *FP;
   54: Address UP=NULL;
   55: 
   56: #ifdef GFORTH_DEBUGGING
   57: /* define some VM registers as global variables, so they survive exceptions;
   58:    global register variables are not up to the task (according to the 
   59:    GNU C manual) */
   60: Xt *saved_ip;
   61: Cell *rp;
   62: #endif
   63: 
   64: #ifdef NO_IP
   65: Label next_code;
   66: #endif
   67: 
   68: #ifdef HAS_FILE
   69: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
   70: char* pfileattr[6]={"r","r","r+","r+","w","w"};
   71: 
   72: #ifndef O_BINARY
   73: #define O_BINARY 0
   74: #endif
   75: #ifndef O_TEXT
   76: #define O_TEXT 0
   77: #endif
   78: 
   79: int ufileattr[6]= {
   80:   O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
   81:   O_RDWR  |O_BINARY, O_RDWR  |O_BINARY,
   82:   O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
   83: #endif
   84: /* end global vars for engine.c */
   85: 
   86: #define PRIM_VERSION 1
   87: /* increment this whenever the primitives change in an incompatible way */
   88: 
   89: #ifndef DEFAULTPATH
   90: #  define DEFAULTPATH "."
   91: #endif
   92: 
   93: #ifdef MSDOS
   94: jmp_buf throw_jmp_buf;
   95: #endif
   96: 
   97: #if defined(DOUBLY_INDIRECT)
   98: #  define CFA(n)	({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
   99: #else
  100: #  define CFA(n)	((Cell)(symbols+((n)&~0x4000UL)))
  101: #endif
  102: 
  103: #define maxaligned(n)	(typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
  104: 
  105: static UCell dictsize=0;
  106: static UCell dsize=0;
  107: static UCell rsize=0;
  108: static UCell fsize=0;
  109: static UCell lsize=0;
  110: int offset_image=0;
  111: int die_on_signal=0;
  112: #ifndef INCLUDE_IMAGE
  113: static int clear_dictionary=0;
  114: UCell pagesize=1;
  115: char *progname;
  116: #else
  117: char *progname = "gforth";
  118: int optind = 1;
  119: #endif
  120: 
  121: #define CODE_BLOCK_SIZE (64*1024)
  122: Address code_area=0;
  123: Cell code_area_size = CODE_BLOCK_SIZE;
  124: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
  125: 					   does for the dictionary */
  126: Address start_flush=0; /* start of unflushed code */
  127: Cell last_jump=0; /* if the last prim was compiled without jump, this
  128:                      is it's number, otherwise this contains 0 */
  129: 
  130: static int no_super=0;   /* true if compile_prim should not fuse prims */
  131: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
  132: 					     dynamically */
  133: 
  134: #ifdef HAS_DEBUG
  135: int debug=0;
  136: #else
  137: # define perror(x...)
  138: # define fprintf(x...)
  139: #endif
  140: 
  141: ImageHeader *gforth_header;
  142: Label *vm_prims;
  143: #ifdef DOUBLY_INDIRECT
  144: Label *xts; /* same content as vm_prims, but should only be used for xts */
  145: #endif
  146: 
  147: #ifdef MEMCMP_AS_SUBROUTINE
  148: int gforth_memcmp(const char * s1, const char * s2, size_t n)
  149: {
  150:   return memcmp(s1, s2, n);
  151: }
  152: #endif
  153: 
  154: /* image file format:
  155:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
  156:  *   padding to a multiple of 8
  157:  *   magic: "Gforth3x" means format 0.6,
  158:  *              where x is a byte with
  159:  *              bit 7:   reserved = 0
  160:  *              bit 6:5: address unit size 2^n octets
  161:  *              bit 4:3: character size 2^n octets
  162:  *              bit 2:1: cell size 2^n octets
  163:  *              bit 0:   endian, big=0, little=1.
  164:  *  The magic are always 8 octets, no matter what the native AU/character size is
  165:  *  padding to max alignment (no padding necessary on current machines)
  166:  *  ImageHeader structure (see forth.h)
  167:  *  data (size in ImageHeader.image_size)
  168:  *  tags ((if relocatable, 1 bit/data cell)
  169:  *
  170:  * tag==1 means that the corresponding word is an address;
  171:  * If the word is >=0, the address is within the image;
  172:  * addresses within the image are given relative to the start of the image.
  173:  * If the word =-1 (CF_NIL), the address is NIL,
  174:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
  175:  * If the word =CF(DODOES), it's a DOES> CFA
  176:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
  177:  *					possibly containing a jump to dodoes)
  178:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
  179:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
  180:  *                                        it's the threaded code of a primitive
  181:  * bits 13..9 of a primitive token state which group the primitive belongs to,
  182:  * bits 8..0 of a primitive token index into the group
  183:  */
  184: 
  185: static Cell groups[32] = {
  186:   0,
  187: #define GROUP(x, n) DOESJUMP+1+n,
  188: #include "prim_grp.i"
  189: #define GROUP(x, n)
  190: };
  191: 
  192: void relocate(Cell *image, const char *bitstring, 
  193:               int size, int base, Label symbols[])
  194: {
  195:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
  196:   Cell token;
  197:   char bits;
  198:   Cell max_symbols;
  199:   /* 
  200:    * A virtual start address that's the real start address minus 
  201:    * the one in the image 
  202:    */
  203:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
  204: 
  205:   /* group index into table */
  206:   
  207: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
  208:   
  209:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
  210:     ;
  211:   max_symbols--;
  212:   size/=sizeof(Cell);
  213: 
  214:   for(k=0; k<=steps; k++) {
  215:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  216:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
  217:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
  218: 	/* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
  219:         token=image[i];
  220: 	if(token<0) {
  221: 	  int group = (-token & 0x3E00) >> 9;
  222: 	  if(group == 0) {
  223: 	    switch(token|0x4000) {
  224: 	    case CF_NIL      : image[i]=0; break;
  225: #if !defined(DOUBLY_INDIRECT)
  226: 	    case CF(DOCOL)   :
  227: 	    case CF(DOVAR)   :
  228: 	    case CF(DOCON)   :
  229: 	    case CF(DOUSER)  : 
  230: 	    case CF(DODEFER) : 
  231: 	    case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
  232: 	    case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
  233: #endif /* !defined(DOUBLY_INDIRECT) */
  234: 	    case CF(DODOES)  :
  235: 	      MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
  236: 	      break;
  237: 	    default          : /* backward compatibility */
  238: /*	      printf("Code field generation image[%x]:=CFA(%x)\n",
  239: 		     i, CF(image[i])); */
  240: 	      if (CF((token | 0x4000))<max_symbols) {
  241: 		image[i]=(Cell)CFA(CF(token));
  242: #ifdef DIRECT_THREADED
  243: 		if ((token & 0x4000) == 0) /* threade code, no CFA */
  244: 		  compile_prim1(&image[i]);
  245: #endif
  246: 	      } else
  247: 		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],PACKAGE_VERSION);
  248: 	    }
  249: 	  } else {
  250: 	    int tok = -token & 0x1FF;
  251: 	    if (tok < (groups[group+1]-groups[group])) {
  252: #if defined(DOUBLY_INDIRECT)
  253: 	      image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
  254: #else
  255: 	      image[i]=(Cell)CFA((groups[group]+tok));
  256: #endif
  257: #ifdef DIRECT_THREADED
  258: 	      if ((token & 0x4000) == 0) /* threade code, no CFA */
  259: 		compile_prim1(&image[i]);
  260: #endif
  261: 	    } else
  262: 	      fprintf(stderr,"Primitive %x, %d of group %d used in this image at $%lx is not implemented by this\n engine (%s); executing this code will crash.\n", -token, tok, group, (long)&image[i],PACKAGE_VERSION);
  263: 	  }
  264: 	} else {
  265:           // if base is > 0: 0 is a null reference so don't adjust
  266:           if (token>=base) {
  267:             image[i]+=(Cell)start;
  268:           }
  269:         }
  270:       }
  271:     }
  272:   }
  273:   finish_code();
  274:   ((ImageHeader*)(image))->base = (Address) image;
  275: }
  276: 
  277: UCell checksum(Label symbols[])
  278: {
  279:   UCell r=PRIM_VERSION;
  280:   Cell i;
  281: 
  282:   for (i=DOCOL; i<=DOESJUMP; i++) {
  283:     r ^= (UCell)(symbols[i]);
  284:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  285:   }
  286: #ifdef DIRECT_THREADED
  287:   /* we have to consider all the primitives */
  288:   for (; symbols[i]!=(Label)0; i++) {
  289:     r ^= (UCell)(symbols[i]);
  290:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  291:   }
  292: #else
  293:   /* in indirect threaded code all primitives are accessed through the
  294:      symbols table, so we just have to put the base address of symbols
  295:      in the checksum */
  296:   r ^= (UCell)symbols;
  297: #endif
  298:   return r;
  299: }
  300: 
  301: Address verbose_malloc(Cell size)
  302: {
  303:   Address r;
  304:   /* leave a little room (64B) for stack underflows */
  305:   if ((r = malloc(size+64))==NULL) {
  306:     perror(progname);
  307:     exit(1);
  308:   }
  309:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
  310:   if (debug)
  311:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
  312:   return r;
  313: }
  314: 
  315: static Address next_address=0;
  316: void after_alloc(Address r, Cell size)
  317: {
  318:   if (r != (Address)-1) {
  319:     if (debug)
  320:       fprintf(stderr, "success, address=$%lx\n", (long) r);
  321:     if (pagesize != 1)
  322:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
  323:   } else {
  324:     if (debug)
  325:       fprintf(stderr, "failed: %s\n", strerror(errno));
  326:   }
  327: }
  328: 
  329: #ifndef MAP_FAILED
  330: #define MAP_FAILED ((Address) -1)
  331: #endif
  332: #ifndef MAP_FILE
  333: # define MAP_FILE 0
  334: #endif
  335: #ifndef MAP_PRIVATE
  336: # define MAP_PRIVATE 0
  337: #endif
  338: 
  339: #if defined(HAVE_MMAP)
  340: static Address alloc_mmap(Cell size)
  341: {
  342:   Address r;
  343: 
  344: #if defined(MAP_ANON)
  345:   if (debug)
  346:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
  347:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
  348: #else /* !defined(MAP_ANON) */
  349:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
  350:      apparently defaults) */
  351:   static int dev_zero=-1;
  352: 
  353:   if (dev_zero == -1)
  354:     dev_zero = open("/dev/zero", O_RDONLY);
  355:   if (dev_zero == -1) {
  356:     r = MAP_FAILED;
  357:     if (debug)
  358:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
  359: 	      strerror(errno));
  360:   } else {
  361:     if (debug)
  362:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
  363:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
  364:   }
  365: #endif /* !defined(MAP_ANON) */
  366:   after_alloc(r, size);
  367:   return r;  
  368: }
  369: #endif
  370: 
  371: Address my_alloc(Cell size)
  372: {
  373: #if HAVE_MMAP
  374:   Address r;
  375: 
  376:   r=alloc_mmap(size);
  377:   if (r!=MAP_FAILED)
  378:     return r;
  379: #endif /* HAVE_MMAP */
  380:   /* use malloc as fallback */
  381:   return verbose_malloc(size);
  382: }
  383: 
  384: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
  385: {
  386:   Address image = MAP_FAILED;
  387: 
  388: #if defined(HAVE_MMAP)
  389:   if (offset==0) {
  390:     image=alloc_mmap(dictsize);
  391:     if (debug)
  392:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
  393:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
  394:     after_alloc(image,dictsize);
  395:   }
  396: #endif /* defined(HAVE_MMAP) */
  397:   if (image == MAP_FAILED) {
  398:     image = my_alloc(dictsize+offset)+offset;
  399:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
  400:     fread(image, 1, imagesize, file);
  401:   }
  402:   return image;
  403: }
  404: 
  405: void set_stack_sizes(ImageHeader * header)
  406: {
  407:   if (dictsize==0)
  408:     dictsize = header->dict_size;
  409:   if (dsize==0)
  410:     dsize = header->data_stack_size;
  411:   if (rsize==0)
  412:     rsize = header->return_stack_size;
  413:   if (fsize==0)
  414:     fsize = header->fp_stack_size;
  415:   if (lsize==0)
  416:     lsize = header->locals_stack_size;
  417:   dictsize=maxaligned(dictsize);
  418:   dsize=maxaligned(dsize);
  419:   rsize=maxaligned(rsize);
  420:   lsize=maxaligned(lsize);
  421:   fsize=maxaligned(fsize);
  422: }
  423: 
  424: void alloc_stacks(ImageHeader * header)
  425: {
  426:   header->dict_size=dictsize;
  427:   header->data_stack_size=dsize;
  428:   header->fp_stack_size=fsize;
  429:   header->return_stack_size=rsize;
  430:   header->locals_stack_size=lsize;
  431: 
  432:   header->data_stack_base=my_alloc(dsize);
  433:   header->fp_stack_base=my_alloc(fsize);
  434:   header->return_stack_base=my_alloc(rsize);
  435:   header->locals_stack_base=my_alloc(lsize);
  436: }
  437: 
  438: #warning You can ignore the warnings about clobbered variables in go_forth
  439: int go_forth(Address image, int stack, Cell *entries)
  440: {
  441:   volatile ImageHeader *image_header = (ImageHeader *)image;
  442:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
  443:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
  444:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
  445: #ifdef GFORTH_DEBUGGING
  446:   volatile Cell *orig_rp0=rp0;
  447: #endif
  448:   Address lp0=image_header->locals_stack_base + lsize;
  449:   Xt *ip0=(Xt *)(image_header->boot_entry);
  450: #ifdef SYSSIGNALS
  451:   int throw_code;
  452: #endif
  453: 
  454:   /* ensure that the cached elements (if any) are accessible */
  455:   IF_spTOS(sp0--);
  456:   IF_fpTOS(fp0--);
  457:   
  458:   for(;stack>0;stack--)
  459:     *--sp0=entries[stack-1];
  460: 
  461: #ifdef SYSSIGNALS
  462:   get_winsize();
  463:    
  464:   install_signal_handlers(); /* right place? */
  465:   
  466:   if ((throw_code=setjmp(throw_jmp_buf))) {
  467:     static Cell signal_data_stack[8];
  468:     static Cell signal_return_stack[8];
  469:     static Float signal_fp_stack[1];
  470: 
  471:     signal_data_stack[7]=throw_code;
  472: 
  473: #ifdef GFORTH_DEBUGGING
  474:     /* fprintf(stderr,"\nrp=%ld\n",(long)rp); */
  475:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
  476:       /* no rstack overflow or underflow */
  477:       rp0 = rp;
  478:       *--rp0 = (Cell)saved_ip;
  479:     }
  480:     else /* I love non-syntactic ifdefs :-) */
  481: #endif
  482:     rp0 = signal_return_stack+8;
  483:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
  484:     
  485:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
  486: 		       rp0, signal_fp_stack, 0));
  487:   }
  488: #endif
  489: 
  490:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
  491: }
  492: 
  493: #ifndef INCLUDE_IMAGE
  494: void print_sizes(Cell sizebyte)
  495:      /* print size information */
  496: {
  497:   static char* endianstring[]= { "   big","little" };
  498:   
  499:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
  500: 	  endianstring[sizebyte & 1],
  501: 	  1 << ((sizebyte >> 1) & 3),
  502: 	  1 << ((sizebyte >> 3) & 3),
  503: 	  1 << ((sizebyte >> 5) & 3));
  504: }
  505: 
  506: #define MAX_IMMARGS 2
  507: 
  508: #ifndef NO_DYNAMIC
  509: typedef struct {
  510:   Label start;
  511:   Cell length; /* only includes the jump iff superend is true*/
  512:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
  513:   char superend; /* true if primitive ends superinstruction, i.e.,
  514:                      unconditional branch, execute, etc. */
  515:   Cell nimmargs;
  516:   struct immarg {
  517:     Cell offset; /* offset of immarg within prim */
  518:     char rel;    /* true if immarg is relative */
  519:   } immargs[MAX_IMMARGS];
  520: } PrimInfo;
  521: 
  522: PrimInfo *priminfos;
  523: PrimInfo **decomp_prims;
  524: 
  525: int compare_priminfo_length(PrimInfo **a, PrimInfo **b)
  526: {
  527:   Cell diff = (*a)->length - (*b)->length;
  528:   if (diff)
  529:     return diff;
  530:   else /* break ties by start address; thus the decompiler produces
  531:           the earliest primitive with the same code (e.g. noop instead
  532:           of (char) and @ instead of >code-address */
  533:     return (*b)->start - (*a)->start;
  534: }
  535: 
  536: #endif /* defined(NO_DYNAMIC) */
  537: Cell npriminfos=0;
  538: 
  539: 
  540: void check_prims(Label symbols1[])
  541: {
  542:   int i;
  543:   Label *symbols2, *symbols3, *ends1;
  544:   static char superend[]={
  545: #include "prim_superend.i"
  546:   };
  547: 
  548:   if (debug)
  549: #ifdef __VERSION__
  550:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
  551: #else
  552: #define xstr(s) str(s)
  553: #define str(s) #s
  554:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
  555: #endif
  556:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
  557:     ;
  558:   npriminfos = i;
  559:   
  560: #ifndef NO_DYNAMIC
  561:   if (no_dynamic)
  562:     return;
  563:   symbols2=engine2(0,0,0,0,0);
  564: #if NO_IP
  565:   symbols3=engine3(0,0,0,0,0);
  566: #else
  567:   symbols3=symbols1;
  568: #endif
  569:   ends1 = symbols1+i+1-DOESJUMP;
  570:   priminfos = calloc(i,sizeof(PrimInfo));
  571:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
  572:     int prim_len = ends1[i]-symbols1[i];
  573:     PrimInfo *pi=&priminfos[i];
  574:     int j=0;
  575:     char *s1 = (char *)symbols1[i];
  576:     char *s2 = (char *)symbols2[i];
  577:     char *s3 = (char *)symbols3[i];
  578: 
  579:     pi->start = s1;
  580:     pi->superend = superend[i-DOESJUMP-1]|no_super;
  581:     if (pi->superend)
  582:       pi->length = symbols1[i+1]-symbols1[i];
  583:     else
  584:       pi->length = prim_len;
  585:     pi->restlength = symbols1[i+1] - symbols1[i] - pi->length;
  586:     pi->nimmargs = 0;
  587:     if (debug)
  588:       fprintf(stderr, "Prim %3d @ %p %p %p, length=%3d restlength=%2d superend=%1d",
  589: 	      i, s1, s2, s3, pi->length, pi->restlength, pi->superend);
  590:     assert(prim_len>=0);
  591:     while (j<(pi->length+pi->restlength)) {
  592:       if (s1[j]==s3[j]) {
  593: 	if (s1[j] != s2[j]) {
  594: 	  pi->start = NULL; /* not relocatable */
  595: 	  if (debug)
  596: 	    fprintf(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
  597: 	  /* assert(j<prim_len); */
  598: 	  break;
  599: 	}
  600: 	j++;
  601:       } else {
  602: 	struct immarg *ia=&pi->immargs[pi->nimmargs];
  603: 
  604: 	pi->nimmargs++;
  605: 	ia->offset=j;
  606: 	if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
  607: 	  ia->rel=0;
  608: 	  if (debug)
  609: 	    fprintf(stderr,"\n   absolute immarg: offset %3d",j);
  610: 	} else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
  611: 		   symbols1[DOESJUMP+1]) {
  612: 	  ia->rel=1;
  613: 	  if (debug)
  614: 	    fprintf(stderr,"\n   relative immarg: offset %3d",j);
  615: 	} else {
  616: 	  pi->start = NULL; /* not relocatable */
  617: 	  if (debug)
  618: 	    fprintf(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
  619: 	  /* assert(j<prim_len);*/
  620: 	  break;
  621: 	}
  622: 	j+=4;
  623:       }
  624:     }
  625:     if (debug)
  626:       fprintf(stderr,"\n");
  627:   }
  628:   decomp_prims = calloc(i,sizeof(PrimInfo *));
  629:   for (i=DOESJUMP+1; i<npriminfos; i++)
  630:     decomp_prims[i] = &(priminfos[i]);
  631:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
  632: 	compare_priminfo_length);
  633: #endif
  634: }
  635: 
  636: #ifndef NO_DYNAMIC
  637: void flush_to_here(void)
  638: {
  639:   FLUSH_ICACHE(start_flush, code_here-start_flush);
  640:   start_flush=code_here;
  641: }
  642: 
  643: void append_jump(void)
  644: {
  645:   if (last_jump) {
  646:     PrimInfo *pi = &priminfos[last_jump];
  647:     
  648:     memcpy(code_here, pi->start+pi->length, pi->restlength);
  649:     code_here += pi->restlength;
  650:     last_jump=0;
  651:     flush_to_here();
  652:   }
  653: }
  654: 
  655: /* Gforth remembers all code blocks in this list.  On forgetting (by
  656: executing a marker) the code blocks are not freed (because Gforth does
  657: not remember how they were allocated; hmm, remembering that might be
  658: easier and cleaner).  Instead, code_here etc. are reset to the old
  659: value, and the "forgotten" code blocks are reused when they are
  660: needed. */
  661: 
  662: struct code_block_list {
  663:   struct code_block_list *next;
  664:   Address block;
  665:   Cell size;
  666: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
  667: 
  668: Address append_prim(Cell p)
  669: {
  670:   PrimInfo *pi = &priminfos[p];
  671:   Address old_code_here = code_here;
  672: 
  673:   if (code_area+code_area_size < code_here+pi->length+pi->restlength) {
  674:     struct code_block_list *p;
  675:     append_jump();
  676:     if (*next_code_blockp == NULL) {
  677:       code_here = start_flush = code_area = my_alloc(code_area_size);
  678:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
  679:       *next_code_blockp = p;
  680:       p->next = NULL;
  681:       p->block = code_here;
  682:       p->size = code_area_size;
  683:     } else {
  684:       p = *next_code_blockp;
  685:       code_here = start_flush = code_area = p->block;
  686:     }
  687:     old_code_here = code_here;
  688:     next_code_blockp = &(p->next);
  689:   }
  690:   memcpy(code_here, pi->start, pi->length);
  691:   code_here += pi->length;
  692:   if (pi->superend)
  693:     flush_to_here();
  694:   return old_code_here;
  695: }
  696: #endif
  697: 
  698: int forget_dyncode(Address code)
  699: {
  700: #ifdef NO_DYNAMIC
  701:   return -1;
  702: #else
  703:   struct code_block_list *p, **pp;
  704: 
  705:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
  706:     if (code >= p->block && code < p->block+p->size) {
  707:       next_code_blockp = &(p->next);
  708:       code_here = start_flush = code;
  709:       code_area = p->block;
  710:       last_jump = 0;
  711:       return -1;
  712:     }
  713:   }
  714:   return -no_dynamic;
  715: #endif /* !defined(NO_DYNAMIC) */
  716: }
  717: 
  718: Label decompile_code(Label code)
  719: {
  720: #ifdef NO_DYNAMIC
  721:   return code;
  722: #else /* !defined(NO_DYNAMIC) */
  723:   Cell i;
  724:   struct code_block_list *p;
  725: 
  726:   /* first, check if we are in code at all */
  727:   for (p = code_block_list;; p = p->next) {
  728:     if (p == NULL)
  729:       return code;
  730:     if (code >= p->block && code < p->block+p->size)
  731:       break;
  732:   }
  733:   /* reverse order because NOOP might match other prims */
  734:   for (i=npriminfos-1; i>DOESJUMP; i--) {
  735:     PrimInfo *pi=decomp_prims[i];
  736:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
  737:       return pi->start;
  738:   }
  739:   return code;
  740: #endif /* !defined(NO_DYNAMIC) */
  741: }
  742: 
  743: #ifdef NO_IP
  744: int nbranchinfos=0;
  745: 
  746: struct branchinfo {
  747:   Label *targetptr; /* *(bi->targetptr) is the target */
  748:   Cell *addressptr; /* store the target here */
  749: } branchinfos[100000];
  750: 
  751: int ndoesexecinfos=0;
  752: struct doesexecinfo {
  753:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
  754:   Cell *xt; /* cfa of word whose does-code needs calling */
  755: } doesexecinfos[10000];
  756: 
  757: /* definitions of N_execute etc. */
  758: #include "prim_num.i"
  759: 
  760: void set_rel_target(Cell *source, Label target)
  761: {
  762:   *source = ((Cell)target)-(((Cell)source)+4);
  763: }
  764: 
  765: void register_branchinfo(Label source, Cell targetptr)
  766: {
  767:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
  768:   bi->targetptr = (Label *)targetptr;
  769:   bi->addressptr = (Cell *)source;
  770:   nbranchinfos++;
  771: }
  772: 
  773: Cell *compile_prim1arg(Cell p)
  774: {
  775:   int l = priminfos[p].length;
  776:   Address old_code_here=code_here;
  777: 
  778:   assert(vm_prims[p]==priminfos[p].start);
  779:   append_prim(p);
  780:   return (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
  781: }
  782: 
  783: Cell *compile_call2(Cell targetptr)
  784: {
  785:   Cell *next_code_target;
  786:   PrimInfo *pi = &priminfos[N_call2];
  787:   Address old_code_here = append_prim(N_call2);
  788: 
  789:   next_code_target = (Cell *)(old_code_here + pi->immargs[0].offset);
  790:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetptr);
  791:   return next_code_target;
  792: }
  793: #endif
  794: 
  795: void finish_code(void)
  796: {
  797: #ifdef NO_IP
  798:   Cell i;
  799: 
  800:   compile_prim1(NULL);
  801:   for (i=0; i<ndoesexecinfos; i++) {
  802:     struct doesexecinfo *dei = &doesexecinfos[i];
  803:     branchinfos[dei->branchinfo].targetptr = DOES_CODE1((dei->xt));
  804:   }
  805:   ndoesexecinfos = 0;
  806:   for (i=0; i<nbranchinfos; i++) {
  807:     struct branchinfo *bi=&branchinfos[i];
  808:     set_rel_target(bi->addressptr, *(bi->targetptr));
  809:   }
  810:   nbranchinfos = 0;
  811:   FLUSH_ICACHE(start_flush, code_here-start_flush);
  812:   start_flush=code_here;
  813: #endif
  814: }
  815: 
  816: void compile_prim1(Cell *start)
  817: {
  818: #if defined(DOUBLY_INDIRECT)
  819:   Label prim=(Label)*start;
  820:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
  821:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
  822:     *start=(Cell)prim;
  823:     return;
  824:   } else {
  825:     *start = prim-((Label)xts)+((Label)vm_prims);
  826:     return;
  827:   }
  828: #elif defined(NO_IP)
  829:   static Cell *last_start=NULL;
  830:   static Xt last_prim=NULL;
  831:   /* delay work by one call in order to get relocated immargs */
  832: 
  833:   if (last_start) {
  834:     unsigned i = last_prim-vm_prims;
  835:     PrimInfo *pi=&priminfos[i];
  836:     Cell *next_code_target=NULL;
  837: 
  838:     assert(i<npriminfos);
  839:     if (i==N_execute||i==N_perform||i==N_lit_perform) {
  840:       next_code_target = compile_prim1arg(N_set_next_code);
  841:     }
  842:     if (i==N_call) {
  843:       next_code_target = compile_call2(last_start[1]);
  844:     } else if (i==N_does_exec) {
  845:       struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
  846:       *compile_prim1arg(N_lit) = (Cell)PFA(last_start[1]);
  847:       /* we cannot determine the callee now (last_start[1] may be a
  848:          forward reference), so just register an arbitrary target, and
  849:          register in dei that we need to fix this before resolving
  850:          branches */
  851:       dei->branchinfo = nbranchinfos;
  852:       dei->xt = (Cell *)(last_start[1]);
  853:       next_code_target = compile_call2(NULL);
  854:     } else if (pi->start == NULL) { /* non-reloc */
  855:       next_code_target = compile_prim1arg(N_set_next_code);
  856:       set_rel_target(compile_prim1arg(N_abranch),*(Xt)last_prim);
  857:     } else {
  858:       unsigned j;
  859:       Address old_code_here = append_prim(i);
  860: 
  861:       for (j=0; j<pi->nimmargs; j++) {
  862: 	struct immarg *ia = &(pi->immargs[j]);
  863: 	Cell argval = last_start[pi->nimmargs - j]; /* !! specific to prims */
  864: 	if (ia->rel) { /* !! assumption: relative refs are branches */
  865: 	  register_branchinfo(old_code_here + ia->offset, argval);
  866: 	} else /* plain argument */
  867: 	  *(Cell *)(old_code_here + ia->offset) = argval;
  868:       }
  869:     }
  870:     if (next_code_target!=NULL)
  871:       *next_code_target = (Cell)code_here;
  872:   }
  873:   if (start) {
  874:     last_prim = (Xt)*start;
  875:     *start = (Cell)code_here;
  876:   }
  877:   last_start = start;
  878:   return;
  879: #elif !defined(NO_DYNAMIC)
  880:   Label prim=(Label)*start;
  881:   unsigned i;
  882:   Address old_code_here;
  883: 
  884:   i = ((Xt)prim)-vm_prims;
  885:   prim = *(Xt)prim;
  886:   if (no_dynamic) {
  887:     *start = (Cell)prim;
  888:     return;
  889:   }
  890:   if (i>=npriminfos || priminfos[i].start == 0) { /* not a relocatable prim */
  891:     append_jump();
  892:     *start = (Cell)prim;
  893:     return;
  894:   }
  895:   assert(priminfos[i].start = prim); 
  896: #ifdef ALIGN_CODE
  897:   /*  ALIGN_CODE;*/
  898: #endif
  899:   assert(prim==priminfos[i].start);
  900:   old_code_here = append_prim(i);
  901:   last_jump = (priminfos[i].superend) ? 0 : i;
  902:   *start = (Cell)old_code_here;
  903:   return;
  904: #else /* !defined(DOUBLY_INDIRECT), no code replication */
  905:   Label prim=(Label)*start;
  906: #if !defined(INDIRECT_THREADED)
  907:   prim = *(Xt)prim;
  908: #endif
  909:   *start = (Cell)prim;
  910:   return;
  911: #endif /* !defined(DOUBLY_INDIRECT) */
  912: }
  913: 
  914: Label compile_prim(Label prim)
  915: {
  916:   Cell x=(Cell)prim;
  917:   assert(0);
  918:   compile_prim1(&x);
  919:   return (Label)x;
  920: }
  921: 
  922: #if defined(PRINT_SUPER_LENGTHS) && !defined(NO_DYNAMIC)
  923: Cell prim_length(Cell prim)
  924: {
  925:   return priminfos[prim+DOESJUMP+1].length;
  926: }
  927: #endif
  928: 
  929: Address loader(FILE *imagefile, char* filename)
  930: /* returns the address of the image proper (after the preamble) */
  931: {
  932:   ImageHeader header;
  933:   Address image;
  934:   Address imp; /* image+preamble */
  935:   Char magic[8];
  936:   char magic7; /* size byte of magic number */
  937:   Cell preamblesize=0;
  938:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
  939:   UCell check_sum;
  940:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
  941: 		 (RELINFOBITS == 16) ? 1 :
  942: 		 (RELINFOBITS == 32) ? 2 : 3);
  943:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
  944: 		   (sizeof(Char) == 2) ? 1 :
  945: 		   (sizeof(Char) == 4) ? 2 : 3) + ausize;
  946:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
  947: 		   (sizeof(Cell) == 2) ? 1 :
  948: 		   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
  949:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
  950: #ifdef WORDS_BIGENDIAN
  951:        0
  952: #else
  953:        1
  954: #endif
  955:     ;
  956: 
  957:   vm_prims = engine(0,0,0,0,0);
  958:   check_prims(vm_prims);
  959: #ifndef DOUBLY_INDIRECT
  960: #ifdef PRINT_SUPER_LENGTHS
  961:   print_super_lengths();
  962: #endif
  963:   check_sum = checksum(vm_prims);
  964: #else /* defined(DOUBLY_INDIRECT) */
  965:   check_sum = (UCell)vm_prims;
  966: #endif /* defined(DOUBLY_INDIRECT) */
  967:   
  968:   do {
  969:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
  970:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
  971: 	      progname, filename);
  972:       exit(1);
  973:     }
  974:     preamblesize+=8;
  975:   } while(memcmp(magic,"Gforth3",7));
  976:   magic7 = magic[7];
  977:   if (debug) {
  978:     magic[7]='\0';
  979:     fprintf(stderr,"Magic found: %s ", magic);
  980:     print_sizes(magic7);
  981:   }
  982: 
  983:   if (magic7 != sizebyte)
  984:     {
  985:       fprintf(stderr,"This image is:         ");
  986:       print_sizes(magic7);
  987:       fprintf(stderr,"whereas the machine is ");
  988:       print_sizes(sizebyte);
  989:       exit(-2);
  990:     };
  991: 
  992:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
  993: 
  994:   set_stack_sizes(&header);
  995:   
  996: #if HAVE_GETPAGESIZE
  997:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
  998: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
  999:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
 1000: #elif PAGESIZE
 1001:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
 1002: #endif
 1003:   if (debug)
 1004:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
 1005: 
 1006:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
 1007: 			  preamblesize+dictsize, data_offset);
 1008:   imp=image+preamblesize;
 1009:   alloc_stacks((ImageHeader *)imp);
 1010:   if (clear_dictionary)
 1011:     memset(imp+header.image_size, 0, dictsize-header.image_size);
 1012:   if(header.base==0 || header.base  == 0x100) {
 1013:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
 1014:     char reloc_bits[reloc_size];
 1015:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
 1016:     fread(reloc_bits, 1, reloc_size, imagefile);
 1017:     relocate((Cell *)imp, reloc_bits, header.image_size, header.base, vm_prims);
 1018: #if 0
 1019:     { /* let's see what the relocator did */
 1020:       FILE *snapshot=fopen("snapshot.fi","wb");
 1021:       fwrite(image,1,imagesize,snapshot);
 1022:       fclose(snapshot);
 1023:     }
 1024: #endif
 1025:   }
 1026:   else if(header.base!=imp) {
 1027:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
 1028: 	    progname, (unsigned long)header.base, (unsigned long)imp);
 1029:     exit(1);
 1030:   }
 1031:   if (header.checksum==0)
 1032:     ((ImageHeader *)imp)->checksum=check_sum;
 1033:   else if (header.checksum != check_sum) {
 1034:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
 1035: 	    progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
 1036:     exit(1);
 1037:   }
 1038: #ifdef DOUBLY_INDIRECT
 1039:   ((ImageHeader *)imp)->xt_base = xts;
 1040: #endif
 1041:   fclose(imagefile);
 1042: 
 1043:   /* unnecessary, except maybe for CODE words */
 1044:   /* FLUSH_ICACHE(imp, header.image_size);*/
 1045: 
 1046:   return imp;
 1047: }
 1048: 
 1049: /* pointer to last '/' or '\' in file, 0 if there is none. */
 1050: char *onlypath(char *filename)
 1051: {
 1052:   return strrchr(filename, DIRSEP);
 1053: }
 1054: 
 1055: FILE *openimage(char *fullfilename)
 1056: {
 1057:   FILE *image_file;
 1058:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
 1059: 
 1060:   image_file=fopen(expfilename,"rb");
 1061:   if (image_file!=NULL && debug)
 1062:     fprintf(stderr, "Opened image file: %s\n", expfilename);
 1063:   return image_file;
 1064: }
 1065: 
 1066: /* try to open image file concat(path[0:len],imagename) */
 1067: FILE *checkimage(char *path, int len, char *imagename)
 1068: {
 1069:   int dirlen=len;
 1070:   char fullfilename[dirlen+strlen(imagename)+2];
 1071: 
 1072:   memcpy(fullfilename, path, dirlen);
 1073:   if (fullfilename[dirlen-1]!=DIRSEP)
 1074:     fullfilename[dirlen++]=DIRSEP;
 1075:   strcpy(fullfilename+dirlen,imagename);
 1076:   return openimage(fullfilename);
 1077: }
 1078: 
 1079: FILE * open_image_file(char * imagename, char * path)
 1080: {
 1081:   FILE * image_file=NULL;
 1082:   char *origpath=path;
 1083:   
 1084:   if(strchr(imagename, DIRSEP)==NULL) {
 1085:     /* first check the directory where the exe file is in !! 01may97jaw */
 1086:     if (onlypath(progname))
 1087:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
 1088:     if (!image_file)
 1089:       do {
 1090: 	char *pend=strchr(path, PATHSEP);
 1091: 	if (pend==NULL)
 1092: 	  pend=path+strlen(path);
 1093: 	if (strlen(path)==0) break;
 1094: 	image_file=checkimage(path, pend-path, imagename);
 1095: 	path=pend+(*pend==PATHSEP);
 1096:       } while (image_file==NULL);
 1097:   } else {
 1098:     image_file=openimage(imagename);
 1099:   }
 1100: 
 1101:   if (!image_file) {
 1102:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
 1103: 	    progname, imagename, origpath);
 1104:     exit(1);
 1105:   }
 1106: 
 1107:   return image_file;
 1108: }
 1109: #endif
 1110: 
 1111: #ifdef HAS_OS
 1112: UCell convsize(char *s, UCell elemsize)
 1113: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
 1114:    of bytes.  the letter at the end indicates the unit, where e stands
 1115:    for the element size. default is e */
 1116: {
 1117:   char *endp;
 1118:   UCell n,m;
 1119: 
 1120:   m = elemsize;
 1121:   n = strtoul(s,&endp,0);
 1122:   if (endp!=NULL) {
 1123:     if (strcmp(endp,"b")==0)
 1124:       m=1;
 1125:     else if (strcmp(endp,"k")==0)
 1126:       m=1024;
 1127:     else if (strcmp(endp,"M")==0)
 1128:       m=1024*1024;
 1129:     else if (strcmp(endp,"G")==0)
 1130:       m=1024*1024*1024;
 1131:     else if (strcmp(endp,"T")==0) {
 1132: #if (SIZEOF_CHAR_P > 4)
 1133:       m=1024L*1024*1024*1024;
 1134: #else
 1135:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
 1136:       exit(1);
 1137: #endif
 1138:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
 1139:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
 1140:       exit(1);
 1141:     }
 1142:   }
 1143:   return n*m;
 1144: }
 1145: 
 1146: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
 1147: {
 1148:   int c;
 1149: 
 1150:   opterr=0;
 1151:   while (1) {
 1152:     int option_index=0;
 1153:     static struct option opts[] = {
 1154:       {"appl-image", required_argument, NULL, 'a'},
 1155:       {"image-file", required_argument, NULL, 'i'},
 1156:       {"dictionary-size", required_argument, NULL, 'm'},
 1157:       {"data-stack-size", required_argument, NULL, 'd'},
 1158:       {"return-stack-size", required_argument, NULL, 'r'},
 1159:       {"fp-stack-size", required_argument, NULL, 'f'},
 1160:       {"locals-stack-size", required_argument, NULL, 'l'},
 1161:       {"path", required_argument, NULL, 'p'},
 1162:       {"version", no_argument, NULL, 'v'},
 1163:       {"help", no_argument, NULL, 'h'},
 1164:       /* put something != 0 into offset_image */
 1165:       {"offset-image", no_argument, &offset_image, 1},
 1166:       {"no-offset-im", no_argument, &offset_image, 0},
 1167:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
 1168:       {"die-on-signal", no_argument, &die_on_signal, 1},
 1169:       {"debug", no_argument, &debug, 1},
 1170:       {"no-super", no_argument, &no_super, 1},
 1171:       {"no-dynamic", no_argument, &no_dynamic, 1},
 1172:       {"dynamic", no_argument, &no_dynamic, 0},
 1173:       {0,0,0,0}
 1174:       /* no-init-file, no-rc? */
 1175:     };
 1176:     
 1177:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
 1178:     
 1179:     switch (c) {
 1180:     case EOF: return;
 1181:     case '?': optind--; return;
 1182:     case 'a': *imagename = optarg; return;
 1183:     case 'i': *imagename = optarg; break;
 1184:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
 1185:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
 1186:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
 1187:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
 1188:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
 1189:     case 'p': *path = optarg; break;
 1190:     case 'o': offset_image = 1; break;
 1191:     case 'n': offset_image = 0; break;
 1192:     case 'c': clear_dictionary = 1; break;
 1193:     case 's': die_on_signal = 1; break;
 1194:     case 'x': debug = 1; break;
 1195:     case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
 1196:     case 'h': 
 1197:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
 1198: Engine Options:\n\
 1199:   --appl-image FILE		    equivalent to '--image-file=FILE --'\n\
 1200:   --clear-dictionary		    Initialize the dictionary with 0 bytes\n\
 1201:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
 1202:   --debug			    Print debugging information during startup\n\
 1203:   --die-on-signal		    exit instead of CATCHing some signals\n\
 1204:   --dynamic			    use dynamic native code\n\
 1205:   -f SIZE, --fp-stack-size=SIZE	    Specify floating point stack size\n\
 1206:   -h, --help			    Print this message and exit\n\
 1207:   -i FILE, --image-file=FILE	    Use image FILE instead of `gforth.fi'\n\
 1208:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
 1209:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
 1210:   --no-dynamic			    Use only statically compiled primitives\n\
 1211:   --no-offset-im		    Load image at normal position\n\
 1212:   --no-super                        No dynamically formed superinstructions\n\
 1213:   --offset-image		    Load image at a different position\n\
 1214:   -p PATH, --path=PATH		    Search path for finding image and sources\n\
 1215:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
 1216:   -v, --version			    Print engine version and exit\n\
 1217: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
 1218:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
 1219: 	      argv[0]);
 1220:       optind--;
 1221:       return;
 1222:     }
 1223:   }
 1224: }
 1225: #endif
 1226: 
 1227: #ifdef INCLUDE_IMAGE
 1228: extern Cell image[];
 1229: extern const char reloc_bits[];
 1230: #endif
 1231: 
 1232: int main(int argc, char **argv, char **env)
 1233: {
 1234: #ifdef HAS_OS
 1235:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
 1236: #else
 1237:   char *path = DEFAULTPATH;
 1238: #endif
 1239: #ifndef INCLUDE_IMAGE
 1240:   char *imagename="gforth.fi";
 1241:   FILE *image_file;
 1242:   Address image;
 1243: #endif
 1244:   int retvalue;
 1245: 	  
 1246: #if defined(i386) && defined(ALIGNMENT_CHECK)
 1247:   /* turn on alignment checks on the 486.
 1248:    * on the 386 this should have no effect. */
 1249:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
 1250:   /* this is unusable with Linux' libc.4.6.27, because this library is
 1251:      not alignment-clean; we would have to replace some library
 1252:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
 1253:      the stack FP-aligned. */
 1254: #endif
 1255: 
 1256:   /* buffering of the user output device */
 1257: #ifdef _IONBF
 1258:   if (isatty(fileno(stdout))) {
 1259:     fflush(stdout);
 1260:     setvbuf(stdout,NULL,_IONBF,0);
 1261:   }
 1262: #endif
 1263: 
 1264:   progname = argv[0];
 1265: 
 1266: #ifdef HAS_OS
 1267:   gforth_args(argc, argv, &path, &imagename);
 1268: #endif
 1269: 
 1270: #ifdef INCLUDE_IMAGE
 1271:   set_stack_sizes((ImageHeader *)image);
 1272:   if(((ImageHeader *)image)->base != image)
 1273:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
 1274: 	     (Label*)engine(0, 0, 0, 0, 0));
 1275:   alloc_stacks((ImageHeader *)image);
 1276: #else
 1277:   image_file = open_image_file(imagename, path);
 1278:   image = loader(image_file, imagename);
 1279: #endif
 1280:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
 1281: 
 1282:   {
 1283:     char path2[strlen(path)+1];
 1284:     char *p1, *p2;
 1285:     Cell environ[]= {
 1286:       (Cell)argc-(optind-1),
 1287:       (Cell)(argv+(optind-1)),
 1288:       (Cell)strlen(path),
 1289:       (Cell)path2};
 1290:     argv[optind-1] = progname;
 1291:     /*
 1292:        for (i=0; i<environ[0]; i++)
 1293:        printf("%s\n", ((char **)(environ[1]))[i]);
 1294:        */
 1295:     /* make path OS-independent by replacing path separators with NUL */
 1296:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
 1297:       if (*p1==PATHSEP)
 1298: 	*p2 = '\0';
 1299:       else
 1300: 	*p2 = *p1;
 1301:     *p2='\0';
 1302:     retvalue = go_forth(image, 4, environ);
 1303: #ifdef VM_PROFILING
 1304:     vm_print_profile(stderr);
 1305: #endif
 1306:     deprep_terminal();
 1307:   }
 1308:   return retvalue;
 1309: }

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