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

1.1       anton       1: /* command line interpretation, image loading etc. for Gforth
                      2: 
                      3: 
1.103     anton       4:   Copyright (C) 1995,1996,1997,1998,2000,2003 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.110     anton     134: static int print_metrics=0; /* if true, print metrics on exit */
1.109     anton     135: static int static_super_number = 10000000; /* number of ss used if available */
1.110     anton     136: static int ss_greedy = 0; /* if true: use greedy, not optimal ss selection */
1.60      anton     137: 
1.30      pazsan    138: #ifdef HAS_DEBUG
1.68      anton     139: int debug=0;
1.31      pazsan    140: #else
                    141: # define perror(x...)
                    142: # define fprintf(x...)
1.30      pazsan    143: #endif
1.31      pazsan    144: 
1.24      anton     145: ImageHeader *gforth_header;
1.43      anton     146: Label *vm_prims;
1.53      anton     147: #ifdef DOUBLY_INDIRECT
                    148: Label *xts; /* same content as vm_prims, but should only be used for xts */
                    149: #endif
1.1       anton     150: 
1.30      pazsan    151: #ifdef MEMCMP_AS_SUBROUTINE
                    152: int gforth_memcmp(const char * s1, const char * s2, size_t n)
                    153: {
                    154:   return memcmp(s1, s2, n);
                    155: }
                    156: #endif
                    157: 
1.1       anton     158: /* image file format:
1.15      pazsan    159:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
1.1       anton     160:  *   padding to a multiple of 8
1.84      anton     161:  *   magic: "Gforth3x" means format 0.6,
1.15      pazsan    162:  *              where x is a byte with
                    163:  *              bit 7:   reserved = 0
                    164:  *              bit 6:5: address unit size 2^n octets
                    165:  *              bit 4:3: character size 2^n octets
                    166:  *              bit 2:1: cell size 2^n octets
                    167:  *              bit 0:   endian, big=0, little=1.
                    168:  *  The magic are always 8 octets, no matter what the native AU/character size is
1.1       anton     169:  *  padding to max alignment (no padding necessary on current machines)
1.24      anton     170:  *  ImageHeader structure (see forth.h)
1.1       anton     171:  *  data (size in ImageHeader.image_size)
                    172:  *  tags ((if relocatable, 1 bit/data cell)
                    173:  *
                    174:  * tag==1 means that the corresponding word is an address;
                    175:  * If the word is >=0, the address is within the image;
                    176:  * addresses within the image are given relative to the start of the image.
                    177:  * If the word =-1 (CF_NIL), the address is NIL,
                    178:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
                    179:  * If the word =CF(DODOES), it's a DOES> CFA
                    180:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
                    181:  *                                     possibly containing a jump to dodoes)
1.51      anton     182:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
                    183:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
                    184:  *                                        it's the threaded code of a primitive
1.85      pazsan    185:  * bits 13..9 of a primitive token state which group the primitive belongs to,
                    186:  * bits 8..0 of a primitive token index into the group
1.1       anton     187:  */
                    188: 
1.85      pazsan    189: static Cell groups[32] = {
                    190:   0,
1.90      anton     191: #undef GROUP
1.85      pazsan    192: #define GROUP(x, n) DOESJUMP+1+n,
1.86      anton     193: #include "prim_grp.i"
1.90      anton     194: #undef GROUP
1.85      pazsan    195: #define GROUP(x, n)
                    196: };
                    197: 
1.46      jwilke    198: void relocate(Cell *image, const char *bitstring, 
1.90      anton     199:               int size, Cell base, Label symbols[])
1.1       anton     200: {
1.16      pazsan    201:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
1.11      pazsan    202:   Cell token;
1.1       anton     203:   char bits;
1.37      anton     204:   Cell max_symbols;
1.46      jwilke    205:   /* 
1.85      pazsan    206:    * A virtual start address that's the real start address minus 
1.46      jwilke    207:    * the one in the image 
                    208:    */
1.45      jwilke    209:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
1.1       anton     210: 
1.85      pazsan    211:   /* group index into table */
1.46      jwilke    212:   
                    213: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
1.37      anton     214:   
                    215:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
                    216:     ;
1.47      anton     217:   max_symbols--;
1.35      pazsan    218:   size/=sizeof(Cell);
                    219: 
1.31      pazsan    220:   for(k=0; k<=steps; k++) {
1.13      pazsan    221:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
1.1       anton     222:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
1.35      pazsan    223:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
                    224:        /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
1.45      jwilke    225:         token=image[i];
1.85      pazsan    226:        if(token<0) {
                    227:          int group = (-token & 0x3E00) >> 9;
                    228:          if(group == 0) {
                    229:            switch(token|0x4000) {
1.1       anton     230:            case CF_NIL      : image[i]=0; break;
                    231: #if !defined(DOUBLY_INDIRECT)
                    232:            case CF(DOCOL)   :
                    233:            case CF(DOVAR)   :
                    234:            case CF(DOCON)   :
                    235:            case CF(DOUSER)  : 
                    236:            case CF(DODEFER) : 
1.11      pazsan    237:            case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
1.92      anton     238:            case CF(DOESJUMP): image[i]=0; break;
1.1       anton     239: #endif /* !defined(DOUBLY_INDIRECT) */
                    240:            case CF(DODOES)  :
1.45      jwilke    241:              MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
1.1       anton     242:              break;
1.85      pazsan    243:            default          : /* backward compatibility */
1.56      anton     244: /*           printf("Code field generation image[%x]:=CFA(%x)\n",
1.1       anton     245:                     i, CF(image[i])); */
1.55      anton     246:              if (CF((token | 0x4000))<max_symbols) {
1.56      anton     247:                image[i]=(Cell)CFA(CF(token));
                    248: #ifdef DIRECT_THREADED
                    249:                if ((token & 0x4000) == 0) /* threade code, no CFA */
1.70      anton     250:                  compile_prim1(&image[i]);
1.56      anton     251: #endif
1.55      anton     252:              } else
1.98      anton     253:                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     254:            }
1.85      pazsan    255:          } else {
                    256:            int tok = -token & 0x1FF;
                    257:            if (tok < (groups[group+1]-groups[group])) {
                    258: #if defined(DOUBLY_INDIRECT)
                    259:              image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
                    260: #else
                    261:              image[i]=(Cell)CFA((groups[group]+tok));
                    262: #endif
                    263: #ifdef DIRECT_THREADED
                    264:              if ((token & 0x4000) == 0) /* threade code, no CFA */
                    265:                compile_prim1(&image[i]);
                    266: #endif
                    267:            } else
1.98      anton     268:              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    269:          }
                    270:        } else {
1.101     anton     271:           /* if base is > 0: 0 is a null reference so don't adjust*/
1.45      jwilke    272:           if (token>=base) {
                    273:             image[i]+=(Cell)start;
                    274:           }
1.46      jwilke    275:         }
1.1       anton     276:       }
                    277:     }
1.31      pazsan    278:   }
1.70      anton     279:   finish_code();
1.26      jwilke    280:   ((ImageHeader*)(image))->base = (Address) image;
1.1       anton     281: }
                    282: 
                    283: UCell checksum(Label symbols[])
                    284: {
                    285:   UCell r=PRIM_VERSION;
                    286:   Cell i;
                    287: 
                    288:   for (i=DOCOL; i<=DOESJUMP; i++) {
                    289:     r ^= (UCell)(symbols[i]);
                    290:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    291:   }
                    292: #ifdef DIRECT_THREADED
                    293:   /* we have to consider all the primitives */
                    294:   for (; symbols[i]!=(Label)0; i++) {
                    295:     r ^= (UCell)(symbols[i]);
                    296:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
                    297:   }
                    298: #else
                    299:   /* in indirect threaded code all primitives are accessed through the
                    300:      symbols table, so we just have to put the base address of symbols
                    301:      in the checksum */
                    302:   r ^= (UCell)symbols;
                    303: #endif
                    304:   return r;
                    305: }
                    306: 
1.3       anton     307: Address verbose_malloc(Cell size)
                    308: {
                    309:   Address r;
                    310:   /* leave a little room (64B) for stack underflows */
                    311:   if ((r = malloc(size+64))==NULL) {
                    312:     perror(progname);
                    313:     exit(1);
                    314:   }
                    315:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
                    316:   if (debug)
                    317:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
                    318:   return r;
                    319: }
                    320: 
1.33      anton     321: static Address next_address=0;
                    322: void after_alloc(Address r, Cell size)
                    323: {
                    324:   if (r != (Address)-1) {
                    325:     if (debug)
                    326:       fprintf(stderr, "success, address=$%lx\n", (long) r);
                    327:     if (pagesize != 1)
                    328:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
                    329:   } else {
                    330:     if (debug)
                    331:       fprintf(stderr, "failed: %s\n", strerror(errno));
                    332:   }
                    333: }
                    334: 
