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

1.1       anton       1: /* command line interpretation, image loading etc. for Gforth
                      2: 
                      3: 
1.39      anton       4:   Copyright (C) 1995,1996,1997,1998,2000 Free Software Foundation, Inc.
1.1       anton       5: 
                      6:   This file is part of Gforth.
                      7: 
                      8:   Gforth is free software; you can redistribute it and/or
                      9:   modify it under the terms of the GNU General Public License
                     10:   as published by the Free Software Foundation; either version 2
                     11:   of the License, or (at your option) any later version.
                     12: 
                     13:   This program is distributed in the hope that it will be useful,
                     14:   but WITHOUT ANY WARRANTY; without even the implied warranty of
                     15:   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     16:   GNU General Public License for more details.
                     17: 
                     18:   You should have received a copy of the GNU General Public License
                     19:   along with this program; if not, write to the Free Software
1.40      anton      20:   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
1.1       anton      21: */
                     22: 
                     23: #include "config.h"
                     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.32      pazsan     31: #ifndef STANDALONE
1.1       anton      32: #include <sys/stat.h>
1.32      pazsan     33: #endif
1.1       anton      34: #include <fcntl.h>
                     35: #include <assert.h>
                     36: #include <stdlib.h>
1.11      pazsan     37: #ifndef STANDALONE
1.1       anton      38: #if HAVE_SYS_MMAN_H
                     39: #include <sys/mman.h>
                     40: #endif
1.11      pazsan     41: #endif
1.1       anton      42: #include "forth.h"
                     43: #include "io.h"
                     44: #include "getopt.h"
1.11      pazsan     45: #ifdef STANDALONE
                     46: #include <systypes.h>
                     47: #endif
1.1       anton      48: 
                     49: #define PRIM_VERSION 1
                     50: /* increment this whenever the primitives change in an incompatible way */
                     51: 
1.14      pazsan     52: #ifndef DEFAULTPATH
1.39      anton      53: #  define DEFAULTPATH "."
1.14      pazsan     54: #endif
                     55: 
1.1       anton      56: #ifdef MSDOS
                     57: jmp_buf throw_jmp_buf;
                     58: #endif
                     59: 
1.56      anton      60: #if defined(DOUBLY_INDIRECT)
                     61: #  define CFA(n)       ({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
1.1       anton      62: #else
1.56      anton      63: #  define CFA(n)       ((Cell)(symbols+((n)&~0x4000UL)))
1.1       anton      64: #endif
                     65: 
                     66: #define maxaligned(n)  (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
                     67: 
                     68: static UCell dictsize=0;
                     69: static UCell dsize=0;
                     70: static UCell rsize=0;
                     71: static UCell fsize=0;
                     72: static UCell lsize=0;
                     73: int offset_image=0;
1.4       anton      74: int die_on_signal=0;
1.13      pazsan     75: #ifndef INCLUDE_IMAGE
1.1       anton      76: static int clear_dictionary=0;
1.24      anton      77: UCell pagesize=1;
1.22      pazsan     78: char *progname;
                     79: #else
                     80: char *progname = "gforth";
                     81: int optind = 1;
1.13      pazsan     82: #endif
1.31      pazsan     83: 
1.75      anton      84: #define CODE_BLOCK_SIZE (64*1024)
1.48      anton      85: Address code_area=0;
1.73      anton      86: Cell code_area_size = CODE_BLOCK_SIZE;
1.75      anton      87: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
                     88:                                           does for the dictionary */
1.65      anton      89: Address start_flush=0; /* start of unflushed code */
1.74      anton      90: Cell last_jump=0; /* if the last prim was compiled without jump, this
                     91:                      is it's number, otherwise this contains 0 */
1.48      anton      92: 
1.60      anton      93: static int no_super=0;   /* true if compile_prim should not fuse prims */
1.66      anton      94: /* --no-dynamic by default on gcc versions >=3.1 (it works with 3.0.4,
                     95:    but not with 3.2) */
                     96: #if (__GNUC__>2 && __GNUC_MINOR__>=1)
1.64      anton      97: static int no_dynamic=1; /* true if compile_prim should not generate code */
1.66      anton      98: #else
                     99: static int no_dynamic=0; /* true if compile_prim should not generate code */
                    100: #endif
1.60      anton     101: 
1.30      pazsan    102: #ifdef HAS_DEBUG
1.68      anton     103: int debug=0;
1.31      pazsan    104: #else
                    105: # define perror(x...)
                    106: # define fprintf(x...)
1.30      pazsan    107: #endif
1.31      pazsan    108: 
1.24      anton     109: ImageHeader *gforth_header;
1.43      anton     110: Label *vm_prims;
1.53      anton     111: #ifdef DOUBLY_INDIRECT
                    112: Label *xts; /* same content as vm_prims, but should only be used for xts */
                    113: #endif
1.1       anton     114: 
1.30      pazsan    115: #ifdef MEMCMP_AS_SUBROUTINE
                    116: int gforth_memcmp(const char * s1, const char * s2, size_t n)
                    117: {
                    118:   return memcmp(s1, s2, n);
                    119: }
                    120: #endif
                    121: 
1.1       anton     122: /* image file format:
1.15      pazsan    123:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
1.1       anton     124:  *   padding to a multiple of 8
1.15      pazsan    125:  *   magic: "Gforth2x" means format 0.4,
                    126:  *              where x is a byte with
                    127:  *              bit 7:   reserved = 0
                    128:  *              bit 6:5: address unit size 2^n octets
                    129:  *              bit 4:3: character size 2^n octets
                    130:  *              bit 2:1: cell size 2^n octets
                    131:  *              bit 0:   endian, big=0, little=1.
                    132:  *  The magic are always 8 octets, no matter what the native AU/character size is
1.1       anton     133:  *  padding to max alignment (no padding necessary on current machines)
1.24      anton     134:  *  ImageHeader structure (see forth.h)
1.1       anton     135:  *  data (size in ImageHeader.image_size)
                    136:  *  tags ((if relocatable, 1 bit/data cell)
                    137:  *
                    138:  * tag==1 means that the corresponding word is an address;
                    139:  * If the word is >=0, the address is within the image;
                    140:  * addresses within the image are given relative to the start of the image.
                    141:  * If the word =-1 (CF_NIL), the address is NIL,
                    142:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
                    143:  * If the word =CF(DODOES), it's a DOES> CFA
                    144:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
                    145:  *                                     possibly containing a jump to dodoes)
1.51      anton     146:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
                    147:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
                    148:  *                                        it's the threaded code of a primitive
1.1       anton     149:  */
                    150: 
1.46      jwilke    151: void relocate(Cell *image, const char *bitstring, 
                    152:               int size, int base, Label symbols[])
