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

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

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