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

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: 
                     60: #if defined(DIRECT_THREADED) 
                     61: #  define CA(n)        (symbols[(n)])
                     62: #else
                     63: #  define CA(n)        ((Cell)(symbols+(n)))
                     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.30      pazsan     84: #ifdef HAS_DEBUG
1.1       anton      85: static int debug=0;
1.31      pazsan     86: #else
                     87: # define debug 0
                     88: # define perror(x...)
                     89: # define fprintf(x...)
1.30      pazsan     90: #endif
1.31      pazsan     91: 
1.24      anton      92: ImageHeader *gforth_header;
1.43      anton      93: Label *vm_prims;
1.1       anton      94: 
1.30      pazsan     95: #ifdef MEMCMP_AS_SUBROUTINE
                     96: int gforth_memcmp(const char * s1, const char * s2, size_t n)
                     97: {
                     98:   return memcmp(s1, s2, n);
                     99: }
                    100: #endif
                    101: 
1.1       anton     102: /* image file format:
1.15      pazsan    103:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
1.1       anton     104:  *   padding to a multiple of 8
1.15      pazsan    105:  *   magic: "Gforth2x" means format 0.4,
                    106:  *              where x is a byte with
                    107:  *              bit 7:   reserved = 0
                    108:  *              bit 6:5: address unit size 2^n octets
                    109:  *              bit 4:3: character size 2^n octets
                    110:  *              bit 2:1: cell size 2^n octets
                    111:  *              bit 0:   endian, big=0, little=1.
                    112:  *  The magic are always 8 octets, no matter what the native AU/character size is
1.1       anton     113:  *  padding to max alignment (no padding necessary on current machines)
1.24      anton     114:  *  ImageHeader structure (see forth.h)
1.1       anton     115:  *  data (size in ImageHeader.image_size)
                    116:  *  tags ((if relocatable, 1 bit/data cell)
                    117:  *
                    118:  * tag==1 means that the corresponding word is an address;
                    119:  * If the word is >=0, the address is within the image;
                    120:  * addresses within the image are given relative to the start of the image.
                    121:  * If the word =-1 (CF_NIL), the address is NIL,
                    122:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
                    123:  * If the word =CF(DODOES), it's a DOES> CFA
                    124:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
                    125:  *                                     possibly containing a jump to dodoes)
                    126:  * If the word is <CF(DOESJUMP), it's a primitive
                    127:  */
                    128: 
1.46      jwilke    129: void relocate(Cell *image, const char *bitstring, 
                    130:               int size, int base, Label symbols[])
1.1       anton     131: {
1.16      pazsan    132:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
1.11      pazsan    133:   Cell token;
1.1       anton     134:   char bits;
1.37      anton     135:   Cell max_symbols;
1.46      jwilke    136:   /* 
                    137:    * A virtial start address that's the real start address minus 
                    138:    * the one in the image 
                    139:    */
1.45      jwilke    140:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
1.1       anton     141: 
1.46      jwilke    142:   
                    143: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
1.37      anton     144:   
                    145:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
                    146:     ;
1.47    ! anton     147:   max_symbols--;
1.35      pazsan    148:   size/=sizeof(Cell);
                    149: 
1.31      pazsan    150:   for(k=0; k<=steps; k++) {
1.13      pazsan    151:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
1.1       anton     152:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
1.35      pazsan    153:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
                    154:        /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
1.45      jwilke    155:         token=image[i];
                    156:        if(token<0)
1.11      pazsan    157:          switch(token)
1.1       anton     158:            {
                    159:            case CF_NIL      : image[i]=0; break;
                    160: #if !defined(DOUBLY_INDIRECT)
                    161:            case CF(DOCOL)   :
                    162:            case CF(DOVAR)   :
                    163:            case CF(DOCON)   :
                    164:            case CF(DOUSER)  : 
                    165:            case CF(DODEFER) : 
1.11      pazsan    166:            case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
1.1       anton     167:            case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
                    168: #endif /* !defined(DOUBLY_INDIRECT) */
                    169:            case CF(DODOES)  :
1.45      jwilke    170:              MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
1.1       anton     171:              break;
                    172:            default          :
                    173: /*           printf("Code field generation image[%x]:=CA(%x)\n",
                    174:                     i, CF(image[i])); */
1.37      anton     175:              if (CF(token)<max_symbols)
                    176:                image[i]=(Cell)CA(CF(token));
                    177:              else
                    178:                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     179:            }
1.46      jwilke    180:        else {
1.45      jwilke    181:           // if base is > 0: 0 is a null reference so don't adjust
                    182:           if (token>=base) {
                    183:             image[i]+=(Cell)start;
                    184:           }
1.46      jwilke    185:         }
1.1       anton     186:       }
                    187:     }