1.34      anton     335: #ifndef MAP_FAILED
                    336: #define MAP_FAILED ((Address) -1)
                    337: #endif
                    338: #ifndef MAP_FILE
                    339: # define MAP_FILE 0
                    340: #endif
                    341: #ifndef MAP_PRIVATE
                    342: # define MAP_PRIVATE 0
                    343: #endif
1.91      anton     344: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
                    345: # define MAP_ANON MAP_ANONYMOUS
                    346: #endif
1.34      anton     347: 
                    348: #if defined(HAVE_MMAP)
                    349: static Address alloc_mmap(Cell size)
1.1       anton     350: {
                    351:   Address r;
                    352: 
                    353: #if defined(MAP_ANON)
                    354:   if (debug)
                    355:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
1.34      anton     356:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
1.1       anton     357: #else /* !defined(MAP_ANON) */
1.17      anton     358:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
                    359:      apparently defaults) */
1.1       anton     360:   static int dev_zero=-1;
                    361: 
                    362:   if (dev_zero == -1)
                    363:     dev_zero = open("/dev/zero", O_RDONLY);
                    364:   if (dev_zero == -1) {
1.34      anton     365:     r = MAP_FAILED;
1.1       anton     366:     if (debug)
                    367:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
                    368:              strerror(errno));
                    369:   } else {
                    370:     if (debug)
                    371:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
                    372:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
                    373:   }
                    374: #endif /* !defined(MAP_ANON) */
1.34      anton     375:   after_alloc(r, size);
                    376:   return r;  
                    377: }
                    378: #endif
                    379: 
                    380: Address my_alloc(Cell size)
                    381: {
                    382: #if HAVE_MMAP
                    383:   Address r;
                    384: 
                    385:   r=alloc_mmap(size);
                    386:   if (r!=MAP_FAILED)
1.1       anton     387:     return r;
                    388: #endif /* HAVE_MMAP */
1.3       anton     389:   /* use malloc as fallback */
                    390:   return verbose_malloc(size);
1.1       anton     391: }
                    392: 
1.34      anton     393: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
1.33      anton     394: {
1.34      anton     395:   Address image = MAP_FAILED;
1.33      anton     396: 
1.56      anton     397: #if defined(HAVE_MMAP)
1.33      anton     398:   if (offset==0) {
1.34      anton     399:     image=alloc_mmap(dictsize);
1.33      anton     400:     if (debug)
1.34      anton     401:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
                    402:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
                    403:     after_alloc(image,dictsize);
1.33      anton     404:   }
1.56      anton     405: #endif /* defined(HAVE_MMAP) */
1.34      anton     406:   if (image == MAP_FAILED) {
1.56      anton     407:     image = my_alloc(dictsize+offset)+offset;
1.33      anton     408:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
1.34      anton     409:     fread(image, 1, imagesize, file);
1.33      anton     410:   }
                    411:   return image;
                    412: }
                    413: 
1.10      pazsan    414: void set_stack_sizes(ImageHeader * header)
                    415: {
                    416:   if (dictsize==0)
                    417:     dictsize = header->dict_size;
                    418:   if (dsize==0)
                    419:     dsize = header->data_stack_size;
                    420:   if (rsize==0)
                    421:     rsize = header->return_stack_size;
                    422:   if (fsize==0)
                    423:     fsize = header->fp_stack_size;
                    424:   if (lsize==0)
                    425:     lsize = header->locals_stack_size;
                    426:   dictsize=maxaligned(dictsize);
                    427:   dsize=maxaligned(dsize);
                    428:   rsize=maxaligned(rsize);
                    429:   lsize=maxaligned(lsize);
                    430:   fsize=maxaligned(fsize);
                    431: }
                    432: 
                    433: void alloc_stacks(ImageHeader * header)
                    434: {
                    435:   header->dict_size=dictsize;
                    436:   header->data_stack_size=dsize;
                    437:   header->fp_stack_size=fsize;
                    438:   header->return_stack_size=rsize;
                    439:   header->locals_stack_size=lsize;
                    440: 
                    441:   header->data_stack_base=my_alloc(dsize);
                    442:   header->fp_stack_base=my_alloc(fsize);
                    443:   header->return_stack_base=my_alloc(rsize);
                    444:   header->locals_stack_base=my_alloc(lsize);
                    445: }
                    446: 
1.44      pazsan    447: #warning You can ignore the warnings about clobbered variables in go_forth
1.11      pazsan    448: int go_forth(Address image, int stack, Cell *entries)
                    449: {
1.38      anton     450:   volatile ImageHeader *image_header = (ImageHeader *)image;
1.18      anton     451:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
1.44      pazsan    452:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
1.18      anton     453:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
1.44      pazsan    454: #ifdef GFORTH_DEBUGGING
1.38      anton     455:   volatile Cell *orig_rp0=rp0;
1.44      pazsan    456: #endif
1.18      anton     457:   Address lp0=image_header->locals_stack_base + lsize;
                    458:   Xt *ip0=(Xt *)(image_header->boot_entry);
1.13      pazsan    459: #ifdef SYSSIGNALS
1.11      pazsan    460:   int throw_code;
1.13      pazsan    461: #endif
1.11      pazsan    462: 
                    463:   /* ensure that the cached elements (if any) are accessible */
1.41      anton     464:   IF_spTOS(sp0--);
                    465:   IF_fpTOS(fp0--);
1.11      pazsan    466:   
                    467:   for(;stack>0;stack--)
1.18      anton     468:     *--sp0=entries[stack-1];
1.11      pazsan    469: 
1.30      pazsan    470: #ifdef SYSSIGNALS
1.11      pazsan    471:   get_winsize();
                    472:    
                    473:   install_signal_handlers(); /* right place? */
                    474:   
                    475:   if ((throw_code=setjmp(throw_jmp_buf))) {
                    476:     static Cell signal_data_stack[8];
                    477:     static Cell signal_return_stack[8];
                    478:     static Float signal_fp_stack[1];
1.13      pazsan    479: 
1.11      pazsan    480:     signal_data_stack[7]=throw_code;
1.18      anton     481: 
                    482: #ifdef GFORTH_DEBUGGING
1.97      anton     483:     if (debug)
                    484:       fprintf(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
                    485:              throw_code, saved_ip, rp);
1.38      anton     486:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
1.18      anton     487:       /* no rstack overflow or underflow */
                    488:       rp0 = rp;
1.63      anton     489:       *--rp0 = (Cell)saved_ip;
1.18      anton     490:     }
                    491:     else /* I love non-syntactic ifdefs :-) */
1.97      anton     492:       rp0 = signal_return_stack+8;
                    493: #else  /* !defined(GFORTH_DEBUGGING) */
                    494:     if (debug)
                    495:       fprintf(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
                    496:       rp0 = signal_return_stack+8;
                    497: #endif /* !defined(GFORTH_DEBUGGING) */
1.25      anton     498:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
1.11      pazsan    499:     
1.33      anton     500:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
1.18      anton     501:                       rp0, signal_fp_stack, 0));
1.11      pazsan    502:   }
1.13      pazsan    503: #endif
1.11      pazsan    504: 
1.33      anton     505:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
1.11      pazsan    506: }
                    507: 
1.30      pazsan    508: #ifndef INCLUDE_IMAGE
1.21      anton     509: void print_sizes(Cell sizebyte)
                    510:      /* print size information */
                    511: {
                    512:   static char* endianstring[]= { "   big","little" };
                    513:   
                    514:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
                    515:          endianstring[sizebyte & 1],
                    516:          1 << ((sizebyte >> 1) & 3),
                    517:          1 << ((sizebyte >> 3) & 3),
                    518:          1 << ((sizebyte >> 5) & 3));
                    519: }
                    520: 
