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

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

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