1.1       anton     153: {
1.16      pazsan    154:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
1.11      pazsan    155:   Cell token;
1.1       anton     156:   char bits;
1.37      anton     157:   Cell max_symbols;
1.46      jwilke    158:   /* 
                    159:    * A virtial start address that's the real start address minus 
                    160:    * the one in the image 
                    161:    */
1.45      jwilke    162:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
1.1       anton     163: 
1.46      jwilke    164:   
                    165: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
1.37      anton     166:   
                    167:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
                    168:     ;
1.47      anton     169:   max_symbols--;
1.35      pazsan    170:   size/=sizeof(Cell);
                    171: 
1.31      pazsan    172:   for(k=0; k<=steps; k++) {
1.13      pazsan    173:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
1.1       anton     174:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
1.35      pazsan    175:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
                    176:        /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
1.45      jwilke    177:         token=image[i];
                    178:        if(token<0)
1.55      anton     179:          switch(token|0x4000)
1.1       anton     180:            {
                    181:            case CF_NIL      : image[i]=0; break;
                    182: #if !defined(DOUBLY_INDIRECT)
                    183:            case CF(DOCOL)   :
                    184:            case CF(DOVAR)   :
                    185:            case CF(DOCON)   :
                    186:            case CF(DOUSER)  : 
                    187:            case CF(DODEFER) : 
1.11      pazsan    188:            case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
1.1       anton     189:            case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
                    190: #endif /* !defined(DOUBLY_INDIRECT) */
                    191:            case CF(DODOES)  :
1.45      jwilke    192:              MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
1.1       anton     193:              break;
                    194:            default          :
1.56      anton     195: /*           printf("Code field generation image[%x]:=CFA(%x)\n",
1.1       anton     196:                     i, CF(image[i])); */
1.55      anton     197:              if (CF((token | 0x4000))<max_symbols) {
1.56      anton     198:                image[i]=(Cell)CFA(CF(token));
                    199: #ifdef DIRECT_THREADED
                    200:                if ((token & 0x4000) == 0) /* threade code, no CFA */
1.70      anton     201:                  compile_prim1(&image[i]);
1.56      anton     202: #endif
1.55      anton     203:              } else
1.37      anton     204:                fprintf(stderr,"Primitive %d used in this image at $%lx is not implemented by this\n engine (%s); executing this code will crash.\n",CF(token),(long)&image[i],VERSION);
1.1       anton     205:            }
1.46      jwilke    206:        else {
1.45      jwilke    207:           // if base is > 0: 0 is a null reference so don't adjust
                    208:           if (token>=base) {
                    209:             image[i]+=(Cell)start;
                    210:           }
1.46      jwilke    211:         }
1.1       anton     212:       }
                    213:     }
1.31      pazsan    214:   }
1.70      anton     215:   finish_code();
1.26      jwilke    216:   ((ImageHeader*)(image))->base = (Address) image;
1.1       anton     217: }
                    218: 
                    219: UCell checksum(Label symbols[])
                    220: {
                    221:   UCell r=PRIM_VERSION;
                    222:   Cell i;
                    223: 
                    224:   for (i=DOCOL; i<=DOESJUMP; i++) {
                    225:     r ^= (UCell)(symbols[i]);
                    226:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    227:   }
                    228: #ifdef DIRECT_THREADED
                    229:   /* we have to consider all the primitives */
                    230:   for (; symbols[i]!=(Label)0; i++) {
                    231:     r ^= (UCell)(symbols[i]);
                    232:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    233:   }
                    234: #else
                    235:   /* in indirect threaded code all primitives are accessed through the
                    236:      symbols table, so we just have to put the base address of symbols
                    237:      in the checksum */
                    238:   r ^= (UCell)symbols;
                    239: #endif
                    240:   return r;
                    241: }
                    242: 
1.3       anton     243: Address verbose_malloc(Cell size)
                    244: {
                    245:   Address r;
                    246:   /* leave a little room (64B) for stack underflows */
                    247:   if ((r = malloc(size+64))==NULL) {
                    248:     perror(progname);
                    249:     exit(1);
                    250:   }
                    251:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
                    252:   if (debug)
                    253:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
                    254:   return r;
                    255: }
                    256: 
1.33      anton     257: static Address next_address=0;
                    258: void after_alloc(Address r, Cell size)
                    259: {
                    260:   if (r != (Address)-1) {
                    261:     if (debug)
                    262:       fprintf(stderr, "success, address=$%lx\n", (long) r);
                    263:     if (pagesize != 1)
                    264:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
                    265:   } else {
                    266:     if (debug)
                    267:       fprintf(stderr, "failed: %s\n", strerror(errno));
                    268:   }
                    269: }
                    270: 
1.34      anton     271: #ifndef MAP_FAILED
                    272: #define MAP_FAILED ((Address) -1)
                    273: #endif
                    274: #ifndef MAP_FILE
                    275: # define MAP_FILE 0
                    276: #endif
                    277: #ifndef MAP_PRIVATE
                    278: # define MAP_PRIVATE 0
                    279: #endif
                    280: 
                    281: #if defined(HAVE_MMAP)
                    282: static Address alloc_mmap(Cell size)
1.1       anton     283: {
                    284:   Address r;
                    285: 
                    286: #if defined(MAP_ANON)
                    287:   if (debug)
                    288:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
1.34      anton     289:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
1.1       anton     290: #else /* !defined(MAP_ANON) */
1.17      anton     291:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
                    292:      apparently defaults) */
1.1       anton     293:   static int dev_zero=-1;
                    294: 
                    295:   if (dev_zero == -1)
                    296:     dev_zero = open("/dev/zero", O_RDONLY);
                    297:   if (dev_zero == -1) {
1.34      anton     298:     r = MAP_FAILED;
1.1       anton     299:     if (debug)
                    300:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
                    301:              strerror(errno));
                    302:   } else {
                    303:     if (debug)
                    304:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
                    305:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
                    306:   }
                    307: #endif /* !defined(MAP_ANON) */
1.34      anton     308:   after_alloc(r, size);
                    309:   return r;  
                    310: }
                    311: #endif
                    312: 
                    313: Address my_alloc(Cell size)
                    314: {
                    315: #if HAVE_MMAP
                    316:   Address r;
                    317: 
                    318:   r=alloc_mmap(size);
                    319:   if (r!=MAP_FAILED)
1.1       anton     320:     return r;
                    321: #endif /* HAVE_MMAP */
1.3       anton     322:   /* use malloc as fallback */
                    323:   return verbose_malloc(size);
1.1       anton     324: }
                    325: 
1.34      anton     326: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
1.33      anton     327: {
1.34      anton     328:   Address image = MAP_FAILED;
1.33      anton     329: 
1.56      anton     330: #if defined(HAVE_MMAP)
1.33      anton     331:   if (offset==0) {
1.34      anton     332:     image=alloc_mmap(dictsize);
1.33      anton     333:     if (debug)
1.34      anton     334:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
                    335:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
                    336:     after_alloc(image,dictsize);
1.33      anton     337:   }
1.56      anton     338: #endif /* defined(HAVE_MMAP) */
1.34      anton     339:   if (image == MAP_FAILED) {
1.56      anton     340:     image = my_alloc(dictsize+offset)+offset;
1.33      anton     341:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
1.34      anton     342:     fread(image, 1, imagesize, file);
1.33      anton     343:   }
                    344:   return image;
                    345: }
                    346: 
