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

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"
1.82      anton      24: #include "forth.h"
1.1       anton      25: #include <errno.h>
                     26: #include <ctype.h>
                     27: #include <stdio.h>
1.2       pazsan     28: #include <unistd.h>
1.1       anton      29: #include <string.h>
                     30: #include <math.h>
                     31: #include <sys/types.h>
1.32      pazsan     32: #ifndef STANDALONE
1.1       anton      33: #include <sys/stat.h>
1.32      pazsan     34: #endif
1.1       anton      35: #include <fcntl.h>
                     36: #include <assert.h>
                     37: #include <stdlib.h>
1.11      pazsan     38: #ifndef STANDALONE
1.1       anton      39: #if HAVE_SYS_MMAN_H
                     40: #include <sys/mman.h>
                     41: #endif
1.11      pazsan     42: #endif
1.1       anton      43: #include "io.h"
                     44: #include "getopt.h"
1.11      pazsan     45: #ifdef STANDALONE
                     46: #include <systypes.h>
                     47: #endif
1.1       anton      48: 
1.79      anton      49: /* global variables for engine.c 
                     50:    We put them here because engine.c is compiled several times in
                     51:    different ways for the same engine. */
                     52: Cell *SP;
                     53: Float *FP;
                     54: Address UP=NULL;
                     55: 
                     56: #ifdef GFORTH_DEBUGGING
                     57: /* define some VM registers as global variables, so they survive exceptions;
                     58:    global register variables are not up to the task (according to the 
                     59:    GNU C manual) */
                     60: Xt *saved_ip;
                     61: Cell *rp;
                     62: #endif
                     63: 
                     64: #ifdef NO_IP
                     65: Label next_code;
                     66: #endif
                     67: 
                     68: #ifdef HAS_FILE
                     69: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
                     70: char* pfileattr[6]={"r","r","r+","r+","w","w"};
                     71: 
                     72: #ifndef O_BINARY
                     73: #define O_BINARY 0
                     74: #endif
                     75: #ifndef O_TEXT
                     76: #define O_TEXT 0
                     77: #endif
                     78: 
                     79: int ufileattr[6]= {
                     80:   O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
                     81:   O_RDWR  |O_BINARY, O_RDWR  |O_BINARY,
                     82:   O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
                     83: #endif
                     84: /* end global vars for engine.c */
                     85: 
1.1       anton      86: #define PRIM_VERSION 1
                     87: /* increment this whenever the primitives change in an incompatible way */
                     88: 
1.14      pazsan     89: #ifndef DEFAULTPATH
1.39      anton      90: #  define DEFAULTPATH "."
1.14      pazsan     91: #endif
                     92: 
1.1       anton      93: #ifdef MSDOS
                     94: jmp_buf throw_jmp_buf;
                     95: #endif
                     96: 
1.56      anton      97: #if defined(DOUBLY_INDIRECT)
                     98: #  define CFA(n)       ({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
1.1       anton      99: #else
1.56      anton     100: #  define CFA(n)       ((Cell)(symbols+((n)&~0x4000UL)))
1.1       anton     101: #endif
                    102: 
                    103: #define maxaligned(n)  (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
                    104: 
                    105: static UCell dictsize=0;
                    106: static UCell dsize=0;
                    107: static UCell rsize=0;
                    108: static UCell fsize=0;
                    109: static UCell lsize=0;
                    110: int offset_image=0;
1.4       anton     111: int die_on_signal=0;
1.13      pazsan    112: #ifndef INCLUDE_IMAGE
1.1       anton     113: static int clear_dictionary=0;
1.24      anton     114: UCell pagesize=1;
1.22      pazsan    115: char *progname;
                    116: #else
                    117: char *progname = "gforth";
                    118: int optind = 1;
1.13      pazsan    119: #endif
1.31      pazsan    120: 
1.75      anton     121: #define CODE_BLOCK_SIZE (64*1024)
1.48      anton     122: Address code_area=0;
1.73      anton     123: Cell code_area_size = CODE_BLOCK_SIZE;
1.75      anton     124: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
                    125:                                           does for the dictionary */
1.65      anton     126: Address start_flush=0; /* start of unflushed code */
1.74      anton     127: Cell last_jump=0; /* if the last prim was compiled without jump, this
                    128:                      is it's number, otherwise this contains 0 */
1.48      anton     129: 
1.60      anton     130: static int no_super=0;   /* true if compile_prim should not fuse prims */
1.81      anton     131: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
                    132:                                             dynamically */
1.60      anton     133: 
1.30      pazsan    134: #ifdef HAS_DEBUG
1.68      anton     135: int debug=0;
1.31      pazsan    136: #else
                    137: # define perror(x...)
                    138: # define fprintf(x...)
1.30      pazsan    139: #endif
1.31      pazsan    140: 
1.24      anton     141: ImageHeader *gforth_header;
1.43      anton     142: Label *vm_prims;
1.53      anton     143: #ifdef DOUBLY_INDIRECT
                    144: Label *xts; /* same content as vm_prims, but should only be used for xts */
                    145: #endif
1.1       anton     146: 
1.30      pazsan    147: #ifdef MEMCMP_AS_SUBROUTINE
                    148: int gforth_memcmp(const char * s1, const char * s2, size_t n)
                    149: {
                    150:   return memcmp(s1, s2, n);
                    151: }
                    152: #endif
                    153: 
1.1       anton     154: /* image file format:
1.15      pazsan    155:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
1.1       anton     156:  *   padding to a multiple of 8
1.15      pazsan    157:  *   magic: "Gforth2x" means format 0.4,
                    158:  *              where x is a byte with
                    159:  *              bit 7:   reserved = 0
                    160:  *              bit 6:5: address unit size 2^n octets
                    161:  *              bit 4:3: character size 2^n octets
                    162:  *              bit 2:1: cell size 2^n octets
                    163:  *              bit 0:   endian, big=0, little=1.
                    164:  *  The magic are always 8 octets, no matter what the native AU/character size is
1.1       anton     165:  *  padding to max alignment (no padding necessary on current machines)
1.24      anton     166:  *  ImageHeader structure (see forth.h)
1.1       anton     167:  *  data (size in ImageHeader.image_size)
                    168:  *  tags ((if relocatable, 1 bit/data cell)
                    169:  *
                    170:  * tag==1 means that the corresponding word is an address;
                    171:  * If the word is >=0, the address is within the image;
                    172:  * addresses within the image are given relative to the start of the image.
                    173:  * If the word =-1 (CF_NIL), the address is NIL,
                    174:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
                    175:  * If the word =CF(DODOES), it's a DOES> CFA
                    176:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
                    177:  *                                     possibly containing a jump to dodoes)
1.51      anton     178:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
                    179:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
                    180:  *                                        it's the threaded code of a primitive
1.1       anton     181:  */
                    182: 
1.46      jwilke    183: void relocate(Cell *image, const char *bitstring, 
                    184:               int size, int base, Label symbols[])
1.1       anton     185: {
1.16      pazsan    186:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
1.11      pazsan    187:   Cell token;
1.1       anton     188:   char bits;
1.37      anton     189:   Cell max_symbols;
1.46      jwilke    190:   /* 
                    191:    * A virtial start address that's the real start address minus 
                    192:    * the one in the image 
                    193:    */
1.45      jwilke    194:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
1.1       anton     195: 
1.46      jwilke    196:   
                    197: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
1.37      anton     198:   
                    199:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
                    200:     ;
1.47      anton     201:   max_symbols--;
1.35      pazsan    202:   size/=sizeof(Cell);
                    203: 
1.31      pazsan    204:   for(k=0; k<=steps; k++) {
1.13      pazsan    205:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
1.1       anton     206:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
1.35      pazsan    207:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
                    208:        /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
1.45      jwilke    209:         token=image[i];
                    210:        if(token<0)
1.55      anton     211:          switch(token|0x4000)
1.1       anton     212:            {
                    213:            case CF_NIL      : image[i]=0; break;
                    214: #if !defined(DOUBLY_INDIRECT)
                    215:            case CF(DOCOL)   :
                    216:            case CF(DOVAR)   :
                    217:            case CF(DOCON)   :
                    218:            case CF(DOUSER)  : 
                    219:            case CF(DODEFER) : 
1.11      pazsan    220:            case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
1.1       anton     221:            case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
                    222: #endif /* !defined(DOUBLY_INDIRECT) */
                    223:            case CF(DODOES)  :
1.45      jwilke    224:              MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
1.1       anton     225:              break;
                    226:            default          :
1.56      anton     227: /*           printf("Code field generation image[%x]:=CFA(%x)\n",
1.1       anton     228:                     i, CF(image[i])); */
1.55      anton     229:              if (CF((token | 0x4000))<max_symbols) {
1.56      anton     230:                image[i]=(Cell)CFA(CF(token));
                    231: #ifdef DIRECT_THREADED
                    232:                if ((token & 0x4000) == 0) /* threade code, no CFA */
1.70      anton     233:                  compile_prim1(&image[i]);
1.56      anton     234: #endif
1.55      anton     235:              } else
1.83    ! anton     236:                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],PACKAGE_VERSION);
1.1       anton     237:            }
1.46      jwilke    238:        else {
1.45      jwilke    239:           // if base is > 0: 0 is a null reference so don't adjust
                    240:           if (token>=base) {
                    241:             image[i]+=(Cell)start;
                    242:           }
1.46      jwilke    243:         }
1.1       anton     244:       }
                    245:     }
