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

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

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