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

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

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