1.106     anton     521: /* static superinstruction stuff */
                    522: 
                    523: struct cost {
                    524:   char loads;       /* number of stack loads */
                    525:   char stores;      /* number of stack stores */
                    526:   char updates;     /* number of stack pointer updates */
                    527:   short offset;      /* offset into super2 table */
                    528:   char length;      /* number of components */
                    529: };
                    530: 
                    531: short super2[] = {
                    532: #include "super2.i"
                    533: };
                    534: 
                    535: struct cost super_costs[] = {
                    536: #include "costs.i"
                    537: };
                    538: 
                    539: #define HASH_SIZE 256
                    540: 
                    541: struct super_table_entry {
                    542:   struct super_table_entry *next;
                    543:   short *start;
                    544:   short length;
                    545:   short super;
                    546: } *super_table[HASH_SIZE];
                    547: int max_super=2;
                    548: 
                    549: int hash_super(short *start, int length)
                    550: {
                    551:   int i, r;
                    552:   
                    553:   for (i=0, r=0; i<length; i++) {
                    554:     r <<= 1;
                    555:     r += start[i];
                    556:   }
                    557:   return r & (HASH_SIZE-1);
                    558: }
                    559: 
                    560: int lookup_super(short *start, int length)
                    561: {
                    562:   int hash=hash_super(start,length);
                    563:   struct super_table_entry *p = super_table[hash];
                    564: 
                    565:   assert(length >= 2);
                    566:   for (; p!=NULL; p = p->next) {
                    567:     if (length == p->length &&
                    568:        memcmp((char *)p->start, (char *)start, length*sizeof(short))==0)
                    569:       return p->super;
                    570:   }
                    571:   return -1;
                    572: }
                    573: 
                    574: void prepare_super_table()
                    575: {
                    576:   int i;
1.109     anton     577:   int nsupers = 0;
1.106     anton     578: 
                    579:   for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
                    580:     struct cost *c = &super_costs[i];
1.109     anton     581:     if (c->length > 1 && nsupers < static_super_number) {
1.106     anton     582:       int hash = hash_super(super2+c->offset, c->length);
                    583:       struct super_table_entry **p = &super_table[hash];
                    584:       struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
                    585:       e->next = *p;
                    586:       e->start = super2 + c->offset;
                    587:       e->length = c->length;
                    588:       e->super = i;
                    589:       *p = e;
                    590:       if (c->length > max_super)
                    591:        max_super = c->length;
1.109     anton     592:       nsupers++;
1.106     anton     593:     }
                    594:   }
1.109     anton     595:   if (debug)
                    596:     fprintf(stderr, "Using %d static superinsts\n", nsupers);
1.106     anton     597: }
                    598: 
                    599: /* dynamic replication/superinstruction stuff */
                    600: 
1.70      anton     601: #define MAX_IMMARGS 2
                    602: 
1.69      anton     603: #ifndef NO_DYNAMIC
1.47      anton     604: typedef struct {
                    605:   Label start;
1.74      anton     606:   Cell length; /* only includes the jump iff superend is true*/
                    607:   Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
1.70      anton     608:   char superend; /* true if primitive ends superinstruction, i.e.,
1.47      anton     609:                      unconditional branch, execute, etc. */
1.70      anton     610:   Cell nimmargs;
                    611:   struct immarg {
                    612:     Cell offset; /* offset of immarg within prim */
                    613:     char rel;    /* true if immarg is relative */
                    614:   } immargs[MAX_IMMARGS];
1.47      anton     615: } PrimInfo;
                    616: 
                    617: PrimInfo *priminfos;
1.76      anton     618: PrimInfo **decomp_prims;
                    619: 
1.90      anton     620: int compare_priminfo_length(const void *_a, const void *_b)
1.76      anton     621: {
1.90      anton     622:   PrimInfo **a = (PrimInfo **)_a;
                    623:   PrimInfo **b = (PrimInfo **)_b;
1.77      anton     624:   Cell diff = (*a)->length - (*b)->length;
                    625:   if (diff)
                    626:     return diff;
                    627:   else /* break ties by start address; thus the decompiler produces
                    628:           the earliest primitive with the same code (e.g. noop instead
                    629:           of (char) and @ instead of >code-address */
                    630:     return (*b)->start - (*a)->start;
1.76      anton     631: }
1.112     anton     632: #endif /* !defined(NO_DYNAMIC) */
1.76      anton     633: 
1.106     anton     634: static char superend[]={
                    635: #include "prim_superend.i"
                    636: };
1.107     anton     637: 
                    638: Cell npriminfos=0;
1.76      anton     639: 
1.113   ! anton     640: int compare_li(const void *pa, const void *pb)
        !           641: {
        !           642: 
        !           643:   int a = *(int *)pa;
        !           644:   int b = *(int *)pb;
        !           645:   Cell r = vm_prims[a]-vm_prims[b];
        !           646:   if (r == 0)
        !           647:     return b - a; /* K labels should be sorted before I labels
        !           648:                     for the same address */
        !           649:   return r;
        !           650: }
        !           651: 
1.47      anton     652: void check_prims(Label symbols1[])
                    653: {
                    654:   int i;
1.90      anton     655: #ifndef NO_DYNAMIC
1.113   ! anton     656:   Label *symbols2, *symbols3, *ends1, *ends1k;
        !           657:   int *labelindexes, *sortindexes, nlabelindexes;
1.90      anton     658: #endif
1.47      anton     659: 
1.66      anton     660:   if (debug)
                    661: #ifdef __VERSION__
                    662:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
                    663: #else
                    664: #define xstr(s) str(s)
                    665: #define str(s) #s
                    666:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
                    667: #endif
1.47      anton     668:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
                    669:     ;
1.55      anton     670:   npriminfos = i;
1.70      anton     671:   
                    672: #ifndef NO_DYNAMIC
1.66      anton     673:   if (no_dynamic)
                    674:     return;
1.55      anton     675:   symbols2=engine2(0,0,0,0,0);
1.70      anton     676: #if NO_IP
                    677:   symbols3=engine3(0,0,0,0,0);
                    678: #else
                    679:   symbols3=symbols1;
                    680: #endif
                    681:   ends1 = symbols1+i+1-DOESJUMP;
1.113   ! anton     682:   ends1k =   ends1+i+1-DOESJUMP;
        !           683: 
        !           684:   /* produce a sortindexes: sortindexes[i] gives the rank of symbols1[i] */
        !           685:   nlabelindexes = 3*(i+1-DOESJUMP)+DOESJUMP;
        !           686:   labelindexes = (int *)alloca(nlabelindexes*sizeof(int));
        !           687:   for (i=0; i<nlabelindexes; i++)
        !           688:     labelindexes[i] = i;
        !           689:   qsort(labelindexes, nlabelindexes, sizeof(int), compare_li);
        !           690:   sortindexes = (int *)alloca(nlabelindexes*sizeof(int));
        !           691:   for (i=0; i<nlabelindexes; i++)
        !           692:     sortindexes[labelindexes[i]] = i;
        !           693:   
1.47      anton     694:   priminfos = calloc(i,sizeof(PrimInfo));
                    695:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
1.70      anton     696:     int prim_len = ends1[i]-symbols1[i];
1.47      anton     697:     PrimInfo *pi=&priminfos[i];
1.70      anton     698:     int j=0;
                    699:     char *s1 = (char *)symbols1[i];
                    700:     char *s2 = (char *)symbols2[i];
                    701:     char *s3 = (char *)symbols3[i];
1.113   ! anton     702:     int endindex = labelindexes[sortindexes[i]+2];
        !           703:     Label endlabel = symbols1[endindex];
1.70      anton     704: 
                    705:     pi->start = s1;
                    706:     pi->superend = superend[i-DOESJUMP-1]|no_super;
                    707:     if (pi->superend)
1.113   ! anton     708:       pi->length = endlabel-symbols1[i];
1.70      anton     709:     else
                    710:       pi->length = prim_len;
1.113   ! anton     711:     pi->restlength = endlabel - symbols1[i] - pi->length;
1.70      anton     712:     pi->nimmargs = 0;
                    713:     if (debug)
1.98      anton     714:       fprintf(stderr, "Prim %3d @ %p %p %p, length=%3ld restlength=%2ld superend=%1d",
                    715:              i, s1, s2, s3, (long)(pi->length), (long)(pi->restlength), pi->superend);
1.113   ! anton     716:     if (sortindexes[i]+1 != sortindexes[i+npriminfos+1-DOESJUMP]) {
        !           717:       pi->start = NULL; /* not relocatable */
        !           718:       if (debug)
        !           719:        fprintf(stderr,"\n   non_reloc: rank[start] = %d, rank[J] = %d\n",
        !           720:                sortindexes[i], sortindexes[i+npriminfos+1-DOESJUMP]);
        !           721:       continue;
        !           722:     }
        !           723:     if (endindex < (ends1k - symbols1)) { /* is endindex not a K-label? */
        !           724:       pi->start = NULL; /* not relocatable */
        !           725:       if (debug)
        !           726:        fprintf(stderr,"\n   non_reloc: endindex = %d\n", endindex);
        !           727:       continue;
        !           728:     }
1.70      anton     729:     assert(prim_len>=0);
1.113   ! anton     730:     assert(pi->restlength >=0);
1.74      anton     731:     while (j<(pi->length+pi->restlength)) {
1.70      anton     732:       if (s1[j]==s3[j]) {
                    733:        if (s1[j] != s2[j]) {
                    734:          pi->start = NULL; /* not relocatable */
                    735:          if (debug)
                    736:            fprintf(stderr,"\n   non_reloc: engine1!=engine2 offset %3d",j);
1.74      anton     737:          /* assert(j<prim_len); */
1.70      anton     738:          break;
                    739:        }
                    740:        j++;
                    741:       } else {
                    742:        struct immarg *ia=&pi->immargs[pi->nimmargs];
                    743: 
                    744:        pi->nimmargs++;
                    745:        ia->offset=j;
                    746:        if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
                    747:          ia->rel=0;
                    748:          if (debug)
                    749:            fprintf(stderr,"\n   absolute immarg: offset %3d",j);
                    750:        } else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
                    751:                   symbols1[DOESJUMP+1]) {
                    752:          ia->rel=1;
                    753:          if (debug)
                    754:            fprintf(stderr,"\n   relative immarg: offset %3d",j);
                    755:        } else {
                    756:          pi->start = NULL; /* not relocatable */
                    757:          if (debug)
                    758:            fprintf(stderr,"\n   non_reloc: engine1!=engine3 offset %3d",j);
1.74      anton     759:          /* assert(j<prim_len);*/
1.70      anton     760:          break;
                    761:        }
                    762:        j+=4;
1.47      anton     763:       }
                    764:     }