1.31      pazsan    246:   }
1.70      anton     247:   finish_code();
1.26      jwilke    248:   ((ImageHeader*)(image))->base = (Address) image;
1.1       anton     249: }
                    250: 
                    251: UCell checksum(Label symbols[])
                    252: {
                    253:   UCell r=PRIM_VERSION;
                    254:   Cell i;
                    255: 
                    256:   for (i=DOCOL; i<=DOESJUMP; i++) {
                    257:     r ^= (UCell)(symbols[i]);
                    258:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    259:   }
                    260: #ifdef DIRECT_THREADED
                    261:   /* we have to consider all the primitives */
                    262:   for (; symbols[i]!=(Label)0; i++) {
                    263:     r ^= (UCell)(symbols[i]);
                    264:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    265:   }
                    266: #else
                    267:   /* in indirect threaded code all primitives are accessed through the
                    268:      symbols table, so we just have to put the base address of symbols
                    269:      in the checksum */
                    270:   r ^= (UCell)symbols;
                    271: #endif
                    272:   return r;
                    273: }
                    274: 
1.3       anton     275: Address verbose_malloc(Cell size)
                    276: {
                    277:   Address r;
                    278:   /* leave a little room (64B) for stack underflows */
                    279:   if ((r = malloc(size+64))==NULL) {
                    280:     perror(progname);
                    281:     exit(1);
                    282:   }
                    283:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
                    284:   if (debug)
                    285:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
                    286:   return r;
                    287: }
                    288: 
1.33      anton     289: static Address next_address=0;
                    290: void after_alloc(Address r, Cell size)
                    291: {
                    292:   if (r != (Address)-1) {
                    293:     if (debug)
                    294:       fprintf(stderr, "success, address=$%lx\n", (long) r);
                    295:     if (pagesize != 1)
                    296:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
                    297:   } else {
                    298:     if (debug)
                    299:       fprintf(stderr, "failed: %s\n", strerror(errno));
                    300:   }
                    301: }
                    302: 
1.34      anton     303: #ifndef MAP_FAILED
                    304: #define MAP_FAILED ((Address) -1)
                    305: #endif
                    306: #ifndef MAP_FILE
                    307: # define MAP_FILE 0
                    308: #endif
                    309: #ifndef MAP_PRIVATE
                    310: # define MAP_PRIVATE 0
                    311: #endif
                    312: 
                    313: #if defined(HAVE_MMAP)
                    314: static Address alloc_mmap(Cell size)
1.1       anton     315: {
                    316:   Address r;
                    317: 
                    318: #if defined(MAP_ANON)
                    319:   if (debug)
                    320:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
1.34      anton     321:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
1.1       anton     322: #else /* !defined(MAP_ANON) */
1.17      anton     323:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
                    324:      apparently defaults) */
1.1       anton     325:   static int dev_zero=-1;
                    326: 
                    327:   if (dev_zero == -1)
                    328:     dev_zero = open("/dev/zero", O_RDONLY);
                    329:   if (dev_zero == -1) {
1.34      anton     330:     r = MAP_FAILED;
1.1       anton     331:     if (debug)
                    332:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
                    333:              strerror(errno));
                    334:   } else {
                    335:     if (debug)
                    336:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
                    337:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
                    338:   }
                    339: #endif /* !defined(MAP_ANON) */
1.34      anton     340:   after_alloc(r, size);
                    341:   return r;  
                    342: }
                    343: #endif
                    344: 
                    345: Address my_alloc(Cell size)
                    346: {
                    347: #if HAVE_MMAP
                    348:   Address r;
                    349: 
                    350:   r=alloc_mmap(size);
                    351:   if (r!=MAP_FAILED)
1.1       anton     352:     return r;
                    353: #endif /* HAVE_MMAP */
1.3       anton     354:   /* use malloc as fallback */
                    355:   return verbose_malloc(size);
1.1       anton     356: }
                    357: 