1.10      pazsan    347: void set_stack_sizes(ImageHeader * header)
                    348: {
                    349:   if (dictsize==0)
                    350:     dictsize = header->dict_size;
                    351:   if (dsize==0)
                    352:     dsize = header->data_stack_size;
                    353:   if (rsize==0)
                    354:     rsize = header->return_stack_size;
                    355:   if (fsize==0)
                    356:     fsize = header->fp_stack_size;
                    357:   if (lsize==0)
                    358:     lsize = header->locals_stack_size;
                    359:   dictsize=maxaligned(dictsize);
                    360:   dsize=maxaligned(dsize);
                    361:   rsize=maxaligned(rsize);
                    362:   lsize=maxaligned(lsize);
                    363:   fsize=maxaligned(fsize);
                    364: }
                    365: 
                    366: void alloc_stacks(ImageHeader * header)
                    367: {
                    368:   header->dict_size=dictsize;
                    369:   header->data_stack_size=dsize;
                    370:   header->fp_stack_size=fsize;
                    371:   header->return_stack_size=rsize;
                    372:   header->locals_stack_size=lsize;
                    373: 
                    374:   header->data_stack_base=my_alloc(dsize);
                    375:   header->fp_stack_base=my_alloc(fsize);
                    376:   header->return_stack_base=my_alloc(rsize);
                    377:   header->locals_stack_base=my_alloc(lsize);
                    378: }
                    379: 
1.44      pazsan    380: #warning You can ignore the warnings about clobbered variables in go_forth
1.11      pazsan    381: int go_forth(Address image, int stack, Cell *entries)
                    382: {
1.38      anton     383:   volatile ImageHeader *image_header = (ImageHeader *)image;
1.18      anton     384:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
1.44      pazsan    385:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
1.18      anton     386:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
1.44      pazsan    387: #ifdef GFORTH_DEBUGGING
1.38      anton     388:   volatile Cell *orig_rp0=rp0;
1.44      pazsan    389: #endif
1.18      anton     390:   Address lp0=image_header->locals_stack_base + lsize;
                    391:   Xt *ip0=(Xt *)(image_header->boot_entry);
1.13      pazsan    392: #ifdef SYSSIGNALS
1.11      pazsan    393:   int throw_code;
1.13      pazsan    394: #endif
1.11      pazsan    395: 
                    396:   /* ensure that the cached elements (if any) are accessible */
1.41      anton     397:   IF_spTOS(sp0--);
                    398:   IF_fpTOS(fp0--);
1.11      pazsan    399:   
                    400:   for(;stack>0;stack--)
1.18      anton     401:     *--sp0=entries[stack-1];
1.11      pazsan    402: 
1.30      pazsan    403: #ifdef SYSSIGNALS
1.11      pazsan    404:   get_winsize();
                    405:    
                    406:   install_signal_handlers(); /* right place? */
                    407:   
                    408:   if ((throw_code=setjmp(throw_jmp_buf))) {
                    409:     static Cell signal_data_stack[8];
                    410:     static Cell signal_return_stack[8];
                    411:     static Float signal_fp_stack[1];
1.13      pazsan    412: 
1.11      pazsan    413:     signal_data_stack[7]=throw_code;
1.18      anton     414: 
                    415: #ifdef GFORTH_DEBUGGING
1.38      anton     416:     /* fprintf(stderr,"\nrp=%ld\n",(long)rp); */
                    417:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
1.18      anton     418:       /* no rstack overflow or underflow */
                    419:       rp0 = rp;
1.63      anton     420:       *--rp0 = (Cell)saved_ip;
1.18      anton     421:     }
                    422:     else /* I love non-syntactic ifdefs :-) */
                    423: #endif
                    424:     rp0 = signal_return_stack+8;
1.25      anton     425:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
1.11      pazsan    426:     
1.33      anton     427:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
1.18      anton     428:                       rp0, signal_fp_stack, 0));
1.11      pazsan    429:   }
1.13      pazsan    430: #endif
1.11      pazsan    431: 
1.33      anton     432:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
1.11      pazsan    433: }
                    434: 
1.30      pazsan    435: #ifndef INCLUDE_IMAGE
1.21      anton     436: void print_sizes(Cell sizebyte)
                    437:      /* print size information */
                    438: {
                    439:   static char* endianstring[]= { "   big","little" };
                    440:   
                    441:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
                    442:          endianstring[sizebyte & 1],
                    443:          1 << ((sizebyte >> 1) & 3),
                    444:          1 << ((sizebyte >> 3) & 3),
                    445:          1 << ((sizebyte >> 5) & 3));
                    446: }
                    447: 
1.70      anton     448: #define MAX_IMMARGS 2
                    449: 
1.69      anton     450: #ifndef NO_DYNAMIC
1.47      anton     451: typedef struct {
                    452:   Label start;
1.74      anton     453:   Cell length; /* only includes the jump iff superend is true*/
                    454:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
1.70      anton     455:   char superend; /* true if primitive ends superinstruction, i.e.,
1.47      anton     456:                      unconditional branch, execute, etc. */
1.70      anton     457:   Cell nimmargs;
                    458:   struct immarg {
                    459:     Cell offset; /* offset of immarg within prim */
                    460:     char rel;    /* true if immarg is relative */
                    461:   } immargs[MAX_IMMARGS];
1.47      anton     462: } PrimInfo;
                    463: 
                    464: PrimInfo *priminfos;
1.76      anton     465: PrimInfo **decomp_prims;
                    466: 
                    467: int compare_priminfo_length(PrimInfo **a, PrimInfo **b)
                    468: {
1.77      anton     469:   Cell diff = (*a)->length - (*b)->length;
                    470:   if (diff)
                    471:     return diff;
                    472:   else /* break ties by start address; thus the decompiler produces
                    473:           the earliest primitive with the same code (e.g. noop instead
                    474:           of (char) and @ instead of >code-address */
                    475:     return (*b)->start - (*a)->start;
1.76      anton     476: }
                    477: 
