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

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

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