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

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

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