1.69      anton     478: #endif /* defined(NO_DYNAMIC) */
1.48      anton     479: Cell npriminfos=0;
1.47      anton     480: 
1.76      anton     481: 
1.47      anton     482: void check_prims(Label symbols1[])
                    483: {
                    484:   int i;
1.70      anton     485:   Label *symbols2, *symbols3, *ends1;
1.49      anton     486:   static char superend[]={
1.48      anton     487: #include "prim_superend.i"
                    488:   };
1.47      anton     489: 
1.66      anton     490:   if (debug)
                    491: #ifdef __VERSION__
                    492:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
                    493: #else
                    494: #define xstr(s) str(s)
                    495: #define str(s) #s
                    496:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
                    497: #endif
1.47      anton     498:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
                    499:     ;
1.55      anton     500:   npriminfos = i;
1.70      anton     501:   
                    502: #ifndef NO_DYNAMIC
1.66      anton     503:   if (no_dynamic)
                    504:     return;
1.55      anton     505:   symbols2=engine2(0,0,0,0,0);
1.70      anton     506: #if NO_IP
                    507:   symbols3=engine3(0,0,0,0,0);
                    508: #else
                    509:   symbols3=symbols1;
                    510: #endif
                    511:   ends1 = symbols1+i+1-DOESJUMP;
1.47      anton     512:   priminfos = calloc(i,sizeof(PrimInfo));
                    513:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
1.70      anton     514:     int prim_len = ends1[i]-symbols1[i];
1.47      anton     515:     PrimInfo *pi=&priminfos[i];
1.70      anton     516:     int j=0;
                    517:     char *s1 = (char *)symbols1[i];
                    518:     char *s2 = (char *)symbols2[i];
                    519:     char *s3 = (char *)symbols3[i];
                    520: 
                    521:     pi->start = s1;
                    522:     pi->superend = superend[i-DOESJUMP-1]|no_super;
                    523:     if (pi->superend)
                    524:       pi->length = symbols1[i+1]-symbols1[i];
                    525:     else
                    526:       pi->length = prim_len;
1.74      anton     527:     pi->restlength = symbols1[i+1] - symbols1[i] - pi->length;
1.70      anton     528:     pi->nimmargs = 0;
                    529:     if (debug)
1.74      anton     530:       fprintf(stderr, "Prim %3d @ %p %p %p, length=%3d restlength=%2d superend=%1d",
                    531:              i, s1, s2, s3, pi->length, pi->restlength, pi->superend);
1.70      anton     532:     assert(prim_len>=0);
1.74      anton     533:     while (j<(pi->length+pi->restlength)) {
1.70      anton     534:       if (s1[j]==s3[j]) {
                    535:        if (s1[j] != s2[j]) {
                    536:          pi->start = NULL; /* not relocatable */
                    537:          if (debug)
                    538:            fprintf(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
1.74      anton     539:          /* assert(j<prim_len); */
1.70      anton     540:          break;
                    541:        }
                    542:        j++;
                    543:       } else {
                    544:        struct immarg *ia=&pi->immargs[pi->nimmargs];
                    545: 
                    546:        pi->nimmargs++;
                    547:        ia->offset=j;
                    548:        if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
                    549:          ia->rel=0;
                    550:          if (debug)
                    551:            fprintf(stderr,"\n   absolute immarg: offset %3d",j);
                    552:        } else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
                    553:                   symbols1[DOESJUMP+1]) {
                    554:          ia->rel=1;
                    555:          if (debug)
                    556:            fprintf(stderr,"\n   relative immarg: offset %3d",j);
                    557:        } else {
                    558:          pi->start = NULL; /* not relocatable */
                    559:          if (debug)
                    560:            fprintf(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
1.74      anton     561:          /* assert(j<prim_len);*/
1.70      anton     562:          break;
                    563:        }
                    564:        j+=4;
1.47      anton     565:       }
                    566:     }
1.70      anton     567:     if (debug)
                    568:       fprintf(stderr,"\n");
                    569:   }
1.76      anton     570:   decomp_prims = calloc(i,sizeof(PrimInfo *));
                    571:   for (i=DOESJUMP+1; i<npriminfos; i++)
                    572:     decomp_prims[i] = &(priminfos[i]);
                    573:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
                    574:        compare_priminfo_length);
1.70      anton     575: #endif
                    576: }
                    577: 
1.74      anton     578: #ifndef NO_DYNAMIC
                    579: void flush_to_here(void)
                    580: {
                    581:   FLUSH_ICACHE(start_flush, code_here-start_flush);
                    582:   start_flush=code_here;
                    583: }
                    584: 
                    585: void append_jump(void)
                    586: {
                    587:   if (last_jump) {
                    588:     PrimInfo *pi = &priminfos[last_jump];
                    589:     
                    590:     memcpy(code_here, pi->start+pi->length, pi->restlength);
                    591:     code_here += pi->restlength;
                    592:     last_jump=0;
                    593:     flush_to_here();
                    594:   }
                    595: }
                    596: 
1.75      anton     597: /* Gforth remembers all code blocks in this list.  On forgetting (by
                    598: executing a marker) the code blocks are not freed (because Gforth does
                    599: not remember how they were allocated; hmm, remembering that might be
                    600: easier and cleaner).  Instead, code_here etc. are reset to the old
                    601: value, and the "forgotten" code blocks are reused when they are
                    602: needed. */
                    603: 
                    604: struct code_block_list {
                    605:   struct code_block_list *next;
                    606:   Address block;
                    607:   Cell size;
                    608: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
                    609: 
1.74      anton     610: Address append_prim(Cell p)
                    611: {
                    612:   PrimInfo *pi = &priminfos[p];
                    613:   Address old_code_here = code_here;
                    614: 
                    615:   if (code_area+code_area_size < code_here+pi->length+pi->restlength) {
1.75      anton     616:     struct code_block_list *p;
1.74      anton     617:     append_jump();
1.75      anton     618:     if (*next_code_blockp == NULL) {
                    619:       code_here = start_flush = code_area = my_alloc(code_area_size);
                    620:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
                    621:       *next_code_blockp = p;
                    622:       p->next = NULL;
                    623:       p->block = code_here;
                    624:       p->size = code_area_size;
                    625:     } else {
                    626:       p = *next_code_blockp;
                    627:       code_here = start_flush = code_area = p->block;
                    628:     }
1.74      anton     629:     old_code_here = code_here;
1.75      anton     630:     next_code_blockp = &(p->next);
1.74      anton     631:   }
                    632:   memcpy(code_here, pi->start, pi->length);
                    633:   code_here += pi->length;
                    634:   if (pi->superend)
                    635:     flush_to_here();
                    636:   return old_code_here;
                    637: }
                    638: #endif
1.75      anton     639: 
                    640: int forget_dyncode(Address code)
                    641: {
                    642: #ifdef NO_DYNAMIC
                    643:   return -1;
                    644: #else
                    645:   struct code_block_list *p, **pp;
                    646: 
                    647:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
                    648:     if (code >= p->block && code < p->block+p->size) {
                    649:       next_code_blockp = &(p->next);
                    650:       code_here = start_flush = code;
                    651:       code_area = p->block;
                    652:       last_jump = 0;
                    653:       return -1;
                    654:     }
                    655:   }
1.78    ! anton     656:   return -no_dynamic;
1.75      anton     657: #endif /* !defined(NO_DYNAMIC) */
                    658: }
                    659: 
