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

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

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