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

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

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