1.34      anton     358: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
1.33      anton     359: {
1.34      anton     360:   Address image = MAP_FAILED;
1.33      anton     361: 
1.56      anton     362: #if defined(HAVE_MMAP)
1.33      anton     363:   if (offset==0) {
1.34      anton     364:     image=alloc_mmap(dictsize);
1.33      anton     365:     if (debug)
1.34      anton     366:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
                    367:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
                    368:     after_alloc(image,dictsize);
1.33      anton     369:   }
1.56      anton     370: #endif /* defined(HAVE_MMAP) */
1.34      anton     371:   if (image == MAP_FAILED) {
1.56      anton     372:     image = my_alloc(dictsize+offset)+offset;
1.33      anton     373:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
1.34      anton     374:     fread(image, 1, imagesize, file);
1.33      anton     375:   }
                    376:   return image;
                    377: }
                    378: 
1.10      pazsan    379: void set_stack_sizes(ImageHeader * header)
                    380: {
                    381:   if (dictsize==0)
                    382:     dictsize = header->dict_size;
                    383:   if (dsize==0)
                    384:     dsize = header->data_stack_size;
                    385:   if (rsize==0)
                    386:     rsize = header->return_stack_size;
                    387:   if (fsize==0)
                    388:     fsize = header->fp_stack_size;
                    389:   if (lsize==0)
                    390:     lsize = header->locals_stack_size;
                    391:   dictsize=maxaligned(dictsize);
                    392:   dsize=maxaligned(dsize);
                    393:   rsize=maxaligned(rsize);
                    394:   lsize=maxaligned(lsize);
                    395:   fsize=maxaligned(fsize);
                    396: }
                    397: 
                    398: void alloc_stacks(ImageHeader * header)
                    399: {
                    400:   header->dict_size=dictsize;
                    401:   header->data_stack_size=dsize;
                    402:   header->fp_stack_size=fsize;
                    403:   header->return_stack_size=rsize;
                    404:   header->locals_stack_size=lsize;
                    405: 
                    406:   header->data_stack_base=my_alloc(dsize);
                    407:   header->fp_stack_base=my_alloc(fsize);
                    408:   header->return_stack_base=my_alloc(rsize);
                    409:   header->locals_stack_base=my_alloc(lsize);
                    410: }
                    411: 
1.44      pazsan    412: #warning You can ignore the warnings about clobbered variables in go_forth
1.11      pazsan    413: int go_forth(Address image, int stack, Cell *entries)
                    414: {
1.38      anton     415:   volatile ImageHeader *image_header = (ImageHeader *)image;
1.18      anton     416:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
1.44      pazsan    417:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
1.18      anton     418:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
1.44      pazsan    419: #ifdef GFORTH_DEBUGGING
1.38      anton     420:   volatile Cell *orig_rp0=rp0;
1.44      pazsan    421: #endif
1.18      anton     422:   Address lp0=image_header->locals_stack_base + lsize;
                    423:   Xt *ip0=(Xt *)(image_header->boot_entry);
1.13      pazsan    424: #ifdef SYSSIGNALS
1.11      pazsan    425:   int throw_code;
1.13      pazsan    426: #endif
1.11      pazsan    427: 
                    428:   /* ensure that the cached elements (if any) are accessible */
1.41      anton     429:   IF_spTOS(sp0--);
                    430:   IF_fpTOS(fp0--);
1.11      pazsan    431:   
                    432:   for(;stack>0;stack--)
1.18      anton     433:     *--sp0=entries[stack-1];
1.11      pazsan    434: 
1.30      pazsan    435: #ifdef SYSSIGNALS
1.11      pazsan    436:   get_winsize();
                    437:    
                    438:   install_signal_handlers(); /* right place? */
                    439:   
                    440:   if ((throw_code=setjmp(throw_jmp_buf))) {
                    441:     static Cell signal_data_stack[8];
                    442:     static Cell signal_return_stack[8];
                    443:     static Float signal_fp_stack[1];
1.13      pazsan    444: 
1.11      pazsan    445:     signal_data_stack[7]=throw_code;
1.18      anton     446: 
                    447: #ifdef GFORTH_DEBUGGING
1.38      anton     448:     /* fprintf(stderr,"\nrp=%ld\n",(long)rp); */
                    449:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
1.18      anton     450:       /* no rstack overflow or underflow */
                    451:       rp0 = rp;
1.63      anton     452:       *--rp0 = (Cell)saved_ip;
1.18      anton     453:     }
                    454:     else /* I love non-syntactic ifdefs :-) */
                    455: #endif
                    456:     rp0 = signal_return_stack+8;
1.25      anton     457:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
1.11      pazsan    458:     
1.33      anton     459:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
1.18      anton     460:                       rp0, signal_fp_stack, 0));
1.11      pazsan    461:   }
1.13      pazsan    462: #endif
1.11      pazsan    463: 
1.33      anton     464:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
1.11      pazsan    465: }
                    466: 
1.30      pazsan    467: #ifndef INCLUDE_IMAGE
1.21      anton     468: void print_sizes(Cell sizebyte)
                    469:      /* print size information */
                    470: {
                    471:   static char* endianstring[]= { "   big","little" };
                    472:   
                    473:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
                    474:          endianstring[sizebyte & 1],
                    475:          1 << ((sizebyte >> 1) & 3),
                    476:          1 << ((sizebyte >> 3) & 3),
                    477:          1 << ((sizebyte >> 5) & 3));
                    478: }
                    479: 
1.70      anton     480: #define MAX_IMMARGS 2
                    481: 
1.69      anton     482: #ifndef NO_DYNAMIC
1.47      anton     483: typedef struct {
                    484:   Label start;
1.74      anton     485:   Cell length; /* only includes the jump iff superend is true*/
                    486:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
1.70      anton     487:   char superend; /* true if primitive ends superinstruction, i.e.,
1.47      anton     488:                      unconditional branch, execute, etc. */
1.70      anton     489:   Cell nimmargs;
                    490:   struct immarg {
                    491:     Cell offset; /* offset of immarg within prim */
                    492:     char rel;    /* true if immarg is relative */
                    493:   } immargs[MAX_IMMARGS];
1.47      anton     494: } PrimInfo;
                    495: 
                    496: PrimInfo *priminfos;
1.76      anton     497: PrimInfo **decomp_prims;
                    498: 
                    499: int compare_priminfo_length(PrimInfo **a, PrimInfo **b)
                    500: {
1.77      anton     501:   Cell diff = (*a)->length - (*b)->length;
                    502:   if (diff)
                    503:     return diff;
                    504:   else /* break ties by start address; thus the decompiler produces
                    505:           the earliest primitive with the same code (e.g. noop instead
                    506:           of (char) and @ instead of >code-address */
                    507:     return (*b)->start - (*a)->start;
1.76      anton     508: }
                    509: 