1.76      anton     660: Label decompile_code(Label code)
1.75      anton     661: {
1.76      anton     662: #ifdef NO_DYNAMIC
                    663:   return code;
                    664: #else /* !defined(NO_DYNAMIC) */
                    665:   Cell i;
1.77      anton     666:   struct code_block_list *p;
1.76      anton     667: 
1.77      anton     668:   /* first, check if we are in code at all */
                    669:   for (p = code_block_list;; p = p->next) {
                    670:     if (p == NULL)
                    671:       return code;
                    672:     if (code >= p->block && code < p->block+p->size)
                    673:       break;
                    674:   }
1.76      anton     675:   /* reverse order because NOOP might match other prims */
                    676:   for (i=npriminfos-1; i>DOESJUMP; i--) {
                    677:     PrimInfo *pi=decomp_prims[i];
                    678:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
                    679:       return pi->start;
                    680:   }
                    681:   return code;
                    682: #endif /* !defined(NO_DYNAMIC) */
1.75      anton     683: }
1.74      anton     684: 
1.70      anton     685: #ifdef NO_IP
                    686: int nbranchinfos=0;
                    687: 
                    688: struct branchinfo {
                    689:   Label *targetptr; /* *(bi->targetptr) is the target */
                    690:   Cell *addressptr; /* store the target here */
                    691: } branchinfos[100000];
                    692: 
                    693: int ndoesexecinfos=0;
                    694: struct doesexecinfo {
                    695:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
                    696:   Cell *xt; /* cfa of word whose does-code needs calling */
                    697: } doesexecinfos[10000];
                    698: 
1.73      anton     699: /* definitions of N_execute etc. */
                    700: #include "prim_num.i"
1.70      anton     701: 
                    702: void set_rel_target(Cell *source, Label target)
                    703: {
                    704:   *source = ((Cell)target)-(((Cell)source)+4);
                    705: }
                    706: 
                    707: void register_branchinfo(Label source, Cell targetptr)
                    708: {
                    709:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
                    710:   bi->targetptr = (Label *)targetptr;
                    711:   bi->addressptr = (Cell *)source;
                    712:   nbranchinfos++;
                    713: }
                    714: 
                    715: Cell *compile_prim1arg(Cell p)
                    716: {
                    717:   int l = priminfos[p].length;
                    718:   Address old_code_here=code_here;
                    719: 
1.74      anton     720:   assert(vm_prims[p]==priminfos[p].start);
                    721:   append_prim(p);
1.70      anton     722:   return (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
                    723: }
                    724: 
                    725: Cell *compile_call2(Cell targetptr)
                    726: {
                    727:   Cell *next_code_target;
1.73      anton     728:   PrimInfo *pi = &priminfos[N_call2];
1.74      anton     729:   Address old_code_here = append_prim(N_call2);
1.70      anton     730: 
1.74      anton     731:   next_code_target = (Cell *)(old_code_here + pi->immargs[0].offset);
                    732:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetptr);
1.70      anton     733:   return next_code_target;
                    734: }
                    735: #endif
                    736: 
                    737: void finish_code(void)
                    738: {
                    739: #ifdef NO_IP
                    740:   Cell i;
                    741: 
                    742:   compile_prim1(NULL);
                    743:   for (i=0; i<ndoesexecinfos; i++) {
                    744:     struct doesexecinfo *dei = &doesexecinfos[i];
                    745:     branchinfos[dei->branchinfo].targetptr = DOES_CODE1((dei->xt));
                    746:   }
                    747:   ndoesexecinfos = 0;
                    748:   for (i=0; i<nbranchinfos; i++) {
                    749:     struct branchinfo *bi=&branchinfos[i];
                    750:     set_rel_target(bi->addressptr, *(bi->targetptr));
                    751:   }
                    752:   nbranchinfos = 0;
                    753:   FLUSH_ICACHE(start_flush, code_here-start_flush);
                    754:   start_flush=code_here;
1.48      anton     755: #endif
                    756: }
                    757: 
1.70      anton     758: void compile_prim1(Cell *start)
1.48      anton     759: {
1.61      anton     760: #if defined(DOUBLY_INDIRECT)
1.70      anton     761:   Label prim=(Label)*start;
1.54      anton     762:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
                    763:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
1.70      anton     764:     *start=(Cell)prim;
                    765:     return;
                    766:   } else {
                    767:     *start = prim-((Label)xts)+((Label)vm_prims);
                    768:     return;
                    769:   }
                    770: #elif defined(NO_IP)
                    771:   static Cell *last_start=NULL;
                    772:   static Xt last_prim=NULL;
                    773:   /* delay work by one call in order to get relocated immargs */
                    774: 
                    775:   if (last_start) {
                    776:     unsigned i = last_prim-vm_prims;
                    777:     PrimInfo *pi=&priminfos[i];
                    778:     Cell *next_code_target=NULL;
                    779: 
                    780:     assert(i<npriminfos);
1.73      anton     781:     if (i==N_execute||i==N_perform||i==N_lit_perform) {
                    782:       next_code_target = compile_prim1arg(N_set_next_code);
1.70      anton     783:     }
1.73      anton     784:     if (i==N_call) {
1.70      anton     785:       next_code_target = compile_call2(last_start[1]);
1.73      anton     786:     } else if (i==N_does_exec) {
1.70      anton     787:       struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
1.73      anton     788:       *compile_prim1arg(N_lit) = (Cell)PFA(last_start[1]);
1.70      anton     789:       /* we cannot determine the callee now (last_start[1] may be a
                    790:          forward reference), so just register an arbitrary target, and
                    791:          register in dei that we need to fix this before resolving
                    792:          branches */
                    793:       dei->branchinfo = nbranchinfos;
                    794:       dei->xt = (Cell *)(last_start[1]);
                    795:       next_code_target = compile_call2(NULL);
                    796:     } else if (pi->start == NULL) { /* non-reloc */
1.73      anton     797:       next_code_target = compile_prim1arg(N_set_next_code);
                    798:       set_rel_target(compile_prim1arg(N_abranch),*(Xt)last_prim);
1.70      anton     799:     } else {
                    800:       unsigned j;
1.74      anton     801:       Address old_code_here = append_prim(i);
1.70      anton     802: 
                    803:       for (j=0; j<pi->nimmargs; j++) {
                    804:        struct immarg *ia = &(pi->immargs[j]);
                    805:        Cell argval = last_start[pi->nimmargs - j]; /* !! specific to prims */
                    806:        if (ia->rel) { /* !! assumption: relative refs are branches */
1.74      anton     807:          register_branchinfo(old_code_here + ia->offset, argval);
1.70      anton     808:        } else /* plain argument */
1.74      anton     809:          *(Cell *)(old_code_here + ia->offset) = argval;
1.70      anton     810:       }
                    811:     }
                    812:     if (next_code_target!=NULL)
                    813:       *next_code_target = (Cell)code_here;
                    814:   }
                    815:   if (start) {
                    816:     last_prim = (Xt)*start;
                    817:     *start = (Cell)code_here;
                    818:   }
                    819:   last_start = start;
                    820:   return;
                    821: #elif !defined(NO_DYNAMIC)
                    822:   Label prim=(Label)*start;