1.70      anton     765:     if (debug)
                    766:       fprintf(stderr,"\n");
                    767:   }
1.76      anton     768:   decomp_prims = calloc(i,sizeof(PrimInfo *));
                    769:   for (i=DOESJUMP+1; i<npriminfos; i++)
                    770:     decomp_prims[i] = &(priminfos[i]);
                    771:   qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
                    772:        compare_priminfo_length);
1.70      anton     773: #endif
                    774: }
                    775: 
1.74      anton     776: void flush_to_here(void)
                    777: {
1.93      anton     778: #ifndef NO_DYNAMIC
1.100     anton     779:   if (start_flush)
                    780:     FLUSH_ICACHE(start_flush, code_here-start_flush);
1.74      anton     781:   start_flush=code_here;
1.93      anton     782: #endif
1.74      anton     783: }
                    784: 
1.93      anton     785: #ifndef NO_DYNAMIC
1.74      anton     786: void append_jump(void)
                    787: {
                    788:   if (last_jump) {
                    789:     PrimInfo *pi = &priminfos[last_jump];
                    790:     
                    791:     memcpy(code_here, pi->start+pi->length, pi->restlength);
                    792:     code_here += pi->restlength;
                    793:     last_jump=0;
                    794:   }
                    795: }
                    796: 
1.75      anton     797: /* Gforth remembers all code blocks in this list.  On forgetting (by
                    798: executing a marker) the code blocks are not freed (because Gforth does
                    799: not remember how they were allocated; hmm, remembering that might be
                    800: easier and cleaner).  Instead, code_here etc. are reset to the old
                    801: value, and the "forgotten" code blocks are reused when they are
                    802: needed. */
                    803: 
                    804: struct code_block_list {
                    805:   struct code_block_list *next;
                    806:   Address block;
                    807:   Cell size;
                    808: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
                    809: 
1.74      anton     810: Address append_prim(Cell p)
                    811: {
                    812:   PrimInfo *pi = &priminfos[p];
                    813:   Address old_code_here = code_here;
                    814: 
                    815:   if (code_area+code_area_size < code_here+pi->length+pi->restlength) {
1.75      anton     816:     struct code_block_list *p;
1.74      anton     817:     append_jump();
1.93      anton     818:     flush_to_here();
1.75      anton     819:     if (*next_code_blockp == NULL) {
                    820:       code_here = start_flush = code_area = my_alloc(code_area_size);
                    821:       p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
                    822:       *next_code_blockp = p;
                    823:       p->next = NULL;
                    824:       p->block = code_here;
                    825:       p->size = code_area_size;
                    826:     } else {
                    827:       p = *next_code_blockp;
                    828:       code_here = start_flush = code_area = p->block;
                    829:     }
1.74      anton     830:     old_code_here = code_here;
1.75      anton     831:     next_code_blockp = &(p->next);
1.74      anton     832:   }
                    833:   memcpy(code_here, pi->start, pi->length);
                    834:   code_here += pi->length;
                    835:   return old_code_here;
                    836: }
                    837: #endif
1.75      anton     838: 
                    839: int forget_dyncode(Address code)
                    840: {
                    841: #ifdef NO_DYNAMIC
                    842:   return -1;
                    843: #else
                    844:   struct code_block_list *p, **pp;
                    845: 
                    846:   for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
                    847:     if (code >= p->block && code < p->block+p->size) {
                    848:       next_code_blockp = &(p->next);
                    849:       code_here = start_flush = code;
                    850:       code_area = p->block;
                    851:       last_jump = 0;
                    852:       return -1;
                    853:     }
                    854:   }
1.78      anton     855:   return -no_dynamic;
1.75      anton     856: #endif /* !defined(NO_DYNAMIC) */
                    857: }
                    858: 
1.104     anton     859: long dyncodesize(void)
                    860: {
                    861: #ifndef NO_DYNAMIC
1.106     anton     862:   struct code_block_list *p;
1.104     anton     863:   long size=0;
                    864:   for (p=code_block_list; p!=NULL; p=p->next) {
                    865:     if (code_here >= p->block && code_here < p->block+p->size)
                    866:       return size + (code_here - p->block);
                    867:     else
                    868:       size += p->size;
                    869:   }
                    870: #endif /* !defined(NO_DYNAMIC) */
                    871:   return 0;
                    872: }
                    873: 
1.90      anton     874: Label decompile_code(Label _code)
1.75      anton     875: {
1.76      anton     876: #ifdef NO_DYNAMIC
1.90      anton     877:   return _code;
1.76      anton     878: #else /* !defined(NO_DYNAMIC) */
                    879:   Cell i;
1.77      anton     880:   struct code_block_list *p;
1.90      anton     881:   Address code=_code;
1.76      anton     882: 
1.77      anton     883:   /* first, check if we are in code at all */
                    884:   for (p = code_block_list;; p = p->next) {
                    885:     if (p == NULL)
                    886:       return code;
                    887:     if (code >= p->block && code < p->block+p->size)
                    888:       break;
                    889:   }
1.76      anton     890:   /* reverse order because NOOP might match other prims */
                    891:   for (i=npriminfos-1; i>DOESJUMP; i--) {
                    892:     PrimInfo *pi=decomp_prims[i];
                    893:     if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
                    894:       return pi->start;
                    895:   }
                    896:   return code;
                    897: #endif /* !defined(NO_DYNAMIC) */
1.75      anton     898: }
1.74      anton     899: 
1.70      anton     900: #ifdef NO_IP
                    901: int nbranchinfos=0;
                    902: 
                    903: struct branchinfo {
                    904:   Label *targetptr; /* *(bi->targetptr) is the target */
                    905:   Cell *addressptr; /* store the target here */
                    906: } branchinfos[100000];
                    907: 
                    908: int ndoesexecinfos=0;
                    909: struct doesexecinfo {
                    910:   int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
                    911:   Cell *xt; /* cfa of word whose does-code needs calling */
                    912: } doesexecinfos[10000];
                    913: 
1.73      anton     914: /* definitions of N_execute etc. */
                    915: #include "prim_num.i"
