File:  [gforth] / gforth / engine / main.c
Revision 1.187: download - view: text, annotated - select for diffs
Sun Sep 9 09:41:31 2007 UTC (16 years, 7 months ago) by anton
Branches: MAIN
CVS tags: HEAD
bugfix (reserve stack space for FTOS even if USE_NO_FTOS is defined)
  A better way to fix this would be to use an appropriate cache-fast.vmg

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

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