1.31      pazsan    188:   }
1.26      jwilke    189:   ((ImageHeader*)(image))->base = (Address) image;
1.1       anton     190: }
                    191: 
                    192: UCell checksum(Label symbols[])
                    193: {
                    194:   UCell r=PRIM_VERSION;
                    195:   Cell i;
                    196: 
                    197:   for (i=DOCOL; i<=DOESJUMP; i++) {
                    198:     r ^= (UCell)(symbols[i]);
                    199:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    200:   }
                    201: #ifdef DIRECT_THREADED
                    202:   /* we have to consider all the primitives */
                    203:   for (; symbols[i]!=(Label)0; i++) {
                    204:     r ^= (UCell)(symbols[i]);
                    205:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    206:   }
                    207: #else
                    208:   /* in indirect threaded code all primitives are accessed through the
                    209:      symbols table, so we just have to put the base address of symbols
                    210:      in the checksum */
                    211:   r ^= (UCell)symbols;
                    212: #endif
                    213:   return r;
                    214: }
                    215: 
1.3       anton     216: Address verbose_malloc(Cell size)
                    217: {
                    218:   Address r;
                    219:   /* leave a little room (64B) for stack underflows */
                    220:   if ((r = malloc(size+64))==NULL) {
                    221:     perror(progname);
                    222:     exit(1);
                    223:   }
                    224:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
                    225:   if (debug)
                    226:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
                    227:   return r;
                    228: }
                    229: 
1.33      anton     230: static Address next_address=0;
                    231: void after_alloc(Address r, Cell size)
                    232: {
                    233:   if (r != (Address)-1) {
                    234:     if (debug)
                    235:       fprintf(stderr, "success, address=$%lx\n", (long) r);
                    236:     if (pagesize != 1)
                    237:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
                    238:   } else {
                    239:     if (debug)
                    240:       fprintf(stderr, "failed: %s\n", strerror(errno));
                    241:   }
                    242: }
                    243: 
1.34      anton     244: #ifndef MAP_FAILED
                    245: #define MAP_FAILED ((Address) -1)
                    246: #endif
                    247: #ifndef MAP_FILE
                    248: # define MAP_FILE 0
                    249: #endif
                    250: #ifndef MAP_PRIVATE
                    251: # define MAP_PRIVATE 0
                    252: #endif
                    253: 
                    254: #if defined(HAVE_MMAP)
                    255: static Address alloc_mmap(Cell size)
1.1       anton     256: {
                    257:   Address r;
                    258: 
                    259: #if defined(MAP_ANON)
                    260:   if (debug)
                    261:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
1.34      anton     262:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
1.1       anton     263: #else /* !defined(MAP_ANON) */
1.17      anton     264:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
                    265:      apparently defaults) */
1.1       anton     266:   static int dev_zero=-1;
                    267: 
                    268:   if (dev_zero == -1)
                    269:     dev_zero = open("/dev/zero", O_RDONLY);
                    270:   if (dev_zero == -1) {
1.34      anton     271:     r = MAP_FAILED;
1.1       anton     272:     if (debug)
                    273:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
                    274:              strerror(errno));
                    275:   } else {
                    276:     if (debug)
                    277:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
                    278:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
                    279:   }
                    280: #endif /* !defined(MAP_ANON) */