1.58      anton     823:   unsigned i;
1.74      anton     824:   Address old_code_here;
1.48      anton     825: 
1.58      anton     826:   i = ((Xt)prim)-vm_prims;
1.56      anton     827:   prim = *(Xt)prim;
1.70      anton     828:   if (no_dynamic) {
                    829:     *start = (Cell)prim;
                    830:     return;
                    831:   }
1.58      anton     832:   if (i>=npriminfos || priminfos[i].start == 0) { /* not a relocatable prim */
1.74      anton     833:     append_jump();
1.70      anton     834:     *start = (Cell)prim;
                    835:     return;
1.47      anton     836:   }
1.58      anton     837:   assert(priminfos[i].start = prim); 
1.50      anton     838: #ifdef ALIGN_CODE
                    839:   ALIGN_CODE;
                    840: #endif
1.74      anton     841:   assert(prim==priminfos[i].start);
                    842:   old_code_here = append_prim(i);
                    843:   last_jump = (priminfos[i].superend) ? 0 : i;
1.70      anton     844:   *start = (Cell)old_code_here;
                    845:   return;
1.61      anton     846: #else /* !defined(DOUBLY_INDIRECT), no code replication */
1.70      anton     847:   Label prim=(Label)*start;
1.61      anton     848: #if !defined(INDIRECT_THREADED)
1.56      anton     849:   prim = *(Xt)prim;
1.61      anton     850: #endif
1.70      anton     851:   *start = (Cell)prim;
                    852:   return;
1.54      anton     853: #endif /* !defined(DOUBLY_INDIRECT) */
1.70      anton     854: }
                    855: 
                    856: Label compile_prim(Label prim)
                    857: {
                    858:   Cell x=(Cell)prim;
                    859:   compile_prim1(&x);
                    860:   return (Label)x;
1.47      anton     861: }
                    862: 
1.69      anton     863: #if defined(PRINT_SUPER_LENGTHS) && !defined(NO_DYNAMIC)
1.59      anton     864: Cell prim_length(Cell prim)
                    865: {
                    866:   return priminfos[prim+DOESJUMP+1].length;
                    867: }
                    868: #endif
                    869: 
1.1       anton     870: Address loader(FILE *imagefile, char* filename)
                    871: /* returns the address of the image proper (after the preamble) */
                    872: {
                    873:   ImageHeader header;
                    874:   Address image;
                    875:   Address imp; /* image+preamble */
1.17      anton     876:   Char magic[8];
                    877:   char magic7; /* size byte of magic number */
1.1       anton     878:   Cell preamblesize=0;
1.6       pazsan    879:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1.1       anton     880:   UCell check_sum;
1.15      pazsan    881:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
                    882:                 (RELINFOBITS == 16) ? 1 :
                    883:                 (RELINFOBITS == 32) ? 2 : 3);
                    884:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
                    885:                   (sizeof(Char) == 2) ? 1 :
                    886:                   (sizeof(Char) == 4) ? 2 : 3) + ausize;
                    887:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
                    888:                   (sizeof(Cell) == 2) ? 1 :
                    889:                   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1.21      anton     890:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
                    891: #ifdef WORDS_BIGENDIAN
                    892:        0
                    893: #else
                    894:        1
                    895: #endif
                    896:     ;
1.1       anton     897: 
1.43      anton     898:   vm_prims = engine(0,0,0,0,0);
1.47      anton     899:   check_prims(vm_prims);
1.1       anton     900: #ifndef DOUBLY_INDIRECT
1.59      anton     901: #ifdef PRINT_SUPER_LENGTHS
                    902:   print_super_lengths();
                    903: #endif
1.43      anton     904:   check_sum = checksum(vm_prims);
1.1       anton     905: #else /* defined(DOUBLY_INDIRECT) */
1.43      anton     906:   check_sum = (UCell)vm_prims;
1.1       anton     907: #endif /* defined(DOUBLY_INDIRECT) */
1.10      pazsan    908:   
                    909:   do {
                    910:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1.15      pazsan    911:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.4) image.\n",
1.10      pazsan    912:              progname, filename);
                    913:       exit(1);
1.1       anton     914:     }
1.10      pazsan    915:     preamblesize+=8;
1.15      pazsan    916:   } while(memcmp(magic,"Gforth2",7));
1.17      anton     917:   magic7 = magic[7];
1.1       anton     918:   if (debug) {
1.17      anton     919:     magic[7]='\0';
1.21      anton     920:     fprintf(stderr,"Magic found: %s ", magic);
                    921:     print_sizes(magic7);
1.1       anton     922:   }
                    923: 
1.21      anton     924:   if (magic7 != sizebyte)
                    925:     {
                    926:       fprintf(stderr,"This image is:         ");
                    927:       print_sizes(magic7);
                    928:       fprintf(stderr,"whereas the machine is ");
                    929:       print_sizes(sizebyte);
1.1       anton     930:       exit(-2);
                    931:     };
                    932: 
                    933:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1.10      pazsan    934: 
                    935:   set_stack_sizes(&header);
1.1       anton     936:   
                    937: #if HAVE_GETPAGESIZE
                    938:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
                    939: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
                    940:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
                    941: #elif PAGESIZE
                    942:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
                    943: #endif
                    944:   if (debug)
1.5       jwilke    945:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1.1       anton     946: 
1.34      anton     947:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
                    948:                          preamblesize+dictsize, data_offset);
1.33      anton     949:   imp=image+preamblesize;
1.57      anton     950:   alloc_stacks((ImageHeader *)imp);
1.1       anton     951:   if (clear_dictionary)
1.33      anton     952:     memset(imp+header.image_size, 0, dictsize-header.image_size);
1.46      jwilke    953:   if(header.base==0 || header.base  == 0x100) {
1.1       anton     954:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
                    955:     char reloc_bits[reloc_size];
1.33      anton     956:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1.10      pazsan    957:     fread(reloc_bits, 1, reloc_size, imagefile);
1.45      jwilke    958:     relocate((Cell *)imp, reloc_bits, header.image_size, header.base, vm_prims);
1.1       anton     959: #if 0
                    960:     { /* let's see what the relocator did */
                    961:       FILE *snapshot=fopen("snapshot.fi","wb");
                    962:       fwrite(image,1,imagesize,snapshot);
                    963:       fclose(snapshot);
                    964:     }
                    965: #endif
1.46      jwilke    966:   }
                    967:   else if(header.base!=imp) {
                    968:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
                    969:            progname, (unsigned long)header.base, (unsigned long)imp);
                    970:     exit(1);