1.70      anton     916: 
                    917: void set_rel_target(Cell *source, Label target)
                    918: {
                    919:   *source = ((Cell)target)-(((Cell)source)+4);
                    920: }
                    921: 
                    922: void register_branchinfo(Label source, Cell targetptr)
                    923: {
                    924:   struct branchinfo *bi = &(branchinfos[nbranchinfos]);
                    925:   bi->targetptr = (Label *)targetptr;
                    926:   bi->addressptr = (Cell *)source;
                    927:   nbranchinfos++;
                    928: }
                    929: 
                    930: Cell *compile_prim1arg(Cell p)
                    931: {
                    932:   int l = priminfos[p].length;
                    933:   Address old_code_here=code_here;
                    934: 
1.74      anton     935:   assert(vm_prims[p]==priminfos[p].start);
                    936:   append_prim(p);
1.70      anton     937:   return (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
                    938: }
                    939: 
                    940: Cell *compile_call2(Cell targetptr)
                    941: {
                    942:   Cell *next_code_target;
1.73      anton     943:   PrimInfo *pi = &priminfos[N_call2];
1.74      anton     944:   Address old_code_here = append_prim(N_call2);
1.70      anton     945: 
1.74      anton     946:   next_code_target = (Cell *)(old_code_here + pi->immargs[0].offset);
                    947:   register_branchinfo(old_code_here + pi->immargs[1].offset, targetptr);
1.70      anton     948:   return next_code_target;
                    949: }
                    950: #endif
                    951: 
                    952: void finish_code(void)
                    953: {
                    954: #ifdef NO_IP
                    955:   Cell i;
                    956: 
                    957:   compile_prim1(NULL);
                    958:   for (i=0; i<ndoesexecinfos; i++) {
                    959:     struct doesexecinfo *dei = &doesexecinfos[i];
                    960:     branchinfos[dei->branchinfo].targetptr = DOES_CODE1((dei->xt));
                    961:   }
                    962:   ndoesexecinfos = 0;
                    963:   for (i=0; i<nbranchinfos; i++) {
                    964:     struct branchinfo *bi=&branchinfos[i];
                    965:     set_rel_target(bi->addressptr, *(bi->targetptr));
                    966:   }
                    967:   nbranchinfos = 0;
1.48      anton     968: #endif
1.93      anton     969:   flush_to_here();
1.48      anton     970: }
                    971: 
1.108     anton     972: #if 0
1.105     anton     973: /* compile *start into a dynamic superinstruction, updating *start */
                    974: void compile_prim_dyn(Cell *start)
1.48      anton     975: {
1.108     anton     976: #if defined(NO_IP)
1.70      anton     977:   static Cell *last_start=NULL;
                    978:   static Xt last_prim=NULL;
                    979:   /* delay work by one call in order to get relocated immargs */
                    980: 
                    981:   if (last_start) {
                    982:     unsigned i = last_prim-vm_prims;
                    983:     PrimInfo *pi=&priminfos[i];
                    984:     Cell *next_code_target=NULL;
                    985: 
                    986:     assert(i<npriminfos);
1.73      anton     987:     if (i==N_execute||i==N_perform||i==N_lit_perform) {
                    988:       next_code_target = compile_prim1arg(N_set_next_code);
1.70      anton     989:     }
1.73      anton     990:     if (i==N_call) {
1.70      anton     991:       next_code_target = compile_call2(last_start[1]);
1.73      anton     992:     } else if (i==N_does_exec) {
1.70      anton     993:       struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
1.73      anton     994:       *compile_prim1arg(N_lit) = (Cell)PFA(last_start[1]);
1.70      anton     995:       /* we cannot determine the callee now (last_start[1] may be a
                    996:          forward reference), so just register an arbitrary target, and
                    997:          register in dei that we need to fix this before resolving
                    998:          branches */
                    999:       dei->branchinfo = nbranchinfos;
                   1000:       dei->xt = (Cell *)(last_start[1]);
                   1001:       next_code_target = compile_call2(NULL);
                   1002:     } else if (pi->start == NULL) { /* non-reloc */
1.73      anton    1003:       next_code_target = compile_prim1arg(N_set_next_code);
                   1004:       set_rel_target(compile_prim1arg(N_abranch),*(Xt)last_prim);
1.70      anton    1005:     } else {
                   1006:       unsigned j;
1.74      anton    1007:       Address old_code_here = append_prim(i);
1.70      anton    1008: 
                   1009:       for (j=0; j<pi->nimmargs; j++) {
                   1010:        struct immarg *ia = &(pi->immargs[j]);
                   1011:        Cell argval = last_start[pi->nimmargs - j]; /* !! specific to prims */
                   1012:        if (ia->rel) { /* !! assumption: relative refs are branches */
1.74      anton    1013:          register_branchinfo(old_code_here + ia->offset, argval);
1.70      anton    1014:        } else /* plain argument */
1.74      anton    1015:          *(Cell *)(old_code_here + ia->offset) = argval;
1.70      anton    1016:       }
                   1017:     }
                   1018:     if (next_code_target!=NULL)
                   1019:       *next_code_target = (Cell)code_here;
                   1020:   }
                   1021:   if (start) {
                   1022:     last_prim = (Xt)*start;
                   1023:     *start = (Cell)code_here;
                   1024:   }
                   1025:   last_start = start;
                   1026:   return;
                   1027: #elif !defined(NO_DYNAMIC)
                   1028:   Label prim=(Label)*start;
1.58      anton    1029:   unsigned i;
1.74      anton    1030:   Address old_code_here;
1.48      anton    1031: 
1.58      anton    1032:   i = ((Xt)prim)-vm_prims;
1.56      anton    1033:   prim = *(Xt)prim;
1.70      anton    1034:   if (no_dynamic) {
                   1035:     *start = (Cell)prim;
                   1036:     return;
                   1037:   }
1.58      anton    1038:   if (i>=npriminfos || priminfos[i].start == 0) { /* not a relocatable prim */
1.74      anton    1039:     append_jump();
1.70      anton    1040:     *start = (Cell)prim;
                   1041:     return;
1.47      anton    1042:   }
1.58      anton    1043:   assert(priminfos[i].start = prim); 
1.50      anton    1044: #ifdef ALIGN_CODE
1.87      anton    1045:   /*  ALIGN_CODE;*/
1.50      anton    1046: #endif
1.74      anton    1047:   assert(prim==priminfos[i].start);
                   1048:   old_code_here = append_prim(i);
                   1049:   last_jump = (priminfos[i].superend) ? 0 : i;
1.70      anton    1050:   *start = (Cell)old_code_here;
                   1051:   return;
1.61      anton    1052: #else /* !defined(DOUBLY_INDIRECT), no code replication */
1.70      anton    1053:   Label prim=(Label)*start;
1.61      anton    1054: #if !defined(INDIRECT_THREADED)
1.56      anton    1055:   prim = *(Xt)prim;
1.61      anton    1056: #endif
1.70      anton    1057:   *start = (Cell)prim;
                   1058:   return;
1.54      anton    1059: #endif /* !defined(DOUBLY_INDIRECT) */
1.70      anton    1060: }
1.108     anton    1061: #endif /* 0 */
                   1062: 
                   1063: Cell compile_prim_dyn(unsigned p)
                   1064: {
                   1065:   Cell static_prim = (Cell)vm_prims[p+DOESJUMP+1];
                   1066: #if defined(NO_DYNAMIC)
                   1067:   return static_prim;
                   1068: #else /* !defined(NO_DYNAMIC) */
                   1069:   Address old_code_here;
                   1070: 
                   1071:   if (no_dynamic)
                   1072:     return static_prim;
                   1073:   p += DOESJUMP+1;
                   1074:   if (p>=npriminfos || priminfos[p].start == 0) { /* not a relocatable prim */
                   1075:     append_jump();
                   1076:     return static_prim;
                   1077:   }
                   1078:   old_code_here = append_prim(p);
                   1079:   last_jump = (priminfos[p].superend) ? 0 : p;
                   1080:   return (Cell)old_code_here;
                   1081: #endif  /* !defined(NO_DYNAMIC) */
                   1082: }
1.70      anton    1083: 
1.109     anton    1084: #ifndef NO_DYNAMIC
                   1085: int cost_codesize(int prim)
                   1086: {
                   1087:   return priminfos[prim+DOESJUMP+1].length;
                   1088: }
                   1089: #endif
                   1090: 
                   1091: int cost_ls(int prim)
                   1092: {
                   1093:   struct cost *c = super_costs+prim;
                   1094: 
                   1095:   return c->loads + c->stores;
                   1096: }
                   1097: 
                   1098: int cost_lsu(int prim)
                   1099: {
                   1100:   struct cost *c = super_costs+prim;
                   1101: 
                   1102:   return c->loads + c->stores + c->updates;
                   1103: }
                   1104: 
                   1105: int cost_nexts(int prim)
                   1106: {
                   1107:   return 1;
                   1108: }
                   1109: 
                   1110: typedef int Costfunc(int);
                   1111: Costfunc *ss_cost =  /* cost function for optimize_bb */
                   1112: #ifdef NO_DYNAMIC
                   1113: cost_lsu;
                   1114: #else
                   1115: cost_codesize;
                   1116: #endif
                   1117: 
1.110     anton    1118: struct {
                   1119:   Costfunc *costfunc;
                   1120:   char *metricname;
                   1121:   long sum;
                   1122: } cost_sums[] = {
                   1123: #ifndef NO_DYNAMIC
                   1124:   { cost_codesize, "codesize", 0 },
                   1125: #endif
                   1126:   { cost_ls,       "ls",       0 },
                   1127:   { cost_lsu,      "lsu",      0 },
                   1128:   { cost_nexts,    "nexts",    0 }
                   1129: };
                   1130: 
1.106     anton    1131: #define MAX_BB 128 /* maximum number of instructions in BB */
                   1132: 
1.107     anton    1133: /* use dynamic programming to find the shortest paths within the basic
                   1134:    block origs[0..ninsts-1]; optimals[i] contains the superinstruction
                   1135:    on the shortest path to the end of the BB */
                   1136: void optimize_bb(short origs[], short optimals[], int ninsts)
                   1137: {
1.110     anton    1138:   int i,j, mincost;
1.107     anton    1139:   static int costs[MAX_BB+1];
                   1140: 
                   1141:   assert(ninsts<MAX_BB);
                   1142:   costs[ninsts]=0;
                   1143:   for (i=ninsts-1; i>=0; i--) {
                   1144:     optimals[i] = origs[i];
1.110     anton    1145:     costs[i] = mincost = costs[i+1] + ss_cost(optimals[i]);
1.107     anton    1146:     for (j=2; j<=max_super && i+j<=ninsts ; j++) {
                   1147:       int super, jcost;
                   1148: 
                   1149:       super = lookup_super(origs+i,j);
                   1150:       if (super >= 0) {
1.109     anton    1151:        jcost = costs[i+j] + ss_cost(super);
1.110     anton    1152:        if (jcost <= mincost) {
1.107     anton    1153:          optimals[i] = super;
1.110     anton    1154:          mincost = jcost;
                   1155:          if (!ss_greedy)
                   1156:            costs[i] = jcost;
1.107     anton    1157:        }
                   1158:       }
                   1159:     }
                   1160:   }
                   1161: }
                   1162: 
                   1163: /* rewrite the instructions pointed to by instps to use the
                   1164:    superinstructions in optimals */
                   1165: void rewrite_bb(Cell *instps[], short *optimals, int ninsts)
                   1166: {
1.110     anton    1167:   int i,j, nextdyn;
1.108     anton    1168:   Cell inst;
1.107     anton    1169: 
                   1170:   for (i=0, nextdyn=0; i<ninsts; i++) {
1.108     anton    1171:     if (i==nextdyn) { /* compile dynamically */
1.107     anton    1172:       nextdyn += super_costs[optimals[i]].length;
1.108     anton    1173:       inst = compile_prim_dyn(optimals[i]);
1.110     anton    1174:       for (j=0; j<sizeof(cost_sums)/sizeof(cost_sums[0]); j++)
                   1175:        cost_sums[j].sum += cost_sums[j].costfunc(optimals[i]);
1.108     anton    1176:     } else { /* compile statically */
1.109     anton    1177:       inst = (Cell)vm_prims[optimals[i]+DOESJUMP+1];
1.107     anton    1178:     }
1.108     anton    1179:     *(instps[i]) = inst;
1.107     anton    1180:   }
                   1181: }
                   1182: 
1.105     anton    1183: /* compile *start, possibly rewriting it into a static and/or dynamic
                   1184:    superinstruction */
                   1185: void compile_prim1(Cell *start)
1.70      anton    1186: {
1.108     anton    1187: #if defined(DOUBLY_INDIRECT)
                   1188:   Label prim=(Label)*start;
                   1189:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
                   1190:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
                   1191:     *start=(Cell)prim;
                   1192:     return;
                   1193:   } else {
                   1194:     *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
                   1195:     return;
                   1196:   }
                   1197: #elif defined(INDIRECT_THREADED)
                   1198:   return;
1.112     anton    1199: #else /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1.107     anton    1200:   static Cell *instps[MAX_BB];
                   1201:   static short origs[MAX_BB];
                   1202:   static short optimals[MAX_BB];
1.106     anton    1203:   static int ninsts=0;
                   1204:   unsigned prim_num;
                   1205: 
                   1206:   if (start==NULL)
                   1207:     goto end_bb;
                   1208:   prim_num = ((Xt)*start)-vm_prims;
                   1209:   if (prim_num >= npriminfos)
                   1210:     goto end_bb;
                   1211:   assert(ninsts<MAX_BB);
1.107     anton    1212:   instps[ninsts] = start;
                   1213:   origs[ninsts] = prim_num-DOESJUMP-1;
                   1214:   ninsts++;
1.106     anton    1215:   if (ninsts >= MAX_BB || superend[prim_num-DOESJUMP-1]) {
                   1216:   end_bb:
1.107     anton    1217:     optimize_bb(origs,optimals,ninsts);
                   1218:     rewrite_bb(instps,optimals,ninsts);
1.106     anton    1219:     ninsts=0;
                   1220:   }
1.112     anton    1221: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1.47      anton    1222: }
                   1223: 