1.34      anton     281:   after_alloc(r, size);
                    282:   return r;  
                    283: }
                    284: #endif
                    285: 
                    286: Address my_alloc(Cell size)
                    287: {
                    288: #if HAVE_MMAP
                    289:   Address r;
                    290: 
                    291:   r=alloc_mmap(size);
                    292:   if (r!=MAP_FAILED)
1.1       anton     293:     return r;
                    294: #endif /* HAVE_MMAP */
1.3       anton     295:   /* use malloc as fallback */
                    296:   return verbose_malloc(size);
1.1       anton     297: }
                    298: 
1.3       anton     299: #if (defined(mips) && !defined(INDIRECT_THREADED))
                    300: /* the 256MB jump restriction on the MIPS architecture makes the
                    301:    combination of direct threading and mmap unsafe. */
1.33      anton     302: #define mips_dict_alloc 1
1.3       anton     303: #define dict_alloc(size) verbose_malloc(size)
                    304: #else
                    305: #define dict_alloc(size) my_alloc(size)
                    306: #endif
                    307: 
1.34      anton     308: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
1.33      anton     309: {
1.34      anton     310:   Address image = MAP_FAILED;
1.33      anton     311: 
1.34      anton     312: #if defined(HAVE_MMAP) && !defined(mips_dict_alloc)
1.33      anton     313:   if (offset==0) {
1.34      anton     314:     image=alloc_mmap(dictsize);
1.33      anton     315:     if (debug)
1.34      anton     316:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
                    317:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
                    318:     after_alloc(image,dictsize);
1.33      anton     319:   }
1.34      anton     320: #endif /* defined(MAP_ANON) && !defined(mips_dict_alloc) */
                    321:   if (image == MAP_FAILED) {
                    322:     image = dict_alloc(dictsize+offset)+offset;
1.33      anton     323:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
1.34      anton     324:     fread(image, 1, imagesize, file);
1.33      anton     325:   }
                    326:   return image;
                    327: }
                    328: 
1.10      pazsan    329: void set_stack_sizes(ImageHeader * header)
                    330: {
                    331:   if (dictsize==0)
                    332:     dictsize = header->dict_size;
                    333:   if (dsize==0)
                    334:     dsize = header->data_stack_size;
                    335:   if (rsize==0)
                    336:     rsize = header->return_stack_size;
                    337:   if (fsize==0)
                    338:     fsize = header->fp_stack_size;
                    339:   if (lsize==0)
                    340:     lsize = header->locals_stack_size;
                    341:   dictsize=maxaligned(dictsize);
                    342:   dsize=maxaligned(dsize);
                    343:   rsize=maxaligned(rsize);
                    344:   lsize=maxaligned(lsize);
                    345:   fsize=maxaligned(fsize);
                    346: }
                    347: 
                    348: void alloc_stacks(ImageHeader * header)
                    349: {
                    350:   header->dict_size=dictsize;
                    351:   header->data_stack_size=dsize;
                    352:   header->fp_stack_size=fsize;
                    353:   header->return_stack_size=rsize;
                    354:   header->locals_stack_size=lsize;
                    355: 
                    356:   header->data_stack_base=my_alloc(dsize);
                    357:   header->fp_stack_base=my_alloc(fsize);
                    358:   header->return_stack_base=my_alloc(rsize);
                    359:   header->locals_stack_base=my_alloc(lsize);
                    360: }
                    361: 
