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

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

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