File:  [gforth] / gforth / engine / main.c
Revision 1.104: download - view: text, annotated - select for diffs
Sun May 4 08:55:32 2003 UTC (20 years, 11 months ago) by anton
Branches: MAIN
CVS tags: HEAD
added --print-codesize option

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

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