1.69      anton    1224: #if defined(PRINT_SUPER_LENGTHS) && !defined(NO_DYNAMIC)
1.59      anton    1225: Cell prim_length(Cell prim)
                   1226: {
                   1227:   return priminfos[prim+DOESJUMP+1].length;
                   1228: }
                   1229: #endif
                   1230: 
1.1       anton    1231: Address loader(FILE *imagefile, char* filename)
                   1232: /* returns the address of the image proper (after the preamble) */
                   1233: {
                   1234:   ImageHeader header;
                   1235:   Address image;
                   1236:   Address imp; /* image+preamble */
1.17      anton    1237:   Char magic[8];
                   1238:   char magic7; /* size byte of magic number */
1.1       anton    1239:   Cell preamblesize=0;
1.6       pazsan   1240:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1.1       anton    1241:   UCell check_sum;
1.15      pazsan   1242:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
                   1243:                 (RELINFOBITS == 16) ? 1 :
                   1244:                 (RELINFOBITS == 32) ? 2 : 3);
                   1245:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
                   1246:                   (sizeof(Char) == 2) ? 1 :
                   1247:                   (sizeof(Char) == 4) ? 2 : 3) + ausize;
                   1248:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
                   1249:                   (sizeof(Cell) == 2) ? 1 :
                   1250:                   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1.21      anton    1251:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
                   1252: #ifdef WORDS_BIGENDIAN
                   1253:        0
                   1254: #else
                   1255:        1
                   1256: #endif
                   1257:     ;
1.1       anton    1258: 
1.43      anton    1259:   vm_prims = engine(0,0,0,0,0);
1.47      anton    1260:   check_prims(vm_prims);
1.106     anton    1261:   prepare_super_table();
1.1       anton    1262: #ifndef DOUBLY_INDIRECT
1.59      anton    1263: #ifdef PRINT_SUPER_LENGTHS
                   1264:   print_super_lengths();
                   1265: #endif
1.43      anton    1266:   check_sum = checksum(vm_prims);
1.1       anton    1267: #else /* defined(DOUBLY_INDIRECT) */
1.43      anton    1268:   check_sum = (UCell)vm_prims;
1.1       anton    1269: #endif /* defined(DOUBLY_INDIRECT) */
1.10      pazsan   1270:   
                   1271:   do {
                   1272:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1.84      anton    1273:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
1.10      pazsan   1274:              progname, filename);
                   1275:       exit(1);
1.1       anton    1276:     }
1.10      pazsan   1277:     preamblesize+=8;
1.84      anton    1278:   } while(memcmp(magic,"Gforth3",7));
1.17      anton    1279:   magic7 = magic[7];
1.1       anton    1280:   if (debug) {
1.17      anton    1281:     magic[7]='\0';
1.21      anton    1282:     fprintf(stderr,"Magic found: %s ", magic);
                   1283:     print_sizes(magic7);
1.1       anton    1284:   }
                   1285: 
1.21      anton    1286:   if (magic7 != sizebyte)
                   1287:     {
                   1288:       fprintf(stderr,"This image is:         ");
                   1289:       print_sizes(magic7);
                   1290:       fprintf(stderr,"whereas the machine is ");
                   1291:       print_sizes(sizebyte);
1.1       anton    1292:       exit(-2);
                   1293:     };
                   1294: 
                   1295:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1.10      pazsan   1296: 
                   1297:   set_stack_sizes(&header);
1.1       anton    1298:   
                   1299: #if HAVE_GETPAGESIZE
                   1300:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
                   1301: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
                   1302:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
                   1303: #elif PAGESIZE
                   1304:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
                   1305: #endif
                   1306:   if (debug)
1.5       jwilke   1307:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1.1       anton    1308: 
1.34      anton    1309:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
                   1310:                          preamblesize+dictsize, data_offset);
