File:  [gforth] / gforth / engine / main.c
Revision 1.103: download - view: text, annotated - select for diffs
Sun Mar 9 15:17:03 2003 UTC (21 years, 1 month ago) by anton
Branches: MAIN
CVS tags: v0-6-1, v0-6-0, HEAD
updated copyright years

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

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