1.69      anton     510: #endif /* defined(NO_DYNAMIC) */
1.48      anton     511: Cell npriminfos=0;
1.47      anton     512: 
1.76      anton     513: 
1.47      anton     514: void check_prims(Label symbols1[])
                    515: {
                    516:   int i;
1.70      anton     517:   Label *symbols2, *symbols3, *ends1;
1.49      anton     518:   static char superend[]={
1.48      anton     519: #include "prim_superend.i"
                    520:   };
1.47      anton     521: 
1.66      anton     522:   if (debug)
                    523: #ifdef __VERSION__
                    524:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
                    525: #else
                    526: #define xstr(s) str(s)
                    527: #define str(s) #s
                    528:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
                    529: #endif
1.47      anton     530:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
                    531:     ;
1.55      anton     532:   npriminfos = i;
1.70      anton     533:   
                    534: #ifndef NO_DYNAMIC
1.66      anton     535:   if (no_dynamic)
                    536:     return;
1.55      anton     537:   symbols2=engine2(0,0,0,0,0);
1.70      anton     538: #if NO_IP
                    539:   symbols3=engine3(0,0,0,0,0);
                    540: #else
                    541:   symbols3=symbols1;
                    542: #endif
                    543:   ends1 = symbols1+i+1-DOESJUMP;
1.47      anton     544:   priminfos = calloc(i,sizeof(PrimInfo));
                    545:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
1.70      anton     546:     int prim_len = ends1[i]-symbols1[i];
1.47      anton     547:     PrimInfo *pi=&priminfos[i];
1.70      anton     548:     int j=0;
                    549:     char *s1 = (char *)symbols1[i];
                    550:     char *s2 = (char *)symbols2[i];
                    551:     char *s3 = (char *)symbols3[i];
                    552: 
                    553:     pi->start = s1;
                    554:     pi->superend = superend[i-DOESJUMP-1]|no_super;
                    555:     if (pi->superend)
                    556:       pi->length = symbols1[i+1]-symbols1[i];
                    557:     else
                    558:       pi->length = prim_len;
1.74      anton     559:     pi->restlength = symbols1[i+1] - symbols1[i] - pi->length;
1.70      anton     560:     pi->nimmargs = 0;
                    561:     if (debug)
1.74      anton     562:       fprintf(stderr, "Prim %3d @ %p %p %p, length=%3d restlength=%2d superend=%1d",
                    563:              i, s1, s2, s3, pi->length, pi->restlength, pi->superend);
1.70      anton     564:     assert(prim_len>=0);
1.74      anton     565:     while (j<(pi->length+pi->restlength)) {
1.70      anton     566:       if (s1[j]==s3[j]) {
                    567:        if (s1[j] != s2[j]) {
                    568:          pi->start = NULL; /* not relocatable */
                    569:          if (debug)
                    570:            fprintf(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
1.74      anton     571:          /* assert(j<prim_len); */
1.70      anton     572:          break;
                    573:        }
                    574:        j++;
                    575:       } else {
                    576:        struct immarg *ia=&pi->immargs[pi->nimmargs];
                    577: 
                    578:        pi->nimmargs++;
                    579:        ia->offset=j;
                    580:        if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
                    581:          ia->rel=0;
                    582:          if (debug)
                    583:            fprintf(stderr,"\n   absolute immarg: offset %3d",j);
                    584:        } else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
                    585:                   symbols1[DOESJUMP+1]) {
                    586:          ia->rel=1;
                    587:          if (debug)
                    588:            fprintf(stderr,"\n   relative immarg: offset %3d",j);
                    589:        } else {
                    590:          pi->start = NULL; /* not relocatable */
                    591:          if (debug)
                    592:            fprintf(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
1.74      anton     593:          /* assert(j<prim_len);*/
1.70      anton     594:          break;
                    595:        }
                    596:        j+=4;
1.47      anton     597:       }
                    598:     }
1.70      anton     599:     if (debug)
                    600:       fprintf(stderr,"\n");
                    601:   }
1.76      anton     602:   decomp_prims = calloc(i,sizeof(PrimInfo *));
                    603:   for (i=DOESJUMP+1; i<npriminfos; i++)
                    604:     decomp_prims[i] = &(priminfos[i]);
                    605:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
                    606:        compare_priminfo_length);
1.70      anton     607: #endif
                    608: }
                    609: 
1.74      anton     610: #ifndef NO_DYNAMIC
                    611: void flush_to_here(void)
                    612: {
                    613:   FLUSH_ICACHE(start_flush, code_here-start_flush);
                    614:   start_flush=code_here;
                    615: }
                    616: 
                    617: void append_jump(void)
                    618: {
                    619:   if (last_jump) {
                    620:     PrimInfo *pi = &priminfos[last_jump];
                    621:     
                    622:     memcpy(code_here, pi->start+pi->length, pi->restlength);
                    623:     code_here += pi->restlength;
                    624:     last_jump=0;
                    625:     flush_to_here();
                    626:   }
                    627: }
                    628: 
1.75      anton     629: /* Gforth remembers all code blocks in this list.  On forgetting (by
                    630: executing a marker) the code blocks are not freed (because Gforth does
                    631: not remember how they were allocated; hmm, remembering that might be
                    632: easier and cleaner).  Instead, code_here etc. are reset to the old
                    633: value, and the "forgotten" code blocks are reused when they are
                    634: needed. */
                    635: 
                    636: struct code_block_list {
                    637:   struct code_block_list *next;
                    638:   Address block;
                    639:   Cell size;
                    640: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
                    641: 
1.74      anton     642: Address append_prim(Cell p)
                    643: {
                    644:   PrimInfo *pi = &priminfos[p];
                    645:   Address old_code_here = code_here;
                    646: 
                    647:   if (code_area+code_area_size < code_here+pi->length+pi->restlength) {
1.75      anton     648:     struct code_block_list *p;
1.74      anton     649:     append_jump();
1.75      anton     650:     if (*next_code_blockp == NULL) {
                    651:       code_here = start_flush = code_area = my_alloc(code_area_size);
                    652:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
                    653:       *next_code_blockp = p;
                    654:       p->next = NULL;
                    655:       p->block = code_here;
                    656:       p->size = code_area_size;
                    657:     } else {
                    658:       p = *next_code_blockp;
                    659:       code_here = start_flush = code_area = p->block;
                    660:     }
1.74      anton     661:     old_code_here = code_here;
1.75      anton     662:     next_code_blockp = &(p->next);
1.74      anton     663:   }
                    664:   memcpy(code_here, pi->start, pi->length);
                    665:   code_here += pi->length;
                    666:   if (pi->superend)
                    667:     flush_to_here();
                    668:   return old_code_here;
                    669: }
                    670: #endif
1.75      anton     671: 
                    672: int forget_dyncode(Address code)
                    673: {
                    674: #ifdef NO_DYNAMIC
                    675:   return -1;
                    676: #else
                    677:   struct code_block_list *p, **pp;
                    678: 
                    679:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
                    680:     if (code >= p->block && code < p->block+p->size) {
                    681:       next_code_blockp = &(p->next);
                    682:       code_here = start_flush = code;
                    683:       code_area = p->block;
                    684:       last_jump = 0;
                    685:       return -1;
                    686:     }
                    687:   }
1.78      anton     688:   return -no_dynamic;
1.75      anton     689: #endif /* !defined(NO_DYNAMIC) */
                    690: }
                    691: 