1.1       anton     971:   }
                    972:   if (header.checksum==0)
                    973:     ((ImageHeader *)imp)->checksum=check_sum;
                    974:   else if (header.checksum != check_sum) {
                    975:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
                    976:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
                    977:     exit(1);
                    978:   }
1.53      anton     979: #ifdef DOUBLY_INDIRECT
                    980:   ((ImageHeader *)imp)->xt_base = xts;
                    981: #endif
1.1       anton     982:   fclose(imagefile);
                    983: 
1.56      anton     984:   /* unnecessary, except maybe for CODE words */
                    985:   /* FLUSH_ICACHE(imp, header.image_size);*/
1.1       anton     986: 
                    987:   return imp;
                    988: }
                    989: 
1.72      anton     990: /* pointer to last '/' or '\' in file, 0 if there is none. */
                    991: char *onlypath(char *filename)
1.10      pazsan    992: {
1.72      anton     993:   return strrchr(filename, DIRSEP);
1.1       anton     994: }
                    995: 
                    996: FILE *openimage(char *fullfilename)
1.10      pazsan    997: {
                    998:   FILE *image_file;
1.28      anton     999:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
1.10      pazsan   1000: 
1.28      anton    1001:   image_file=fopen(expfilename,"rb");
1.1       anton    1002:   if (image_file!=NULL && debug)
1.28      anton    1003:     fprintf(stderr, "Opened image file: %s\n", expfilename);
1.10      pazsan   1004:   return image_file;
1.1       anton    1005: }
                   1006: 
1.28      anton    1007: /* try to open image file concat(path[0:len],imagename) */
1.1       anton    1008: FILE *checkimage(char *path, int len, char *imagename)
1.10      pazsan   1009: {
                   1010:   int dirlen=len;
1.1       anton    1011:   char fullfilename[dirlen+strlen(imagename)+2];
1.10      pazsan   1012: 
1.1       anton    1013:   memcpy(fullfilename, path, dirlen);
1.71      pazsan   1014:   if (fullfilename[dirlen-1]!=DIRSEP)
                   1015:     fullfilename[dirlen++]=DIRSEP;
1.1       anton    1016:   strcpy(fullfilename+dirlen,imagename);
1.10      pazsan   1017:   return openimage(fullfilename);
1.1       anton    1018: }
                   1019: 
1.10      pazsan   1020: FILE * open_image_file(char * imagename, char * path)
1.1       anton    1021: {
1.10      pazsan   1022:   FILE * image_file=NULL;
1.28      anton    1023:   char *origpath=path;
1.10      pazsan   1024:   
1.71      pazsan   1025:   if(strchr(imagename, DIRSEP)==NULL) {
1.10      pazsan   1026:     /* first check the directory where the exe file is in !! 01may97jaw */
                   1027:     if (onlypath(progname))
1.72      anton    1028:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
1.10      pazsan   1029:     if (!image_file)
                   1030:       do {
                   1031:        char *pend=strchr(path, PATHSEP);
                   1032:        if (pend==NULL)
                   1033:          pend=path+strlen(path);
                   1034:        if (strlen(path)==0) break;
                   1035:        image_file=checkimage(path, pend-path, imagename);
                   1036:        path=pend+(*pend==PATHSEP);
                   1037:       } while (image_file==NULL);
                   1038:   } else {
                   1039:     image_file=openimage(imagename);
                   1040:   }
1.1       anton    1041: 
1.10      pazsan   1042:   if (!image_file) {
                   1043:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.28      anton    1044:            progname, imagename, origpath);
1.10      pazsan   1045:     exit(1);
1.7       anton    1046:   }
                   1047: 
1.10      pazsan   1048:   return image_file;
                   1049: }
1.11      pazsan   1050: #endif
                   1051: 
                   1052: #ifdef HAS_OS
                   1053: UCell convsize(char *s, UCell elemsize)
                   1054: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
                   1055:    of bytes.  the letter at the end indicates the unit, where e stands
                   1056:    for the element size. default is e */
                   1057: {
                   1058:   char *endp;
                   1059:   UCell n,m;
                   1060: 
                   1061:   m = elemsize;
                   1062:   n = strtoul(s,&endp,0);
                   1063:   if (endp!=NULL) {
                   1064:     if (strcmp(endp,"b")==0)
                   1065:       m=1;
                   1066:     else if (strcmp(endp,"k")==0)
                   1067:       m=1024;
                   1068:     else if (strcmp(endp,"M")==0)
                   1069:       m=1024*1024;
                   1070:     else if (strcmp(endp,"G")==0)
                   1071:       m=1024*1024*1024;
                   1072:     else if (strcmp(endp,"T")==0) {
                   1073: #if (SIZEOF_CHAR_P > 4)
1.24      anton    1074:       m=1024L*1024*1024*1024;
1.11      pazsan   1075: #else
                   1076:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
                   1077:       exit(1);
                   1078: #endif
                   1079:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                   1080:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
                   1081:       exit(1);
                   1082:     }
                   1083:   }
                   1084:   return n*m;
                   1085: }
