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

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

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