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

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

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