Annotation of gforth/engine/main.c, revision 1.227

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

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