File:
[gforth] /
gforth /
Attic /
main.c
Revision
1.52:
download - view:
text,
annotated -
select for diffs
Tue Jan 14 16:30:51 1997 UTC (27 years, 3 months ago) by
anton
Branches:
MAIN
CVS tags:
HEAD
added PRIM_VERSION to primitives checksum computation.
added and documented environmental queries return-stack-cells,
stack-cells, and floating-stack.
fixed make test for 64-bit machines.
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: #define PRIM_VERSION 1
43: /* increment this whenever the primitives change in an incompatible way */
44:
45: #ifdef MSDOS
46: jmp_buf throw_jmp_buf;
47: #endif
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 UCell dictsize=0;
62: static UCell dsize=0;
63: static UCell rsize=0;
64: static UCell fsize=0;
65: static UCell 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=PRIM_VERSION;
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)+image_offset;
275: rewind(imagefile); /* fseek(imagefile,0L,SEEK_SET); */
276: if (clear_dictionary)
277: memset(image,0,dictsize);
278: fread(image,1,preamblesize+header.image_size,imagefile);
279: imp=image+preamblesize;
280: if(header.base==0) {
281: Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
282: char reloc_bits[reloc_size];
283: fread(reloc_bits,1,reloc_size,imagefile);
284: relocate((Cell *)imp,reloc_bits,header.image_size,symbols);
285: #if 0
286: { /* let's see what the relocator did */
287: FILE *snapshot=fopen("snapshot.fi","wb");
288: fwrite(image,1,imagesize,snapshot);
289: fclose(snapshot);
290: }
291: #endif
292: }
293: else if(header.base!=imp) {
294: fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
295: progname, (unsigned long)header.base, (unsigned long)imp);
296: exit(1);
297: }
298: if (header.checksum==0)
299: ((ImageHeader *)imp)->checksum=check_sum;
300: else if (header.checksum != check_sum) {
301: fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\nThe Gforth installer should look into the INSTALL file\n",
302: progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
303: exit(1);
304: }
305: fclose(imagefile);
306:
307: ((ImageHeader *)imp)->dict_size=dictsize;
308: ((ImageHeader *)imp)->data_stack_size=dsize;
309: ((ImageHeader *)imp)->fp_stack_size=fsize;
310: ((ImageHeader *)imp)->return_stack_size=rsize;
311: ((ImageHeader *)imp)->locals_stack_size=lsize;
312:
313: ((ImageHeader *)imp)->data_stack_base=my_alloc(dsize);
314: ((ImageHeader *)imp)->fp_stack_base=my_alloc(fsize);
315: ((ImageHeader *)imp)->return_stack_base=my_alloc(rsize);
316: ((ImageHeader *)imp)->locals_stack_base=my_alloc(lsize);
317:
318: CACHE_FLUSH(imp, header.image_size);
319:
320: return imp;
321: }
322:
323: int go_forth(Address image, int stack, Cell *entries)
324: {
325: Cell *sp=(Cell*)(((ImageHeader *)image)->data_stack_base + dsize);
326: Float *fp=(Float *)(((ImageHeader *)image)->fp_stack_base + fsize);
327: Cell *rp=(Cell *)(((ImageHeader *)image)->return_stack_base + rsize);
328: Address lp=((ImageHeader *)image)->locals_stack_base + lsize;
329: Xt *ip=(Xt *)(((ImageHeader *)image)->boot_entry);
330: int throw_code;
331:
332: /* ensure that the cached elements (if any) are accessible */
333: IF_TOS(sp--);
334: IF_FTOS(fp--);
335:
336: for(;stack>0;stack--)
337: *--sp=entries[stack-1];
338:
339: #if !defined(MSDOS) && !defined(_WIN32) && !defined(__EMX__)
340: get_winsize();
341: #endif
342:
343: install_signal_handlers(); /* right place? */
344:
345: if ((throw_code=setjmp(throw_jmp_buf))) {
346: static Cell signal_data_stack[8];
347: static Cell signal_return_stack[8];
348: static Float signal_fp_stack[1];
349:
350: signal_data_stack[7]=throw_code;
351:
352: return((int)engine(((ImageHeader *)image)->throw_entry,signal_data_stack+7,
353: signal_return_stack+8,signal_fp_stack,0));
354: }
355:
356: return((int)engine(ip,sp,rp,fp,lp));
357: }
358:
359: UCell convsize(char *s, UCell elemsize)
360: /* converts s of the format #+u (e.g. 25k) into the number of bytes.
361: the unit u can be one of bekM, where e stands for the element
362: size. default is e */
363: {
364: char *endp;
365: UCell n,m;
366:
367: m = elemsize;
368: n = strtoul(s,&endp,0);
369: if (endp!=NULL) {
370: if (strcmp(endp,"b")==0)
371: m=1;
372: else if (strcmp(endp,"k")==0)
373: m=1024;
374: else if (strcmp(endp,"M")==0)
375: m=1024*1024;
376: else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
377: fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
378: exit(1);
379: }
380: }
381: return n*m;
382: }
383:
384: int main(int argc, char **argv, char **env)
385: {
386: char *path, *path1;
387: char *imagename="gforth.fi";
388: FILE *image_file;
389: int c, retvalue;
390:
391: #if defined(i386) && defined(ALIGNMENT_CHECK) && !defined(DIRECT_THREADED)
392: /* turn on alignment checks on the 486.
393: * on the 386 this should have no effect. */
394: __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
395: /* this is unusable with Linux' libc.4.6.27, because this library is
396: not alignment-clean; we would have to replace some library
397: functions (e.g., memcpy) to make it work */
398: #endif
399:
400: progname = argv[0];
401: if ((path1=getenv("GFORTHPATH"))==NULL)
402: path1 = DEFAULTPATH;
403:
404: opterr=0;
405: while (1) {
406: int option_index=0;
407: static struct option opts[] = {
408: {"image-file", required_argument, NULL, 'i'},
409: {"dictionary-size", required_argument, NULL, 'm'},
410: {"data-stack-size", required_argument, NULL, 'd'},
411: {"return-stack-size", required_argument, NULL, 'r'},
412: {"fp-stack-size", required_argument, NULL, 'f'},
413: {"locals-stack-size", required_argument, NULL, 'l'},
414: {"path", required_argument, NULL, 'p'},
415: {"version", no_argument, NULL, 'v'},
416: {"help", no_argument, NULL, 'h'},
417: /* put something != 0 into image_offset; it should be a
418: not-too-large max-aligned number */
419: {"offset-image", no_argument, &image_offset, 28*sizeof(Cell)},
420: {"clear-dictionary", no_argument, &clear_dictionary, 1},
421: {"debug", no_argument, &debug, 1},
422: {0,0,0,0}
423: /* no-init-file, no-rc? */
424: };
425:
426: c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vh", opts, &option_index);
427:
428: if (c==EOF)
429: break;
430: if (c=='?') {
431: optind--;
432: break;
433: }
434: switch (c) {
435: case 'i': imagename = optarg; break;
436: case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
437: case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
438: case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
439: case 'f': fsize = convsize(optarg,sizeof(Float)); break;
440: case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
441: case 'p': path1 = optarg; break;
442: case 'v': fprintf(stderr, "gforth %s\n", gforth_version); exit(0);
443: case 'h':
444: fprintf(stderr, "Usage: %s [engine options] [image arguments]\n\
445: Engine Options:\n\
446: --clear-dictionary Initialize the dictionary with 0 bytes\n\
447: -d SIZE, --data-stack-size=SIZE Specify data stack size\n\
448: --debug Print debugging information during startup\n\
449: -f SIZE, --fp-stack-size=SIZE Specify floating point stack size\n\
450: -h, --help Print this message and exit\n\
451: -i FILE, --image-file=FILE Use image FILE instead of `gforth.fi'\n\
452: -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
453: -m SIZE, --dictionary-size=SIZE Specify Forth dictionary size\n\
454: --offset-image Load image at a different position\n\
455: -p PATH, --path=PATH Search path for finding image and sources\n\
456: -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
457: -v, --version Print version and exit\n\
458: SIZE arguments consists of an integer followed by a unit. The unit can be\n\
459: `b' (bytes), `e' (elements), `k' (kilobytes), or `M' (Megabytes).\n\
460: \n\
461: Arguments of default image `gforth.fi':\n\
462: FILE load FILE (with `require')\n\
463: -e STRING, --evaluate STRING interpret STRING (with `EVALUATE')\n",
464: argv[0]); exit(0);
465: }
466: }
467: path=path1;
468:
469: if(strchr(imagename, '/')==NULL)
470: {
471: do {
472: char *pend=strchr(path, PATHSEP);
473: if (pend==NULL)
474: pend=path+strlen(path);
475: if (strlen(path)==0) {
476: fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
477: progname, imagename, path1);
478: exit(1);
479: }
480: {
481: int dirlen=pend-path;
482: char fullfilename[dirlen+strlen(imagename)+2];
483: memcpy(fullfilename, path, dirlen);
484: if (fullfilename[dirlen-1]!='/')
485: fullfilename[dirlen++]='/';
486: strcpy(fullfilename+dirlen,imagename);
487: image_file=fopen(fullfilename,"rb");
488: }
489: path=pend+(*pend==PATHSEP);
490: } while (image_file==NULL);
491: }
492: else
493: {
494: image_file=fopen(imagename,"rb");
495: }
496:
497: {
498: char path2[strlen(path1)+1];
499: char *p1, *p2;
500: Cell environ[]= {
501: (Cell)argc-(optind-1),
502: (Cell)(argv+(optind-1)),
503: (Cell)strlen(path1),
504: (Cell)path2};
505: argv[optind-1] = progname;
506: /*
507: for (i=0; i<environ[0]; i++)
508: printf("%s\n", ((char **)(environ[1]))[i]);
509: */
510: /* make path OS-independent by replacing path separators with NUL */
511: for (p1=path1, p2=path2; *p1!='\0'; p1++, p2++)
512: if (*p1==PATHSEP)
513: *p2 = '\0';
514: else
515: *p2 = *p1;
516: *p2='\0';
517: retvalue=go_forth(loader(image_file, imagename),4,environ);
518: deprep_terminal();
519: exit(retvalue);
520: }
521: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>