1.76      anton     692: Label decompile_code(Label code)
1.75      anton     693: {
1.76      anton     694: #ifdef NO_DYNAMIC
                    695:   return code;
                    696: #else /* !defined(NO_DYNAMIC) */
                    697:   Cell i;
1.77      anton     698:   struct code_block_list *p;
1.76      anton     699: 
1.77      anton     700:   /* first, check if we are in code at all */
                    701:   for (p = code_block_list;; p = p->next) {
                    702:     if (p == NULL)
                    703:       return code;
                    704:     if (code >= p->block && code < p->block+p->size)
                    705:       break;
                    706:   }
1.76      anton     707:   /* reverse order because NOOP might match other prims */
                    708:   for (i=npriminfos-1; i>DOESJUMP; i--) {
                    709:     PrimInfo *pi=decomp_prims[i];
                    710:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
                    711:       return pi->start;
                    712:   }
                    713:   return code;
                    714: #endif /* !defined(NO_DYNAMIC) */
1.75      anton     715: }
1.74      anton     716: 
1.70      anton     717: #ifdef NO_IP
                    718: int nbranchinfos=0;
                    719: 
                    720: struct branchinfo {
                    721:   Label *targetptr; /* *(bi->targetptr) is the target */
                    722:   Cell *addressptr; /* store the target here */
                    723: } branchinfos[100000];
                    724: 
                    725: int ndoesexecinfos=0;
                    726: struct doesexecinfo {
                    727:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
                    728:   Cell *xt; /* cfa of word whose does-code needs calling */
                    729: } doesexecinfos[10000];
                    730: 
1.73      anton     731: /* definitions of N_execute etc. */
                    732: #include "prim_num.i"
1.70      anton     733: 
                    734: void set_rel_target(Cell *source, Label target)
                    735: {
                    736:   *source = ((Cell)target)-(((Cell)source)+4);
                    737: }
                    738: 
                    739: void register_branchinfo(Label source, Cell targetptr)
                    740: {
                    741:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
                    742:   bi->targetptr = (Label *)targetptr;
                    743:   bi->addressptr = (Cell *)source;
                    744:   nbranchinfos++;
                    745: }
                    746: 
                    747: Cell *compile_prim1arg(Cell p)
                    748: {
                    749:   int l = priminfos[p].length;
                    750:   Address old_code_here=code_here;
                    751: 
1.74      anton     752:   assert(vm_prims[p]==priminfos[p].start);
                    753:   append_prim(p);
1.70      anton     754:   return (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
                    755: }
                    756: 
                    757: Cell *compile_call2(Cell targetptr)
                    758: {
                    759:   Cell *next_code_target;
1.73      anton     760:   PrimInfo *pi = &priminfos[N_call2];
1.74      anton     761:   Address old_code_here = append_prim(N_call2);
1.70      anton     762: 
1.74      anton     763:   next_code_target = (Cell *)(old_code_here + pi->immargs[0].offset);
                    764:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetptr);
1.70      anton     765:   return next_code_target;
                    766: }
                    767: #endif
                    768: 
                    769: void finish_code(void)
                    770: {
                    771: #ifdef NO_IP
                    772:   Cell i;
                    773: 
                    774:   compile_prim1(NULL);
                    775:   for (i=0; i<ndoesexecinfos; i++) {
                    776:     struct doesexecinfo *dei = &doesexecinfos[i];
                    777:     branchinfos[dei->branchinfo].targetptr = DOES_CODE1((dei->xt));
                    778:   }
                    779:   ndoesexecinfos = 0;
                    780:   for (i=0; i<nbranchinfos; i++) {
                    781:     struct branchinfo *bi=&branchinfos[i];
                    782:     set_rel_target(bi->addressptr, *(bi->targetptr));
                    783:   }
                    784:   nbranchinfos = 0;
                    785:   FLUSH_ICACHE(start_flush, code_here-start_flush);
                    786:   start_flush=code_here;
1.48      anton     787: #endif
                    788: }
                    789: 
1.70      anton     790: void compile_prim1(Cell *start)
1.48      anton     791: {
1.61      anton     792: #if defined(DOUBLY_INDIRECT)
1.70      anton     793:   Label prim=(Label)*start;
1.54      anton     794:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
                    795:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
1.70      anton     796:     *start=(Cell)prim;
                    797:     return;
                    798:   } else {
                    799:     *start = prim-((Label)xts)+((Label)vm_prims);
                    800:     return;
                    801:   }
                    802: #elif defined(NO_IP)
                    803:   static Cell *last_start=NULL;
                    804:   static Xt last_prim=NULL;
                    805:   /* delay work by one call in order to get relocated immargs */
                    806: 
                    807:   if (last_start) {
                    808:     unsigned i = last_prim-vm_prims;
                    809:     PrimInfo *pi=&priminfos[i];
                    810:     Cell *next_code_target=NULL;
                    811: 
                    812:     assert(i<npriminfos);
1.73      anton     813:     if (i==N_execute||i==N_perform||i==N_lit_perform) {
                    814:       next_code_target = compile_prim1arg(N_set_next_code);
1.70      anton     815:     }
1.73      anton     816:     if (i==N_call) {
1.70      anton     817:       next_code_target = compile_call2(last_start[1]);
1.73      anton     818:     } else if (i==N_does_exec) {
1.70      anton     819:       struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
1.73      anton     820:       *compile_prim1arg(N_lit) = (Cell)PFA(last_start[1]);
1.70      anton     821:       /* we cannot determine the callee now (last_start[1] may be a
                    822:          forward reference), so just register an arbitrary target, and
                    823:          register in dei that we need to fix this before resolving
                    824:          branches */
                    825:       dei->branchinfo = nbranchinfos;
                    826:       dei->xt = (Cell *)(last_start[1]);
                    827:       next_code_target = compile_call2(NULL);
                    828:     } else if (pi->start == NULL) { /* non-reloc */
1.73      anton     829:       next_code_target = compile_prim1arg(N_set_next_code);
                    830:       set_rel_target(compile_prim1arg(N_abranch),*(Xt)last_prim);
1.70      anton     831:     } else {
                    832:       unsigned j;
1.74      anton     833:       Address old_code_here = append_prim(i);
1.70      anton     834: 
                    835:       for (j=0; j<pi->nimmargs; j++) {
                    836:        struct immarg *ia = &(pi->immargs[j]);
                    837:        Cell argval = last_start[pi->nimmargs - j]; /* !! specific to prims */
                    838:        if (ia->rel) { /* !! assumption: relative refs are branches */
1.74      anton     839:          register_branchinfo(old_code_here + ia->offset, argval);
1.70      anton     840:        } else /* plain argument */
1.74      anton     841:          *(Cell *)(old_code_here + ia->offset) = argval;
1.70      anton     842:       }
                    843:     }
                    844:     if (next_code_target!=NULL)
                    845:       *next_code_target = (Cell)code_here;
                    846:   }
                    847:   if (start) {
                    848:     last_prim = (Xt)*start;
                    849:     *start = (Cell)code_here;
                    850:   }
                    851:   last_start = start;
                    852:   return;
                    853: #elif !defined(NO_DYNAMIC)
                    854:   Label prim=(Label)*start;
