Annotation of gforth/engine/main.c, revision 1.2
1.1 anton 1: /* command line interpretation, image loading etc. for Gforth
2:
3:
4: Copyright (C) 1995 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., 675 Mass Ave, Cambridge, MA 02139, USA.
21: */
22:
23: #include "config.h"
24: #include <errno.h>
25: #include <ctype.h>
26: #include <stdio.h>
1.2 ! pazsan 27: #include <unistd.h>
1.1 anton 28: #include <string.h>
29: #include <math.h>
30: #include <sys/types.h>
31: #include <sys/stat.h>
32: #include <fcntl.h>
33: #include <assert.h>
34: #include <stdlib.h>
35: #if HAVE_SYS_MMAN_H
36: #include <sys/mman.h>
37: #endif
38: #include "forth.h"
39: #include "io.h"
40: #include "getopt.h"
41: #include "version.h"
42:
43: #define PRIM_VERSION 1
44: /* increment this whenever the primitives change in an incompatible way */
45:
46: #ifdef MSDOS
47: jmp_buf throw_jmp_buf;
48: # ifndef DEFAULTPATH
49: # define DEFAULTPATH "."
50: # endif
51: #endif
52:
53: #if defined(DIRECT_THREADED)
54: # define CA(n) (symbols[(n)])
55: #else
56: # define CA(n) ((Cell)(symbols+(n)))
57: #endif
58:
59: #define maxaligned(n) (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
60:
61: static UCell dictsize=0;
62: static UCell dsize=0;
63: static UCell rsize=0;
64: static UCell fsize=0;
65: static UCell lsize=0;
66: int offset_image=0;
67: static int clear_dictionary=0;
68: static int debug=0;
69: static size_t pagesize=0;
70: char *progname;
71:
72: /* image file format:
73: * "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.3.0 -i\n")
74: * padding to a multiple of 8
75: * magic: "Gforth1x" means format 0.2,
76: * where x is even for big endian and odd for little endian
77: * and x & ~1 is the size of the cell in bytes.
78: * padding to max alignment (no padding necessary on current machines)
79: * ImageHeader structure (see below)
80: * data (size in ImageHeader.image_size)
81: * tags ((if relocatable, 1 bit/data cell)
82: *
83: * tag==1 means that the corresponding word is an address;
84: * If the word is >=0, the address is within the image;
85: * addresses within the image are given relative to the start of the image.
86: * If the word =-1 (CF_NIL), the address is NIL,
87: * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
88: * If the word =CF(DODOES), it's a DOES> CFA
89: * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
90: * possibly containing a jump to dodoes)
91: * If the word is <CF(DOESJUMP), it's a primitive
92: */
93:
94: typedef struct {
95: Address base; /* base address of image (0 if relocatable) */
96: UCell checksum; /* checksum of ca's to protect against some
97: incompatible binary/executable combinations
98: (0 if relocatable) */
99: UCell image_size; /* all sizes in bytes */
100: UCell dict_size;
101: UCell data_stack_size;
102: UCell fp_stack_size;
103: UCell return_stack_size;
104: UCell locals_stack_size;
105: Xt *boot_entry; /* initial ip for booting (in BOOT) */
106: Xt *throw_entry; /* ip after signal (in THROW) */
107: Cell unused1; /* possibly tib stack size */
108: Cell unused2;
109: Address data_stack_base; /* this and the following fields are initialized by the loader */
110: Address fp_stack_base;
111: Address return_stack_base;
112: Address locals_stack_base;
113: } ImageHeader;
114: /* the image-header is created in main.fs */
115:
116: void relocate(Cell *image, char *bitstring, int size, Label symbols[])
117: {
118: int i=0, j, k, steps=(size/sizeof(Cell))/8;
119: char bits;
120: /* static char bits[8]={0x80,0x40,0x20,0x10,0x08,0x04,0x02,0x01};*/
121:
122: /* printf("relocating %x[%x]\n", image, size); */
123:
124: for(k=0; k<=steps; k++)
125: for(j=0, bits=bitstring[k]; j<8; j++, i++, bits<<=1) {
126: /* fprintf(stderr,"relocate: image[%d]\n", i);*/
127: if(bits & 0x80) {
128: /* fprintf(stderr,"relocate: image[%d]=%d\n", i, image[i]);*/
129: if(image[i]<0)
130: switch(image[i])
131: {
132: case CF_NIL : image[i]=0; break;
133: #if !defined(DOUBLY_INDIRECT)
134: case CF(DOCOL) :
135: case CF(DOVAR) :
136: case CF(DOCON) :
137: case CF(DOUSER) :
138: case CF(DODEFER) :
139: case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(image[i])]); break;
140: case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
141: #endif /* !defined(DOUBLY_INDIRECT) */
142: case CF(DODOES) :
143: MAKE_DOES_CF(image+i,image[i+1]+((Cell)image));
144: break;
145: default :
146: /* printf("Code field generation image[%x]:=CA(%x)\n",
147: i, CF(image[i])); */
148: image[i]=(Cell)CA(CF(image[i]));
149: }
150: else
151: image[i]+=(Cell)image;
152: }
153: }
154: }
155:
156: UCell checksum(Label symbols[])
157: {
158: UCell r=PRIM_VERSION;
159: Cell i;
160:
161: for (i=DOCOL; i<=DOESJUMP; i++) {
162: r ^= (UCell)(symbols[i]);
163: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
164: }
165: #ifdef DIRECT_THREADED
166: /* we have to consider all the primitives */
167: for (; symbols[i]!=(Label)0; i++) {
168: r ^= (UCell)(symbols[i]);
169: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
170: }
171: #else
172: /* in indirect threaded code all primitives are accessed through the
173: symbols table, so we just have to put the base address of symbols
174: in the checksum */
175: r ^= (UCell)symbols;
176: #endif
177: return r;
178: }
179:
180: Address my_alloc(Cell size)
181: {
182: static Address next_address=0;
183: Address r;
184:
185: /* the 256MB jump restriction on the MIPS architecture makes the
186: combination of direct threading and mmap unsafe. */
187: #if HAVE_MMAP && (!defined(mips) || defined(INDIRECT_THREADED))
188: #if defined(MAP_ANON)
189: if (debug)
190: fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
191: r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
192: #else /* !defined(MAP_ANON) */
193: /* Ultrix (at least does not define MAP_FILE and MAP_PRIVATE (both are
194: apparently defaults*/
195: #ifndef MAP_FILE
196: # define MAP_FILE 0
197: #endif
198: #ifndef MAP_PRIVATE
199: # define MAP_PRIVATE 0
200: #endif
201: static int dev_zero=-1;
202:
203: if (dev_zero == -1)
204: dev_zero = open("/dev/zero", O_RDONLY);
205: if (dev_zero == -1) {
206: r = (Address)-1;
207: if (debug)
208: fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ",
209: strerror(errno));
210: } else {
211: if (debug)
212: fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
213: r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
214: }
215: #endif /* !defined(MAP_ANON) */
216:
217: if (r != (Address)-1) {
218: if (debug)
219: fprintf(stderr, "success, address=$%lx\n", (long) r);
220: if (pagesize != 0)
221: next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
222: return r;
223: }
224: if (debug)
225: fprintf(stderr, "failed: %s\n", strerror(errno));
226: #endif /* HAVE_MMAP */
227: /* use malloc as fallback, leave a little room (64B) for stack underflows */
228: if ((r = malloc(size+64))==NULL) {
229: perror(progname);
230: exit(1);
231: }
232: r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
233: if (debug)
234: fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
235: return r;
236: }
237:
238: Address loader(FILE *imagefile, char* filename)
239: /* returns the address of the image proper (after the preamble) */
240: {
241: ImageHeader header;
242: Address image;
243: Address imp; /* image+preamble */
244: Char magic[9];
245: Cell preamblesize=0;
246: Label *symbols = engine(0,0,0,0,0);
247: Cell data_offset = offset_image ? 28*sizeof(Cell) : 0;
248: UCell check_sum;
249: static char* endianstring[]= { "big","little" };
250:
251: #ifndef DOUBLY_INDIRECT
252: check_sum = checksum(symbols);
253: #else /* defined(DOUBLY_INDIRECT) */
254: check_sum = (UCell)symbols;
255: #endif /* defined(DOUBLY_INDIRECT) */
256:
257: do
258: {
259: if(fread(magic,sizeof(Char),8,imagefile) < 8) {
260: fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.2) image.\n",
261: progname, filename);
262: exit(1);
263: }
264: preamblesize+=8;
265: }
266: while(memcmp(magic,"Gforth1",7));
267: if (debug) {
268: magic[8]='\0';
269: fprintf(stderr,"Magic found: %s\n", magic);
270: }
271:
272: if(magic[7] != sizeof(Cell) +
273: #ifdef WORDS_BIGENDIAN
274: '0'
275: #else
276: '1'
277: #endif
278: )
279: { fprintf(stderr,"This image is %d bit %s-endian, whereas the machine is %d bit %s-endian.\n",
280: ((magic[7]-'0')&~1)*8, endianstring[magic[7]&1],
281: sizeof(Cell)*8, endianstring[
282: #ifdef WORDS_BIGENDIAN
283: 0
284: #else
285: 1
286: #endif
287: ]);
288: exit(-2);
289: };
290:
291: fread((void *)&header,sizeof(ImageHeader),1,imagefile);
292: if (dictsize==0)
293: dictsize = header.dict_size;
294: if (dsize==0)
295: dsize=header.data_stack_size;
296: if (rsize==0)
297: rsize=header.return_stack_size;
298: if (fsize==0)
299: fsize=header.fp_stack_size;
300: if (lsize==0)
301: lsize=header.locals_stack_size;
302: dictsize=maxaligned(dictsize);
303: dsize=maxaligned(dsize);
304: rsize=maxaligned(rsize);
305: lsize=maxaligned(lsize);
306: fsize=maxaligned(fsize);
307:
308: #if HAVE_GETPAGESIZE
309: pagesize=getpagesize(); /* Linux/GNU libc offers this */
310: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
311: pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
312: #elif PAGESIZE
313: pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
314: #endif
315: if (debug)
316: fprintf(stderr,"pagesize=%d\n",pagesize);
317:
318: image = my_alloc(preamblesize+dictsize+data_offset)+data_offset;
319: rewind(imagefile); /* fseek(imagefile,0L,SEEK_SET); */
320: if (clear_dictionary)
321: memset(image,0,dictsize);
322: fread(image,1,preamblesize+header.image_size,imagefile);
323: imp=image+preamblesize;
324: if(header.base==0) {
325: Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
326: char reloc_bits[reloc_size];
327: fread(reloc_bits,1,reloc_size,imagefile);
328: relocate((Cell *)imp,reloc_bits,header.image_size,symbols);
329: #if 0
330: { /* let's see what the relocator did */
331: FILE *snapshot=fopen("snapshot.fi","wb");
332: fwrite(image,1,imagesize,snapshot);
333: fclose(snapshot);
334: }
335: #endif
336: }
337: else if(header.base!=imp) {
338: fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
339: progname, (unsigned long)header.base, (unsigned long)imp);
340: exit(1);
341: }
342: if (header.checksum==0)
343: ((ImageHeader *)imp)->checksum=check_sum;
344: else if (header.checksum != check_sum) {
345: fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
346: progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
347: exit(1);
348: }
349: fclose(imagefile);
350:
351: ((ImageHeader *)imp)->dict_size=dictsize;
352: ((ImageHeader *)imp)->data_stack_size=dsize;
353: ((ImageHeader *)imp)->fp_stack_size=fsize;
354: ((ImageHeader *)imp)->return_stack_size=rsize;
355: ((ImageHeader *)imp)->locals_stack_size=lsize;
356:
357: ((ImageHeader *)imp)->data_stack_base=my_alloc(dsize);
358: ((ImageHeader *)imp)->fp_stack_base=my_alloc(fsize);
359: ((ImageHeader *)imp)->return_stack_base=my_alloc(rsize);
360: ((ImageHeader *)imp)->locals_stack_base=my_alloc(lsize);
361:
362: CACHE_FLUSH(imp, header.image_size);
363:
364: return imp;
365: }
366:
367: int go_forth(Address image, int stack, Cell *entries)
368: {
369: Cell *sp=(Cell*)(((ImageHeader *)image)->data_stack_base + dsize);
370: Float *fp=(Float *)(((ImageHeader *)image)->fp_stack_base + fsize);
371: Cell *rp=(Cell *)(((ImageHeader *)image)->return_stack_base + rsize);
372: Address lp=((ImageHeader *)image)->locals_stack_base + lsize;
373: Xt *ip=(Xt *)(((ImageHeader *)image)->boot_entry);
374: int throw_code;
375:
376: /* ensure that the cached elements (if any) are accessible */
377: IF_TOS(sp--);
378: IF_FTOS(fp--);
379:
380: for(;stack>0;stack--)
381: *--sp=entries[stack-1];
382:
383: #if !defined(MSDOS) && !defined(_WIN32) && !defined(__EMX__)
384: get_winsize();
385: #endif
386:
387: install_signal_handlers(); /* right place? */
388:
389: if ((throw_code=setjmp(throw_jmp_buf))) {
390: static Cell signal_data_stack[8];
391: static Cell signal_return_stack[8];
392: static Float signal_fp_stack[1];
393:
394: signal_data_stack[7]=throw_code;
395:
396: return((int)engine(((ImageHeader *)image)->throw_entry,signal_data_stack+7,
397: signal_return_stack+8,signal_fp_stack,0));
398: }
399:
400: return((int)engine(ip,sp,rp,fp,lp));
401: }
402:
403: UCell convsize(char *s, UCell elemsize)
1.2 ! pazsan 404: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
1.1 anton 405: of bytes. the letter at the end indicates the unit, where e stands
406: for the element size. default is e */
407: {
408: char *endp;
409: UCell n,m;
410:
411: m = elemsize;
412: n = strtoul(s,&endp,0);
413: if (endp!=NULL) {
414: if (strcmp(endp,"b")==0)
415: m=1;
416: else if (strcmp(endp,"k")==0)
417: m=1024;
418: else if (strcmp(endp,"M")==0)
419: m=1024*1024;
1.2 ! pazsan 420: else if (strcmp(endp,"G")==0)
! 421: m=1024*1024*1024;
! 422: #if (SIZEOF_CHAR_P > 4)
! 423: else if (strcmp(endp,"T")==0)
! 424: m=1024*1024*1024*1024;
! 425: #endif
1.1 anton 426: else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
427: fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
428: exit(1);
429: }
430: }
431: return n*m;
432: }
433:
434: int onlypath(char *file)
435: { int i;
436: i=strlen(file);
437: while (i) { if (file[i]=='\\' || file[i]=='/') break;
438: i--; }
439: return (i);
440: }
441:
442: FILE *openimage(char *fullfilename)
443: { FILE *image_file;
444: image_file=fopen(fullfilename,"rb");
445: if (image_file!=NULL && debug)
446: fprintf(stderr, "Opened image file: %s\n", fullfilename);
447: return (image_file);
448: }
449:
450: FILE *checkimage(char *path, int len, char *imagename)
451: { int dirlen=len;
452: char fullfilename[dirlen+strlen(imagename)+2];
453: memcpy(fullfilename, path, dirlen);
454: if (fullfilename[dirlen-1]!='/')
455: fullfilename[dirlen++]='/';
456: strcpy(fullfilename+dirlen,imagename);
457: return (openimage(fullfilename));
458: }
459:
460: int main(int argc, char **argv, char **env)
461: {
462: char *path, *path1;
463: char *imagename="gforth.fi";
464: FILE *image_file;
465: int c, retvalue;
466:
467: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
468: /* turn on alignment checks on the 486.
469: * on the 386 this should have no effect. */
470: __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
471: /* this is unusable with Linux' libc.4.6.27, because this library is
472: not alignment-clean; we would have to replace some library
473: functions (e.g., memcpy) to make it work */
474: #endif
475:
476: progname = argv[0];
477: if ((path1=getenv("GFORTHPATH"))==NULL)
478: path1 = DEFAULTPATH;
479:
480: opterr=0;
481: while (1) {
482: int option_index=0;
483: static struct option opts[] = {
484: {"image-file", required_argument, NULL, 'i'},
485: {"dictionary-size", required_argument, NULL, 'm'},
486: {"data-stack-size", required_argument, NULL, 'd'},
487: {"return-stack-size", required_argument, NULL, 'r'},
488: {"fp-stack-size", required_argument, NULL, 'f'},
489: {"locals-stack-size", required_argument, NULL, 'l'},
490: {"path", required_argument, NULL, 'p'},
491: {"version", no_argument, NULL, 'v'},
492: {"help", no_argument, NULL, 'h'},
493: /* put something != 0 into offset_image */
494: {"offset-image", no_argument, &offset_image, 1},
495: {"no-offset-im", no_argument, &offset_image, 0},
496: {"clear-dictionary", no_argument, &clear_dictionary, 1},
497: {"debug", no_argument, &debug, 1},
498: {0,0,0,0}
499: /* no-init-file, no-rc? */
500: };
501:
502: c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vh", opts, &option_index);
503:
504: if (c==EOF)
505: break;
506: if (c=='?') {
507: optind--;
508: break;
509: }
510: switch (c) {
511: case 'i': imagename = optarg; break;
512: case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
513: case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
514: case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
515: case 'f': fsize = convsize(optarg,sizeof(Float)); break;
516: case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
517: case 'p': path1 = optarg; break;
518: case 'v': fprintf(stderr, "gforth %s\n", gforth_version); exit(0);
519: case 'h':
520: fprintf(stderr, "Usage: %s [engine options] [image arguments]\n\
521: Engine Options:\n\
522: -c, --clear-dictionary Initialize the dictionary with 0 bytes\n\
523: -d SIZE, --data-stack-size=SIZE Specify data stack size\n\
524: --debug Print debugging information during startup\n\
525: -f SIZE, --fp-stack-size=SIZE Specify floating point stack size\n\
526: -h, --help Print this message and exit\n\
527: -i FILE, --image-file=FILE Use image FILE instead of `gforth.fi'\n\
528: -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
529: -m SIZE, --dictionary-size=SIZE Specify Forth dictionary size\n\
530: --offset-image Load image at a different position\n\
531: -p PATH, --path=PATH Search path for finding image and sources\n\
532: -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
533: -v, --version Print version and exit\n\
534: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
535: `b' (bytes), `e' (elements), `k' (kilobytes), or `M' (Megabytes).\n\
536: \n\
537: Arguments of default image `gforth.fi':\n\
538: FILE load FILE (with `require')\n\
539: -e STRING, --evaluate STRING interpret STRING (with `EVALUATE')\n",
540: argv[0]); exit(0);
541: }
542: }
543: path=path1;
544: image_file=NULL;
545:
546: if(strchr(imagename, '/')==NULL)
547: {
548: /* first check the directory where the exe file is in !! 01may97jaw */
549: if (onlypath(progname))
550: image_file=checkimage(progname, onlypath(progname), imagename);
551: if (!image_file)
552: do {
553: char *pend=strchr(path, PATHSEP);
554: if (pend==NULL)
555: pend=path+strlen(path);
556: if (strlen(path)==0) break;
557: image_file=checkimage(path, pend-path, imagename);
558: path=pend+(*pend==PATHSEP);
559: } while (image_file==NULL);
560: }
561: else
562: { image_file=openimage(imagename);
563: }
564:
565: if (!image_file)
566: { fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
567: progname, imagename, path1);
568: exit(1);
569: }
570:
571: {
572: char path2[strlen(path1)+1];
573: char *p1, *p2;
574: Cell environ[]= {
575: (Cell)argc-(optind-1),
576: (Cell)(argv+(optind-1)),
577: (Cell)strlen(path1),
578: (Cell)path2};
579: argv[optind-1] = progname;
580: /*
581: for (i=0; i<environ[0]; i++)
582: printf("%s\n", ((char **)(environ[1]))[i]);
583: */
584: /* make path OS-independent by replacing path separators with NUL */
585: for (p1=path1, p2=path2; *p1!='\0'; p1++, p2++)
586: if (*p1==PATHSEP)
587: *p2 = '\0';
588: else
589: *p2 = *p1;
590: *p2='\0';
591: retvalue=go_forth(loader(image_file, imagename),4,environ);
592: deprep_terminal();
593: exit(retvalue);
594: }
595: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>