1.44      pazsan    362: #warning You can ignore the warnings about clobbered variables in go_forth
1.11      pazsan    363: int go_forth(Address image, int stack, Cell *entries)
                    364: {
1.38      anton     365:   volatile ImageHeader *image_header = (ImageHeader *)image;
1.18      anton     366:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
1.44      pazsan    367:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
1.18      anton     368:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
1.44      pazsan    369: #ifdef GFORTH_DEBUGGING
1.38      anton     370:   volatile Cell *orig_rp0=rp0;
1.44      pazsan    371: #endif
1.18      anton     372:   Address lp0=image_header->locals_stack_base + lsize;
                    373:   Xt *ip0=(Xt *)(image_header->boot_entry);
1.13      pazsan    374: #ifdef SYSSIGNALS
1.11      pazsan    375:   int throw_code;
1.13      pazsan    376: #endif
1.11      pazsan    377: 
                    378:   /* ensure that the cached elements (if any) are accessible */
1.41      anton     379:   IF_spTOS(sp0--);
                    380:   IF_fpTOS(fp0--);
1.11      pazsan    381:   
                    382:   for(;stack>0;stack--)
1.18      anton     383:     *--sp0=entries[stack-1];
1.11      pazsan    384: 
1.30      pazsan    385: #ifdef SYSSIGNALS
1.11      pazsan    386:   get_winsize();
                    387:    
                    388:   install_signal_handlers(); /* right place? */
                    389:   
                    390:   if ((throw_code=setjmp(throw_jmp_buf))) {
                    391:     static Cell signal_data_stack[8];
                    392:     static Cell signal_return_stack[8];
                    393:     static Float signal_fp_stack[1];
1.13      pazsan    394: 
1.11      pazsan    395:     signal_data_stack[7]=throw_code;
1.18      anton     396: 
                    397: #ifdef GFORTH_DEBUGGING
1.38      anton     398:     /* fprintf(stderr,"\nrp=%ld\n",(long)rp); */
                    399:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
1.18      anton     400:       /* no rstack overflow or underflow */
                    401:       rp0 = rp;
1.27      anton     402:       *--rp0 = (Cell)ip;
1.18      anton     403:     }
                    404:     else /* I love non-syntactic ifdefs :-) */
                    405: #endif
                    406:     rp0 = signal_return_stack+8;
1.25      anton     407:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
1.11      pazsan    408:     
1.33      anton     409:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
1.18      anton     410:                       rp0, signal_fp_stack, 0));
1.11      pazsan    411:   }
1.13      pazsan    412: #endif
1.11      pazsan    413: 
1.33      anton     414:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
1.11      pazsan    415: }
                    416: 
1.21      anton     417: 
1.30      pazsan    418: #ifndef INCLUDE_IMAGE
1.21      anton     419: void print_sizes(Cell sizebyte)
                    420:      /* print size information */
                    421: {
                    422:   static char* endianstring[]= { "   big","little" };
                    423:   
                    424:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
                    425:          endianstring[sizebyte & 1],
                    426:          1 << ((sizebyte >> 1) & 3),
                    427:          1 << ((sizebyte >> 3) & 3),
                    428:          1 << ((sizebyte >> 5) & 3));
                    429: }
                    430: 
1.47    ! anton     431: typedef struct {
        !           432:   Label start;
        !           433:   Cell length; /* excluding the jump */
        !           434:   char super_end; /* true if primitive ends superinstruction, i.e.,
        !           435:                      unconditional branch, execute, etc. */
        !           436: } PrimInfo;
        !           437: 
        !           438: PrimInfo *priminfos;
        !           439: 
        !           440: void check_prims(Label symbols1[])
        !           441: {
        !           442: #ifndef DOUBLY_INDIRECT
        !           443:   int i;
        !           444:   Label *symbols2=engine2(0,0,0,0,0);
        !           445: 
        !           446:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
        !           447:     ;
        !           448:   priminfos = calloc(i,sizeof(PrimInfo));
        !           449:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
        !           450:     int prim_len=symbols1[i+1]-symbols1[i];
        !           451:     PrimInfo *pi=&priminfos[i];
        !           452:     int j;
        !           453:     for (j=prim_len-3; ; j--) {
        !           454:       if (((*(Cell *)(symbols1[i]+j)) & 0xfff8ff) == 0xfc60ff) {
        !           455:        /* jmp -4(reg), i.e., the NEXT jump */
        !           456:        prim_len = j;
        !           457:        break;
        !           458:       }
        !           459:       if (j==0) { /* NEXT jump not found, e.g., execute */
        !           460:        pi->super_end = 1;
        !           461:        break;
        !           462:       }
        !           463:     }
        !           464:     /* fprintf(stderr,"checking primitive %d: memcmp(%p, %p, %d)\n",
        !           465:        i, symbols1[i], symbols2[i], prim_len);*/
        !           466:     if (memcmp(symbols1[i],symbols2[i],prim_len)!=0) {
        !           467:       if (debug)
        !           468:        fprintf(stderr,"Primitive %d not relocatable: memcmp(%p, %p, %d)\n",
        !           469:                i, symbols1[i], symbols2[i], prim_len);
        !           470:     } else {
        !           471:       pi->start = symbols1[i];
        !           472:       pi->length = prim_len;
        !           473:       if (debug)
        !           474:        fprintf(stderr,"Primitive %d relocatable: start %p, length %ld, super_end %d\n",
        !           475:                i, pi->start, pi->length, pi->super_end);
        !           476:     }      
        !           477:   }
        !           478: #endif
        !           479: }
        !           480: 