1.58      anton     855:   unsigned i;
1.74      anton     856:   Address old_code_here;
1.48      anton     857: 
1.58      anton     858:   i = ((Xt)prim)-vm_prims;
1.56      anton     859:   prim = *(Xt)prim;
1.70      anton     860:   if (no_dynamic) {
                    861:     *start = (Cell)prim;
                    862:     return;
                    863:   }
1.58      anton     864:   if (i>=npriminfos || priminfos[i].start == 0) { /* not a relocatable prim */
1.74      anton     865:     append_jump();
1.70      anton     866:     *start = (Cell)prim;
                    867:     return;
1.47      anton     868:   }
1.58      anton     869:   assert(priminfos[i].start = prim); 
1.50      anton     870: #ifdef ALIGN_CODE
                    871:   ALIGN_CODE;
                    872: #endif
1.74      anton     873:   assert(prim==priminfos[i].start);
                    874:   old_code_here = append_prim(i);
                    875:   last_jump = (priminfos[i].superend) ? 0 : i;
1.70      anton     876:   *start = (Cell)old_code_here;
                    877:   return;
1.61      anton     878: #else /* !defined(DOUBLY_INDIRECT), no code replication */
1.70      anton     879:   Label prim=(Label)*start;
1.61      anton     880: #if !defined(INDIRECT_THREADED)
1.56      anton     881:   prim = *(Xt)prim;
1.61      anton     882: #endif
1.70      anton     883:   *start = (Cell)prim;
                    884:   return;
1.54      anton     885: #endif /* !defined(DOUBLY_INDIRECT) */
1.70      anton     886: }
                    887: 
                    888: Label compile_prim(Label prim)
                    889: {
                    890:   Cell x=(Cell)prim;
1.80      anton     891:   assert(0);
1.70      anton     892:   compile_prim1(&x);
                    893:   return (Label)x;
1.47      anton     894: }
                    895: 
1.69      anton     896: #if defined(PRINT_SUPER_LENGTHS) && !defined(NO_DYNAMIC)
1.59      anton     897: Cell prim_length(Cell prim)
                    898: {
                    899:   return priminfos[prim+DOESJUMP+1].length;
                    900: }
                    901: #endif
                    902: 
1.1       anton     903: Address loader(FILE *imagefile, char* filename)
                    904: /* returns the address of the image proper (after the preamble) */
                    905: {
                    906:   ImageHeader header;
                    907:   Address image;
                    908:   Address imp; /* image+preamble */
1.17      anton     909:   Char magic[8];
                    910:   char magic7; /* size byte of magic number */
1.1       anton     911:   Cell preamblesize=0;
1.6       pazsan    912:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1.1       anton     913:   UCell check_sum;
1.15      pazsan    914:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
                    915:                 (RELINFOBITS == 16) ? 1 :
                    916:                 (RELINFOBITS == 32) ? 2 : 3);
                    917:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
                    918:                   (sizeof(Char) == 2) ? 1 :
                    919:                   (sizeof(Char) == 4) ? 2 : 3) + ausize;
                    920:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
                    921:                   (sizeof(Cell) == 2) ? 1 :
                    922:                   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1.21      anton     923:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
                    924: #ifdef WORDS_BIGENDIAN
                    925:        0
                    926: #else
                    927:        1
                    928: #endif
                    929:     ;
1.1       anton     930: 
1.43      anton     931:   vm_prims = engine(0,0,0,0,0);
1.47      anton     932:   check_prims(vm_prims);
1.1       anton     933: #ifndef DOUBLY_INDIRECT
1.59      anton     934: #ifdef PRINT_SUPER_LENGTHS
                    935:   print_super_lengths();
                    936: #endif
1.43      anton     937:   check_sum = checksum(vm_prims);
1.1       anton     938: #else /* defined(DOUBLY_INDIRECT) */
1.43      anton     939:   check_sum = (UCell)vm_prims;
1.1       anton     940: #endif /* defined(DOUBLY_INDIRECT) */
1.10      pazsan    941:   
                    942:   do {
                    943:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1.15      pazsan    944:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.4) image.\n",
1.10      pazsan    945:              progname, filename);
                    946:       exit(1);
1.1       anton     947:     }
1.10      pazsan    948:     preamblesize+=8;
1.15      pazsan    949:   } while(memcmp(magic,"Gforth2",7));
1.17      anton     950:   magic7 = magic[7];
1.1       anton     951:   if (debug) {
1.17      anton     952:     magic[7]='\0';
1.21      anton     953:     fprintf(stderr,"Magic found: %s ", magic);
                    954:     print_sizes(magic7);
1.1       anton     955:   }
                    956: 
1.21      anton     957:   if (magic7 != sizebyte)
                    958:     {
                    959:       fprintf(stderr,"This image is:         ");
                    960:       print_sizes(magic7);
                    961:       fprintf(stderr,"whereas the machine is ");
                    962:       print_sizes(sizebyte);
1.1       anton     963:       exit(-2);
                    964:     };
                    965: 
                    966:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1.10      pazsan    967: 
                    968:   set_stack_sizes(&header);
1.1       anton     969:   
                    970: #if HAVE_GETPAGESIZE
                    971:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
                    972: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
                    973:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
                    974: #elif PAGESIZE
                    975:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
                    976: #endif
                    977:   if (debug)
1.5       jwilke    978:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1.1       anton     979: 
1.34      anton     980:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
                    981:                          preamblesize+dictsize, data_offset);
1.33      anton     982:   imp=image+preamblesize;
1.57      anton     983:   alloc_stacks((ImageHeader *)imp);
1.1       anton     984:   if (clear_dictionary)
1.33      anton     985:     memset(imp+header.image_size, 0, dictsize-header.image_size);
1.46      jwilke    986:   if(header.base==0 || header.base  == 0x100) {
1.1       anton     987:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
                    988:     char reloc_bits[reloc_size];
1.33      anton     989:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1.10      pazsan    990:     fread(reloc_bits, 1, reloc_size, imagefile);
1.45      jwilke    991:     relocate((Cell *)imp, reloc_bits, header.image_size, header.base, vm_prims);
1.1       anton     992: #if 0
                    993:     { /* let's see what the relocator did */
                    994:       FILE *snapshot=fopen("snapshot.fi","wb");
                    995:       fwrite(image,1,imagesize,snapshot);
                    996:       fclose(snapshot);
                    997:     }
                    998: #endif
1.46      jwilke    999:   }
                   1000:   else if(header.base!=imp) {
                   1001:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
                   1002:            progname, (unsigned long)header.base, (unsigned long)imp);
                   1003:     exit(1);
