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

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

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