1.1       anton     481: Address loader(FILE *imagefile, char* filename)
                    482: /* returns the address of the image proper (after the preamble) */
                    483: {
                    484:   ImageHeader header;
                    485:   Address image;
                    486:   Address imp; /* image+preamble */
1.17      anton     487:   Char magic[8];
                    488:   char magic7; /* size byte of magic number */
1.1       anton     489:   Cell preamblesize=0;
1.6       pazsan    490:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1.1       anton     491:   UCell check_sum;
1.15      pazsan    492:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
                    493:                 (RELINFOBITS == 16) ? 1 :
                    494:                 (RELINFOBITS == 32) ? 2 : 3);
                    495:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
                    496:                   (sizeof(Char) == 2) ? 1 :
                    497:                   (sizeof(Char) == 4) ? 2 : 3) + ausize;
                    498:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
                    499:                   (sizeof(Cell) == 2) ? 1 :
                    500:                   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1.21      anton     501:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
                    502: #ifdef WORDS_BIGENDIAN
                    503:        0
                    504: #else
                    505:        1
                    506: #endif
                    507:     ;
1.1       anton     508: 
1.43      anton     509:   vm_prims = engine(0,0,0,0,0);
1.47    ! anton     510:   check_prims(vm_prims);
1.1       anton     511: #ifndef DOUBLY_INDIRECT
1.43      anton     512:   check_sum = checksum(vm_prims);
1.1       anton     513: #else /* defined(DOUBLY_INDIRECT) */
1.43      anton     514:   check_sum = (UCell)vm_prims;
1.1       anton     515: #endif /* defined(DOUBLY_INDIRECT) */
1.10      pazsan    516:   
                    517:   do {
                    518:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1.15      pazsan    519:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.4) image.\n",
1.10      pazsan    520:              progname, filename);
                    521:       exit(1);
1.1       anton     522:     }
1.10      pazsan    523:     preamblesize+=8;
1.15      pazsan    524:   } while(memcmp(magic,"Gforth2",7));
1.17      anton     525:   magic7 = magic[7];
1.1       anton     526:   if (debug) {
1.17      anton     527:     magic[7]='\0';
1.21      anton     528:     fprintf(stderr,"Magic found: %s ", magic);
                    529:     print_sizes(magic7);
1.1       anton     530:   }
                    531: 
1.21      anton     532:   if (magic7 != sizebyte)
                    533:     {
                    534:       fprintf(stderr,"This image is:         ");
                    535:       print_sizes(magic7);
                    536:       fprintf(stderr,"whereas the machine is ");
                    537:       print_sizes(sizebyte);
1.1       anton     538:       exit(-2);
                    539:     };
                    540: 
                    541:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1.10      pazsan    542: 
                    543:   set_stack_sizes(&header);
1.1       anton     544:   
                    545: #if HAVE_GETPAGESIZE
                    546:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
                    547: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
                    548:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
                    549: #elif PAGESIZE
                    550:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
                    551: #endif
                    552:   if (debug)
1.5       jwilke    553:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1.1       anton     554: 
1.34      anton     555:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
                    556:                          preamblesize+dictsize, data_offset);
1.33      anton     557:   imp=image+preamblesize;
1.1       anton     558:   if (clear_dictionary)
1.33      anton     559:     memset(imp+header.image_size, 0, dictsize-header.image_size);
1.46      jwilke    560:   if(header.base==0 || header.base  == 0x100) {
1.1       anton     561:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
                    562:     char reloc_bits[reloc_size];
1.33      anton     563:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1.10      pazsan    564:     fread(reloc_bits, 1, reloc_size, imagefile);
1.45      jwilke    565:     relocate((Cell *)imp, reloc_bits, header.image_size, header.base, vm_prims);
1.1       anton     566: #if 0
                    567:     { /* let's see what the relocator did */
                    568:       FILE *snapshot=fopen("snapshot.fi","wb");
                    569:       fwrite(image,1,imagesize,snapshot);
                    570:       fclose(snapshot);
                    571:     }
                    572: #endif
1.46      jwilke    573:   }
                    574:   else if(header.base!=imp) {
                    575:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
                    576:            progname, (unsigned long)header.base, (unsigned long)imp);
                    577:     exit(1);
