File:
[gforth] /
gforth /
Attic /
main.c
Revision
1.49:
download - view:
text,
annotated -
select for diffs
Sat Dec 28 17:19:25 1996 UTC (27 years, 4 months ago) by
anton
Branches:
MAIN
CVS tags:
HEAD
use mmap for allocating the dictionary and the stacks on some systems
added installdirs target to Makefile.in.
Use mkinstalldirs instead of install-sh -d.
added version-stamp to avoid recompiling everything after changing Makefile.in.
mostly fixed the maiming of words containing '/' in TAGS
added options --clear-dictionary and --debug.
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>
27: #include <string.h>
28: #include <math.h>
29: #include <sys/types.h>
30: #include <sys/stat.h>
31: #include <fcntl.h>
32: #include <assert.h>
33: #include <stdlib.h>
34: #if HAVE_SYS_MMAN_H
35: #include <sys/mman.h>
36: #endif
37: #include "forth.h"
38: #include "io.h"
39: #include "getopt.h"
40: #include "version.h"
41:
42: #ifdef MSDOS
43: jmp_buf throw_jmp_buf;
44: #endif
45:
46: /* Define FUZZ for better image positioning */
47: #define FUZZ 0x4000
48:
49: #ifndef DEFAULTPATH
50: # define DEFAULTPATH "/usr/local/lib/gforth:."
51: #endif
52:
53: #ifdef 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 Cell dictsize=0;
62: static Cell dsize=0;
63: static Cell rsize=0;
64: static Cell fsize=0;
65: static Cell lsize=0;
66: static int image_offset=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.2.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: if(bits & 0x80)
127: if(image[i]<0)
128: switch(image[i])
129: {
130: case CF_NIL : image[i]=0; break;
131: case CF(DOCOL) :
132: case CF(DOVAR) :
133: case CF(DOCON) :
134: case CF(DOUSER) :
135: case CF(DODEFER) :
136: case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(image[i])]); break;
137: case CF(DODOES) : MAKE_DOES_CF(image+i,image[i+1]+((Cell)image));
138: break;
139: case CF(DOESJUMP): MAKE_DOES_HANDLER(image+i); break;
140: default :
141: /* printf("Code field generation image[%x]:=CA(%x)\n",
142: i, CF(image[i]));
143: */ image[i]=(Cell)CA(CF(image[i]));
144: }
145: else
146: image[i]+=(Cell)image;
147: }
148:
149: UCell checksum(Label symbols[])
150: {
151: UCell r=0;
152: Cell i;
153:
154: for (i=DOCOL; i<=DOESJUMP; i++) {
155: r ^= (UCell)(symbols[i]);
156: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
157: }
158: #ifdef DIRECT_THREADED
159: /* we have to consider all the primitives */
160: for (; symbols[i]!=(Label)0; i++) {
161: r ^= (UCell)(symbols[i]);
162: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
163: }
164: #else
165: /* in indirect threaded code all primitives are accessed through the
166: symbols table, so we just have to put the base address of symbols
167: in the checksum */
168: r ^= (UCell)symbols;
169: #endif
170: return r;
171: }
172:
173: Address my_alloc(Cell size)
174: {
175: static Address next_address=0;
176: Address r;
177:
178: #if HAVE_MMAP && defined(MAP_ANON)
179: if (debug)
180: fprintf(stderr,"try mmap($%lx, $%lx, ...); ", (long)next_address, (long)size);
181: r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
182: if (r != (Address)-1) {
183: if (debug)
184: fprintf(stderr, "success, address=$%lx\n", (long) r);
185: if (pagesize != 0)
186: next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
187: return r;
188: }
189: if (debug)
190: fprintf(stderr, "failed: %s\n", strerror(errno));
191: #endif
192: /* use malloc as fallback, leave a little room (64B) for stack underflows */
193: if ((r = malloc(size+64))==NULL) {
194: perror(progname);
195: exit(1);
196: }
197: if (debug)
198: fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
199: return r;
200: }
201:
202: Address loader(FILE *imagefile, char* filename)
203: /* returns the address of the image proper (after the preamble) */
204: {
205: ImageHeader header;
206: Address image;
207: Address imp; /* image+preamble */
208: Char magic[8];
209: Cell preamblesize=0;
210: Label *symbols=engine(0,0,0,0,0);
211: UCell check_sum=checksum(symbols);
212:
213: static char* endianstring[]= { "big","little" };
214:
215: do
216: {
217: if(fread(magic,sizeof(Char),8,imagefile) < 8) {
218: fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.2) image.\n",
219: progname, filename);
220: exit(1);
221: }
222: preamblesize+=8;
223: }
224: while(memcmp(magic,"Gforth1",7));
225: if (debug)
226: fprintf(stderr,"Magic found: %-8s\n",magic);
227:
228: if(magic[7] != sizeof(Cell) +
229: #ifdef WORDS_BIGENDIAN
230: '0'
231: #else
232: '1'
233: #endif
234: )
235: { fprintf(stderr,"This image is %d bit %s-endian, whereas the machine is %d bit %s-endian.\n",
236: ((magic[7]-'0')&~1)*8, endianstring[magic[7]&1],
237: sizeof(Cell)*8, endianstring[
238: #ifdef WORDS_BIGENDIAN
239: 0
240: #else
241: 1
242: #endif
243: ]);
244: exit(-2);
245: };
246:
247: fread((void *)&header,sizeof(ImageHeader),1,imagefile);
248: if (dictsize==0)
249: dictsize = header.dict_size;
250: if (dsize==0)
251: dsize=header.data_stack_size;
252: if (rsize==0)
253: rsize=header.return_stack_size;
254: if (fsize==0)
255: fsize=header.fp_stack_size;
256: if (lsize==0)
257: lsize=header.locals_stack_size;
258: dictsize=maxaligned(dictsize);
259: dsize=maxaligned(dsize);
260: rsize=maxaligned(rsize);
261: lsize=maxaligned(lsize);
262: fsize=maxaligned(fsize);
263:
264: #if HAVE_GETPAGESIZE
265: pagesize=getpagesize(); /* Linux/GNU libc offers this */
266: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
267: pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
268: #elif PAGESIZE
269: pagesize=PAGESIZE; /* in limits.h accoring to Gallmeister's POSIX.4 book */
270: #endif
271: if (debug)
272: fprintf(stderr,"pagesize=%d\n",pagesize);
273:
274: image = my_alloc(preamblesize+dictsize+image_offset+FUZZ)+image_offset;
275: if(header.base==0)
276: image += FUZZ/2;
277: else
278: if((UCell)(header.base - (Cell)image + preamblesize) < FUZZ)
279: image = header.base - preamblesize;
280: rewind(imagefile); /* fseek(imagefile,0L,SEEK_SET); */
281: if (clear_dictionary)
282: memset(image,0,dictsize);
283: fread(image,1,preamblesize+header.image_size,imagefile);
284: imp=image+preamblesize;
285: if(header.base==0) {
286: Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
287: char reloc_bits[reloc_size];
288: fread(reloc_bits,1,reloc_size,imagefile);
289: relocate((Cell *)imp,reloc_bits,header.image_size,symbols);
290: #if 0
291: { /* let's see what the relocator did */
292: FILE *snapshot=fopen("snapshot.fi","wb");
293: fwrite(image,1,imagesize,snapshot);
294: fclose(snapshot);
295: }
296: #endif
297: }
298: else if(header.base!=imp) {
299: fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\nThe Gforth installer should look into the INSTALL file\n",
300: progname, (unsigned long)header.base, (unsigned long)imp);
301: exit(1);
302: }
303: if (header.checksum==0)
304: ((ImageHeader *)imp)->checksum=check_sum;
305: else if (header.checksum != check_sum) {
306: fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\nThe Gforth installer should look into the INSTALL file\n",
307: progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
308: exit(1);
309: }
310: fclose(imagefile);
311:
312: ((ImageHeader *)imp)->dict_size=dictsize;
313: ((ImageHeader *)imp)->data_stack_size=dsize;
314: ((ImageHeader *)imp)->fp_stack_size=fsize;
315: ((ImageHeader *)imp)->return_stack_size=rsize;
316: ((ImageHeader *)imp)->locals_stack_size=lsize;
317:
318: ((ImageHeader *)imp)->data_stack_base=my_alloc(dsize);
319: ((ImageHeader *)imp)->fp_stack_base=my_alloc(fsize);
320: ((ImageHeader *)imp)->return_stack_base=my_alloc(rsize);
321: ((ImageHeader *)imp)->locals_stack_base=my_alloc(lsize);
322:
323: CACHE_FLUSH(imp, header.image_size);
324:
325: return imp;
326: }
327:
328: int go_forth(Address image, int stack, Cell *entries)
329: {
330: Cell *sp=(Cell*)(((ImageHeader *)image)->data_stack_base + dsize);
331: Float *fp=(Float *)(((ImageHeader *)image)->fp_stack_base + fsize);
332: Cell *rp=(Cell *)(((ImageHeader *)image)->return_stack_base + rsize);
333: Address lp=((ImageHeader *)image)->locals_stack_base + lsize;
334: Xt *ip=(Xt *)(((ImageHeader *)image)->boot_entry);
335: int throw_code;
336:
337: /* ensure that the cached elements (if any) are accessible */
338: IF_TOS(sp--);
339: IF_FTOS(fp--);
340:
341: for(;stack>0;stack--)
342: *--sp=entries[stack-1];
343:
344: #if !defined(MSDOS) && !defined(_WIN32) && !defined(__EMX__)
345: get_winsize();
346: #endif
347:
348: install_signal_handlers(); /* right place? */
349:
350: if ((throw_code=setjmp(throw_jmp_buf))) {
351: static Cell signal_data_stack[8];
352: static Cell signal_return_stack[8];
353: static Float signal_fp_stack[1];
354:
355: signal_data_stack[7]=throw_code;
356:
357: return((int)engine(((ImageHeader *)image)->throw_entry,signal_data_stack+7,
358: signal_return_stack+8,signal_fp_stack,0));
359: }
360:
361: return((int)engine(ip,sp,rp,fp,lp));
362: }
363:
364: int convsize(char *s, int elemsize)
365: /* converts s of the format #+u (e.g. 25k) into the number of bytes.
366: the unit u can be one of bekM, where e stands for the element
367: size. default is e */
368: {
369: char *endp;
370: int n,m;
371:
372: m = elemsize;
373: n = strtoul(s,&endp,0);
374: if (endp!=NULL) {
375: if (strcmp(endp,"b")==0)
376: m=1;
377: else if (strcmp(endp,"k")==0)
378: m=1024;
379: else if (strcmp(endp,"M")==0)
380: m=1024*1024;
381: else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
382: fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
383: exit(1);
384: }
385: }
386: return n*m;
387: }
388:
389: int main(int argc, char **argv, char **env)
390: {
391: char *path, *path1;
392: char *imagename="gforth.fi";
393: FILE *image_file;
394: int c, retvalue;
395:
396: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
397: /* turn on alignment checks on the 486.
398: * on the 386 this should have no effect. */
399: __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
400: /* this is unusable with Linux' libc.4.6.27, because this library is
401: not alignment-clean; we would have to replace some library
402: functions (e.g., memcpy) to make it work */
403: #endif
404:
405: progname = argv[0];
406: if ((path1=getenv("GFORTHPATH"))==NULL)
407: path1 = DEFAULTPATH;
408:
409: opterr=0;
410: while (1) {
411: int option_index=0;
412: static struct option opts[] = {
413: {"image-file", required_argument, NULL, 'i'},
414: {"dictionary-size", required_argument, NULL, 'm'},
415: {"data-stack-size", required_argument, NULL, 'd'},
416: {"return-stack-size", required_argument, NULL, 'r'},
417: {"fp-stack-size", required_argument, NULL, 'f'},
418: {"locals-stack-size", required_argument, NULL, 'l'},
419: {"path", required_argument, NULL, 'p'},
420: {"version", no_argument, NULL, 'v'},
421: {"help", no_argument, NULL, 'h'},
422: /* put something != 0 into image_offset; it should be a
423: not-too-large max-aligned number */
424: {"offset-image", no_argument, &image_offset, 28*sizeof(Cell)},
425: {"clear-dictionary", no_argument, &clear_dictionary, 1},
426: {"debug", no_argument, &debug, 1},
427: {0,0,0,0}
428: /* no-init-file, no-rc? */
429: };
430:
431: c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vh", opts, &option_index);
432:
433: if (c==EOF)
434: break;
435: if (c=='?') {
436: optind--;
437: break;
438: }
439: switch (c) {
440: case 'i': imagename = optarg; break;
441: case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
442: case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
443: case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
444: case 'f': fsize = convsize(optarg,sizeof(Float)); break;
445: case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
446: case 'p': path1 = optarg; break;
447: case 'v': fprintf(stderr, "gforth %s\n", gforth_version); exit(0);
448: case 'h':
449: fprintf(stderr, "Usage: %s [engine options] [image arguments]\n\
450: Engine Options:\n\
451: --clear-dictionary Initialize the dictionary with 0 bytes\n\
452: -d SIZE, --data-stack-size=SIZE Specify data stack size\n\
453: --debug Print debugging information during startup\n\
454: -f SIZE, --fp-stack-size=SIZE Specify floating point stack size\n\
455: -h, --help Print this message and exit\n\
456: -i FILE, --image-file=FILE Use image FILE instead of `gforth.fi'\n\
457: -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
458: -m SIZE, --dictionary-size=SIZE Specify Forth dictionary size\n\
459: --offset-image Load image at a different position\n\
460: -p PATH, --path=PATH Search path for finding image and sources\n\
461: -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
462: -v, --version Print version and exit\n\
463: SIZE arguments consists of an integer followed by a unit. The unit can be\n\
464: `b' (bytes), `e' (elements), `k' (kilobytes), or `M' (Megabytes).\n\
465: \n\
466: Arguments of default image `gforth.fi':\n\
467: FILE load FILE (with `require')\n\
468: -e STRING, --evaluate STRING interpret STRING (with `EVALUATE')\n",
469: argv[0]); exit(0);
470: }
471: }
472: path=path1;
473:
474: if(strchr(imagename, '/')==NULL)
475: {
476: do {
477: char *pend=strchr(path, PATHSEP);
478: if (pend==NULL)
479: pend=path+strlen(path);
480: if (strlen(path)==0) {
481: fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
482: progname, imagename, path1);
483: exit(1);
484: }
485: {
486: int dirlen=pend-path;
487: char fullfilename[dirlen+strlen(imagename)+2];
488: memcpy(fullfilename, path, dirlen);
489: if (fullfilename[dirlen-1]!='/')
490: fullfilename[dirlen++]='/';
491: strcpy(fullfilename+dirlen,imagename);
492: image_file=fopen(fullfilename,"rb");
493: }
494: path=pend+(*pend==PATHSEP);
495: } while (image_file==NULL);
496: }
497: else
498: {
499: image_file=fopen(imagename,"rb");
500: }
501:
502: {
503: char path2[strlen(path1)+1];
504: char *p1, *p2;
505: Cell environ[]= {
506: (Cell)argc-(optind-1),
507: (Cell)(argv+(optind-1)),
508: (Cell)strlen(path1),
509: (Cell)path2};
510: argv[optind-1] = progname;
511: /*
512: for (i=0; i<environ[0]; i++)
513: printf("%s\n", ((char **)(environ[1]))[i]);
514: */
515: /* make path OS-independent by replacing path separators with NUL */
516: for (p1=path1, p2=path2; *p1!='\0'; p1++, p2++)
517: if (*p1==PATHSEP)
518: *p2 = '\0';
519: else
520: *p2 = *p1;
521: *p2='\0';
522: retvalue=go_forth(loader(image_file, imagename),4,environ);
523: deprep_terminal();
524: exit(retvalue);
525: }
526: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>