1.33      anton    1311:   imp=image+preamblesize;
1.57      anton    1312:   alloc_stacks((ImageHeader *)imp);
1.1       anton    1313:   if (clear_dictionary)
1.33      anton    1314:     memset(imp+header.image_size, 0, dictsize-header.image_size);
1.90      anton    1315:   if(header.base==0 || header.base  == (Address)0x100) {
1.1       anton    1316:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
                   1317:     char reloc_bits[reloc_size];
1.33      anton    1318:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1.10      pazsan   1319:     fread(reloc_bits, 1, reloc_size, imagefile);
1.90      anton    1320:     relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
1.1       anton    1321: #if 0
                   1322:     { /* let's see what the relocator did */
                   1323:       FILE *snapshot=fopen("snapshot.fi","wb");
                   1324:       fwrite(image,1,imagesize,snapshot);
                   1325:       fclose(snapshot);
                   1326:     }
                   1327: #endif
1.46      jwilke   1328:   }
                   1329:   else if(header.base!=imp) {
                   1330:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
                   1331:            progname, (unsigned long)header.base, (unsigned long)imp);
                   1332:     exit(1);
1.1       anton    1333:   }
                   1334:   if (header.checksum==0)
                   1335:     ((ImageHeader *)imp)->checksum=check_sum;
                   1336:   else if (header.checksum != check_sum) {
                   1337:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
                   1338:            progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
                   1339:     exit(1);
                   1340:   }
1.53      anton    1341: #ifdef DOUBLY_INDIRECT
                   1342:   ((ImageHeader *)imp)->xt_base = xts;
                   1343: #endif
1.1       anton    1344:   fclose(imagefile);
                   1345: 
1.56      anton    1346:   /* unnecessary, except maybe for CODE words */
                   1347:   /* FLUSH_ICACHE(imp, header.image_size);*/
1.1       anton    1348: 
                   1349:   return imp;
                   1350: }
                   1351: 
1.72      anton    1352: /* pointer to last '/' or '\' in file, 0 if there is none. */
                   1353: char *onlypath(char *filename)
1.10      pazsan   1354: {
1.72      anton    1355:   return strrchr(filename, DIRSEP);
1.1       anton    1356: }
                   1357: 
                   1358: FILE *openimage(char *fullfilename)
1.10      pazsan   1359: {
                   1360:   FILE *image_file;
1.28      anton    1361:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
1.10      pazsan   1362: 
1.28      anton    1363:   image_file=fopen(expfilename,"rb");
1.1       anton    1364:   if (image_file!=NULL && debug)
1.28      anton    1365:     fprintf(stderr, "Opened image file: %s\n", expfilename);
1.10      pazsan   1366:   return image_file;
1.1       anton    1367: }
                   1368: 
1.28      anton    1369: /* try to open image file concat(path[0:len],imagename) */
1.1       anton    1370: FILE *checkimage(char *path, int len, char *imagename)
1.10      pazsan   1371: {
                   1372:   int dirlen=len;
1.1       anton    1373:   char fullfilename[dirlen+strlen(imagename)+2];
1.10      pazsan   1374: 
1.1       anton    1375:   memcpy(fullfilename, path, dirlen);
1.71      pazsan   1376:   if (fullfilename[dirlen-1]!=DIRSEP)
                   1377:     fullfilename[dirlen++]=DIRSEP;
1.1       anton    1378:   strcpy(fullfilename+dirlen,imagename);
1.10      pazsan   1379:   return openimage(fullfilename);
1.1       anton    1380: }
                   1381: 
1.10      pazsan   1382: FILE * open_image_file(char * imagename, char * path)
1.1       anton    1383: {
1.10      pazsan   1384:   FILE * image_file=NULL;
1.28      anton    1385:   char *origpath=path;
1.10      pazsan   1386:   
1.71      pazsan   1387:   if(strchr(imagename, DIRSEP)==NULL) {
1.10      pazsan   1388:     /* first check the directory where the exe file is in !! 01may97jaw */
                   1389:     if (onlypath(progname))
1.72      anton    1390:       image_file=checkimage(progname, onlypath(progname)-progname, imagename);
1.10      pazsan   1391:     if (!image_file)
                   1392:       do {
                   1393:        char *pend=strchr(path, PATHSEP);
                   1394:        if (pend==NULL)
                   1395:          pend=path+strlen(path);
                   1396:        if (strlen(path)==0) break;
                   1397:        image_file=checkimage(path, pend-path, imagename);
                   1398:        path=pend+(*pend==PATHSEP);
                   1399:       } while (image_file==NULL);
                   1400:   } else {
                   1401:     image_file=openimage(imagename);
                   1402:   }
1.1       anton    1403: 
1.10      pazsan   1404:   if (!image_file) {
                   1405:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1.28      anton    1406:            progname, imagename, origpath);
1.10      pazsan   1407:     exit(1);
1.7       anton    1408:   }
                   1409: 
1.10      pazsan   1410:   return image_file;
                   1411: }
1.11      pazsan   1412: #endif
                   1413: 
                   1414: #ifdef HAS_OS
                   1415: UCell convsize(char *s, UCell elemsize)
                   1416: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
                   1417:    of bytes.  the letter at the end indicates the unit, where e stands
                   1418:    for the element size. default is e */
                   1419: {
                   1420:   char *endp;
                   1421:   UCell n,m;
                   1422: 
                   1423:   m = elemsize;
                   1424:   n = strtoul(s,&endp,0);
                   1425:   if (endp!=NULL) {
                   1426:     if (strcmp(endp,"b")==0)
                   1427:       m=1;
                   1428:     else if (strcmp(endp,"k")==0)
                   1429:       m=1024;
                   1430:     else if (strcmp(endp,"M")==0)
                   1431:       m=1024*1024;
                   1432:     else if (strcmp(endp,"G")==0)
                   1433:       m=1024*1024*1024;
                   1434:     else if (strcmp(endp,"T")==0) {
                   1435: #if (SIZEOF_CHAR_P > 4)
1.24      anton    1436:       m=1024L*1024*1024*1024;
1.11      pazsan   1437: #else
                   1438:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
                   1439:       exit(1);
                   1440: #endif
                   1441:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
                   1442:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
                   1443:       exit(1);
                   1444:     }
                   1445:   }
                   1446:   return n*m;
                   1447: }
1.10      pazsan   1448: 
1.109     anton    1449: enum {
                   1450:   ss_number = 256,
                   1451:   ss_min_codesize,
                   1452:   ss_min_ls,
                   1453:   ss_min_lsu,
                   1454:   ss_min_nexts,
                   1455: };
                   1456: 