1.1       anton     578:   }
                    579:   if (header.checksum==0)
                    580:     ((ImageHeader *)imp)->checksum=check_sum;
                    581:   else if (header.checksum != check_sum) {
                    582:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
                    583:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
                    584:     exit(1);
                    585:   }
                    586:   fclose(imagefile);
                    587: 
1.10      pazsan    588:   alloc_stacks((ImageHeader *)imp);
1.1       anton     589: 
                    590:   CACHE_FLUSH(imp, header.image_size);
                    591: 
                    592:   return imp;
                    593: }
                    594: 
1.28      anton     595: /* index of last '/' or '\' in file, 0 if there is none. !! Hmm, could
                    596:    be implemented with strrchr and the separator should be
                    597:    OS-dependent */
1.1       anton     598: int onlypath(char *file)
1.10      pazsan    599: {
                    600:   int i;
1.1       anton     601:   i=strlen(file);
1.10      pazsan    602:   while (i) {
                    603:     if (file[i]=='\\' || file[i]=='/') break;
                    604:     i--;
                    605:   }
                    606:   return i;
1.1       anton     607: }
                    608: 
                    609: FILE *openimage(char *fullfilename)
1.10      pazsan    610: {
                    611:   FILE *image_file;
1.28      anton     612:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
1.10      pazsan    613: 
1.28      anton     614:   image_file=fopen(expfilename,"rb");
1.1       anton     615:   if (image_file!=NULL && debug)
1.28      anton     616:     fprintf(stderr, "Opened image file: %s\n", expfilename);
1.10      pazsan    617:   return image_file;
1.1       anton     618: }
                    619: 
1.28      anton     620: /* try to open image file concat(path[0:len],imagename) */
1.1       anton     621: FILE *checkimage(char *path, int len, char *imagename)
1.10      pazsan    622: {
                    623:   int dirlen=len;
1.1       anton     624:   char fullfilename[dirlen+strlen(imagename)+2];
1.10      pazsan    625: 
1.1       anton     626:   memcpy(fullfilename, path, dirlen);
                    627:   if (fullfilename[dirlen-1]!='/')
                    628:     fullfilename[dirlen++]='/';
                    629:   strcpy(fullfilename+dirlen,imagename);
1.10      pazsan    630:   return openimage(fullfilename);
1.1       anton     631: }
                    632: 
1.10      pazsan    633: FILE * open_image_file(char * imagename, char * path)
1.1       anton     634: {
1.10      pazsan    635:   FILE * image_file=NULL;
1.28      anton     636:   char *origpath=path;
1.10      pazsan    637:   
                    638:   if(strchr(imagename, '/')==NULL) {
                    639:     /* first check the directory where the exe file is in !! 01may97jaw */
                    640:     if (onlypath(progname))
                    641:       image_file=checkimage(progname, onlypath(progname), imagename);
                    642:     if (!image_file)
                    643:       do {
                    644:        char *pend=strchr(path, PATHSEP);
                    645:        if (pend==NULL)
                    646:          pend=path+strlen(path);
                    647:        if (strlen(path)==0) break;
                    648:        image_file=checkimage(path, pend-path, imagename);
                    649:        path=pend+(*pend==PATHSEP);
                    650:       } while (image_file==NULL);
                    651:   } else {
                    652:     image_file=openimage(imagename);
                    653:   }
1.1       anton     654: 
1.10      pazsan    655:   if (!image_file) {
                    656:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.28      anton     657:            progname, imagename, origpath);
1.10      pazsan    658:     exit(1);
1.7       anton     659:   }
                    660: 
1.10      pazsan    661:   return image_file;
                    662: }