1.1       anton    1004:   }
                   1005:   if (header.checksum==0)
                   1006:     ((ImageHeader *)imp)->checksum=check_sum;
                   1007:   else if (header.checksum != check_sum) {
                   1008:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
                   1009:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
                   1010:     exit(1);
                   1011:   }
1.53      anton    1012: #ifdef DOUBLY_INDIRECT
                   1013:   ((ImageHeader *)imp)->xt_base = xts;
                   1014: #endif
1.1       anton    1015:   fclose(imagefile);
                   1016: 
1.56      anton    1017:   /* unnecessary, except maybe for CODE words */
                   1018:   /* FLUSH_ICACHE(imp, header.image_size);*/
1.1       anton    1019: 
                   1020:   return imp;
                   1021: }
                   1022: 
1.72      anton    1023: /* pointer to last '/' or '\' in file, 0 if there is none. */
                   1024: char *onlypath(char *filename)
1.10      pazsan   1025: {
1.72      anton    1026:   return strrchr(filename, DIRSEP);
1.1       anton    1027: }
                   1028: 
                   1029: FILE *openimage(char *fullfilename)
1.10      pazsan   1030: {
                   1031:   FILE *image_file;
1.28      anton    1032:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
1.10      pazsan   1033: 
1.28      anton    1034:   image_file=fopen(expfilename,"rb");
1.1       anton    1035:   if (image_file!=NULL && debug)
1.28      anton    1036:     fprintf(stderr, "Opened image file: %s\n", expfilename);
1.10      pazsan   1037:   return image_file;
1.1       anton    1038: }
                   1039: 
1.28      anton    1040: /* try to open image file concat(path[0:len],imagename) */
1.1       anton    1041: FILE *checkimage(char *path, int len, char *imagename)
1.10      pazsan   1042: {
                   1043:   int dirlen=len;
1.1       anton    1044:   char fullfilename[dirlen+strlen(imagename)+2];
1.10      pazsan   1045: 
1.1       anton    1046:   memcpy(fullfilename, path, dirlen);
1.71      pazsan   1047:   if (fullfilename[dirlen-1]!=DIRSEP)
                   1048:     fullfilename[dirlen++]=DIRSEP;
1.1       anton    1049:   strcpy(fullfilename+dirlen,imagename);
1.10      pazsan   1050:   return openimage(fullfilename);
1.1       anton    1051: }
                   1052: 
1.10      pazsan   1053: FILE * open_image_file(char * imagename, char * path)
1.1       anton    1054: {
1.10      pazsan   1055:   FILE * image_file=NULL;
1.28      anton    1056:   char *origpath=path;
1.10      pazsan   1057:   
1.71      pazsan   1058:   if(strchr(imagename, DIRSEP)==NULL) {
1.10      pazsan   1059:     /* first check the directory where the exe file is in !! 01may97jaw */
                   1060:     if (onlypath(progname))
1.72      anton    1061:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
1.10      pazsan   1062:     if (!image_file)
                   1063:       do {
                   1064:        char *pend=strchr(path, PATHSEP);
                   1065:        if (pend==NULL)
                   1066:          pend=path+strlen(path);
                   1067:        if (strlen(path)==0) break;
                   1068:        image_file=checkimage(path, pend-path, imagename);
                   1069:        path=pend+(*pend==PATHSEP);
                   1070:       } while (image_file==NULL);
                   1071:   } else {
                   1072:     image_file=openimage(imagename);
                   1073:   }
1.1       anton    1074: 
1.10      pazsan   1075:   if (!image_file) {
                   1076:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.28      anton    1077:            progname, imagename, origpath);
1.10      pazsan   1078:     exit(1);
1.7       anton    1079:   }
                   1080: 
1.10      pazsan   1081:   return image_file;
                   1082: }
1.11      pazsan   1083: #endif
                   1084: 
                   1085: #ifdef HAS_OS
                   1086: UCell convsize(char *s, UCell elemsize)
                   1087: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
                   1088:    of bytes.  the letter at the end indicates the unit, where e stands
                   1089:    for the element size. default is e */
                   1090: {
                   1091:   char *endp;
                   1092:   UCell n,m;
                   1093: 
                   1094:   m = elemsize;
                   1095:   n = strtoul(s,&endp,0);
                   1096:   if (endp!=NULL) {
                   1097:     if (strcmp(endp,"b")==0)
                   1098:       m=1;
                   1099:     else if (strcmp(endp,"k")==0)
                   1100:       m=1024;
                   1101:     else if (strcmp(endp,"M")==0)
                   1102:       m=1024*1024;
                   1103:     else if (strcmp(endp,"G")==0)
                   1104:       m=1024*1024*1024;
                   1105:     else if (strcmp(endp,"T")==0) {
                   1106: #if (SIZEOF_CHAR_P > 4)
1.24      anton    1107:       m=1024L*1024*1024*1024;
1.11      pazsan   1108: #else
                   1109:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
                   1110:       exit(1);
                   1111: #endif
                   1112:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                   1113:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
                   1114:       exit(1);
                   1115:     }
                   1116:   }
                   1117:   return n*m;
                   1118: }