1.10      pazsan   1086: 
                   1087: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
                   1088: {
                   1089:   int c;
                   1090: 
1.1       anton    1091:   opterr=0;
                   1092:   while (1) {
                   1093:     int option_index=0;
                   1094:     static struct option opts[] = {
1.29      anton    1095:       {"appl-image", required_argument, NULL, 'a'},
1.1       anton    1096:       {"image-file", required_argument, NULL, 'i'},
                   1097:       {"dictionary-size", required_argument, NULL, 'm'},
                   1098:       {"data-stack-size", required_argument, NULL, 'd'},
                   1099:       {"return-stack-size", required_argument, NULL, 'r'},
                   1100:       {"fp-stack-size", required_argument, NULL, 'f'},
                   1101:       {"locals-stack-size", required_argument, NULL, 'l'},
                   1102:       {"path", required_argument, NULL, 'p'},
                   1103:       {"version", no_argument, NULL, 'v'},
                   1104:       {"help", no_argument, NULL, 'h'},
                   1105:       /* put something != 0 into offset_image */
                   1106:       {"offset-image", no_argument, &offset_image, 1},
                   1107:       {"no-offset-im", no_argument, &offset_image, 0},
                   1108:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
1.4       anton    1109:       {"die-on-signal", no_argument, &die_on_signal, 1},
1.1       anton    1110:       {"debug", no_argument, &debug, 1},
1.60      anton    1111:       {"no-super", no_argument, &no_super, 1},
                   1112:       {"no-dynamic", no_argument, &no_dynamic, 1},
1.66      anton    1113:       {"dynamic", no_argument, &no_dynamic, 0},
1.1       anton    1114:       {0,0,0,0}
                   1115:       /* no-init-file, no-rc? */
                   1116:     };
                   1117:     
1.36      pazsan   1118:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1.1       anton    1119:     
                   1120:     switch (c) {
1.29      anton    1121:     case EOF: return;
                   1122:     case '?': optind--; return;
                   1123:     case 'a': *imagename = optarg; return;
1.10      pazsan   1124:     case 'i': *imagename = optarg; break;
1.1       anton    1125:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                   1126:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                   1127:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                   1128:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                   1129:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.10      pazsan   1130:     case 'p': *path = optarg; break;
1.36      pazsan   1131:     case 'o': offset_image = 1; break;
                   1132:     case 'n': offset_image = 0; break;
                   1133:     case 'c': clear_dictionary = 1; break;
                   1134:     case 's': die_on_signal = 1; break;
                   1135:     case 'x': debug = 1; break;
1.8       anton    1136:     case 'v': fprintf(stderr, "gforth %s\n", VERSION); exit(0);
1.1       anton    1137:     case 'h': 
1.29      anton    1138:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1.1       anton    1139: Engine Options:\n\
1.29      anton    1140:   --appl-image FILE                equivalent to '--image-file=FILE --'\n\
1.10      pazsan   1141:   --clear-dictionary               Initialize the dictionary with 0 bytes\n\
                   1142:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
                   1143:   --debug                          Print debugging information during startup\n\
                   1144:   --die-on-signal                  exit instead of CATCHing some signals\n\
1.66      anton    1145:   --dynamic                        use dynamic native code\n\
1.10      pazsan   1146:   -f SIZE, --fp-stack-size=SIZE            Specify floating point stack size\n\
                   1147:   -h, --help                       Print this message and exit\n\
                   1148:   -i FILE, --image-file=FILE       Use image FILE instead of `gforth.fi'\n\
                   1149:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
                   1150:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
1.60      anton    1151:   --no-dynamic                     Use only statically compiled primitives\n\
1.10      pazsan   1152:   --no-offset-im                   Load image at normal position\n\
1.60      anton    1153:   --no-super                        No dynamically formed superinstructions\n\
1.10      pazsan   1154:   --offset-image                   Load image at a different position\n\
                   1155:   -p PATH, --path=PATH             Search path for finding image and sources\n\
                   1156:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
1.66      anton    1157:   -v, --version                            Print engine version and exit\n\
1.1       anton    1158: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1.10      pazsan   1159:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
                   1160:              argv[0]);
                   1161:       optind--;
                   1162:       return;
1.1       anton    1163:     }
                   1164:   }
1.10      pazsan   1165: }
1.11      pazsan   1166: #endif
1.10      pazsan   1167: 
                   1168: #ifdef INCLUDE_IMAGE
                   1169: extern Cell image[];
                   1170: extern const char reloc_bits[];
                   1171: #endif
                   1172: 
1.67      pazsan   1173: DCell double2ll(Float r)
                   1174: {
                   1175: #ifndef BUGGY_LONG_LONG
                   1176:   return (DCell)(r);
                   1177: #else
                   1178:   DCell d;
                   1179:   d.hi = ldexp(r,-(int)(CELL_BITS)) - (r<0);
                   1180:   d.lo = r-ldexp((Float)d.hi,CELL_BITS);
                   1181:   return d;
                   1182: #endif
                   1183: }
                   1184: 
1.10      pazsan   1185: int main(int argc, char **argv, char **env)
                   1186: {
1.30      pazsan   1187: #ifdef HAS_OS
1.10      pazsan   1188:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1.30      pazsan   1189: #else
                   1190:   char *path = DEFAULTPATH;
                   1191: #endif
1.13      pazsan   1192: #ifndef INCLUDE_IMAGE
1.10      pazsan   1193:   char *imagename="gforth.fi";
                   1194:   FILE *image_file;
                   1195:   Address image;
                   1196: #endif
                   1197:   int retvalue;
                   1198:          
1.56      anton    1199: #if defined(i386) && defined(ALIGNMENT_CHECK)
1.10      pazsan   1200:   /* turn on alignment checks on the 486.
                   1201:    * on the 386 this should have no effect. */
                   1202:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
                   1203:   /* this is unusable with Linux' libc.4.6.27, because this library is
                   1204:      not alignment-clean; we would have to replace some library
                   1205:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
                   1206:      the stack FP-aligned. */
                   1207: #endif
                   1208: 
                   1209:   /* buffering of the user output device */
1.11      pazsan   1210: #ifdef _IONBF
1.10      pazsan   1211:   if (isatty(fileno(stdout))) {
                   1212:     fflush(stdout);
                   1213:     setvbuf(stdout,NULL,_IONBF,0);
1.1       anton    1214:   }
1.11      pazsan   1215: #endif
1.1       anton    1216: 
1.10      pazsan   1217:   progname = argv[0];
                   1218: 
1.11      pazsan   1219: #ifdef HAS_OS
1.10      pazsan   1220:   gforth_args(argc, argv, &path, &imagename);
1.11      pazsan   1221: #endif
1.10      pazsan   1222: 
                   1223: #ifdef INCLUDE_IMAGE
                   1224:   set_stack_sizes((ImageHeader *)image);
1.22      pazsan   1225:   if(((ImageHeader *)image)->base != image)
                   1226:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
                   1227:             (Label*)engine(0, 0, 0, 0, 0));
1.10      pazsan   1228:   alloc_stacks((ImageHeader *)image);
                   1229: #else
                   1230:   image_file = open_image_file(imagename, path);
                   1231:   image = loader(image_file, imagename);
                   1232: #endif
1.24      anton    1233:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1.1       anton    1234: 
                   1235:   {
1.10      pazsan   1236:     char path2[strlen(path)+1];
1.1       anton    1237:     char *p1, *p2;
                   1238:     Cell environ[]= {
                   1239:       (Cell)argc-(optind-1),
                   1240:       (Cell)(argv+(optind-1)),
1.10      pazsan   1241:       (Cell)strlen(path),
1.1       anton    1242:       (Cell)path2};
                   1243:     argv[optind-1] = progname;
                   1244:     /*
                   1245:        for (i=0; i<environ[0]; i++)
                   1246:        printf("%s\n", ((char **)(environ[1]))[i]);
                   1247:        */
                   1248:     /* make path OS-independent by replacing path separators with NUL */
1.10      pazsan   1249:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1.1       anton    1250:       if (*p1==PATHSEP)
                   1251:        *p2 = '\0';
                   1252:       else
                   1253:        *p2 = *p1;
                   1254:     *p2='\0';
1.10      pazsan   1255:     retvalue = go_forth(image, 4, environ);
1.42      anton    1256: #ifdef VM_PROFILING
                   1257:     vm_print_profile(stderr);
                   1258: #endif
1.1       anton    1259:     deprep_terminal();
                   1260:   }
1.13      pazsan   1261:   return retvalue;
1.1       anton    1262: }

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