1.11      pazsan    663: #endif
                    664: 
                    665: #ifdef HAS_OS
                    666: UCell convsize(char *s, UCell elemsize)
                    667: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
                    668:    of bytes.  the letter at the end indicates the unit, where e stands
                    669:    for the element size. default is e */
                    670: {
                    671:   char *endp;
                    672:   UCell n,m;
                    673: 
                    674:   m = elemsize;
                    675:   n = strtoul(s,&endp,0);
                    676:   if (endp!=NULL) {
                    677:     if (strcmp(endp,"b")==0)
                    678:       m=1;
                    679:     else if (strcmp(endp,"k")==0)
                    680:       m=1024;
                    681:     else if (strcmp(endp,"M")==0)
                    682:       m=1024*1024;
                    683:     else if (strcmp(endp,"G")==0)
                    684:       m=1024*1024*1024;
                    685:     else if (strcmp(endp,"T")==0) {
                    686: #if (SIZEOF_CHAR_P > 4)
1.24      anton     687:       m=1024L*1024*1024*1024;
1.11      pazsan    688: #else
                    689:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
                    690:       exit(1);
                    691: #endif
                    692:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                    693:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
                    694:       exit(1);
                    695:     }
                    696:   }
                    697:   return n*m;
                    698: }
1.10      pazsan    699: 
                    700: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
                    701: {
                    702:   int c;
                    703: 
1.1       anton     704:   opterr=0;
                    705:   while (1) {
                    706:     int option_index=0;
                    707:     static struct option opts[] = {
1.29      anton     708:       {"appl-image", required_argument, NULL, 'a'},
1.1       anton     709:       {"image-file", required_argument, NULL, 'i'},
                    710:       {"dictionary-size", required_argument, NULL, 'm'},
                    711:       {"data-stack-size", required_argument, NULL, 'd'},
                    712:       {"return-stack-size", required_argument, NULL, 'r'},
                    713:       {"fp-stack-size", required_argument, NULL, 'f'},
                    714:       {"locals-stack-size", required_argument, NULL, 'l'},
                    715:       {"path", required_argument, NULL, 'p'},
                    716:       {"version", no_argument, NULL, 'v'},
                    717:       {"help", no_argument, NULL, 'h'},
                    718:       /* put something != 0 into offset_image */
                    719:       {"offset-image", no_argument, &offset_image, 1},
                    720:       {"no-offset-im", no_argument, &offset_image, 0},
                    721:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
1.4       anton     722:       {"die-on-signal", no_argument, &die_on_signal, 1},
1.1       anton     723:       {"debug", no_argument, &debug, 1},
                    724:       {0,0,0,0}
                    725:       /* no-init-file, no-rc? */
                    726:     };
                    727:     
1.36      pazsan    728:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1.1       anton     729:     
                    730:     switch (c) {
1.29      anton     731:     case EOF: return;
                    732:     case '?': optind--; return;
                    733:     case 'a': *imagename = optarg; return;
1.10      pazsan    734:     case 'i': *imagename = optarg; break;
1.1       anton     735:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                    736:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                    737:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                    738:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                    739:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.10      pazsan    740:     case 'p': *path = optarg; break;
1.36      pazsan    741:     case 'o': offset_image = 1; break;
                    742:     case 'n': offset_image = 0; break;
                    743:     case 'c': clear_dictionary = 1; break;
                    744:     case 's': die_on_signal = 1; break;
                    745:     case 'x': debug = 1; break;
1.8       anton     746:     case 'v': fprintf(stderr, "gforth %s\n", VERSION); exit(0);
1.1       anton     747:     case 'h': 
1.29      anton     748:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1.1       anton     749: Engine Options:\n\
1.29      anton     750:   --appl-image FILE                equivalent to '--image-file=FILE --'\n\
1.10      pazsan    751:   --clear-dictionary               Initialize the dictionary with 0 bytes\n\
                    752:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
                    753:   --debug                          Print debugging information during startup\n\
                    754:   --die-on-signal                  exit instead of CATCHing some signals\n\
                    755:   -f SIZE, --fp-stack-size=SIZE            Specify floating point stack size\n\
                    756:   -h, --help                       Print this message and exit\n\
                    757:   -i FILE, --image-file=FILE       Use image FILE instead of `gforth.fi'\n\
                    758:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
                    759:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
                    760:   --no-offset-im                   Load image at normal position\n\
                    761:   --offset-image                   Load image at a different position\n\
                    762:   -p PATH, --path=PATH             Search path for finding image and sources\n\
                    763:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
                    764:   -v, --version                            Print version and exit\n\
1.1       anton     765: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1.10      pazsan    766:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
                    767:              argv[0]);
                    768:       optind--;
                    769:       return;
1.1       anton     770:     }
                    771:   }
1.10      pazsan    772: }
1.11      pazsan    773: #endif
1.10      pazsan    774: 
                    775: #ifdef INCLUDE_IMAGE
                    776: extern Cell image[];
                    777: extern const char reloc_bits[];
                    778: #endif
                    779: 
                    780: int main(int argc, char **argv, char **env)
                    781: {
1.30      pazsan    782: #ifdef HAS_OS
1.10      pazsan    783:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1.30      pazsan    784: #else
                    785:   char *path = DEFAULTPATH;
                    786: #endif
1.13      pazsan    787: #ifndef INCLUDE_IMAGE
1.10      pazsan    788:   char *imagename="gforth.fi";
                    789:   FILE *image_file;
                    790:   Address image;
                    791: #endif
                    792:   int retvalue;
                    793:          
                    794: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
                    795:   /* turn on alignment checks on the 486.
                    796:    * on the 386 this should have no effect. */
                    797:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
                    798:   /* this is unusable with Linux' libc.4.6.27, because this library is
                    799:      not alignment-clean; we would have to replace some library
                    800:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
                    801:      the stack FP-aligned. */
                    802: #endif
                    803: 
                    804:   /* buffering of the user output device */
1.11      pazsan    805: #ifdef _IONBF
1.10      pazsan    806:   if (isatty(fileno(stdout))) {
                    807:     fflush(stdout);
                    808:     setvbuf(stdout,NULL,_IONBF,0);
1.1       anton     809:   }
1.11      pazsan    810: #endif
1.1       anton     811: 
1.10      pazsan    812:   progname = argv[0];
                    813: 
1.11      pazsan    814: #ifdef HAS_OS
1.10      pazsan    815:   gforth_args(argc, argv, &path, &imagename);
1.11      pazsan    816: #endif
1.10      pazsan    817: 
                    818: #ifdef INCLUDE_IMAGE
                    819:   set_stack_sizes((ImageHeader *)image);
1.22      pazsan    820:   if(((ImageHeader *)image)->base != image)
                    821:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
                    822:             (Label*)engine(0, 0, 0, 0, 0));
1.10      pazsan    823:   alloc_stacks((ImageHeader *)image);
                    824: #else
                    825:   image_file = open_image_file(imagename, path);
                    826:   image = loader(image_file, imagename);
                    827: #endif
1.24      anton     828:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1.1       anton     829: 
                    830:   {
1.10      pazsan    831:     char path2[strlen(path)+1];
1.1       anton     832:     char *p1, *p2;
                    833:     Cell environ[]= {
                    834:       (Cell)argc-(optind-1),
                    835:       (Cell)(argv+(optind-1)),
1.10      pazsan    836:       (Cell)strlen(path),
1.1       anton     837:       (Cell)path2};
                    838:     argv[optind-1] = progname;
                    839:     /*
                    840:        for (i=0; i<environ[0]; i++)
                    841:        printf("%s\n", ((char **)(environ[1]))[i]);
                    842:        */
                    843:     /* make path OS-independent by replacing path separators with NUL */
1.10      pazsan    844:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1.1       anton     845:       if (*p1==PATHSEP)
                    846:        *p2 = '\0';
                    847:       else
                    848:        *p2 = *p1;
                    849:     *p2='\0';
1.10      pazsan    850:     retvalue = go_forth(image, 4, environ);
1.42      anton     851: #ifdef VM_PROFILING
                    852:     vm_print_profile(stderr);
                    853: #endif
1.1       anton     854:     deprep_terminal();
                    855:   }
1.13      pazsan    856:   return retvalue;
1.1       anton     857: }

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