1.10      pazsan   1119: 
                   1120: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
                   1121: {
                   1122:   int c;
                   1123: 
1.1       anton    1124:   opterr=0;
                   1125:   while (1) {
                   1126:     int option_index=0;
                   1127:     static struct option opts[] = {
1.29      anton    1128:       {"appl-image", required_argument, NULL, 'a'},
1.1       anton    1129:       {"image-file", required_argument, NULL, 'i'},
                   1130:       {"dictionary-size", required_argument, NULL, 'm'},
                   1131:       {"data-stack-size", required_argument, NULL, 'd'},
                   1132:       {"return-stack-size", required_argument, NULL, 'r'},
                   1133:       {"fp-stack-size", required_argument, NULL, 'f'},
                   1134:       {"locals-stack-size", required_argument, NULL, 'l'},
                   1135:       {"path", required_argument, NULL, 'p'},
                   1136:       {"version", no_argument, NULL, 'v'},
                   1137:       {"help", no_argument, NULL, 'h'},
                   1138:       /* put something != 0 into offset_image */
                   1139:       {"offset-image", no_argument, &offset_image, 1},
                   1140:       {"no-offset-im", no_argument, &offset_image, 0},
                   1141:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
1.4       anton    1142:       {"die-on-signal", no_argument, &die_on_signal, 1},
1.1       anton    1143:       {"debug", no_argument, &debug, 1},
1.60      anton    1144:       {"no-super", no_argument, &no_super, 1},
                   1145:       {"no-dynamic", no_argument, &no_dynamic, 1},
1.66      anton    1146:       {"dynamic", no_argument, &no_dynamic, 0},
1.1       anton    1147:       {0,0,0,0}
                   1148:       /* no-init-file, no-rc? */
                   1149:     };
                   1150:     
1.36      pazsan   1151:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1.1       anton    1152:     
                   1153:     switch (c) {
1.29      anton    1154:     case EOF: return;
                   1155:     case '?': optind--; return;
                   1156:     case 'a': *imagename = optarg; return;
1.10      pazsan   1157:     case 'i': *imagename = optarg; break;
1.1       anton    1158:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                   1159:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                   1160:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                   1161:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                   1162:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.10      pazsan   1163:     case 'p': *path = optarg; break;
1.36      pazsan   1164:     case 'o': offset_image = 1; break;
                   1165:     case 'n': offset_image = 0; break;
                   1166:     case 'c': clear_dictionary = 1; break;
                   1167:     case 's': die_on_signal = 1; break;
                   1168:     case 'x': debug = 1; break;
1.83    ! anton    1169:     case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
1.1       anton    1170:     case 'h': 
1.29      anton    1171:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1.1       anton    1172: Engine Options:\n\
1.29      anton    1173:   --appl-image FILE                equivalent to '--image-file=FILE --'\n\
1.10      pazsan   1174:   --clear-dictionary               Initialize the dictionary with 0 bytes\n\
                   1175:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
                   1176:   --debug                          Print debugging information during startup\n\
                   1177:   --die-on-signal                  exit instead of CATCHing some signals\n\
1.66      anton    1178:   --dynamic                        use dynamic native code\n\
1.10      pazsan   1179:   -f SIZE, --fp-stack-size=SIZE            Specify floating point stack size\n\
                   1180:   -h, --help                       Print this message and exit\n\
                   1181:   -i FILE, --image-file=FILE       Use image FILE instead of `gforth.fi'\n\
                   1182:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
                   1183:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
1.60      anton    1184:   --no-dynamic                     Use only statically compiled primitives\n\
1.10      pazsan   1185:   --no-offset-im                   Load image at normal position\n\
1.60      anton    1186:   --no-super                        No dynamically formed superinstructions\n\
1.10      pazsan   1187:   --offset-image                   Load image at a different position\n\
                   1188:   -p PATH, --path=PATH             Search path for finding image and sources\n\
                   1189:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
1.66      anton    1190:   -v, --version                            Print engine version and exit\n\
1.1       anton    1191: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1.10      pazsan   1192:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
                   1193:              argv[0]);
                   1194:       optind--;
                   1195:       return;
1.1       anton    1196:     }
                   1197:   }
1.10      pazsan   1198: }
1.11      pazsan   1199: #endif
1.10      pazsan   1200: 
                   1201: #ifdef INCLUDE_IMAGE
                   1202: extern Cell image[];
                   1203: extern const char reloc_bits[];
                   1204: #endif
                   1205: 
1.67      pazsan   1206: DCell double2ll(Float r)
                   1207: {
                   1208: #ifndef BUGGY_LONG_LONG
                   1209:   return (DCell)(r);
                   1210: #else
                   1211:   DCell d;
                   1212:   d.hi = ldexp(r,-(int)(CELL_BITS)) - (r<0);
                   1213:   d.lo = r-ldexp((Float)d.hi,CELL_BITS);
                   1214:   return d;
                   1215: #endif
                   1216: }
                   1217: 
1.10      pazsan   1218: int main(int argc, char **argv, char **env)
                   1219: {
1.30      pazsan   1220: #ifdef HAS_OS
1.10      pazsan   1221:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1.30      pazsan   1222: #else
                   1223:   char *path = DEFAULTPATH;
                   1224: #endif
1.13      pazsan   1225: #ifndef INCLUDE_IMAGE
1.10      pazsan   1226:   char *imagename="gforth.fi";
                   1227:   FILE *image_file;
                   1228:   Address image;
                   1229: #endif
                   1230:   int retvalue;
                   1231:          
1.56      anton    1232: #if defined(i386) && defined(ALIGNMENT_CHECK)
1.10      pazsan   1233:   /* turn on alignment checks on the 486.
                   1234:    * on the 386 this should have no effect. */
                   1235:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
                   1236:   /* this is unusable with Linux' libc.4.6.27, because this library is
                   1237:      not alignment-clean; we would have to replace some library
                   1238:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
                   1239:      the stack FP-aligned. */
                   1240: #endif
                   1241: 
                   1242:   /* buffering of the user output device */
1.11      pazsan   1243: #ifdef _IONBF
1.10      pazsan   1244:   if (isatty(fileno(stdout))) {
                   1245:     fflush(stdout);
                   1246:     setvbuf(stdout,NULL,_IONBF,0);
1.1       anton    1247:   }
1.11      pazsan   1248: #endif
1.1       anton    1249: 
1.10      pazsan   1250:   progname = argv[0];
                   1251: 
1.11      pazsan   1252: #ifdef HAS_OS
1.10      pazsan   1253:   gforth_args(argc, argv, &path, &imagename);
1.11      pazsan   1254: #endif
1.10      pazsan   1255: 
                   1256: #ifdef INCLUDE_IMAGE
                   1257:   set_stack_sizes((ImageHeader *)image);
1.22      pazsan   1258:   if(((ImageHeader *)image)->base != image)
                   1259:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
                   1260:             (Label*)engine(0, 0, 0, 0, 0));
1.10      pazsan   1261:   alloc_stacks((ImageHeader *)image);
                   1262: #else
                   1263:   image_file = open_image_file(imagename, path);
                   1264:   image = loader(image_file, imagename);
                   1265: #endif
1.24      anton    1266:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1.1       anton    1267: 
                   1268:   {
1.10      pazsan   1269:     char path2[strlen(path)+1];
1.1       anton    1270:     char *p1, *p2;
                   1271:     Cell environ[]= {
                   1272:       (Cell)argc-(optind-1),
                   1273:       (Cell)(argv+(optind-1)),
1.10      pazsan   1274:       (Cell)strlen(path),
1.1       anton    1275:       (Cell)path2};
                   1276:     argv[optind-1] = progname;
                   1277:     /*
                   1278:        for (i=0; i<environ[0]; i++)
                   1279:        printf("%s\n", ((char **)(environ[1]))[i]);
                   1280:        */
                   1281:     /* make path OS-independent by replacing path separators with NUL */
1.10      pazsan   1282:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1.1       anton    1283:       if (*p1==PATHSEP)
                   1284:        *p2 = '\0';
                   1285:       else
                   1286:        *p2 = *p1;
                   1287:     *p2='\0';
1.10      pazsan   1288:     retvalue = go_forth(image, 4, environ);
1.42      anton    1289: #ifdef VM_PROFILING
                   1290:     vm_print_profile(stderr);
                   1291: #endif
1.1       anton    1292:     deprep_terminal();
                   1293:   }
1.13      pazsan   1294:   return retvalue;
1.1       anton    1295: }

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