File:  [gforth] / gforth / engine / main.c
Revision 1.178: download - view: text, annotated - select for diffs
Mon Apr 9 22:36:01 2007 UTC (17 years ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Some stuff to get closer to run Gforth on NXT

    1: /* command line interpretation, image loading etc. for Gforth
    2: 
    3: 
    4:   Copyright (C) 1995,1996,1997,1998,2000,2003,2004,2005,2006 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: typedef enum prim_num {
   51: /* definitions of N_execute etc. */
   52: #include PRIM_NUM_I
   53:   N_START_SUPER
   54: } PrimNum;
   55: 
   56: /* global variables for engine.c 
   57:    We put them here because engine.c is compiled several times in
   58:    different ways for the same engine. */
   59: Cell *gforth_SP;
   60: Float *gforth_FP;
   61: Address gforth_UP=NULL;
   62: 
   63: #ifdef HAS_FFCALL
   64: Cell *gforth_RP;
   65: Address gforth_LP;
   66: 
   67: #include <callback.h>
   68: 
   69: va_alist gforth_clist;
   70: 
   71: void gforth_callback(Xt* fcall, void * alist)
   72: {
   73:   /* save global valiables */
   74:   Cell *rp = gforth_RP;
   75:   Cell *sp = gforth_SP;
   76:   Float *fp = gforth_FP;
   77:   Address lp = gforth_LP;
   78:   va_alist clist = gforth_clist;
   79: 
   80:   gforth_clist = (va_alist)alist;
   81: 
   82:   gforth_engine(fcall, sp, rp, fp, lp);
   83: 
   84:   /* restore global variables */
   85:   gforth_RP = rp;
   86:   gforth_SP = sp;
   87:   gforth_FP = fp;
   88:   gforth_LP = lp;
   89:   gforth_clist = clist;
   90: }
   91: #endif
   92: 
   93: #ifdef HAS_LIBFFI
   94: Cell *gforth_RP;
   95: Address gforth_LP;
   96: 
   97: #include <ffi.h>
   98: 
   99: void ** gforth_clist;
  100: void * gforth_ritem;
  101: 
  102: void gforth_callback(ffi_cif * cif, void * resp, void ** args, void * ip)
  103: {
  104:   Cell *rp = gforth_RP;
  105:   Cell *sp = gforth_SP;
  106:   Float *fp = gforth_FP;
  107:   Address lp = gforth_LP;
  108:   void ** clist = gforth_clist;
  109:   void * ritem = gforth_ritem;
  110: 
  111:   gforth_clist = args;
  112:   gforth_ritem = resp;
  113: 
  114:   gforth_engine((Xt *)ip, sp, rp, fp, lp);
  115: 
  116:   /* restore global variables */
  117:   gforth_RP = rp;
  118:   gforth_SP = sp;
  119:   gforth_FP = fp;
  120:   gforth_LP = lp;
  121:   gforth_clist = clist;
  122:   gforth_ritem = ritem;
  123: }
  124: #endif
  125: 
  126: #ifdef GFORTH_DEBUGGING
  127: /* define some VM registers as global variables, so they survive exceptions;
  128:    global register variables are not up to the task (according to the 
  129:    GNU C manual) */
  130: Xt *saved_ip;
  131: Cell *rp;
  132: #endif
  133: 
  134: #ifdef NO_IP
  135: Label next_code;
  136: #endif
  137: 
  138: #ifdef HAS_FILE
  139: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
  140: char* pfileattr[6]={"r","r","r+","r+","w","w"};
  141: 
  142: #ifndef O_BINARY
  143: #define O_BINARY 0
  144: #endif
  145: #ifndef O_TEXT
  146: #define O_TEXT 0
  147: #endif
  148: 
  149: int ufileattr[6]= {
  150:   O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
  151:   O_RDWR  |O_BINARY, O_RDWR  |O_BINARY,
  152:   O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
  153: #endif
  154: /* end global vars for engine.c */
  155: 
  156: #define PRIM_VERSION 1
  157: /* increment this whenever the primitives change in an incompatible way */
  158: 
  159: #ifndef DEFAULTPATH
  160: #  define DEFAULTPATH "."
  161: #endif
  162: 
  163: #ifdef MSDOS
  164: jmp_buf throw_jmp_buf;
  165: #endif
  166: 
  167: #if defined(DOUBLY_INDIRECT)
  168: #  define CFA(n)	({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
  169: #else
  170: #  define CFA(n)	((Cell)(symbols+((n)&~0x4000UL)))
  171: #endif
  172: 
  173: #define maxaligned(n)	(typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
  174: 
  175: static UCell dictsize=0;
  176: static UCell dsize=0;
  177: static UCell rsize=0;
  178: static UCell fsize=0;
  179: static UCell lsize=0;
  180: int offset_image=0;
  181: int die_on_signal=0;
  182: int ignore_async_signals=0;
  183: #ifndef INCLUDE_IMAGE
  184: static int clear_dictionary=0;
  185: UCell pagesize=1;
  186: char *progname;
  187: #else
  188: char *progname = "gforth";
  189: int optind = 1;
  190: #endif
  191: 
  192: #define CODE_BLOCK_SIZE (512*1024) /* !! overflow handling for -native */
  193: Address code_area=0;
  194: Cell code_area_size = CODE_BLOCK_SIZE;
  195: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
  196: 					   does for the dictionary */
  197: Address start_flush=NULL; /* start of unflushed code */
  198: Cell last_jump=0; /* if the last prim was compiled without jump, this
  199:                      is it's number, otherwise this contains 0 */
  200: 
  201: static int no_super=0;   /* true if compile_prim should not fuse prims */
  202: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
  203: 					     dynamically */
  204: static int print_metrics=0; /* if true, print metrics on exit */
  205: static int static_super_number = 0; /* number of ss used if available */
  206:                                     /* disabled because of tpa */
  207: #define MAX_STATE 9 /* maximum number of states */
  208: static int maxstates = MAX_STATE; /* number of states for stack caching */
  209: static int ss_greedy = 0; /* if true: use greedy, not optimal ss selection */
  210: static int diag = 0; /* if true: print diagnostic informations */
  211: static int tpa_noequiv = 0;     /* if true: no state equivalence checking */
  212: static int tpa_noautomaton = 0; /* if true: no tree parsing automaton */
  213: static int tpa_trace = 0; /* if true: data for line graph of new states etc. */
  214: static int relocs = 0;
  215: static int nonrelocs = 0;
  216: 
  217: #ifdef HAS_DEBUG
  218: int debug=0;
  219: # define debugp(x...) if (debug) fprintf(x);
  220: #else
  221: # define perror(x...)
  222: # define fprintf(x...)
  223: # define debugp(x...)
  224: #endif
  225: 
  226: ImageHeader *gforth_header;
  227: Label *vm_prims;
  228: #ifdef DOUBLY_INDIRECT
  229: Label *xts; /* same content as vm_prims, but should only be used for xts */
  230: #endif
  231: 
  232: #ifndef NO_DYNAMIC
  233: #define MAX_IMMARGS 2
  234: 
  235: typedef struct {
  236:   Label start; /* NULL if not relocatable */
  237:   Cell length; /* only includes the jump iff superend is true*/
  238:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
  239:   char superend; /* true if primitive ends superinstruction, i.e.,
  240:                      unconditional branch, execute, etc. */
  241:   Cell nimmargs;
  242:   struct immarg {
  243:     Cell offset; /* offset of immarg within prim */
  244:     char rel;    /* true if immarg is relative */
  245:   } immargs[MAX_IMMARGS];
  246: } PrimInfo;
  247: 
  248: PrimInfo *priminfos;
  249: PrimInfo **decomp_prims;
  250: 
  251: const char const* const prim_names[]={
  252: #include PRIM_NAMES_I
  253: };
  254: 
  255: void init_ss_cost(void);
  256: 
  257: static int is_relocatable(int p)
  258: {
  259:   return !no_dynamic && priminfos[p].start != NULL;
  260: }
  261: #else /* defined(NO_DYNAMIC) */
  262: static int is_relocatable(int p)
  263: {
  264:   return 0;
  265: }
  266: #endif /* defined(NO_DYNAMIC) */
  267: 
  268: #ifdef MEMCMP_AS_SUBROUTINE
  269: int gforth_memcmp(const char * s1, const char * s2, size_t n)
  270: {
  271:   return memcmp(s1, s2, n);
  272: }
  273: #endif
  274: 
  275: static Cell max(Cell a, Cell b)
  276: {
  277:   return a>b?a:b;
  278: }
  279: 
  280: static Cell min(Cell a, Cell b)
  281: {
  282:   return a<b?a:b;
  283: }
  284: 
  285: #ifndef STANDALONE
  286: /* image file format:
  287:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
  288:  *   padding to a multiple of 8
  289:  *   magic: "Gforth3x" means format 0.6,
  290:  *              where x is a byte with
  291:  *              bit 7:   reserved = 0
  292:  *              bit 6:5: address unit size 2^n octets
  293:  *              bit 4:3: character size 2^n octets
  294:  *              bit 2:1: cell size 2^n octets
  295:  *              bit 0:   endian, big=0, little=1.
  296:  *  The magic are always 8 octets, no matter what the native AU/character size is
  297:  *  padding to max alignment (no padding necessary on current machines)
  298:  *  ImageHeader structure (see forth.h)
  299:  *  data (size in ImageHeader.image_size)
  300:  *  tags ((if relocatable, 1 bit/data cell)
  301:  *
  302:  * tag==1 means that the corresponding word is an address;
  303:  * If the word is >=0, the address is within the image;
  304:  * addresses within the image are given relative to the start of the image.
  305:  * If the word =-1 (CF_NIL), the address is NIL,
  306:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
  307:  * If the word =CF(DODOES), it's a DOES> CFA
  308:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
  309:  *					possibly containing a jump to dodoes)
  310:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
  311:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
  312:  *                                        it's the threaded code of a primitive
  313:  * bits 13..9 of a primitive token state which group the primitive belongs to,
  314:  * bits 8..0 of a primitive token index into the group
  315:  */
  316: 
  317: Cell groups[32] = {
  318:   0,
  319:   0
  320: #undef GROUP
  321: #undef GROUPADD
  322: #define GROUPADD(n) +n
  323: #define GROUP(x, n) , 0
  324: #include PRIM_GRP_I
  325: #undef GROUP
  326: #undef GROUPADD
  327: #define GROUP(x, n)
  328: #define GROUPADD(n)
  329: };
  330: 
  331: static unsigned char *branch_targets(Cell *image, const unsigned char *bitstring,
  332: 			      int size, Cell base)
  333:      /* produce a bitmask marking all the branch targets */
  334: {
  335:   int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
  336:   Cell token;
  337:   unsigned char bits;
  338:   unsigned char *result=malloc(steps);
  339: 
  340:   memset(result, 0, steps);
  341:   for(k=0; k<steps; k++) {
  342:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  343:       if(bits & (1U << (RELINFOBITS-1))) {
  344: 	assert(i*sizeof(Cell) < size);
  345:         token=image[i];
  346: 	if (token>=base) { /* relocatable address */
  347: 	  UCell bitnum=(token-base)/sizeof(Cell);
  348: 	  if (bitnum/RELINFOBITS < (UCell)steps)
  349: 	    result[bitnum/RELINFOBITS] |= 1U << ((~bitnum)&(RELINFOBITS-1));
  350: 	}
  351:       }
  352:     }
  353:   }
  354:   return result;
  355: }
  356: 
  357: void gforth_relocate(Cell *image, const Char *bitstring, 
  358: 		     UCell size, Cell base, Label symbols[])
  359: {
  360:   int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
  361:   Cell token;
  362:   char bits;
  363:   Cell max_symbols;
  364:   /* 
  365:    * A virtual start address that's the real start address minus 
  366:    * the one in the image 
  367:    */
  368:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
  369:   unsigned char *targets = branch_targets(image, bitstring, size, base);
  370: 
  371:   /* group index into table */
  372:   if(groups[31]==0) {
  373:     int groupsum=0;
  374:     for(i=0; i<32; i++) {
  375:       groupsum += groups[i];
  376:       groups[i] = groupsum;
  377:       /* printf("group[%d]=%d\n",i,groupsum); */
  378:     }
  379:     i=0;
  380:   }
  381:   
  382: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
  383:   
  384:   for (max_symbols=0; symbols[max_symbols]!=0; max_symbols++)
  385:     ;
  386:   max_symbols--;
  387: 
  388:   for(k=0; k<steps; k++) {
  389:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  390:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
  391:       if(bits & (1U << (RELINFOBITS-1))) {
  392: 	assert(i*sizeof(Cell) < size);
  393: 	/* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
  394:         token=image[i];
  395: 	if(token<0) {
  396: 	  int group = (-token & 0x3E00) >> 9;
  397: 	  if(group == 0) {
  398: 	    switch(token|0x4000) {
  399: 	    case CF_NIL      : image[i]=0; break;
  400: #if !defined(DOUBLY_INDIRECT)
  401: 	    case CF(DOCOL)   :
  402: 	    case CF(DOVAR)   :
  403: 	    case CF(DOCON)   :
  404: 	    case CF(DOUSER)  : 
  405: 	    case CF(DODEFER) : 
  406: 	    case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
  407: 	    case CF(DOESJUMP): image[i]=0; break;
  408: #endif /* !defined(DOUBLY_INDIRECT) */
  409: 	    case CF(DODOES)  :
  410: 	      MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
  411: 	      break;
  412: 	    default          : /* backward compatibility */
  413: /*	      printf("Code field generation image[%x]:=CFA(%x)\n",
  414: 		     i, CF(image[i])); */
  415: 	      if (CF((token | 0x4000))<max_symbols) {
  416: 		image[i]=(Cell)CFA(CF(token));
  417: #ifdef DIRECT_THREADED
  418: 		if ((token & 0x4000) == 0) { /* threade code, no CFA */
  419: 		  if (targets[k] & (1U<<(RELINFOBITS-1-j)))
  420: 		    compile_prim1(0);
  421: 		  compile_prim1(&image[i]);
  422: 		}
  423: #endif
  424: 	      } else
  425: 		fprintf(stderr,"Primitive %ld used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n",(long)CF(token),(long)&image[i], i, PACKAGE_VERSION);
  426: 	    }
  427: 	  } else {
  428: 	    int tok = -token & 0x1FF;
  429: 	    if (tok < (groups[group+1]-groups[group])) {
  430: #if defined(DOUBLY_INDIRECT)
  431: 	      image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
  432: #else
  433: 	      image[i]=(Cell)CFA((groups[group]+tok));
  434: #endif
  435: #ifdef DIRECT_THREADED
  436: 	      if ((token & 0x4000) == 0) { /* threade code, no CFA */
  437: 		if (targets[k] & (1U<<(RELINFOBITS-1-j)))
  438: 		  compile_prim1(0);
  439: 		compile_prim1(&image[i]);
  440: 	      }
  441: #endif
  442: 	    } else
  443: 	      fprintf(stderr,"Primitive %lx, %d of group %d used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n", (long)-token, tok, group, (long)&image[i],i,PACKAGE_VERSION);
  444: 	  }
  445: 	} else {
  446:           /* if base is > 0: 0 is a null reference so don't adjust*/
  447:           if (token>=base) {
  448:             image[i]+=(Cell)start;
  449:           }
  450:         }
  451:       }
  452:     }
  453:   }
  454:   free(targets);
  455:   finish_code();
  456:   ((ImageHeader*)(image))->base = (Address) image;
  457: }
  458: 
  459: #ifndef DOUBLY_INDIRECT
  460: static UCell checksum(Label symbols[])
  461: {
  462:   UCell r=PRIM_VERSION;
  463:   Cell i;
  464: 
  465:   for (i=DOCOL; i<=DOESJUMP; i++) {
  466:     r ^= (UCell)(symbols[i]);
  467:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  468:   }
  469: #ifdef DIRECT_THREADED
  470:   /* we have to consider all the primitives */
  471:   for (; symbols[i]!=(Label)0; i++) {
  472:     r ^= (UCell)(symbols[i]);
  473:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  474:   }
  475: #else
  476:   /* in indirect threaded code all primitives are accessed through the
  477:      symbols table, so we just have to put the base address of symbols
  478:      in the checksum */
  479:   r ^= (UCell)symbols;
  480: #endif
  481:   return r;
  482: }
  483: #endif
  484: 
  485: static Address verbose_malloc(Cell size)
  486: {
  487:   Address r;
  488:   /* leave a little room (64B) for stack underflows */
  489:   if ((r = malloc(size+64))==NULL) {
  490:     perror(progname);
  491:     exit(1);
  492:   }
  493:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
  494:   debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
  495:   return r;
  496: }
  497: 
  498: static Address next_address=0;
  499: static void after_alloc(Address r, Cell size)
  500: {
  501:   if (r != (Address)-1) {
  502:     debugp(stderr, "success, address=$%lx\n", (long) r);
  503: #if 0
  504:     /* not needed now that we protect the stacks with mprotect */
  505:     if (pagesize != 1)
  506:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
  507: #endif
  508:   } else {
  509:     debugp(stderr, "failed: %s\n", strerror(errno));
  510:   }
  511: }
  512: 
  513: #ifndef MAP_FAILED
  514: #define MAP_FAILED ((Address) -1)
  515: #endif
  516: #ifndef MAP_FILE
  517: # define MAP_FILE 0
  518: #endif
  519: #ifndef MAP_PRIVATE
  520: # define MAP_PRIVATE 0
  521: #endif
  522: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
  523: # define MAP_ANON MAP_ANONYMOUS
  524: #endif
  525: 
  526: #if defined(HAVE_MMAP)
  527: static Address alloc_mmap(Cell size)
  528: {
  529:   Address r;
  530: 
  531: #if defined(MAP_ANON)
  532:   debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
  533:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
  534: #else /* !defined(MAP_ANON) */
  535:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
  536:      apparently defaults) */
  537:   static int dev_zero=-1;
  538: 
  539:   if (dev_zero == -1)
  540:     dev_zero = open("/dev/zero", O_RDONLY);
  541:   if (dev_zero == -1) {
  542:     r = MAP_FAILED;
  543:     debugp(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
  544: 	      strerror(errno));
  545:   } else {
  546:     debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
  547:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
  548:   }
  549: #endif /* !defined(MAP_ANON) */
  550:   after_alloc(r, size);
  551:   return r;  
  552: }
  553: 
  554: static void page_noaccess(Address a)
  555: {
  556:   /* try mprotect first; with munmap the page might be allocated later */
  557:   debugp(stderr, "try mprotect(%p,%ld,PROT_NONE); ", a, (long)pagesize);
  558:   if (mprotect(a, pagesize, PROT_NONE)==0) {
  559:     debugp(stderr, "ok\n");
  560:     return;
  561:   }
  562:   debugp(stderr, "failed: %s\n", strerror(errno));
  563:   debugp(stderr, "try munmap(%p,%ld); ", a, (long)pagesize);
  564:   if (munmap(a,pagesize)==0) {
  565:     debugp(stderr, "ok\n");
  566:     return;
  567:   }
  568:   debugp(stderr, "failed: %s\n", strerror(errno));
  569: }  
  570: 
  571: static size_t wholepage(size_t n)
  572: {
  573:   return (n+pagesize-1)&~(pagesize-1);
  574: }
  575: #endif
  576: 
  577: Address gforth_alloc(Cell size)
  578: {
  579: #if HAVE_MMAP
  580:   Address r;
  581: 
  582:   r=alloc_mmap(size);
  583:   if (r!=(Address)MAP_FAILED)
  584:     return r;
  585: #endif /* HAVE_MMAP */
  586:   /* use malloc as fallback */
  587:   return verbose_malloc(size);
  588: }
  589: 
  590: static Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
  591: {
  592:   Address image = MAP_FAILED;
  593: 
  594: #if defined(HAVE_MMAP)
  595:   if (offset==0) {
  596:     image=alloc_mmap(dictsize);
  597:     if (image != (Address)MAP_FAILED) {
  598:       Address image1;
  599:       debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
  600:       image1 = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
  601:       after_alloc(image1,dictsize);
  602:       if (image1 == (Address)MAP_FAILED)
  603: 	goto read_image;
  604:     }
  605:   }
  606: #endif /* defined(HAVE_MMAP) */
  607:   if (image == (Address)MAP_FAILED) {
  608:     image = gforth_alloc(dictsize+offset)+offset;
  609:   read_image:
  610:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
  611:     fread(image, 1, imagesize, file);
  612:   }
  613:   return image;
  614: }
  615: #endif
  616: 
  617: void set_stack_sizes(ImageHeader * header)
  618: {
  619:   if (dictsize==0)
  620:     dictsize = header->dict_size;
  621:   if (dsize==0)
  622:     dsize = header->data_stack_size;
  623:   if (rsize==0)
  624:     rsize = header->return_stack_size;
  625:   if (fsize==0)
  626:     fsize = header->fp_stack_size;
  627:   if (lsize==0)
  628:     lsize = header->locals_stack_size;
  629:   dictsize=maxaligned(dictsize);
  630:   dsize=maxaligned(dsize);
  631:   rsize=maxaligned(rsize);
  632:   lsize=maxaligned(lsize);
  633:   fsize=maxaligned(fsize);
  634: }
  635: 
  636: #ifdef STANDALONE
  637: void alloc_stacks(ImageHeader * h)
  638: {
  639: #define SSTACKSIZE 0x200
  640:   static Cell dstack[SSTACKSIZE+1];
  641:   static Cell rstack[SSTACKSIZE+1];
  642: 
  643:   h->dict_size=dictsize;
  644:   h->data_stack_size=dsize;
  645:   h->fp_stack_size=fsize;
  646:   h->return_stack_size=rsize;
  647:   h->locals_stack_size=lsize;
  648: 
  649:   h->data_stack_base=dstack+SSTACKSIZE;
  650:   //  h->fp_stack_base=gforth_alloc(fsize);
  651:   h->return_stack_base=rstack+SSTACKSIZE;
  652:   //  h->locals_stack_base=gforth_alloc(lsize);
  653: }
  654: #else
  655: void alloc_stacks(ImageHeader * h)
  656: {
  657:   h->dict_size=dictsize;
  658:   h->data_stack_size=dsize;
  659:   h->fp_stack_size=fsize;
  660:   h->return_stack_size=rsize;
  661:   h->locals_stack_size=lsize;
  662: 
  663: #if defined(HAVE_MMAP) && !defined(STANDALONE)
  664:   if (pagesize > 1) {
  665:     size_t p = pagesize;
  666:     size_t totalsize =
  667:       wholepage(dsize)+wholepage(fsize)+wholepage(rsize)+wholepage(lsize)+5*p;
  668:     Address a = alloc_mmap(totalsize);
  669:     if (a != (Address)MAP_FAILED) {
  670:       page_noaccess(a); a+=p; h->  data_stack_base=a; a+=wholepage(dsize);
  671:       page_noaccess(a); a+=p; h->    fp_stack_base=a; a+=wholepage(fsize);
  672:       page_noaccess(a); a+=p; h->return_stack_base=a; a+=wholepage(rsize);
  673:       page_noaccess(a); a+=p; h->locals_stack_base=a; a+=wholepage(lsize);
  674:       page_noaccess(a);
  675:       debugp(stderr,"stack addresses: d=%p f=%p r=%p l=%p\n",
  676: 	     h->data_stack_base,
  677: 	     h->fp_stack_base,
  678: 	     h->return_stack_base,
  679: 	     h->locals_stack_base);
  680:       return;
  681:     }
  682:   }
  683: #endif
  684:   h->data_stack_base=gforth_alloc(dsize);
  685:   h->fp_stack_base=gforth_alloc(fsize);
  686:   h->return_stack_base=gforth_alloc(rsize);
  687:   h->locals_stack_base=gforth_alloc(lsize);
  688: }
  689: #endif
  690: 
  691: #warning You can ignore the warnings about clobbered variables in gforth_go
  692: int gforth_go(Address image, int stack, Cell *entries)
  693: {
  694:   volatile ImageHeader *image_header = (ImageHeader *)image;
  695:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
  696:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
  697:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
  698: #ifdef GFORTH_DEBUGGING
  699:   volatile Cell *orig_rp0=rp0;
  700: #endif
  701:   Address lp0=image_header->locals_stack_base + lsize;
  702:   Xt *ip0=(Xt *)(image_header->boot_entry);
  703: #ifdef SYSSIGNALS
  704:   int throw_code;
  705: #endif
  706: 
  707:   /* ensure that the cached elements (if any) are accessible */
  708: #if !(defined(GFORTH_DEBUGGING) || defined(INDIRECT_THREADED) || defined(DOUBLY_INDIRECT) || defined(VM_PROFILING))
  709:   sp0 -= 8; /* make stuff below bottom accessible for stack caching */
  710: #endif
  711:   IF_fpTOS(fp0--);
  712:   
  713:   for(;stack>0;stack--)
  714:     *--sp0=entries[stack-1];
  715: 
  716: #if defined(SYSSIGNALS) && !defined(STANDALONE)
  717:   get_winsize();
  718:    
  719:   install_signal_handlers(); /* right place? */
  720:   
  721:   if ((throw_code=setjmp(throw_jmp_buf))) {
  722:     static Cell signal_data_stack[24];
  723:     static Cell signal_return_stack[16];
  724:     static Float signal_fp_stack[1];
  725: 
  726:     signal_data_stack[15]=throw_code;
  727: 
  728: #ifdef GFORTH_DEBUGGING
  729:     debugp(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
  730: 	      throw_code, saved_ip, rp);
  731:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
  732:       /* no rstack overflow or underflow */
  733:       rp0 = rp;
  734:       *--rp0 = (Cell)saved_ip;
  735:     }
  736:     else /* I love non-syntactic ifdefs :-) */
  737:       rp0 = signal_return_stack+16;
  738: #else  /* !defined(GFORTH_DEBUGGING) */
  739:     debugp(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
  740:       rp0 = signal_return_stack+16;
  741: #endif /* !defined(GFORTH_DEBUGGING) */
  742:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
  743:     
  744:     return((int)(Cell)gforth_engine(image_header->throw_entry, signal_data_stack+15,
  745: 		       rp0, signal_fp_stack, 0));
  746:   }
  747: #endif
  748: 
  749:   return((int)(Cell)gforth_engine(ip0,sp0,rp0,fp0,lp0));
  750: }
  751: 
  752: #if !defined(INCLUDE_IMAGE) && !defined(STANDALONE)
  753: static void print_sizes(Cell sizebyte)
  754:      /* print size information */
  755: {
  756:   static char* endianstring[]= { "   big","little" };
  757:   
  758:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
  759: 	  endianstring[sizebyte & 1],
  760: 	  1 << ((sizebyte >> 1) & 3),
  761: 	  1 << ((sizebyte >> 3) & 3),
  762: 	  1 << ((sizebyte >> 5) & 3));
  763: }
  764: 
  765: /* static superinstruction stuff */
  766: 
  767: struct cost { /* super_info might be a more accurate name */
  768:   char loads;       /* number of stack loads */
  769:   char stores;      /* number of stack stores */
  770:   char updates;     /* number of stack pointer updates */
  771:   char branch;	    /* is it a branch (SET_IP) */
  772:   unsigned char state_in;    /* state on entry */
  773:   unsigned char state_out;   /* state on exit */
  774:   unsigned char imm_ops;     /* number of immediate operands */
  775:   short offset;     /* offset into super2 table */
  776:   unsigned char length;      /* number of components */
  777: };
  778: 
  779: PrimNum super2[] = {
  780: #include SUPER2_I
  781: };
  782: 
  783: struct cost super_costs[] = {
  784: #include COSTS_I
  785: };
  786: 
  787: struct super_state {
  788:   struct super_state *next;
  789:   PrimNum super;
  790: };
  791: 
  792: #define HASH_SIZE 256
  793: 
  794: struct super_table_entry {
  795:   struct super_table_entry *next;
  796:   PrimNum *start;
  797:   short length;
  798:   struct super_state *ss_list; /* list of supers */
  799: } *super_table[HASH_SIZE];
  800: int max_super=2;
  801: 
  802: struct super_state *state_transitions=NULL;
  803: 
  804: static int hash_super(PrimNum *start, int length)
  805: {
  806:   int i, r;
  807:   
  808:   for (i=0, r=0; i<length; i++) {
  809:     r <<= 1;
  810:     r += start[i];
  811:   }
  812:   return r & (HASH_SIZE-1);
  813: }
  814: 
  815: static struct super_state **lookup_super(PrimNum *start, int length)
  816: {
  817:   int hash=hash_super(start,length);
  818:   struct super_table_entry *p = super_table[hash];
  819: 
  820:   /* assert(length >= 2); */
  821:   for (; p!=NULL; p = p->next) {
  822:     if (length == p->length &&
  823: 	memcmp((char *)p->start, (char *)start, length*sizeof(PrimNum))==0)
  824:       return &(p->ss_list);
  825:   }
  826:   return NULL;
  827: }
  828: 
  829: static void prepare_super_table()
  830: {
  831:   int i;
  832:   int nsupers = 0;
  833: 
  834:   for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
  835:     struct cost *c = &super_costs[i];
  836:     if ((c->length < 2 || nsupers < static_super_number) &&
  837: 	c->state_in < maxstates && c->state_out < maxstates) {
  838:       struct super_state **ss_listp= lookup_super(super2+c->offset, c->length);
  839:       struct super_state *ss = malloc(sizeof(struct super_state));
  840:       ss->super= i;
  841:       if (c->offset==N_noop && i != N_noop) {
  842: 	if (is_relocatable(i)) {
  843: 	  ss->next = state_transitions;
  844: 	  state_transitions = ss;
  845: 	}
  846:       } else if (ss_listp != NULL) {
  847: 	ss->next = *ss_listp;
  848: 	*ss_listp = ss;
  849:       } else {
  850: 	int hash = hash_super(super2+c->offset, c->length);
  851: 	struct super_table_entry **p = &super_table[hash];
  852: 	struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
  853: 	ss->next = NULL;
  854: 	e->next = *p;
  855: 	e->start = super2 + c->offset;
  856: 	e->length = c->length;
  857: 	e->ss_list = ss;
  858: 	*p = e;
  859:       }
  860:       if (c->length > max_super)
  861: 	max_super = c->length;
  862:       if (c->length >= 2)
  863: 	nsupers++;
  864:     }
  865:   }
  866:   debugp(stderr, "Using %d static superinsts\n", nsupers);
  867: }
  868: 
  869: /* dynamic replication/superinstruction stuff */
  870: 
  871: #ifndef NO_DYNAMIC
  872: static int compare_priminfo_length(const void *_a, const void *_b)
  873: {
  874:   PrimInfo **a = (PrimInfo **)_a;
  875:   PrimInfo **b = (PrimInfo **)_b;
  876:   Cell diff = (*a)->length - (*b)->length;
  877:   if (diff)
  878:     return diff;
  879:   else /* break ties by start address; thus the decompiler produces
  880:           the earliest primitive with the same code (e.g. noop instead
  881:           of (char) and @ instead of >code-address */
  882:     return (*b)->start - (*a)->start;
  883: }
  884: #endif /* !defined(NO_DYNAMIC) */
  885: 
  886: static char MAYBE_UNUSED superend[]={
  887: #include PRIM_SUPEREND_I
  888: };
  889: 
  890: Cell npriminfos=0;
  891: 
  892: Label goto_start;
  893: Cell goto_len;
  894: 
  895: #ifndef NO_DYNAMIC
  896: static int compare_labels(const void *pa, const void *pb)
  897: {
  898:   Label a = *(Label *)pa;
  899:   Label b = *(Label *)pb;
  900:   return a-b;
  901: }
  902: #endif
  903: 
  904: static Label bsearch_next(Label key, Label *a, UCell n)
  905:      /* a is sorted; return the label >=key that is the closest in a;
  906:         return NULL if there is no label in a >=key */
  907: {
  908:   int mid = (n-1)/2;
  909:   if (n<1)
  910:     return NULL;
  911:   if (n == 1) {
  912:     if (a[0] < key)
  913:       return NULL;
  914:     else
  915:       return a[0];
  916:   }
  917:   if (a[mid] < key)
  918:     return bsearch_next(key, a+mid+1, n-mid-1);
  919:   else
  920:     return bsearch_next(key, a, mid+1);
  921: }
  922: 
  923: static void check_prims(Label symbols1[])
  924: {
  925:   int i;
  926: #ifndef NO_DYNAMIC
  927:   Label *symbols2, *symbols3, *ends1, *ends1j, *ends1jsorted, *goto_p;
  928:   int nends1j;
  929: #endif
  930: 
  931:   if (debug)
  932: #ifdef __VERSION__
  933:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
  934: #else
  935: #define xstr(s) str(s)
  936: #define str(s) #s
  937:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
  938: #endif
  939:   for (i=0; symbols1[i]!=0; i++)
  940:     ;
  941:   npriminfos = i;
  942:   
  943: #ifndef NO_DYNAMIC
  944:   if (no_dynamic)
  945:     return;
  946:   symbols2=gforth_engine2(0,0,0,0,0);
  947: #if NO_IP
  948:   symbols3=gforth_engine3(0,0,0,0,0);
  949: #else
  950:   symbols3=symbols1;
  951: #endif
  952:   ends1 = symbols1+i+1;
  953:   ends1j =   ends1+i;
  954:   goto_p = ends1j+i+1; /* goto_p[0]==before; ...[1]==after;*/
  955:   nends1j = i+1;
  956:   ends1jsorted = (Label *)alloca(nends1j*sizeof(Label));
  957:   memcpy(ends1jsorted,ends1j,nends1j*sizeof(Label));
  958:   qsort(ends1jsorted, nends1j, sizeof(Label), compare_labels);
  959: 
  960:   /* check whether the "goto *" is relocatable */
  961:   goto_len = goto_p[1]-goto_p[0];
  962:   debugp(stderr, "goto * %p %p len=%ld\n",
  963: 	 goto_p[0],symbols2[goto_p-symbols1],goto_len);
  964:   if (memcmp(goto_p[0],symbols2[goto_p-symbols1],goto_len)!=0) { /* unequal */
  965:     no_dynamic=1;
  966:     debugp(stderr,"  not relocatable, disabling dynamic code generation\n");
  967:     init_ss_cost();
  968:     return;
  969:   }
  970:   goto_start = goto_p[0];
  971:   
  972:   priminfos = calloc(i,sizeof(PrimInfo));
  973:   for (i=0; symbols1[i]!=0; i++) {
  974:     int prim_len = ends1[i]-symbols1[i];
  975:     PrimInfo *pi=&priminfos[i];
  976:     struct cost *sc=&super_costs[i];
  977:     int j=0;
  978:     char *s1 = (char *)symbols1[i];
  979:     char *s2 = (char *)symbols2[i];
  980:     char *s3 = (char *)symbols3[i];
  981:     Label endlabel = bsearch_next(symbols1[i]+1,ends1jsorted,nends1j);
  982: 
  983:     pi->start = s1;
  984:     pi->superend = superend[i]|no_super;
  985:     pi->length = prim_len;
  986:     pi->restlength = endlabel - symbols1[i] - pi->length;
  987:     pi->nimmargs = 0;
  988:     relocs++;
  989:     debugp(stderr, "%-15s %d-%d %4d %p %p %p len=%3ld rest=%2ld send=%1d",
  990: 	   prim_names[i], sc->state_in, sc->state_out,
  991: 	   i, s1, s2, s3, (long)(pi->length), (long)(pi->restlength),
  992: 	   pi->superend);
  993:     if (endlabel == NULL) {
  994:       pi->start = NULL; /* not relocatable */
  995:       if (pi->length<0) pi->length=100;
  996:       debugp(stderr,"\n   non_reloc: no J label > start found\n");
  997:       relocs--;
  998:       nonrelocs++;
  999:       continue;
 1000:     }
 1001:     if (ends1[i] > endlabel && !pi->superend) {
 1002:       pi->start = NULL; /* not relocatable */
 1003:       pi->length = endlabel-symbols1[i];
 1004:       debugp(stderr,"\n   non_reloc: there is a J label before the K label (restlength<0)\n");
 1005:       relocs--;
 1006:       nonrelocs++;
 1007:       continue;
 1008:     }
 1009:     if (ends1[i] < pi->start && !pi->superend) {
 1010:       pi->start = NULL; /* not relocatable */
 1011:       pi->length = endlabel-symbols1[i];
 1012:       debugp(stderr,"\n   non_reloc: K label before I label (length<0)\n");
 1013:       relocs--;
 1014:       nonrelocs++;
 1015:       continue;
 1016:     }
 1017:     assert(pi->length>=0);
 1018:     assert(pi->restlength >=0);
 1019:     while (j<(pi->length+pi->restlength)) {
 1020:       if (s1[j]==s3[j]) {
 1021: 	if (s1[j] != s2[j]) {
 1022: 	  pi->start = NULL; /* not relocatable */
 1023: 	  debugp(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
 1024: 	  /* assert(j<prim_len); */
 1025: 	  relocs--;
 1026: 	  nonrelocs++;
 1027: 	  break;
 1028: 	}
 1029: 	j++;
 1030:       } else {
 1031: 	struct immarg *ia=&pi->immargs[pi->nimmargs];
 1032: 
 1033: 	pi->nimmargs++;
 1034: 	ia->offset=j;
 1035: 	if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
 1036: 	  ia->rel=0;
 1037: 	  debugp(stderr,"\n   absolute immarg: offset %3d",j);
 1038: 	} else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
 1039: 		   symbols1[DOESJUMP+1]) {
 1040: 	  ia->rel=1;
 1041: 	  debugp(stderr,"\n   relative immarg: offset %3d",j);
 1042: 	} else {
 1043: 	  pi->start = NULL; /* not relocatable */
 1044: 	  debugp(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
 1045: 	  /* assert(j<prim_len);*/
 1046: 	  relocs--;
 1047: 	  nonrelocs++;
 1048: 	  break;
 1049: 	}
 1050: 	j+=4;
 1051:       }
 1052:     }
 1053:     debugp(stderr,"\n");
 1054:   }
 1055:   decomp_prims = calloc(i,sizeof(PrimInfo *));
 1056:   for (i=DOESJUMP+1; i<npriminfos; i++)
 1057:     decomp_prims[i] = &(priminfos[i]);
 1058:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
 1059: 	compare_priminfo_length);
 1060: #endif
 1061: }
 1062: 
 1063: static void flush_to_here(void)
 1064: {
 1065: #ifndef NO_DYNAMIC
 1066:   if (start_flush)
 1067:     FLUSH_ICACHE(start_flush, code_here-start_flush);
 1068:   start_flush=code_here;
 1069: #endif
 1070: }
 1071: 
 1072: #ifndef NO_DYNAMIC
 1073: static void append_jump(void)
 1074: {
 1075:   if (last_jump) {
 1076:     PrimInfo *pi = &priminfos[last_jump];
 1077:     
 1078:     memcpy(code_here, pi->start+pi->length, pi->restlength);
 1079:     code_here += pi->restlength;
 1080:     memcpy(code_here, goto_start, goto_len);
 1081:     code_here += goto_len;
 1082:     last_jump=0;
 1083:   }
 1084: }
 1085: 
 1086: /* Gforth remembers all code blocks in this list.  On forgetting (by
 1087: executing a marker) the code blocks are not freed (because Gforth does
 1088: not remember how they were allocated; hmm, remembering that might be
 1089: easier and cleaner).  Instead, code_here etc. are reset to the old
 1090: value, and the "forgotten" code blocks are reused when they are
 1091: needed. */
 1092: 
 1093: struct code_block_list {
 1094:   struct code_block_list *next;
 1095:   Address block;
 1096:   Cell size;
 1097: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
 1098: 
 1099: static Address append_prim(Cell p)
 1100: {
 1101:   PrimInfo *pi = &priminfos[p];
 1102:   Address old_code_here = code_here;
 1103: 
 1104:   if (code_area+code_area_size < code_here+pi->length+pi->restlength+goto_len) {
 1105:     struct code_block_list *p;
 1106:     append_jump();
 1107:     flush_to_here();
 1108:     if (*next_code_blockp == NULL) {
 1109:       code_here = start_flush = code_area = gforth_alloc(code_area_size);
 1110:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
 1111:       *next_code_blockp = p;
 1112:       p->next = NULL;
 1113:       p->block = code_here;
 1114:       p->size = code_area_size;
 1115:     } else {
 1116:       p = *next_code_blockp;
 1117:       code_here = start_flush = code_area = p->block;
 1118:     }
 1119:     old_code_here = code_here;
 1120:     next_code_blockp = &(p->next);
 1121:   }
 1122:   memcpy(code_here, pi->start, pi->length);
 1123:   code_here += pi->length;
 1124:   return old_code_here;
 1125: }
 1126: #endif
 1127: 
 1128: int forget_dyncode(Address code)
 1129: {
 1130: #ifdef NO_DYNAMIC
 1131:   return -1;
 1132: #else
 1133:   struct code_block_list *p, **pp;
 1134: 
 1135:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
 1136:     if (code >= p->block && code < p->block+p->size) {
 1137:       next_code_blockp = &(p->next);
 1138:       code_here = start_flush = code;
 1139:       code_area = p->block;
 1140:       last_jump = 0;
 1141:       return -1;
 1142:     }
 1143:   }
 1144:   return -no_dynamic;
 1145: #endif /* !defined(NO_DYNAMIC) */
 1146: }
 1147: 
 1148: static long dyncodesize(void)
 1149: {
 1150: #ifndef NO_DYNAMIC
 1151:   struct code_block_list *p;
 1152:   long size=0;
 1153:   for (p=code_block_list; p!=NULL; p=p->next) {
 1154:     if (code_here >= p->block && code_here < p->block+p->size)
 1155:       return size + (code_here - p->block);
 1156:     else
 1157:       size += p->size;
 1158:   }
 1159: #endif /* !defined(NO_DYNAMIC) */
 1160:   return 0;
 1161: }
 1162: 
 1163: Label decompile_code(Label _code)
 1164: {
 1165: #ifdef NO_DYNAMIC
 1166:   return _code;
 1167: #else /* !defined(NO_DYNAMIC) */
 1168:   Cell i;
 1169:   struct code_block_list *p;
 1170:   Address code=_code;
 1171: 
 1172:   /* first, check if we are in code at all */
 1173:   for (p = code_block_list;; p = p->next) {
 1174:     if (p == NULL)
 1175:       return code;
 1176:     if (code >= p->block && code < p->block+p->size)
 1177:       break;
 1178:   }
 1179:   /* reverse order because NOOP might match other prims */
 1180:   for (i=npriminfos-1; i>DOESJUMP; i--) {
 1181:     PrimInfo *pi=decomp_prims[i];
 1182:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
 1183:       return vm_prims[super2[super_costs[pi-priminfos].offset]];
 1184:     /* return pi->start;*/
 1185:   }
 1186:   return code;
 1187: #endif /* !defined(NO_DYNAMIC) */
 1188: }
 1189: 
 1190: #ifdef NO_IP
 1191: int nbranchinfos=0;
 1192: 
 1193: struct branchinfo {
 1194:   Label **targetpp; /* **(bi->targetpp) is the target */
 1195:   Cell *addressptr; /* store the target here */
 1196: } branchinfos[100000];
 1197: 
 1198: int ndoesexecinfos=0;
 1199: struct doesexecinfo {
 1200:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
 1201:   Label *targetp; /*target for branch (because this is not in threaded code)*/
 1202:   Cell *xt; /* cfa of word whose does-code needs calling */
 1203: } doesexecinfos[10000];
 1204: 
 1205: static void set_rel_target(Cell *source, Label target)
 1206: {
 1207:   *source = ((Cell)target)-(((Cell)source)+4);
 1208: }
 1209: 
 1210: static void register_branchinfo(Label source, Cell *targetpp)
 1211: {
 1212:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
 1213:   bi->targetpp = (Label **)targetpp;
 1214:   bi->addressptr = (Cell *)source;
 1215:   nbranchinfos++;
 1216: }
 1217: 
 1218: static Address compile_prim1arg(PrimNum p, Cell **argp)
 1219: {
 1220:   Address old_code_here=append_prim(p);
 1221: 
 1222:   assert(vm_prims[p]==priminfos[p].start);
 1223:   *argp = (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
 1224:   return old_code_here;
 1225: }
 1226: 
 1227: static Address compile_call2(Cell *targetpp, Cell **next_code_targetp)
 1228: {
 1229:   PrimInfo *pi = &priminfos[N_call2];
 1230:   Address old_code_here = append_prim(N_call2);
 1231: 
 1232:   *next_code_targetp = (Cell *)(old_code_here + pi->immargs[0].offset);
 1233:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetpp);
 1234:   return old_code_here;
 1235: }
 1236: #endif
 1237: 
 1238: void finish_code(void)
 1239: {
 1240: #ifdef NO_IP
 1241:   Cell i;
 1242: 
 1243:   compile_prim1(NULL);
 1244:   for (i=0; i<ndoesexecinfos; i++) {
 1245:     struct doesexecinfo *dei = &doesexecinfos[i];
 1246:     dei->targetp = (Label *)DOES_CODE1((dei->xt));
 1247:     branchinfos[dei->branchinfo].targetpp = &(dei->targetp);
 1248:   }
 1249:   ndoesexecinfos = 0;
 1250:   for (i=0; i<nbranchinfos; i++) {
 1251:     struct branchinfo *bi=&branchinfos[i];
 1252:     set_rel_target(bi->addressptr, **(bi->targetpp));
 1253:   }
 1254:   nbranchinfos = 0;
 1255: #else
 1256:   compile_prim1(NULL);
 1257: #endif
 1258:   flush_to_here();
 1259: }
 1260: 
 1261: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
 1262: #ifdef NO_IP
 1263: static Cell compile_prim_dyn(PrimNum p, Cell *tcp)
 1264:      /* compile prim #p dynamically (mod flags etc.) and return start
 1265: 	address of generated code for putting it into the threaded
 1266: 	code. This function is only called if all the associated
 1267: 	inline arguments of p are already in place (at tcp[1] etc.) */
 1268: {
 1269:   PrimInfo *pi=&priminfos[p];
 1270:   Cell *next_code_target=NULL;
 1271:   Address codeaddr;
 1272:   Address primstart;
 1273:   
 1274:   assert(p<npriminfos);
 1275:   if (p==N_execute || p==N_perform || p==N_lit_perform) {
 1276:     codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
 1277:     primstart = append_prim(p);
 1278:     goto other_prim;
 1279:   } else if (p==N_call) {
 1280:     codeaddr = compile_call2(tcp+1, &next_code_target);
 1281:   } else if (p==N_does_exec) {
 1282:     struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
 1283:     Cell *arg;
 1284:     codeaddr = compile_prim1arg(N_lit,&arg);
 1285:     *arg = (Cell)PFA(tcp[1]);
 1286:     /* we cannot determine the callee now (last_start[1] may be a
 1287:        forward reference), so just register an arbitrary target, and
 1288:        register in dei that we need to fix this before resolving
 1289:        branches */
 1290:     dei->branchinfo = nbranchinfos;
 1291:     dei->xt = (Cell *)(tcp[1]);
 1292:     compile_call2(0, &next_code_target);
 1293:   } else if (!is_relocatable(p)) {
 1294:     Cell *branch_target;
 1295:     codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
 1296:     compile_prim1arg(N_branch,&branch_target);
 1297:     set_rel_target(branch_target,vm_prims[p]);
 1298:   } else {
 1299:     unsigned j;
 1300: 
 1301:     codeaddr = primstart = append_prim(p);
 1302:   other_prim:
 1303:     for (j=0; j<pi->nimmargs; j++) {
 1304:       struct immarg *ia = &(pi->immargs[j]);
 1305:       Cell *argp = tcp + pi->nimmargs - j;
 1306:       Cell argval = *argp; /* !! specific to prims */
 1307:       if (ia->rel) { /* !! assumption: relative refs are branches */
 1308: 	register_branchinfo(primstart + ia->offset, argp);
 1309:       } else /* plain argument */
 1310: 	*(Cell *)(primstart + ia->offset) = argval;
 1311:     }
 1312:   }
 1313:   if (next_code_target!=NULL)
 1314:     *next_code_target = (Cell)code_here;
 1315:   return (Cell)codeaddr;
 1316: }
 1317: #else /* !defined(NO_IP) */
 1318: static Cell compile_prim_dyn(PrimNum p, Cell *tcp)
 1319:      /* compile prim #p dynamically (mod flags etc.) and return start
 1320:         address of generated code for putting it into the threaded code */
 1321: {
 1322:   Cell static_prim = (Cell)vm_prims[p];
 1323: #if defined(NO_DYNAMIC)
 1324:   return static_prim;
 1325: #else /* !defined(NO_DYNAMIC) */
 1326:   Address old_code_here;
 1327: 
 1328:   if (no_dynamic)
 1329:     return static_prim;
 1330:   if (p>=npriminfos || !is_relocatable(p)) {
 1331:     append_jump();
 1332:     return static_prim;
 1333:   }
 1334:   old_code_here = append_prim(p);
 1335:   last_jump = p;
 1336:   if (priminfos[p].superend)
 1337:     append_jump();
 1338:   return (Cell)old_code_here;
 1339: #endif  /* !defined(NO_DYNAMIC) */
 1340: }
 1341: #endif /* !defined(NO_IP) */
 1342: #endif
 1343: 
 1344: #ifndef NO_DYNAMIC
 1345: static int cost_codesize(int prim)
 1346: {
 1347:   return priminfos[prim].length;
 1348: }
 1349: #endif
 1350: 
 1351: static int cost_ls(int prim)
 1352: {
 1353:   struct cost *c = super_costs+prim;
 1354: 
 1355:   return c->loads + c->stores;
 1356: }
 1357: 
 1358: static int cost_lsu(int prim)
 1359: {
 1360:   struct cost *c = super_costs+prim;
 1361: 
 1362:   return c->loads + c->stores + c->updates;
 1363: }
 1364: 
 1365: static int cost_nexts(int prim)
 1366: {
 1367:   return 1;
 1368: }
 1369: 
 1370: typedef int Costfunc(int);
 1371: Costfunc *ss_cost =  /* cost function for optimize_bb */
 1372: #ifdef NO_DYNAMIC
 1373: cost_lsu;
 1374: #else
 1375: cost_codesize;
 1376: #endif
 1377: 
 1378: struct {
 1379:   Costfunc *costfunc;
 1380:   char *metricname;
 1381:   long sum;
 1382: } cost_sums[] = {
 1383: #ifndef NO_DYNAMIC
 1384:   { cost_codesize, "codesize", 0 },
 1385: #endif
 1386:   { cost_ls,       "ls",       0 },
 1387:   { cost_lsu,      "lsu",      0 },
 1388:   { cost_nexts,    "nexts",    0 }
 1389: };
 1390: 
 1391: #ifndef NO_DYNAMIC
 1392: void init_ss_cost(void) {
 1393:   if (no_dynamic && ss_cost == cost_codesize) {
 1394:     ss_cost = cost_nexts;
 1395:     cost_sums[0] = cost_sums[1]; /* don't use cost_codesize for print-metrics */
 1396:     debugp(stderr, "--no-dynamic conflicts with --ss-min-codesize, reverting to --ss-min-nexts\n");
 1397:   }
 1398: }
 1399: #endif
 1400: 
 1401: #define MAX_BB 128 /* maximum number of instructions in BB */
 1402: #define INF_COST 1000000 /* infinite cost */
 1403: #define CANONICAL_STATE 0
 1404: 
 1405: struct waypoint {
 1406:   int cost;     /* the cost from here to the end */
 1407:   PrimNum inst; /* the inst used from here to the next waypoint */
 1408:   char relocatable; /* the last non-transition was relocatable */
 1409:   char no_transition; /* don't use the next transition (relocatability)
 1410: 		       * or this transition (does not change state) */
 1411: };
 1412: 
 1413: struct tpa_state { /* tree parsing automaton (like) state */
 1414:   /* labeling is back-to-front */
 1415:   struct waypoint *inst;  /* in front of instruction */
 1416:   struct waypoint *trans; /* in front of instruction and transition */
 1417: }; 
 1418: 
 1419: struct tpa_state *termstate = NULL; /* initialized in loader() */
 1420: 
 1421: /* statistics about tree parsing (lazyburg) stuff */
 1422: long lb_basic_blocks = 0;
 1423: long lb_labeler_steps = 0;
 1424: long lb_labeler_automaton = 0;
 1425: long lb_labeler_dynprog = 0;
 1426: long lb_newstate_equiv = 0;
 1427: long lb_newstate_new = 0;
 1428: long lb_applicable_base_rules = 0;
 1429: long lb_applicable_chain_rules = 0;
 1430: 
 1431: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
 1432: static void init_waypoints(struct waypoint ws[])
 1433: {
 1434:   int k;
 1435: 
 1436:   for (k=0; k<maxstates; k++)
 1437:     ws[k].cost=INF_COST;
 1438: }
 1439: 
 1440: static struct tpa_state *empty_tpa_state()
 1441: {
 1442:   struct tpa_state *s = malloc(sizeof(struct tpa_state));
 1443: 
 1444:   s->inst  = calloc(maxstates,sizeof(struct waypoint));
 1445:   init_waypoints(s->inst);
 1446:   s->trans = calloc(maxstates,sizeof(struct waypoint));
 1447:   /* init_waypoints(s->trans);*/
 1448:   return s;
 1449: }
 1450: 
 1451: static void transitions(struct tpa_state *t)
 1452: {
 1453:   int k;
 1454:   struct super_state *l;
 1455:   
 1456:   for (k=0; k<maxstates; k++) {
 1457:     t->trans[k] = t->inst[k];
 1458:     t->trans[k].no_transition = 1;
 1459:   }
 1460:   for (l = state_transitions; l != NULL; l = l->next) {
 1461:     PrimNum s = l->super;
 1462:     int jcost;
 1463:     struct cost *c=super_costs+s;
 1464:     struct waypoint *wi=&(t->trans[c->state_in]);
 1465:     struct waypoint *wo=&(t->inst[c->state_out]);
 1466:     lb_applicable_chain_rules++;
 1467:     if (wo->cost == INF_COST)
 1468:       continue;
 1469:     jcost = wo->cost + ss_cost(s);
 1470:     if (jcost <= wi->cost) {
 1471:       wi->cost = jcost;
 1472:       wi->inst = s;
 1473:       wi->relocatable = wo->relocatable;
 1474:       wi->no_transition = 0;
 1475:       /* if (ss_greedy) wi->cost = wo->cost ? */
 1476:     }
 1477:   }
 1478: }
 1479: 
 1480: static struct tpa_state *make_termstate()
 1481: {
 1482:   struct tpa_state *s = empty_tpa_state();
 1483: 
 1484:   s->inst[CANONICAL_STATE].cost = 0;
 1485:   transitions(s);
 1486:   return s;
 1487: }
 1488: #endif
 1489: 
 1490: #define TPA_SIZE 16384
 1491: 
 1492: struct tpa_entry {
 1493:   struct tpa_entry *next;
 1494:   PrimNum inst;
 1495:   struct tpa_state *state_behind;  /* note: brack-to-front labeling */
 1496:   struct tpa_state *state_infront; /* note: brack-to-front labeling */
 1497: } *tpa_table[TPA_SIZE];
 1498: 
 1499: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
 1500: static Cell hash_tpa(PrimNum p, struct tpa_state *t)
 1501: {
 1502:   UCell it = (UCell )t;
 1503:   return (p+it+(it>>14))&(TPA_SIZE-1);
 1504: }
 1505: 
 1506: static struct tpa_state **lookup_tpa(PrimNum p, struct tpa_state *t2)
 1507: {
 1508:   int hash=hash_tpa(p, t2);
 1509:   struct tpa_entry *te = tpa_table[hash];
 1510: 
 1511:   if (tpa_noautomaton) {
 1512:     static struct tpa_state *t;
 1513:     t = NULL;
 1514:     return &t;
 1515:   }
 1516:   for (; te!=NULL; te = te->next) {
 1517:     if (p == te->inst && t2 == te->state_behind)
 1518:       return &(te->state_infront);
 1519:   }
 1520:   te = (struct tpa_entry *)malloc(sizeof(struct tpa_entry));
 1521:   te->next = tpa_table[hash];
 1522:   te->inst = p;
 1523:   te->state_behind = t2;
 1524:   te->state_infront = NULL;
 1525:   tpa_table[hash] = te;
 1526:   return &(te->state_infront);
 1527: }
 1528: 
 1529: static void tpa_state_normalize(struct tpa_state *t)
 1530: {
 1531:   /* normalize so cost of canonical state=0; this may result in
 1532:      negative states for some states */
 1533:   int d = t->inst[CANONICAL_STATE].cost;
 1534:   int i;
 1535: 
 1536:   for (i=0; i<maxstates; i++) {
 1537:     if (t->inst[i].cost != INF_COST)
 1538:       t->inst[i].cost -= d;
 1539:     if (t->trans[i].cost != INF_COST)
 1540:       t->trans[i].cost -= d;
 1541:   }
 1542: }
 1543: 
 1544: static int tpa_state_equivalent(struct tpa_state *t1, struct tpa_state *t2)
 1545: {
 1546:   return (memcmp(t1->inst, t2->inst, maxstates*sizeof(struct waypoint)) == 0 &&
 1547: 	  memcmp(t1->trans,t2->trans,maxstates*sizeof(struct waypoint)) == 0);
 1548: }
 1549: #endif
 1550: 
 1551: struct tpa_state_entry {
 1552:   struct tpa_state_entry *next;
 1553:   struct tpa_state *state;
 1554: } *tpa_state_table[TPA_SIZE];
 1555: 
 1556: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
 1557: static Cell hash_tpa_state(struct tpa_state *t)
 1558: {
 1559:   int *ti = (int *)(t->inst);
 1560:   int *tt = (int *)(t->trans);
 1561:   int r=0;
 1562:   int i;
 1563: 
 1564:   for (i=0; ti+i < (int *)(t->inst+maxstates); i++)
 1565:     r += ti[i]+tt[i];
 1566:   return (r+(r>>14)+(r>>22)) & (TPA_SIZE-1);
 1567: }
 1568: 
 1569: static struct tpa_state *lookup_tpa_state(struct tpa_state *t)
 1570: {
 1571:   Cell hash = hash_tpa_state(t);
 1572:   struct tpa_state_entry *te = tpa_state_table[hash];
 1573:   struct tpa_state_entry *tn;
 1574: 
 1575:   if (!tpa_noequiv) {
 1576:     for (; te!=NULL; te = te->next) {
 1577:       if (tpa_state_equivalent(t, te->state)) {
 1578: 	lb_newstate_equiv++;
 1579: 	free(t->inst);
 1580: 	free(t->trans);
 1581: 	free(t);
 1582: 	return te->state;
 1583:       }
 1584:     }
 1585:     tn = (struct tpa_state_entry *)malloc(sizeof(struct tpa_state_entry));
 1586:     tn->next = te;
 1587:     tn->state = t;
 1588:     tpa_state_table[hash] = tn;
 1589:   }
 1590:   lb_newstate_new++;
 1591:   if (tpa_trace)
 1592:     fprintf(stderr, "%ld %ld lb_states\n", lb_labeler_steps, lb_newstate_new);
 1593:   return t;
 1594: }
 1595: 
 1596: /* use dynamic programming to find the shortest paths within the basic
 1597:    block origs[0..ninsts-1] and rewrite the instructions pointed to by
 1598:    instps to use it */
 1599: static void optimize_rewrite(Cell *instps[], PrimNum origs[], int ninsts)
 1600: {
 1601:   int i,j;
 1602:   struct tpa_state *ts[ninsts+1];
 1603:   int nextdyn, nextstate, no_transition;
 1604:   
 1605:   lb_basic_blocks++;
 1606:   ts[ninsts] = termstate;
 1607:   for (i=ninsts-1; i>=0; i--) {
 1608:     struct tpa_state **tp = lookup_tpa(origs[i],ts[i+1]);
 1609:     struct tpa_state *t = *tp;
 1610:     lb_labeler_steps++;
 1611:     if (t) {
 1612:       ts[i] = t;
 1613:       lb_labeler_automaton++;
 1614:     }
 1615:     else {
 1616:       lb_labeler_dynprog++;
 1617:       ts[i] = empty_tpa_state();
 1618:       for (j=1; j<=max_super && i+j<=ninsts; j++) {
 1619: 	struct super_state **superp = lookup_super(origs+i, j);
 1620: 	if (superp!=NULL) {
 1621: 	  struct super_state *supers = *superp;
 1622: 	  for (; supers!=NULL; supers = supers->next) {
 1623: 	    PrimNum s = supers->super;
 1624: 	    int jcost;
 1625: 	    struct cost *c=super_costs+s;
 1626: 	    struct waypoint *wi=&(ts[i]->inst[c->state_in]);
 1627: 	    struct waypoint *wo=&(ts[i+j]->trans[c->state_out]);
 1628: 	    int no_transition = wo->no_transition;
 1629: 	    lb_applicable_base_rules++;
 1630: 	    if (!(is_relocatable(s)) && !wo->relocatable) {
 1631: 	      wo=&(ts[i+j]->inst[c->state_out]);
 1632: 	      no_transition=1;
 1633: 	    }
 1634: 	    if (wo->cost == INF_COST) 
 1635: 	      continue;
 1636: 	    jcost = wo->cost + ss_cost(s);
 1637: 	    if (jcost <= wi->cost) {
 1638: 	      wi->cost = jcost;
 1639: 	      wi->inst = s;
 1640: 	      wi->relocatable = is_relocatable(s);
 1641: 	      wi->no_transition = no_transition;
 1642: 	      /* if (ss_greedy) wi->cost = wo->cost ? */
 1643: 	    }
 1644: 	  }
 1645: 	}
 1646:       }
 1647:       transitions(ts[i]);
 1648:       tpa_state_normalize(ts[i]);
 1649:       *tp = ts[i] = lookup_tpa_state(ts[i]);
 1650:       if (tpa_trace)
 1651: 	fprintf(stderr, "%ld %ld lb_table_entries\n", lb_labeler_steps, lb_labeler_dynprog);
 1652:     }
 1653:   }
 1654:   /* now rewrite the instructions */
 1655:   nextdyn=0;
 1656:   nextstate=CANONICAL_STATE;
 1657:   no_transition = ((!ts[0]->trans[nextstate].relocatable) 
 1658: 		   ||ts[0]->trans[nextstate].no_transition);
 1659:   for (i=0; i<ninsts; i++) {
 1660:     Cell tc=0, tc2;
 1661:     if (i==nextdyn) {
 1662:       if (!no_transition) {
 1663: 	/* process trans */
 1664: 	PrimNum p = ts[i]->trans[nextstate].inst;
 1665: 	struct cost *c = super_costs+p;
 1666: 	assert(ts[i]->trans[nextstate].cost != INF_COST);
 1667: 	assert(c->state_in==nextstate);
 1668: 	tc = compile_prim_dyn(p,NULL);
 1669: 	nextstate = c->state_out;
 1670:       }
 1671:       {
 1672: 	/* process inst */
 1673: 	PrimNum p = ts[i]->inst[nextstate].inst;
 1674: 	struct cost *c=super_costs+p;
 1675: 	assert(c->state_in==nextstate);
 1676: 	assert(ts[i]->inst[nextstate].cost != INF_COST);
 1677: #if defined(GFORTH_DEBUGGING)
 1678: 	assert(p == origs[i]);
 1679: #endif
 1680: 	tc2 = compile_prim_dyn(p,instps[i]);
 1681: 	if (no_transition || !is_relocatable(p))
 1682: 	  /* !! actually what we care about is if and where
 1683: 	   * compile_prim_dyn() puts NEXTs */
 1684: 	  tc=tc2;
 1685: 	no_transition = ts[i]->inst[nextstate].no_transition;
 1686: 	nextstate = c->state_out;
 1687: 	nextdyn += c->length;
 1688:       }
 1689:     } else {
 1690: #if defined(GFORTH_DEBUGGING)
 1691:       assert(0);
 1692: #endif
 1693:       tc=0;
 1694:       /* tc= (Cell)vm_prims[ts[i]->inst[CANONICAL_STATE].inst]; */
 1695:     }
 1696:     *(instps[i]) = tc;
 1697:   }      
 1698:   if (!no_transition) {
 1699:     PrimNum p = ts[i]->trans[nextstate].inst;
 1700:     struct cost *c = super_costs+p;
 1701:     assert(c->state_in==nextstate);
 1702:     assert(ts[i]->trans[nextstate].cost != INF_COST);
 1703:     assert(i==nextdyn);
 1704:     (void)compile_prim_dyn(p,NULL);
 1705:     nextstate = c->state_out;
 1706:   }
 1707:   assert(nextstate==CANONICAL_STATE);
 1708: }
 1709: #endif
 1710: 
 1711: /* compile *start, possibly rewriting it into a static and/or dynamic
 1712:    superinstruction */
 1713: void compile_prim1(Cell *start)
 1714: {
 1715: #if defined(DOUBLY_INDIRECT)
 1716:   Label prim;
 1717: 
 1718:   if (start==NULL)
 1719:     return;
 1720:   prim = (Label)*start;
 1721:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
 1722:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
 1723:     *start=(Cell)prim;
 1724:     return;
 1725:   } else {
 1726:     *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
 1727:     return;
 1728:   }
 1729: #elif defined(INDIRECT_THREADED)
 1730:   return;
 1731: #else /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
 1732:   /* !! does not work, for unknown reasons; but something like this is
 1733:      probably needed to ensure that we don't call compile_prim_dyn
 1734:      before the inline arguments are there */
 1735:   static Cell *instps[MAX_BB];
 1736:   static PrimNum origs[MAX_BB];
 1737:   static int ninsts=0;
 1738:   PrimNum prim_num;
 1739: 
 1740:   if (start==NULL || ninsts >= MAX_BB ||
 1741:       (ninsts>0 && superend[origs[ninsts-1]])) {
 1742:     /* after bb, or at the start of the next bb */
 1743:     optimize_rewrite(instps,origs,ninsts);
 1744:     /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts); */
 1745:     ninsts=0;
 1746:     if (start==NULL)
 1747:       return;
 1748:   }
 1749:   prim_num = ((Xt)*start)-vm_prims;
 1750:   if(prim_num >= npriminfos) {
 1751:     optimize_rewrite(instps,origs,ninsts);
 1752:     /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts);*/
 1753:     ninsts=0;
 1754:     return;
 1755:   }    
 1756:   assert(ninsts<MAX_BB);
 1757:   instps[ninsts] = start;
 1758:   origs[ninsts] = prim_num;
 1759:   ninsts++;
 1760: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
 1761: }
 1762: 
 1763: #ifndef STANDALONE
 1764: Address gforth_loader(FILE *imagefile, char* filename)
 1765: /* returns the address of the image proper (after the preamble) */
 1766: {
 1767:   ImageHeader header;
 1768:   Address image;
 1769:   Address imp; /* image+preamble */
 1770:   Char magic[8];
 1771:   char magic7; /* size byte of magic number */
 1772:   Cell preamblesize=0;
 1773:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
 1774:   UCell check_sum;
 1775:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
 1776: 		 (RELINFOBITS == 16) ? 1 :
 1777: 		 (RELINFOBITS == 32) ? 2 : 3);
 1778:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
 1779: 		   (sizeof(Char) == 2) ? 1 :
 1780: 		   (sizeof(Char) == 4) ? 2 : 3) + ausize;
 1781:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
 1782: 		   (sizeof(Cell) == 2) ? 1 :
 1783: 		   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
 1784:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
 1785: #ifdef WORDS_BIGENDIAN
 1786:        0
 1787: #else
 1788:        1
 1789: #endif
 1790:     ;
 1791: 
 1792:   vm_prims = gforth_engine(0,0,0,0,0);
 1793:   check_prims(vm_prims);
 1794:   prepare_super_table();
 1795: #ifndef DOUBLY_INDIRECT
 1796: #ifdef PRINT_SUPER_LENGTHS
 1797:   print_super_lengths();
 1798: #endif
 1799:   check_sum = checksum(vm_prims);
 1800: #else /* defined(DOUBLY_INDIRECT) */
 1801:   check_sum = (UCell)vm_prims;
 1802: #endif /* defined(DOUBLY_INDIRECT) */
 1803: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
 1804:   termstate = make_termstate();
 1805: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
 1806:   
 1807:   do {
 1808:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
 1809:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
 1810: 	      progname, filename);
 1811:       exit(1);
 1812:     }
 1813:     preamblesize+=8;
 1814:   } while(memcmp(magic,"Gforth3",7));
 1815:   magic7 = magic[7];
 1816:   if (debug) {
 1817:     magic[7]='\0';
 1818:     fprintf(stderr,"Magic found: %s ", magic);
 1819:     print_sizes(magic7);
 1820:   }
 1821: 
 1822:   if (magic7 != sizebyte)
 1823:     {
 1824:       fprintf(stderr,"This image is:         ");
 1825:       print_sizes(magic7);
 1826:       fprintf(stderr,"whereas the machine is ");
 1827:       print_sizes(sizebyte);
 1828:       exit(-2);
 1829:     };
 1830: 
 1831:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
 1832: 
 1833:   set_stack_sizes(&header);
 1834:   
 1835: #if HAVE_GETPAGESIZE
 1836:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
 1837: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
 1838:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
 1839: #elif PAGESIZE
 1840:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
 1841: #endif
 1842:   debugp(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
 1843: 
 1844:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
 1845: 			  preamblesize+dictsize, data_offset);
 1846:   imp=image+preamblesize;
 1847: 
 1848:   alloc_stacks((ImageHeader *)imp);
 1849:   if (clear_dictionary)
 1850:     memset(imp+header.image_size, 0, dictsize-header.image_size);
 1851:   if(header.base==0 || header.base  == (Address)0x100) {
 1852:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
 1853:     Char reloc_bits[reloc_size];
 1854:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
 1855:     fread(reloc_bits, 1, reloc_size, imagefile);
 1856:     gforth_relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
 1857: #if 0
 1858:     { /* let's see what the relocator did */
 1859:       FILE *snapshot=fopen("snapshot.fi","wb");
 1860:       fwrite(image,1,imagesize,snapshot);
 1861:       fclose(snapshot);
 1862:     }
 1863: #endif
 1864:   }
 1865:   else if(header.base!=imp) {
 1866:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
 1867: 	    progname, (unsigned long)header.base, (unsigned long)imp);
 1868:     exit(1);
 1869:   }
 1870:   if (header.checksum==0)
 1871:     ((ImageHeader *)imp)->checksum=check_sum;
 1872:   else if (header.checksum != check_sum) {
 1873:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
 1874: 	    progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
 1875:     exit(1);
 1876:   }
 1877: #ifdef DOUBLY_INDIRECT
 1878:   ((ImageHeader *)imp)->xt_base = xts;
 1879: #endif
 1880:   fclose(imagefile);
 1881: 
 1882:   /* unnecessary, except maybe for CODE words */
 1883:   /* FLUSH_ICACHE(imp, header.image_size);*/
 1884: 
 1885:   return imp;
 1886: }
 1887: #endif
 1888: 
 1889: /* pointer to last '/' or '\' in file, 0 if there is none. */
 1890: static char *onlypath(char *filename)
 1891: {
 1892:   return strrchr(filename, DIRSEP);
 1893: }
 1894: 
 1895: static FILE *openimage(char *fullfilename)
 1896: {
 1897:   FILE *image_file;
 1898:   char * expfilename = tilde_cstr((Char *)fullfilename, strlen(fullfilename), 1);
 1899: 
 1900:   image_file=fopen(expfilename,"rb");
 1901:   if (image_file!=NULL && debug)
 1902:     fprintf(stderr, "Opened image file: %s\n", expfilename);
 1903:   return image_file;
 1904: }
 1905: 
 1906: /* try to open image file concat(path[0:len],imagename) */
 1907: static FILE *checkimage(char *path, int len, char *imagename)
 1908: {
 1909:   int dirlen=len;
 1910:   char fullfilename[dirlen+strlen((char *)imagename)+2];
 1911: 
 1912:   memcpy(fullfilename, path, dirlen);
 1913:   if (fullfilename[dirlen-1]!=DIRSEP)
 1914:     fullfilename[dirlen++]=DIRSEP;
 1915:   strcpy(fullfilename+dirlen,imagename);
 1916:   return openimage(fullfilename);
 1917: }
 1918: 
 1919: static FILE * open_image_file(char * imagename, char * path)
 1920: {
 1921:   FILE * image_file=NULL;
 1922:   char *origpath=path;
 1923:   
 1924:   if(strchr(imagename, DIRSEP)==NULL) {
 1925:     /* first check the directory where the exe file is in !! 01may97jaw */
 1926:     if (onlypath(progname))
 1927:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
 1928:     if (!image_file)
 1929:       do {
 1930: 	char *pend=strchr(path, PATHSEP);
 1931: 	if (pend==NULL)
 1932: 	  pend=path+strlen(path);
 1933: 	if (strlen(path)==0) break;
 1934: 	image_file=checkimage(path, pend-path, imagename);
 1935: 	path=pend+(*pend==PATHSEP);
 1936:       } while (image_file==NULL);
 1937:   } else {
 1938:     image_file=openimage(imagename);
 1939:   }
 1940: 
 1941:   if (!image_file) {
 1942:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
 1943: 	    progname, imagename, origpath);
 1944:     exit(1);
 1945:   }
 1946: 
 1947:   return image_file;
 1948: }
 1949: #endif
 1950: 
 1951: #ifdef STANDALONE_ALLOC
 1952: Address gforth_alloc(Cell size)
 1953: {
 1954:   Address r;
 1955:   /* leave a little room (64B) for stack underflows */
 1956:   if ((r = malloc(size+64))==NULL) {
 1957:     perror(progname);
 1958:     exit(1);
 1959:   }
 1960:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
 1961:   debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
 1962:   return r;
 1963: }
 1964: #endif
 1965: 
 1966: #ifdef HAS_OS
 1967: static UCell convsize(char *s, UCell elemsize)
 1968: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
 1969:    of bytes.  the letter at the end indicates the unit, where e stands
 1970:    for the element size. default is e */
 1971: {
 1972:   char *endp;
 1973:   UCell n,m;
 1974: 
 1975:   m = elemsize;
 1976:   n = strtoul(s,&endp,0);
 1977:   if (endp!=NULL) {
 1978:     if (strcmp(endp,"b")==0)
 1979:       m=1;
 1980:     else if (strcmp(endp,"k")==0)
 1981:       m=1024;
 1982:     else if (strcmp(endp,"M")==0)
 1983:       m=1024*1024;
 1984:     else if (strcmp(endp,"G")==0)
 1985:       m=1024*1024*1024;
 1986:     else if (strcmp(endp,"T")==0) {
 1987: #if (SIZEOF_CHAR_P > 4)
 1988:       m=1024L*1024*1024*1024;
 1989: #else
 1990:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
 1991:       exit(1);
 1992: #endif
 1993:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
 1994:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
 1995:       exit(1);
 1996:     }
 1997:   }
 1998:   return n*m;
 1999: }
 2000: 
 2001: enum {
 2002:   ss_number = 256,
 2003:   ss_states,
 2004:   ss_min_codesize,
 2005:   ss_min_ls,
 2006:   ss_min_lsu,
 2007:   ss_min_nexts,
 2008: };
 2009: 
 2010: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
 2011: {
 2012:   int c;
 2013: 
 2014:   opterr=0;
 2015:   while (1) {
 2016:     int option_index=0;
 2017:     static struct option opts[] = {
 2018:       {"appl-image", required_argument, NULL, 'a'},
 2019:       {"image-file", required_argument, NULL, 'i'},
 2020:       {"dictionary-size", required_argument, NULL, 'm'},
 2021:       {"data-stack-size", required_argument, NULL, 'd'},
 2022:       {"return-stack-size", required_argument, NULL, 'r'},
 2023:       {"fp-stack-size", required_argument, NULL, 'f'},
 2024:       {"locals-stack-size", required_argument, NULL, 'l'},
 2025:       {"path", required_argument, NULL, 'p'},
 2026:       {"version", no_argument, NULL, 'v'},
 2027:       {"help", no_argument, NULL, 'h'},
 2028:       /* put something != 0 into offset_image */
 2029:       {"offset-image", no_argument, &offset_image, 1},
 2030:       {"no-offset-im", no_argument, &offset_image, 0},
 2031:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
 2032:       {"die-on-signal", no_argument, &die_on_signal, 1},
 2033:       {"ignore-async-signals", no_argument, &ignore_async_signals, 1},
 2034:       {"debug", no_argument, &debug, 1},
 2035:       {"diag", no_argument, &diag, 1},
 2036:       {"no-super", no_argument, &no_super, 1},
 2037:       {"no-dynamic", no_argument, &no_dynamic, 1},
 2038:       {"dynamic", no_argument, &no_dynamic, 0},
 2039:       {"print-metrics", no_argument, &print_metrics, 1},
 2040:       {"ss-number", required_argument, NULL, ss_number},
 2041:       {"ss-states", required_argument, NULL, ss_states},
 2042: #ifndef NO_DYNAMIC
 2043:       {"ss-min-codesize", no_argument, NULL, ss_min_codesize},
 2044: #endif
 2045:       {"ss-min-ls",       no_argument, NULL, ss_min_ls},
 2046:       {"ss-min-lsu",      no_argument, NULL, ss_min_lsu},
 2047:       {"ss-min-nexts",    no_argument, NULL, ss_min_nexts},
 2048:       {"ss-greedy",       no_argument, &ss_greedy, 1},
 2049:       {"tpa-noequiv",     no_argument, &tpa_noequiv, 1},
 2050:       {"tpa-noautomaton", no_argument, &tpa_noautomaton, 1},
 2051:       {"tpa-trace",	  no_argument, &tpa_trace, 1},
 2052:       {0,0,0,0}
 2053:       /* no-init-file, no-rc? */
 2054:     };
 2055:     
 2056:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
 2057:     
 2058:     switch (c) {
 2059:     case EOF: return;
 2060:     case '?': optind--; return;
 2061:     case 'a': *imagename = optarg; return;
 2062:     case 'i': *imagename = optarg; break;
 2063:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
 2064:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
 2065:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
 2066:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
 2067:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
 2068:     case 'p': *path = optarg; break;
 2069:     case 'o': offset_image = 1; break;
 2070:     case 'n': offset_image = 0; break;
 2071:     case 'c': clear_dictionary = 1; break;
 2072:     case 's': die_on_signal = 1; break;
 2073:     case 'x': debug = 1; break;
 2074:     case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
 2075:     case ss_number: static_super_number = atoi(optarg); break;
 2076:     case ss_states: maxstates = max(min(atoi(optarg),MAX_STATE),1); break;
 2077: #ifndef NO_DYNAMIC
 2078:     case ss_min_codesize: ss_cost = cost_codesize; break;
 2079: #endif
 2080:     case ss_min_ls:       ss_cost = cost_ls;       break;
 2081:     case ss_min_lsu:      ss_cost = cost_lsu;      break;
 2082:     case ss_min_nexts:    ss_cost = cost_nexts;    break;
 2083:     case 'h': 
 2084:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
 2085: Engine Options:\n\
 2086:   --appl-image FILE		    equivalent to '--image-file=FILE --'\n\
 2087:   --clear-dictionary		    Initialize the dictionary with 0 bytes\n\
 2088:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
 2089:   --debug			    Print debugging information during startup\n\
 2090:   --diag			    Print diagnostic information during startup\n\
 2091:   --die-on-signal		    exit instead of THROWing some signals\n\
 2092:   --dynamic			    use dynamic native code\n\
 2093:   -f SIZE, --fp-stack-size=SIZE	    Specify floating point stack size\n\
 2094:   -h, --help			    Print this message and exit\n\
 2095:   --ignore-async-signals            ignore instead of THROWing async. signals\n\
 2096:   -i FILE, --image-file=FILE	    Use image FILE instead of `gforth.fi'\n\
 2097:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
 2098:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
 2099:   --no-dynamic			    Use only statically compiled primitives\n\
 2100:   --no-offset-im		    Load image at normal position\n\
 2101:   --no-super                        No dynamically formed superinstructions\n\
 2102:   --offset-image		    Load image at a different position\n\
 2103:   -p PATH, --path=PATH		    Search path for finding image and sources\n\
 2104:   --print-metrics		    Print some code generation metrics on exit\n\
 2105:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
 2106:   --ss-greedy                       greedy, not optimal superinst selection\n\
 2107:   --ss-min-codesize                 select superinsts for smallest native code\n\
 2108:   --ss-min-ls                       minimize loads and stores\n\
 2109:   --ss-min-lsu                      minimize loads, stores, and pointer updates\n\
 2110:   --ss-min-nexts                    minimize the number of static superinsts\n\
 2111:   --ss-number=N                     use N static superinsts (default max)\n\
 2112:   --ss-states=N                     N states for stack caching (default max)\n\
 2113:   --tpa-noequiv                     automaton without state equivalence\n\
 2114:   --tpa-noautomaton                 dynamic programming only\n\
 2115:   --tpa-trace                       report new states etc.\n\
 2116:   -v, --version			    Print engine version and exit\n\
 2117: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
 2118:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
 2119: 	      argv[0]);
 2120:       optind--;
 2121:       return;
 2122:     }
 2123:   }
 2124: }
 2125: #endif
 2126: 
 2127: static void print_diag()
 2128: {
 2129: 
 2130: #if !defined(HAVE_GETRUSAGE) || (!defined(HAS_FFCALL) && !defined(HAS_LIBFFI))
 2131:   fprintf(stderr, "*** missing functionality ***\n"
 2132: #ifndef HAVE_GETRUSAGE
 2133: 	  "    no getrusage -> CPUTIME broken\n"
 2134: #endif
 2135: #if !defined(HAS_FFCALL) && !defined(HAS_LIBFFI)
 2136: 	  "    no ffcall -> only old-style foreign function calls (no fflib.fs)\n"
 2137: #endif
 2138: 	  );
 2139: #endif
 2140:   if((relocs < nonrelocs) ||
 2141: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
 2142:      1
 2143: #else
 2144:      0
 2145: #endif
 2146:      )
 2147:     debugp(stderr, "relocs: %d:%d\n", relocs, nonrelocs);
 2148:     fprintf(stderr, "*** %sperformance problems ***\n%s",
 2149: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D) || !defined(FORCE_REG) || defined(BUGGY_LONG_LONG)
 2150: 	    "",
 2151: #else
 2152: 	    "no ",
 2153: #endif
 2154: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
 2155: 	    "    double-cell integer type buggy ->\n        "
 2156: #ifdef BUGGY_LL_CMP
 2157: 	    "CMP, "
 2158: #endif
 2159: #ifdef BUGGY_LL_MUL
 2160: 	    "MUL, "
 2161: #endif
 2162: #ifdef BUGGY_LL_DIV
 2163: 	    "DIV, "
 2164: #endif
 2165: #ifdef BUGGY_LL_ADD
 2166: 	    "ADD, "
 2167: #endif
 2168: #ifdef BUGGY_LL_SHIFT
 2169: 	    "SHIFT, "
 2170: #endif
 2171: #ifdef BUGGY_LL_D2F
 2172: 	    "D2F, "
 2173: #endif
 2174: #ifdef BUGGY_LL_F2D
 2175: 	    "F2D, "
 2176: #endif
 2177: 	    "\b\b slow\n"
 2178: #endif
 2179: #ifndef FORCE_REG
 2180: 	    "    automatic register allocation: performance degradation possible\n"
 2181: #endif
 2182: #if !defined(FORCE_REG) || defined(BUGGY_LONG_LONG)
 2183: 	    "*** Suggested remedy: try ./configure"
 2184: #ifndef FORCE_REG
 2185: 	    " --enable-force-reg"
 2186: #endif
 2187: #ifdef BUGGY_LONG_LONG
 2188: 	    " --enable-force-ll"
 2189: #endif
 2190: 	    "\n"
 2191: #else
 2192: 	    ""
 2193: #endif
 2194: 	    ,
 2195: 	    (relocs < nonrelocs) ? "    gcc PR 15242 -> no dynamic code generation (use gcc-2.95 instead)\n" : "");
 2196: }
 2197: 
 2198: #ifdef INCLUDE_IMAGE
 2199: extern Cell image[];
 2200: extern const char reloc_bits[];
 2201: #endif
 2202: 
 2203: int main(int argc, char **argv, char **env)
 2204: {
 2205: #ifdef HAS_OS
 2206:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
 2207: #else
 2208:   char *path = DEFAULTPATH;
 2209: #endif
 2210: #ifndef INCLUDE_IMAGE
 2211:   char *imagename="gforth.fi";
 2212:   FILE *image_file;
 2213:   Address image;
 2214: #endif
 2215:   int retvalue;
 2216: 	  
 2217: #if defined(i386) && defined(ALIGNMENT_CHECK)
 2218:   /* turn on alignment checks on the 486.
 2219:    * on the 386 this should have no effect. */
 2220:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
 2221:   /* this is unusable with Linux' libc.4.6.27, because this library is
 2222:      not alignment-clean; we would have to replace some library
 2223:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
 2224:      the stack FP-aligned. */
 2225: #endif
 2226: 
 2227:   /* buffering of the user output device */
 2228: #ifdef _IONBF
 2229:   if (isatty(fileno(stdout))) {
 2230:     fflush(stdout);
 2231:     setvbuf(stdout,NULL,_IONBF,0);
 2232:   }
 2233: #endif
 2234: 
 2235:   progname = argv[0];
 2236: 
 2237: #ifdef HAS_OS
 2238:   gforth_args(argc, argv, &path, &imagename);
 2239: #ifndef NO_DYNAMIC
 2240:   init_ss_cost();
 2241: #endif /* !defined(NO_DYNAMIC) */
 2242: #endif /* defined(HAS_OS) */
 2243: 
 2244: #ifdef STANDALONE
 2245:   image = gforth_engine(0, 0, 0, 0, 0);
 2246:   alloc_stacks((ImageHeader *)image);
 2247: #else
 2248:   image_file = open_image_file(imagename, path);
 2249:   image = gforth_loader(image_file, imagename);
 2250: #endif
 2251:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
 2252: 
 2253:   if (diag)
 2254:     print_diag();
 2255:   {
 2256:     char path2[strlen(path)+1];
 2257:     char *p1, *p2;
 2258:     Cell environ[]= {
 2259:       (Cell)argc-(optind-1),
 2260:       (Cell)(argv+(optind-1)),
 2261:       (Cell)strlen(path),
 2262:       (Cell)path2};
 2263:     argv[optind-1] = progname;
 2264:     /*
 2265:        for (i=0; i<environ[0]; i++)
 2266:        printf("%s\n", ((char **)(environ[1]))[i]);
 2267:        */
 2268:     /* make path OS-independent by replacing path separators with NUL */
 2269:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
 2270:       if (*p1==PATHSEP)
 2271: 	*p2 = '\0';
 2272:       else
 2273: 	*p2 = *p1;
 2274:     *p2='\0';
 2275:     retvalue = gforth_go(image, 4, environ);
 2276: #if defined(SIGPIPE) && !defined(STANDALONE)
 2277:     bsd_signal(SIGPIPE, SIG_IGN);
 2278: #endif
 2279: #ifdef VM_PROFILING
 2280:     vm_print_profile(stderr);
 2281: #endif
 2282:     deprep_terminal();
 2283:   }
 2284:   if (print_metrics) {
 2285:     int i;
 2286:     fprintf(stderr, "code size = %8ld\n", dyncodesize());
 2287: #ifndef STANDALONE
 2288:     for (i=0; i<sizeof(cost_sums)/sizeof(cost_sums[0]); i++)
 2289:       fprintf(stderr, "metric %8s: %8ld\n",
 2290: 	      cost_sums[i].metricname, cost_sums[i].sum);
 2291: #endif
 2292:     fprintf(stderr,"lb_basic_blocks = %ld\n", lb_basic_blocks);
 2293:     fprintf(stderr,"lb_labeler_steps = %ld\n", lb_labeler_steps);
 2294:     fprintf(stderr,"lb_labeler_automaton = %ld\n", lb_labeler_automaton);
 2295:     fprintf(stderr,"lb_labeler_dynprog = %ld\n", lb_labeler_dynprog);
 2296:     fprintf(stderr,"lb_newstate_equiv = %ld\n", lb_newstate_equiv);
 2297:     fprintf(stderr,"lb_newstate_new = %ld\n", lb_newstate_new);
 2298:     fprintf(stderr,"lb_applicable_base_rules = %ld\n", lb_applicable_base_rules);
 2299:     fprintf(stderr,"lb_applicable_chain_rules = %ld\n", lb_applicable_chain_rules);
 2300:   }
 2301:   if (tpa_trace) {
 2302:     fprintf(stderr, "%ld %ld lb_states\n", lb_labeler_steps, lb_newstate_new);
 2303:     fprintf(stderr, "%ld %ld lb_table_entries\n", lb_labeler_steps, lb_labeler_dynprog);
 2304:   }
 2305:   return retvalue;
 2306: }

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