File:  [gforth] / gforth / engine / main.c
Revision 1.67: download - view: text, annotated - select for diffs
Fri Oct 4 19:17:06 2002 UTC (21 years, 6 months ago) by pazsan
Branches: MAIN
CVS tags: HEAD
Fixes for GCC 3.2

    1: /* command line interpretation, image loading etc. for Gforth
    2: 
    3: 
    4:   Copyright (C) 1995,1996,1997,1998,2000 Free Software Foundation, Inc.
    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
   20:   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
   21: */
   22: 
   23: #include "config.h"
   24: #include <errno.h>
   25: #include <ctype.h>
   26: #include <stdio.h>
   27: #include <unistd.h>
   28: #include <string.h>
   29: #include <math.h>
   30: #include <sys/types.h>
   31: #ifndef STANDALONE
   32: #include <sys/stat.h>
   33: #endif
   34: #include <fcntl.h>
   35: #include <assert.h>
   36: #include <stdlib.h>
   37: #ifndef STANDALONE
   38: #if HAVE_SYS_MMAN_H
   39: #include <sys/mman.h>
   40: #endif
   41: #endif
   42: #include "forth.h"
   43: #include "io.h"
   44: #include "getopt.h"
   45: #ifdef STANDALONE
   46: #include <systypes.h>
   47: #endif
   48: 
   49: #define PRIM_VERSION 1
   50: /* increment this whenever the primitives change in an incompatible way */
   51: 
   52: #ifndef DEFAULTPATH
   53: #  define DEFAULTPATH "."
   54: #endif
   55: 
   56: #ifdef MSDOS
   57: jmp_buf throw_jmp_buf;
   58: #endif
   59: 
   60: #if defined(DOUBLY_INDIRECT)
   61: #  define CFA(n)	({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
   62: #else
   63: #  define CFA(n)	((Cell)(symbols+((n)&~0x4000UL)))
   64: #endif
   65: 
   66: #define maxaligned(n)	(typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
   67: 
   68: static UCell dictsize=0;
   69: static UCell dsize=0;
   70: static UCell rsize=0;
   71: static UCell fsize=0;
   72: static UCell lsize=0;
   73: int offset_image=0;
   74: int die_on_signal=0;
   75: #ifndef INCLUDE_IMAGE
   76: static int clear_dictionary=0;
   77: UCell pagesize=1;
   78: char *progname;
   79: #else
   80: char *progname = "gforth";
   81: int optind = 1;
   82: #endif
   83: 
   84: Address code_area=0;
   85: Address code_here=0; /* does for code-area what HERE does for the dictionary */
   86: Address start_flush=0; /* start of unflushed code */
   87: 
   88: static int no_super=0;   /* true if compile_prim should not fuse prims */
   89: /* --no-dynamic by default on gcc versions >=3.1 (it works with 3.0.4,
   90:    but not with 3.2) */
   91: #if (__GNUC__>2 && __GNUC_MINOR__>=1)
   92: static int no_dynamic=1; /* true if compile_prim should not generate code */
   93: #else
   94: static int no_dynamic=0; /* true if compile_prim should not generate code */
   95: #endif
   96: 
   97: #ifdef HAS_DEBUG
   98: static int debug=0;
   99: #else
  100: # define debug 0
  101: # define perror(x...)
  102: # define fprintf(x...)
  103: #endif
  104: 
  105: ImageHeader *gforth_header;
  106: Label *vm_prims;
  107: #ifdef DOUBLY_INDIRECT
  108: Label *xts; /* same content as vm_prims, but should only be used for xts */
  109: #endif
  110: 
  111: #ifdef MEMCMP_AS_SUBROUTINE
  112: int gforth_memcmp(const char * s1, const char * s2, size_t n)
  113: {
  114:   return memcmp(s1, s2, n);
  115: }
  116: #endif
  117: 
  118: /* image file format:
  119:  *  "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
  120:  *   padding to a multiple of 8
  121:  *   magic: "Gforth2x" means format 0.4,
  122:  *              where x is a byte with
  123:  *              bit 7:   reserved = 0
  124:  *              bit 6:5: address unit size 2^n octets
  125:  *              bit 4:3: character size 2^n octets
  126:  *              bit 2:1: cell size 2^n octets
  127:  *              bit 0:   endian, big=0, little=1.
  128:  *  The magic are always 8 octets, no matter what the native AU/character size is
  129:  *  padding to max alignment (no padding necessary on current machines)
  130:  *  ImageHeader structure (see forth.h)
  131:  *  data (size in ImageHeader.image_size)
  132:  *  tags ((if relocatable, 1 bit/data cell)
  133:  *
  134:  * tag==1 means that the corresponding word is an address;
  135:  * If the word is >=0, the address is within the image;
  136:  * addresses within the image are given relative to the start of the image.
  137:  * If the word =-1 (CF_NIL), the address is NIL,
  138:  * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
  139:  * If the word =CF(DODOES), it's a DOES> CFA
  140:  * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
  141:  *					possibly containing a jump to dodoes)
  142:  * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
  143:  * If the word is <CF(DOESJUMP) and bit 14 is clear, 
  144:  *                                        it's the threaded code of a primitive
  145:  */
  146: 
  147: void relocate(Cell *image, const char *bitstring, 
  148:               int size, int base, Label symbols[])
  149: {
  150:   int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
  151:   Cell token;
  152:   char bits;
  153:   Cell max_symbols;
  154:   /* 
  155:    * A virtial start address that's the real start address minus 
  156:    * the one in the image 
  157:    */
  158:   Cell *start = (Cell * ) (((void *) image) - ((void *) base));
  159: 
  160:   
  161: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
  162:   
  163:   for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
  164:     ;
  165:   max_symbols--;
  166:   size/=sizeof(Cell);
  167: 
  168:   for(k=0; k<=steps; k++) {
  169:     for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
  170:       /*      fprintf(stderr,"relocate: image[%d]\n", i);*/
  171:       if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
  172: 	/* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
  173:         token=image[i];
  174: 	if(token<0)
  175: 	  switch(token|0x4000)
  176: 	    {
  177: 	    case CF_NIL      : image[i]=0; break;
  178: #if !defined(DOUBLY_INDIRECT)
  179: 	    case CF(DOCOL)   :
  180: 	    case CF(DOVAR)   :
  181: 	    case CF(DOCON)   :
  182: 	    case CF(DOUSER)  : 
  183: 	    case CF(DODEFER) : 
  184: 	    case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
  185: 	    case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
  186: #endif /* !defined(DOUBLY_INDIRECT) */
  187: 	    case CF(DODOES)  :
  188: 	      MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
  189: 	      break;
  190: 	    default          :
  191: /*	      printf("Code field generation image[%x]:=CFA(%x)\n",
  192: 		     i, CF(image[i])); */
  193: 	      if (CF((token | 0x4000))<max_symbols) {
  194: 		image[i]=(Cell)CFA(CF(token));
  195: #ifdef DIRECT_THREADED
  196: 		if ((token & 0x4000) == 0) /* threade code, no CFA */
  197: 		  image[i] = (Cell)compile_prim((Label)image[i]);
  198: #endif
  199: 	      } else
  200: 		fprintf(stderr,"Primitive %d used in this image at $%lx is not implemented by this\n engine (%s); executing this code will crash.\n",CF(token),(long)&image[i],VERSION);
  201: 	    }
  202: 	else {
  203:           // if base is > 0: 0 is a null reference so don't adjust
  204:           if (token>=base) {
  205:             image[i]+=(Cell)start;
  206:           }
  207:         }
  208:       }
  209:     }
  210:   }
  211:   ((ImageHeader*)(image))->base = (Address) image;
  212: }
  213: 
  214: UCell checksum(Label symbols[])
  215: {
  216:   UCell r=PRIM_VERSION;
  217:   Cell i;
  218: 
  219:   for (i=DOCOL; i<=DOESJUMP; i++) {
  220:     r ^= (UCell)(symbols[i]);
  221:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  222:   }
  223: #ifdef DIRECT_THREADED
  224:   /* we have to consider all the primitives */
  225:   for (; symbols[i]!=(Label)0; i++) {
  226:     r ^= (UCell)(symbols[i]);
  227:     r = (r << 5) | (r >> (8*sizeof(Cell)-5));
  228:   }
  229: #else
  230:   /* in indirect threaded code all primitives are accessed through the
  231:      symbols table, so we just have to put the base address of symbols
  232:      in the checksum */
  233:   r ^= (UCell)symbols;
  234: #endif
  235:   return r;
  236: }
  237: 
  238: Address verbose_malloc(Cell size)
  239: {
  240:   Address r;
  241:   /* leave a little room (64B) for stack underflows */
  242:   if ((r = malloc(size+64))==NULL) {
  243:     perror(progname);
  244:     exit(1);
  245:   }
  246:   r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
  247:   if (debug)
  248:     fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
  249:   return r;
  250: }
  251: 
  252: static Address next_address=0;
  253: void after_alloc(Address r, Cell size)
  254: {
  255:   if (r != (Address)-1) {
  256:     if (debug)
  257:       fprintf(stderr, "success, address=$%lx\n", (long) r);
  258:     if (pagesize != 1)
  259:       next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
  260:   } else {
  261:     if (debug)
  262:       fprintf(stderr, "failed: %s\n", strerror(errno));
  263:   }
  264: }
  265: 
  266: #ifndef MAP_FAILED
  267: #define MAP_FAILED ((Address) -1)
  268: #endif
  269: #ifndef MAP_FILE
  270: # define MAP_FILE 0
  271: #endif
  272: #ifndef MAP_PRIVATE
  273: # define MAP_PRIVATE 0
  274: #endif
  275: 
  276: #if defined(HAVE_MMAP)
  277: static Address alloc_mmap(Cell size)
  278: {
  279:   Address r;
  280: 
  281: #if defined(MAP_ANON)
  282:   if (debug)
  283:     fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
  284:   r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
  285: #else /* !defined(MAP_ANON) */
  286:   /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
  287:      apparently defaults) */
  288:   static int dev_zero=-1;
  289: 
  290:   if (dev_zero == -1)
  291:     dev_zero = open("/dev/zero", O_RDONLY);
  292:   if (dev_zero == -1) {
  293:     r = MAP_FAILED;
  294:     if (debug)
  295:       fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ", 
  296: 	      strerror(errno));
  297:   } else {
  298:     if (debug)
  299:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
  300:     r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
  301:   }
  302: #endif /* !defined(MAP_ANON) */
  303:   after_alloc(r, size);
  304:   return r;  
  305: }
  306: #endif
  307: 
  308: Address my_alloc(Cell size)
  309: {
  310: #if HAVE_MMAP
  311:   Address r;
  312: 
  313:   r=alloc_mmap(size);
  314:   if (r!=MAP_FAILED)
  315:     return r;
  316: #endif /* HAVE_MMAP */
  317:   /* use malloc as fallback */
  318:   return verbose_malloc(size);
  319: }
  320: 
  321: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
  322: {
  323:   Address image = MAP_FAILED;
  324: 
  325: #if defined(HAVE_MMAP)
  326:   if (offset==0) {
  327:     image=alloc_mmap(dictsize);
  328:     if (debug)
  329:       fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
  330:     image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
  331:     after_alloc(image,dictsize);
  332:   }
  333: #endif /* defined(HAVE_MMAP) */
  334:   if (image == MAP_FAILED) {
  335:     image = my_alloc(dictsize+offset)+offset;
  336:     rewind(file);  /* fseek(imagefile,0L,SEEK_SET); */
  337:     fread(image, 1, imagesize, file);
  338:   }
  339:   return image;
  340: }
  341: 
  342: void set_stack_sizes(ImageHeader * header)
  343: {
  344:   if (dictsize==0)
  345:     dictsize = header->dict_size;
  346:   if (dsize==0)
  347:     dsize = header->data_stack_size;
  348:   if (rsize==0)
  349:     rsize = header->return_stack_size;
  350:   if (fsize==0)
  351:     fsize = header->fp_stack_size;
  352:   if (lsize==0)
  353:     lsize = header->locals_stack_size;
  354:   dictsize=maxaligned(dictsize);
  355:   dsize=maxaligned(dsize);
  356:   rsize=maxaligned(rsize);
  357:   lsize=maxaligned(lsize);
  358:   fsize=maxaligned(fsize);
  359: }
  360: 
  361: void alloc_stacks(ImageHeader * header)
  362: {
  363:   header->dict_size=dictsize;
  364:   header->data_stack_size=dsize;
  365:   header->fp_stack_size=fsize;
  366:   header->return_stack_size=rsize;
  367:   header->locals_stack_size=lsize;
  368: 
  369:   header->data_stack_base=my_alloc(dsize);
  370:   header->fp_stack_base=my_alloc(fsize);
  371:   header->return_stack_base=my_alloc(rsize);
  372:   header->locals_stack_base=my_alloc(lsize);
  373:   code_here = start_flush = code_area = my_alloc(dictsize);
  374: }
  375: 
  376: #warning You can ignore the warnings about clobbered variables in go_forth
  377: int go_forth(Address image, int stack, Cell *entries)
  378: {
  379:   volatile ImageHeader *image_header = (ImageHeader *)image;
  380:   Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
  381:   Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
  382:   Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
  383: #ifdef GFORTH_DEBUGGING
  384:   volatile Cell *orig_rp0=rp0;
  385: #endif
  386:   Address lp0=image_header->locals_stack_base + lsize;
  387:   Xt *ip0=(Xt *)(image_header->boot_entry);
  388: #ifdef SYSSIGNALS
  389:   int throw_code;
  390: #endif
  391: 
  392:   /* ensure that the cached elements (if any) are accessible */
  393:   IF_spTOS(sp0--);
  394:   IF_fpTOS(fp0--);
  395:   
  396:   for(;stack>0;stack--)
  397:     *--sp0=entries[stack-1];
  398: 
  399: #ifdef SYSSIGNALS
  400:   get_winsize();
  401:    
  402:   install_signal_handlers(); /* right place? */
  403:   
  404:   if ((throw_code=setjmp(throw_jmp_buf))) {
  405:     static Cell signal_data_stack[8];
  406:     static Cell signal_return_stack[8];
  407:     static Float signal_fp_stack[1];
  408: 
  409:     signal_data_stack[7]=throw_code;
  410: 
  411: #ifdef GFORTH_DEBUGGING
  412:     /* fprintf(stderr,"\nrp=%ld\n",(long)rp); */
  413:     if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
  414:       /* no rstack overflow or underflow */
  415:       rp0 = rp;
  416:       *--rp0 = (Cell)saved_ip;
  417:     }
  418:     else /* I love non-syntactic ifdefs :-) */
  419: #endif
  420:     rp0 = signal_return_stack+8;
  421:     /* fprintf(stderr, "rp=$%x\n",rp0);*/
  422:     
  423:     return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
  424: 		       rp0, signal_fp_stack, 0));
  425:   }
  426: #endif
  427: 
  428:   return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
  429: }
  430: 
  431: 
  432: #ifndef INCLUDE_IMAGE
  433: void print_sizes(Cell sizebyte)
  434:      /* print size information */
  435: {
  436:   static char* endianstring[]= { "   big","little" };
  437:   
  438:   fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
  439: 	  endianstring[sizebyte & 1],
  440: 	  1 << ((sizebyte >> 1) & 3),
  441: 	  1 << ((sizebyte >> 3) & 3),
  442: 	  1 << ((sizebyte >> 5) & 3));
  443: }
  444: 
  445: typedef struct {
  446:   Label start;
  447:   Cell length; /* excluding the jump */
  448:   char super_end; /* true if primitive ends superinstruction, i.e.,
  449:                      unconditional branch, execute, etc. */
  450: } PrimInfo;
  451: 
  452: PrimInfo *priminfos;
  453: Cell npriminfos=0;
  454: 
  455: void check_prims(Label symbols1[])
  456: {
  457:   int i;
  458:   Label *symbols2;
  459:   static char superend[]={
  460: #include "prim_superend.i"
  461:   };
  462: 
  463:   if (debug)
  464: #ifdef __VERSION__
  465:     fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
  466: #else
  467: #define xstr(s) str(s)
  468: #define str(s) #s
  469:   fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n"); 
  470: #endif
  471:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
  472:     ;
  473:   npriminfos = i;
  474: 
  475: #if defined(IS_NEXT_JUMP) && !defined(DOUBLY_INDIRECT)
  476:   if (no_dynamic)
  477:     return;
  478:   symbols2=engine2(0,0,0,0,0);
  479:   priminfos = calloc(i,sizeof(PrimInfo));
  480:   for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
  481:     int prim_len=symbols1[i+1]-symbols1[i];
  482:     PrimInfo *pi=&priminfos[i];
  483:     int j;
  484:     pi->super_end = superend[i-DOESJUMP-1]|no_super;
  485:     for (j=prim_len-IND_JUMP_LENGTH; ; j--) {
  486:       if (IS_NEXT_JUMP(symbols1[i]+j)) {
  487: 	prim_len = j;
  488: 	if (pi->super_end)
  489: 	  prim_len += IND_JUMP_LENGTH; /* include the jump */
  490: 	break;
  491:       }
  492:       if (j==0) { /* NEXT jump not found, e.g., execute */
  493: 	if (!pi->super_end && debug)
  494: 	  fprintf(stderr, "NEXT jump not found for primitive %d, making it super_end\n", i);
  495:         pi->super_end = 1;
  496: 	break;
  497:       }
  498:     }
  499:     pi->length = prim_len;
  500:     /* fprintf(stderr,"checking primitive %d: memcmp(%p, %p, %d)\n",
  501:        i, symbols1[i], symbols2[i], prim_len);*/
  502:     if (memcmp(symbols1[i],symbols2[i],prim_len)!=0) {
  503:       if (debug)
  504: 	fprintf(stderr,"Primitive %d not relocatable: memcmp(%p, %p, %d)\n",
  505: 		i, symbols1[i], symbols2[i], prim_len);
  506:     } else {
  507:       pi->start = symbols1[i];
  508:       if (debug)
  509: 	fprintf(stderr,"Primitive %d relocatable: start %p, length %ld, super_end %d\n",
  510: 		i, pi->start, pi->length, pi->super_end);
  511:     }      
  512:   }  
  513: #endif
  514: }
  515: 
  516: Label compile_prim(Label prim)
  517: {
  518: #if defined(DOUBLY_INDIRECT)
  519:   if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
  520:     fprintf(stderr,"compile_prim encountered xt %p\n", prim);
  521:     return prim;
  522:   } else
  523:     return prim-((Label)xts)+((Label)vm_prims);
  524: #elif defined(IND_JUMP_LENGTH) && !defined(VM_PROFILING) && !defined(INDIRECT_THREADED)
  525:   unsigned i;
  526:   Address old_code_here=code_here;
  527:   static Address last_jump=0;
  528: 
  529:   i = ((Xt)prim)-vm_prims;
  530:   prim = *(Xt)prim;
  531:   if (no_dynamic)
  532:     return prim;
  533:   if (i>=npriminfos || priminfos[i].start == 0) { /* not a relocatable prim */
  534:     if (last_jump) { /* make sure the last sequence is complete */
  535:       memcpy(code_here, last_jump, IND_JUMP_LENGTH);
  536:       code_here += IND_JUMP_LENGTH;
  537:       last_jump = 0;
  538:       FLUSH_ICACHE(start_flush, code_here-start_flush);
  539:       start_flush=code_here;
  540:     }
  541:     return prim;
  542:   }
  543:   assert(priminfos[i].start = prim); 
  544: #ifdef ALIGN_CODE
  545:   ALIGN_CODE;
  546: #endif
  547:   memcpy(code_here, (Address)prim, priminfos[i].length);
  548:   code_here += priminfos[i].length;
  549:   last_jump = (priminfos[i].super_end) ? 0 : (prim+priminfos[i].length);
  550:   if (last_jump == 0) {
  551:     FLUSH_ICACHE(start_flush, code_here-start_flush);
  552:     start_flush=code_here;
  553:   }
  554:   return (Label)old_code_here;
  555: #else /* !defined(DOUBLY_INDIRECT), no code replication */
  556: #if !defined(INDIRECT_THREADED)
  557:   prim = *(Xt)prim;
  558: #endif
  559:   return prim;
  560: #endif /* !defined(DOUBLY_INDIRECT) */
  561: }
  562: 
  563: #ifdef PRINT_SUPER_LENGTHS
  564: Cell prim_length(Cell prim)
  565: {
  566:   return priminfos[prim+DOESJUMP+1].length;
  567: }
  568: #endif
  569: 
  570: Address loader(FILE *imagefile, char* filename)
  571: /* returns the address of the image proper (after the preamble) */
  572: {
  573:   ImageHeader header;
  574:   Address image;
  575:   Address imp; /* image+preamble */
  576:   Char magic[8];
  577:   char magic7; /* size byte of magic number */
  578:   Cell preamblesize=0;
  579:   Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
  580:   UCell check_sum;
  581:   Cell ausize = ((RELINFOBITS ==  8) ? 0 :
  582: 		 (RELINFOBITS == 16) ? 1 :
  583: 		 (RELINFOBITS == 32) ? 2 : 3);
  584:   Cell charsize = ((sizeof(Char) == 1) ? 0 :
  585: 		   (sizeof(Char) == 2) ? 1 :
  586: 		   (sizeof(Char) == 4) ? 2 : 3) + ausize;
  587:   Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
  588: 		   (sizeof(Cell) == 2) ? 1 :
  589: 		   (sizeof(Cell) == 4) ? 2 : 3) + ausize;
  590:   Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
  591: #ifdef WORDS_BIGENDIAN
  592:        0
  593: #else
  594:        1
  595: #endif
  596:     ;
  597: 
  598:   vm_prims = engine(0,0,0,0,0);
  599:   check_prims(vm_prims);
  600: #ifndef DOUBLY_INDIRECT
  601: #ifdef PRINT_SUPER_LENGTHS
  602:   print_super_lengths();
  603: #endif
  604:   check_sum = checksum(vm_prims);
  605: #else /* defined(DOUBLY_INDIRECT) */
  606:   check_sum = (UCell)vm_prims;
  607: #endif /* defined(DOUBLY_INDIRECT) */
  608:   
  609:   do {
  610:     if(fread(magic,sizeof(Char),8,imagefile) < 8) {
  611:       fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.4) image.\n",
  612: 	      progname, filename);
  613:       exit(1);
  614:     }
  615:     preamblesize+=8;
  616:   } while(memcmp(magic,"Gforth2",7));
  617:   magic7 = magic[7];
  618:   if (debug) {
  619:     magic[7]='\0';
  620:     fprintf(stderr,"Magic found: %s ", magic);
  621:     print_sizes(magic7);
  622:   }
  623: 
  624:   if (magic7 != sizebyte)
  625:     {
  626:       fprintf(stderr,"This image is:         ");
  627:       print_sizes(magic7);
  628:       fprintf(stderr,"whereas the machine is ");
  629:       print_sizes(sizebyte);
  630:       exit(-2);
  631:     };
  632: 
  633:   fread((void *)&header,sizeof(ImageHeader),1,imagefile);
  634: 
  635:   set_stack_sizes(&header);
  636:   
  637: #if HAVE_GETPAGESIZE
  638:   pagesize=getpagesize(); /* Linux/GNU libc offers this */
  639: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
  640:   pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
  641: #elif PAGESIZE
  642:   pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
  643: #endif
  644:   if (debug)
  645:     fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
  646: 
  647:   image = dict_alloc_read(imagefile, preamblesize+header.image_size,
  648: 			  preamblesize+dictsize, data_offset);
  649:   imp=image+preamblesize;
  650:   alloc_stacks((ImageHeader *)imp);
  651:   if (clear_dictionary)
  652:     memset(imp+header.image_size, 0, dictsize-header.image_size);
  653:   if(header.base==0 || header.base  == 0x100) {
  654:     Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
  655:     char reloc_bits[reloc_size];
  656:     fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
  657:     fread(reloc_bits, 1, reloc_size, imagefile);
  658:     relocate((Cell *)imp, reloc_bits, header.image_size, header.base, vm_prims);
  659: #if 0
  660:     { /* let's see what the relocator did */
  661:       FILE *snapshot=fopen("snapshot.fi","wb");
  662:       fwrite(image,1,imagesize,snapshot);
  663:       fclose(snapshot);
  664:     }
  665: #endif
  666:   }
  667:   else if(header.base!=imp) {
  668:     fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
  669: 	    progname, (unsigned long)header.base, (unsigned long)imp);
  670:     exit(1);
  671:   }
  672:   if (header.checksum==0)
  673:     ((ImageHeader *)imp)->checksum=check_sum;
  674:   else if (header.checksum != check_sum) {
  675:     fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
  676: 	    progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
  677:     exit(1);
  678:   }
  679: #ifdef DOUBLY_INDIRECT
  680:   ((ImageHeader *)imp)->xt_base = xts;
  681: #endif
  682:   fclose(imagefile);
  683: 
  684:   /* unnecessary, except maybe for CODE words */
  685:   /* FLUSH_ICACHE(imp, header.image_size);*/
  686: 
  687:   return imp;
  688: }
  689: 
  690: /* index of last '/' or '\' in file, 0 if there is none. !! Hmm, could
  691:    be implemented with strrchr and the separator should be
  692:    OS-dependent */
  693: int onlypath(char *file)
  694: {
  695:   int i;
  696:   i=strlen(file);
  697:   while (i) {
  698:     if (file[i]=='\\' || file[i]=='/') break;
  699:     i--;
  700:   }
  701:   return i;
  702: }
  703: 
  704: FILE *openimage(char *fullfilename)
  705: {
  706:   FILE *image_file;
  707:   char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
  708: 
  709:   image_file=fopen(expfilename,"rb");
  710:   if (image_file!=NULL && debug)
  711:     fprintf(stderr, "Opened image file: %s\n", expfilename);
  712:   return image_file;
  713: }
  714: 
  715: /* try to open image file concat(path[0:len],imagename) */
  716: FILE *checkimage(char *path, int len, char *imagename)
  717: {
  718:   int dirlen=len;
  719:   char fullfilename[dirlen+strlen(imagename)+2];
  720: 
  721:   memcpy(fullfilename, path, dirlen);
  722:   if (fullfilename[dirlen-1]!='/')
  723:     fullfilename[dirlen++]='/';
  724:   strcpy(fullfilename+dirlen,imagename);
  725:   return openimage(fullfilename);
  726: }
  727: 
  728: FILE * open_image_file(char * imagename, char * path)
  729: {
  730:   FILE * image_file=NULL;
  731:   char *origpath=path;
  732:   
  733:   if(strchr(imagename, '/')==NULL) {
  734:     /* first check the directory where the exe file is in !! 01may97jaw */
  735:     if (onlypath(progname))
  736:       image_file=checkimage(progname, onlypath(progname), imagename);
  737:     if (!image_file)
  738:       do {
  739: 	char *pend=strchr(path, PATHSEP);
  740: 	if (pend==NULL)
  741: 	  pend=path+strlen(path);
  742: 	if (strlen(path)==0) break;
  743: 	image_file=checkimage(path, pend-path, imagename);
  744: 	path=pend+(*pend==PATHSEP);
  745:       } while (image_file==NULL);
  746:   } else {
  747:     image_file=openimage(imagename);
  748:   }
  749: 
  750:   if (!image_file) {
  751:     fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
  752: 	    progname, imagename, origpath);
  753:     exit(1);
  754:   }
  755: 
  756:   return image_file;
  757: }
  758: #endif
  759: 
  760: #ifdef HAS_OS
  761: UCell convsize(char *s, UCell elemsize)
  762: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
  763:    of bytes.  the letter at the end indicates the unit, where e stands
  764:    for the element size. default is e */
  765: {
  766:   char *endp;
  767:   UCell n,m;
  768: 
  769:   m = elemsize;
  770:   n = strtoul(s,&endp,0);
  771:   if (endp!=NULL) {
  772:     if (strcmp(endp,"b")==0)
  773:       m=1;
  774:     else if (strcmp(endp,"k")==0)
  775:       m=1024;
  776:     else if (strcmp(endp,"M")==0)
  777:       m=1024*1024;
  778:     else if (strcmp(endp,"G")==0)
  779:       m=1024*1024*1024;
  780:     else if (strcmp(endp,"T")==0) {
  781: #if (SIZEOF_CHAR_P > 4)
  782:       m=1024L*1024*1024*1024;
  783: #else
  784:       fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
  785:       exit(1);
  786: #endif
  787:     } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
  788:       fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
  789:       exit(1);
  790:     }
  791:   }
  792:   return n*m;
  793: }
  794: 
  795: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
  796: {
  797:   int c;
  798: 
  799:   opterr=0;
  800:   while (1) {
  801:     int option_index=0;
  802:     static struct option opts[] = {
  803:       {"appl-image", required_argument, NULL, 'a'},
  804:       {"image-file", required_argument, NULL, 'i'},
  805:       {"dictionary-size", required_argument, NULL, 'm'},
  806:       {"data-stack-size", required_argument, NULL, 'd'},
  807:       {"return-stack-size", required_argument, NULL, 'r'},
  808:       {"fp-stack-size", required_argument, NULL, 'f'},
  809:       {"locals-stack-size", required_argument, NULL, 'l'},
  810:       {"path", required_argument, NULL, 'p'},
  811:       {"version", no_argument, NULL, 'v'},
  812:       {"help", no_argument, NULL, 'h'},
  813:       /* put something != 0 into offset_image */
  814:       {"offset-image", no_argument, &offset_image, 1},
  815:       {"no-offset-im", no_argument, &offset_image, 0},
  816:       {"clear-dictionary", no_argument, &clear_dictionary, 1},
  817:       {"die-on-signal", no_argument, &die_on_signal, 1},
  818:       {"debug", no_argument, &debug, 1},
  819:       {"no-super", no_argument, &no_super, 1},
  820:       {"no-dynamic", no_argument, &no_dynamic, 1},
  821:       {"dynamic", no_argument, &no_dynamic, 0},
  822:       {0,0,0,0}
  823:       /* no-init-file, no-rc? */
  824:     };
  825:     
  826:     c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
  827:     
  828:     switch (c) {
  829:     case EOF: return;
  830:     case '?': optind--; return;
  831:     case 'a': *imagename = optarg; return;
  832:     case 'i': *imagename = optarg; break;
  833:     case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
  834:     case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
  835:     case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
  836:     case 'f': fsize = convsize(optarg,sizeof(Float)); break;
  837:     case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
  838:     case 'p': *path = optarg; break;
  839:     case 'o': offset_image = 1; break;
  840:     case 'n': offset_image = 0; break;
  841:     case 'c': clear_dictionary = 1; break;
  842:     case 's': die_on_signal = 1; break;
  843:     case 'x': debug = 1; break;
  844:     case 'v': fprintf(stderr, "gforth %s\n", VERSION); exit(0);
  845:     case 'h': 
  846:       fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
  847: Engine Options:\n\
  848:   --appl-image FILE		    equivalent to '--image-file=FILE --'\n\
  849:   --clear-dictionary		    Initialize the dictionary with 0 bytes\n\
  850:   -d SIZE, --data-stack-size=SIZE   Specify data stack size\n\
  851:   --debug			    Print debugging information during startup\n\
  852:   --die-on-signal		    exit instead of CATCHing some signals\n\
  853:   --dynamic			    use dynamic native code\n\
  854:   -f SIZE, --fp-stack-size=SIZE	    Specify floating point stack size\n\
  855:   -h, --help			    Print this message and exit\n\
  856:   -i FILE, --image-file=FILE	    Use image FILE instead of `gforth.fi'\n\
  857:   -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
  858:   -m SIZE, --dictionary-size=SIZE   Specify Forth dictionary size\n\
  859:   --no-dynamic			    Use only statically compiled primitives\n\
  860:   --no-offset-im		    Load image at normal position\n\
  861:   --no-super                        No dynamically formed superinstructions\n\
  862:   --offset-image		    Load image at a different position\n\
  863:   -p PATH, --path=PATH		    Search path for finding image and sources\n\
  864:   -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
  865:   -v, --version			    Print engine version and exit\n\
  866: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
  867:   `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
  868: 	      argv[0]);
  869:       optind--;
  870:       return;
  871:     }
  872:   }
  873: }
  874: #endif
  875: 
  876: #ifdef INCLUDE_IMAGE
  877: extern Cell image[];
  878: extern const char reloc_bits[];
  879: #endif
  880: 
  881: DCell double2ll(Float r)
  882: {
  883: #ifndef BUGGY_LONG_LONG
  884:   return (DCell)(r);
  885: #else
  886:   DCell d;
  887:   d.hi = ldexp(r,-(int)(CELL_BITS)) - (r<0);
  888:   d.lo = r-ldexp((Float)d.hi,CELL_BITS);
  889:   return d;
  890: #endif
  891: }
  892: 
  893: int main(int argc, char **argv, char **env)
  894: {
  895: #ifdef HAS_OS
  896:   char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
  897: #else
  898:   char *path = DEFAULTPATH;
  899: #endif
  900: #ifndef INCLUDE_IMAGE
  901:   char *imagename="gforth.fi";
  902:   FILE *image_file;
  903:   Address image;
  904: #endif
  905:   int retvalue;
  906: 	  
  907: #if defined(i386) && defined(ALIGNMENT_CHECK)
  908:   /* turn on alignment checks on the 486.
  909:    * on the 386 this should have no effect. */
  910:   __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
  911:   /* this is unusable with Linux' libc.4.6.27, because this library is
  912:      not alignment-clean; we would have to replace some library
  913:      functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
  914:      the stack FP-aligned. */
  915: #endif
  916: 
  917:   /* buffering of the user output device */
  918: #ifdef _IONBF
  919:   if (isatty(fileno(stdout))) {
  920:     fflush(stdout);
  921:     setvbuf(stdout,NULL,_IONBF,0);
  922:   }
  923: #endif
  924: 
  925:   progname = argv[0];
  926: 
  927: #ifdef HAS_OS
  928:   gforth_args(argc, argv, &path, &imagename);
  929: #endif
  930: 
  931: #ifdef INCLUDE_IMAGE
  932:   set_stack_sizes((ImageHeader *)image);
  933:   if(((ImageHeader *)image)->base != image)
  934:     relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
  935: 	     (Label*)engine(0, 0, 0, 0, 0));
  936:   alloc_stacks((ImageHeader *)image);
  937: #else
  938:   image_file = open_image_file(imagename, path);
  939:   image = loader(image_file, imagename);
  940: #endif
  941:   gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
  942: 
  943:   {
  944:     char path2[strlen(path)+1];
  945:     char *p1, *p2;
  946:     Cell environ[]= {
  947:       (Cell)argc-(optind-1),
  948:       (Cell)(argv+(optind-1)),
  949:       (Cell)strlen(path),
  950:       (Cell)path2};
  951:     argv[optind-1] = progname;
  952:     /*
  953:        for (i=0; i<environ[0]; i++)
  954:        printf("%s\n", ((char **)(environ[1]))[i]);
  955:        */
  956:     /* make path OS-independent by replacing path separators with NUL */
  957:     for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
  958:       if (*p1==PATHSEP)
  959: 	*p2 = '\0';
  960:       else
  961: 	*p2 = *p1;
  962:     *p2='\0';
  963:     retvalue = go_forth(image, 4, environ);
  964: #ifdef VM_PROFILING
  965:     vm_print_profile(stderr);
  966: #endif
  967:     deprep_terminal();
  968:   }
  969:   return retvalue;
  970: }

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