1.10      pazsan   1457: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
                   1458: {
                   1459:   int c;
                   1460: 
1.1       anton    1461:   opterr=0;
                   1462:   while (1) {
                   1463:     int option_index=0;
                   1464:     static struct option opts[] = {
1.29      anton    1465:       {"appl-image", required_argument, NULL, 'a'},
1.1       anton    1466:       {"image-file", required_argument, NULL, 'i'},
                   1467:       {"dictionary-size", required_argument, NULL, 'm'},
                   1468:       {"data-stack-size", required_argument, NULL, 'd'},
                   1469:       {"return-stack-size", required_argument, NULL, 'r'},
                   1470:       {"fp-stack-size", required_argument, NULL, 'f'},
                   1471:       {"locals-stack-size", required_argument, NULL, 'l'},
                   1472:       {"path", required_argument, NULL, 'p'},
                   1473:       {"version", no_argument, NULL, 'v'},
                   1474:       {"help", no_argument, NULL, 'h'},
                   1475:       /* put something != 0 into offset_image */
                   1476:       {"offset-image", no_argument, &offset_image, 1},
                   1477:       {"no-offset-im", no_argument, &offset_image, 0},
                   1478:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
1.4       anton    1479:       {"die-on-signal", no_argument, &die_on_signal, 1},
1.1       anton    1480:       {"debug", no_argument, &debug, 1},
1.60      anton    1481:       {"no-super", no_argument, &no_super, 1},
                   1482:       {"no-dynamic", no_argument, &no_dynamic, 1},
1.66      anton    1483:       {"dynamic", no_argument, &no_dynamic, 0},
1.110     anton    1484:       {"print-metrics", no_argument, &print_metrics, 1},
1.109     anton    1485:       {"ss-number", required_argument, NULL, ss_number},
                   1486: #ifndef NO_DYNAMIC
                   1487:       {"ss-min-codesize", no_argument, NULL, ss_min_codesize},
                   1488: #endif
                   1489:       {"ss-min-ls",       no_argument, NULL, ss_min_ls},
                   1490:       {"ss-min-lsu",      no_argument, NULL, ss_min_lsu},
                   1491:       {"ss-min-nexts",    no_argument, NULL, ss_min_nexts},
1.110     anton    1492:       {"ss-greedy",       no_argument, &ss_greedy, 1},
1.1       anton    1493:       {0,0,0,0}
                   1494:       /* no-init-file, no-rc? */
                   1495:     };
                   1496:     
1.36      pazsan   1497:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1.1       anton    1498:     
                   1499:     switch (c) {
1.29      anton    1500:     case EOF: return;
                   1501:     case '?': optind--; return;
                   1502:     case 'a': *imagename = optarg; return;
1.10      pazsan   1503:     case 'i': *imagename = optarg; break;
1.1       anton    1504:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
                   1505:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
                   1506:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
                   1507:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
                   1508:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1.10      pazsan   1509:     case 'p': *path = optarg; break;
1.36      pazsan   1510:     case 'o': offset_image = 1; break;
                   1511:     case 'n': offset_image = 0; break;
                   1512:     case 'c': clear_dictionary = 1; break;
                   1513:     case 's': die_on_signal = 1; break;
                   1514:     case 'x': debug = 1; break;
1.83      anton    1515:     case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
1.109     anton    1516:     case ss_number: static_super_number = atoi(optarg); break;
                   1517: #ifndef NO_DYNAMIC
                   1518:     case ss_min_codesize: ss_cost = cost_codesize; break;
                   1519: #endif
                   1520:     case ss_min_ls:       ss_cost = cost_ls;       break;
                   1521:     case ss_min_lsu:      ss_cost = cost_lsu;      break;
                   1522:     case ss_min_nexts:    ss_cost = cost_nexts;    break;
1.1       anton    1523:     case 'h': 
1.29      anton    1524:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1.1       anton    1525: Engine Options:\n\
1.29      anton    1526:   --appl-image FILE                equivalent to '--image-file=FILE --'\n\
1.10      pazsan   1527:   --clear-dictionary               Initialize the dictionary with 0 bytes\n\
                   1528:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
                   1529:   --debug                          Print debugging information during startup\n\
                   1530:   --die-on-signal                  exit instead of CATCHing some signals\n\
1.66      anton    1531:   --dynamic                        use dynamic native code\n\
1.10      pazsan   1532:   -f SIZE, --fp-stack-size=SIZE            Specify floating point stack size\n\
                   1533:   -h, --help                       Print this message and exit\n\
                   1534:   -i FILE, --image-file=FILE       Use image FILE instead of `gforth.fi'\n\
                   1535:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
                   1536:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
1.60      anton    1537:   --no-dynamic                     Use only statically compiled primitives\n\
1.10      pazsan   1538:   --no-offset-im                   Load image at normal position\n\
1.60      anton    1539:   --no-super                        No dynamically formed superinstructions\n\
1.10      pazsan   1540:   --offset-image                   Load image at a different position\n\
                   1541:   -p PATH, --path=PATH             Search path for finding image and sources\n\
1.110     anton    1542:   --print-metrics                  Print some code generation metrics on exit\n\
1.10      pazsan   1543:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
1.111     anton    1544:   --ss-greedy                       greedy, not optimal superinst selection\n\
                   1545:   --ss-min-codesize                 select superinsts for smallest native code\n\
                   1546:   --ss-min-ls                       minimize loads and stores\n\
                   1547:   --ss-min-lsu                      minimize loads, stores, and pointer updates\n\
                   1548:   --ss-min-nexts                    minimize the number of static superinsts\n\
                   1549:   --ss-number=N                     use N static superinsts (default max)\n\
1.66      anton    1550:   -v, --version                            Print engine version and exit\n\
1.1       anton    1551: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1.10      pazsan   1552:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
                   1553:              argv[0]);
                   1554:       optind--;
                   1555:       return;
1.1       anton    1556:     }
                   1557:   }
1.10      pazsan   1558: }
1.11      pazsan   1559: #endif
1.10      pazsan   1560: 
                   1561: #ifdef INCLUDE_IMAGE
                   1562: extern Cell image[];
                   1563: extern const char reloc_bits[];
                   1564: #endif
1.67      pazsan   1565: 
1.10      pazsan   1566: int main(int argc, char **argv, char **env)
                   1567: {
1.30      pazsan   1568: #ifdef HAS_OS
1.10      pazsan   1569:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1.30      pazsan   1570: #else
                   1571:   char *path = DEFAULTPATH;
                   1572: #endif
1.13      pazsan   1573: #ifndef INCLUDE_IMAGE
1.10      pazsan   1574:   char *imagename="gforth.fi";
                   1575:   FILE *image_file;
                   1576:   Address image;
                   1577: #endif
                   1578:   int retvalue;
                   1579:          
1.56      anton    1580: #if defined(i386) && defined(ALIGNMENT_CHECK)
1.10      pazsan   1581:   /* turn on alignment checks on the 486.
                   1582:    * on the 386 this should have no effect. */
                   1583:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
                   1584:   /* this is unusable with Linux' libc.4.6.27, because this library is
                   1585:      not alignment-clean; we would have to replace some library
                   1586:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
                   1587:      the stack FP-aligned. */
                   1588: #endif
                   1589: 
                   1590:   /* buffering of the user output device */
1.11      pazsan   1591: #ifdef _IONBF
1.10      pazsan   1592:   if (isatty(fileno(stdout))) {
                   1593:     fflush(stdout);
                   1594:     setvbuf(stdout,NULL,_IONBF,0);
1.1       anton    1595:   }
1.11      pazsan   1596: #endif
1.1       anton    1597: 
1.10      pazsan   1598:   progname = argv[0];
                   1599: 
1.11      pazsan   1600: #ifdef HAS_OS
1.10      pazsan   1601:   gforth_args(argc, argv, &path, &imagename);
1.109     anton    1602: #ifndef NO_DYNAMIC
                   1603:   if (no_dynamic && ss_cost == cost_codesize) {
                   1604:     ss_cost = cost_lsu;
1.110     anton    1605:     cost_sums[0] = cost_sums[1];
1.109     anton    1606:     if (debug)
                   1607:       fprintf(stderr, "--no-dynamic conflicts with --ss-min-codesize, reverting to --ss-min-lsu\n");
                   1608:   }
                   1609: #endif /* !defined(NO_DYNAMIC) */
                   1610: #endif /* defined(HAS_OS) */
1.10      pazsan   1611: 
                   1612: #ifdef INCLUDE_IMAGE
                   1613:   set_stack_sizes((ImageHeader *)image);
1.22      pazsan   1614:   if(((ImageHeader *)image)->base != image)
                   1615:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
                   1616:             (Label*)engine(0, 0, 0, 0, 0));
1.10      pazsan   1617:   alloc_stacks((ImageHeader *)image);
                   1618: #else
                   1619:   image_file = open_image_file(imagename, path);
                   1620:   image = loader(image_file, imagename);
                   1621: #endif
1.24      anton    1622:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1.1       anton    1623: 
                   1624:   {
1.10      pazsan   1625:     char path2[strlen(path)+1];
1.1       anton    1626:     char *p1, *p2;
                   1627:     Cell environ[]= {
                   1628:       (Cell)argc-(optind-1),
                   1629:       (Cell)(argv+(optind-1)),
1.10      pazsan   1630:       (Cell)strlen(path),
1.1       anton    1631:       (Cell)path2};
                   1632:     argv[optind-1] = progname;
                   1633:     /*
                   1634:        for (i=0; i<environ[0]; i++)
                   1635:        printf("%s\n", ((char **)(environ[1]))[i]);
                   1636:        */
                   1637:     /* make path OS-independent by replacing path separators with NUL */
1.10      pazsan   1638:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1.1       anton    1639:       if (*p1==PATHSEP)
                   1640:        *p2 = '\0';
                   1641:       else
                   1642:        *p2 = *p1;
                   1643:     *p2='\0';
1.10      pazsan   1644:     retvalue = go_forth(image, 4, environ);
1.102     anton    1645: #ifdef SIGPIPE
                   1646:     bsd_signal(SIGPIPE, SIG_IGN);
                   1647: #endif
1.42      anton    1648: #ifdef VM_PROFILING
                   1649:     vm_print_profile(stderr);
                   1650: #endif
1.1       anton    1651:     deprep_terminal();
1.104     anton    1652:   }
1.110     anton    1653:   if (print_metrics) {
                   1654:     int i;
                   1655:     fprintf(stderr, "code size = %8ld\n", dyncodesize());
                   1656:     for (i=0; i<sizeof(cost_sums)/sizeof(cost_sums[0]); i++)
                   1657:       fprintf(stderr, "metric %8s: %8ld\n",
                   1658:              cost_sums[i].metricname, cost_sums[i].sum);
1.1       anton    1659:   }
1.13      pazsan   1660:   return retvalue;
1.1       anton    1661: }

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