1: /* command line interpretation, image loading etc. for Gforth
2:
3:
4: Copyright (C) 1995,1996,1997,1998,2000,2003 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 "forth.h"
25: #include <errno.h>
26: #include <ctype.h>
27: #include <stdio.h>
28: #include <unistd.h>
29: #include <string.h>
30: #include <math.h>
31: #include <sys/types.h>
32: #ifndef STANDALONE
33: #include <sys/stat.h>
34: #endif
35: #include <fcntl.h>
36: #include <assert.h>
37: #include <stdlib.h>
38: #include <signal.h>
39: #ifndef STANDALONE
40: #if HAVE_SYS_MMAN_H
41: #include <sys/mman.h>
42: #endif
43: #endif
44: #include "io.h"
45: #include "getopt.h"
46: #ifdef STANDALONE
47: #include <systypes.h>
48: #endif
49:
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:
87: #define PRIM_VERSION 1
88: /* increment this whenever the primitives change in an incompatible way */
89:
90: #ifndef DEFAULTPATH
91: # define DEFAULTPATH "."
92: #endif
93:
94: #ifdef MSDOS
95: jmp_buf throw_jmp_buf;
96: #endif
97:
98: #if defined(DOUBLY_INDIRECT)
99: # define CFA(n) ({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
100: #else
101: # define CFA(n) ((Cell)(symbols+((n)&~0x4000UL)))
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;
112: int die_on_signal=0;
113: #ifndef INCLUDE_IMAGE
114: static int clear_dictionary=0;
115: UCell pagesize=1;
116: char *progname;
117: #else
118: char *progname = "gforth";
119: int optind = 1;
120: #endif
121:
122: #define CODE_BLOCK_SIZE (256*1024)
123: Address code_area=0;
124: Cell code_area_size = CODE_BLOCK_SIZE;
125: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
126: does for the dictionary */
127: Address start_flush=NULL; /* start of unflushed code */
128: Cell last_jump=0; /* if the last prim was compiled without jump, this
129: is it's number, otherwise this contains 0 */
130:
131: static int no_super=0; /* true if compile_prim should not fuse prims */
132: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
133: dynamically */
134: static int print_codesize=0; /* if true, print code size on exit */
135:
136: #ifdef HAS_DEBUG
137: int debug=0;
138: #else
139: # define perror(x...)
140: # define fprintf(x...)
141: #endif
142:
143: ImageHeader *gforth_header;
144: Label *vm_prims;
145: #ifdef DOUBLY_INDIRECT
146: Label *xts; /* same content as vm_prims, but should only be used for xts */
147: #endif
148:
149: #ifdef MEMCMP_AS_SUBROUTINE
150: int gforth_memcmp(const char * s1, const char * s2, size_t n)
151: {
152: return memcmp(s1, s2, n);
153: }
154: #endif
155:
156: /* image file format:
157: * "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
158: * padding to a multiple of 8
159: * magic: "Gforth3x" means format 0.6,
160: * where x is a byte with
161: * bit 7: reserved = 0
162: * bit 6:5: address unit size 2^n octets
163: * bit 4:3: character size 2^n octets
164: * bit 2:1: cell size 2^n octets
165: * bit 0: endian, big=0, little=1.
166: * The magic are always 8 octets, no matter what the native AU/character size is
167: * padding to max alignment (no padding necessary on current machines)
168: * ImageHeader structure (see forth.h)
169: * data (size in ImageHeader.image_size)
170: * tags ((if relocatable, 1 bit/data cell)
171: *
172: * tag==1 means that the corresponding word is an address;
173: * If the word is >=0, the address is within the image;
174: * addresses within the image are given relative to the start of the image.
175: * If the word =-1 (CF_NIL), the address is NIL,
176: * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
177: * If the word =CF(DODOES), it's a DOES> CFA
178: * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
179: * possibly containing a jump to dodoes)
180: * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
181: * If the word is <CF(DOESJUMP) and bit 14 is clear,
182: * it's the threaded code of a primitive
183: * bits 13..9 of a primitive token state which group the primitive belongs to,
184: * bits 8..0 of a primitive token index into the group
185: */
186:
187: static Cell groups[32] = {
188: 0,
189: #undef GROUP
190: #define GROUP(x, n) DOESJUMP+1+n,
191: #include "prim_grp.i"
192: #undef GROUP
193: #define GROUP(x, n)
194: };
195:
196: void relocate(Cell *image, const char *bitstring,
197: int size, Cell base, Label symbols[])
198: {
199: int i=0, j, k, steps=(size/sizeof(Cell))/RELINFOBITS;
200: Cell token;
201: char bits;
202: Cell max_symbols;
203: /*
204: * A virtual start address that's the real start address minus
205: * the one in the image
206: */
207: Cell *start = (Cell * ) (((void *) image) - ((void *) base));
208:
209: /* group index into table */
210:
211: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
212:
213: for (max_symbols=DOESJUMP+1; symbols[max_symbols]!=0; max_symbols++)
214: ;
215: max_symbols--;
216: size/=sizeof(Cell);
217:
218: for(k=0; k<=steps; k++) {
219: for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
220: /* fprintf(stderr,"relocate: image[%d]\n", i);*/
221: if((i < size) && (bits & (1U << (RELINFOBITS-1)))) {
222: /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
223: token=image[i];
224: if(token<0) {
225: int group = (-token & 0x3E00) >> 9;
226: if(group == 0) {
227: switch(token|0x4000) {
228: case CF_NIL : image[i]=0; break;
229: #if !defined(DOUBLY_INDIRECT)
230: case CF(DOCOL) :
231: case CF(DOVAR) :
232: case CF(DOCON) :
233: case CF(DOUSER) :
234: case CF(DODEFER) :
235: case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
236: case CF(DOESJUMP): image[i]=0; break;
237: #endif /* !defined(DOUBLY_INDIRECT) */
238: case CF(DODOES) :
239: MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
240: break;
241: default : /* backward compatibility */
242: /* printf("Code field generation image[%x]:=CFA(%x)\n",
243: i, CF(image[i])); */
244: if (CF((token | 0x4000))<max_symbols) {
245: image[i]=(Cell)CFA(CF(token));
246: #ifdef DIRECT_THREADED
247: if ((token & 0x4000) == 0) /* threade code, no CFA */
248: compile_prim1(&image[i]);
249: #endif
250: } else
251: 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);
252: }
253: } else {
254: int tok = -token & 0x1FF;
255: if (tok < (groups[group+1]-groups[group])) {
256: #if defined(DOUBLY_INDIRECT)
257: image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
258: #else
259: image[i]=(Cell)CFA((groups[group]+tok));
260: #endif
261: #ifdef DIRECT_THREADED
262: if ((token & 0x4000) == 0) /* threade code, no CFA */
263: compile_prim1(&image[i]);
264: #endif
265: } else
266: 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);
267: }
268: } else {
269: /* if base is > 0: 0 is a null reference so don't adjust*/
270: if (token>=base) {
271: image[i]+=(Cell)start;
272: }
273: }
274: }
275: }
276: }
277: finish_code();
278: ((ImageHeader*)(image))->base = (Address) image;
279: }
280:
281: UCell checksum(Label symbols[])
282: {
283: UCell r=PRIM_VERSION;
284: Cell i;
285:
286: for (i=DOCOL; i<=DOESJUMP; i++) {
287: r ^= (UCell)(symbols[i]);
288: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
289: }
290: #ifdef DIRECT_THREADED
291: /* we have to consider all the primitives */
292: for (; symbols[i]!=(Label)0; i++) {
293: r ^= (UCell)(symbols[i]);
294: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
295: }
296: #else
297: /* in indirect threaded code all primitives are accessed through the
298: symbols table, so we just have to put the base address of symbols
299: in the checksum */
300: r ^= (UCell)symbols;
301: #endif
302: return r;
303: }
304:
305: Address verbose_malloc(Cell size)
306: {
307: Address r;
308: /* leave a little room (64B) for stack underflows */
309: if ((r = malloc(size+64))==NULL) {
310: perror(progname);
311: exit(1);
312: }
313: r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
314: if (debug)
315: fprintf(stderr, "malloc succeeds, address=$%lx\n", (long)r);
316: return r;
317: }
318:
319: static Address next_address=0;
320: void after_alloc(Address r, Cell size)
321: {
322: if (r != (Address)-1) {
323: if (debug)
324: fprintf(stderr, "success, address=$%lx\n", (long) r);
325: if (pagesize != 1)
326: next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
327: } else {
328: if (debug)
329: fprintf(stderr, "failed: %s\n", strerror(errno));
330: }
331: }
332:
333: #ifndef MAP_FAILED
334: #define MAP_FAILED ((Address) -1)
335: #endif
336: #ifndef MAP_FILE
337: # define MAP_FILE 0
338: #endif
339: #ifndef MAP_PRIVATE
340: # define MAP_PRIVATE 0
341: #endif
342: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
343: # define MAP_ANON MAP_ANONYMOUS
344: #endif
345:
346: #if defined(HAVE_MMAP)
347: static Address alloc_mmap(Cell size)
348: {
349: Address r;
350:
351: #if defined(MAP_ANON)
352: if (debug)
353: fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
354: r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
355: #else /* !defined(MAP_ANON) */
356: /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
357: apparently defaults) */
358: static int dev_zero=-1;
359:
360: if (dev_zero == -1)
361: dev_zero = open("/dev/zero", O_RDONLY);
362: if (dev_zero == -1) {
363: r = MAP_FAILED;
364: if (debug)
365: fprintf(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ",
366: strerror(errno));
367: } else {
368: if (debug)
369: fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
370: r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
371: }
372: #endif /* !defined(MAP_ANON) */
373: after_alloc(r, size);
374: return r;
375: }
376: #endif
377:
378: Address my_alloc(Cell size)
379: {
380: #if HAVE_MMAP
381: Address r;
382:
383: r=alloc_mmap(size);
384: if (r!=MAP_FAILED)
385: return r;
386: #endif /* HAVE_MMAP */
387: /* use malloc as fallback */
388: return verbose_malloc(size);
389: }
390:
391: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
392: {
393: Address image = MAP_FAILED;
394:
395: #if defined(HAVE_MMAP)
396: if (offset==0) {
397: image=alloc_mmap(dictsize);
398: if (debug)
399: fprintf(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
400: image = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
401: after_alloc(image,dictsize);
402: }
403: #endif /* defined(HAVE_MMAP) */
404: if (image == MAP_FAILED) {
405: image = my_alloc(dictsize+offset)+offset;
406: rewind(file); /* fseek(imagefile,0L,SEEK_SET); */
407: fread(image, 1, imagesize, file);
408: }
409: return image;
410: }
411:
412: void set_stack_sizes(ImageHeader * header)
413: {
414: if (dictsize==0)
415: dictsize = header->dict_size;
416: if (dsize==0)
417: dsize = header->data_stack_size;
418: if (rsize==0)
419: rsize = header->return_stack_size;
420: if (fsize==0)
421: fsize = header->fp_stack_size;
422: if (lsize==0)
423: lsize = header->locals_stack_size;
424: dictsize=maxaligned(dictsize);
425: dsize=maxaligned(dsize);
426: rsize=maxaligned(rsize);
427: lsize=maxaligned(lsize);
428: fsize=maxaligned(fsize);
429: }
430:
431: void alloc_stacks(ImageHeader * header)
432: {
433: header->dict_size=dictsize;
434: header->data_stack_size=dsize;
435: header->fp_stack_size=fsize;
436: header->return_stack_size=rsize;
437: header->locals_stack_size=lsize;
438:
439: header->data_stack_base=my_alloc(dsize);
440: header->fp_stack_base=my_alloc(fsize);
441: header->return_stack_base=my_alloc(rsize);
442: header->locals_stack_base=my_alloc(lsize);
443: }
444:
445: #warning You can ignore the warnings about clobbered variables in go_forth
446: int go_forth(Address image, int stack, Cell *entries)
447: {
448: volatile ImageHeader *image_header = (ImageHeader *)image;
449: Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
450: Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
451: Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
452: #ifdef GFORTH_DEBUGGING
453: volatile Cell *orig_rp0=rp0;
454: #endif
455: Address lp0=image_header->locals_stack_base + lsize;
456: Xt *ip0=(Xt *)(image_header->boot_entry);
457: #ifdef SYSSIGNALS
458: int throw_code;
459: #endif
460:
461: /* ensure that the cached elements (if any) are accessible */
462: IF_spTOS(sp0--);
463: IF_fpTOS(fp0--);
464:
465: for(;stack>0;stack--)
466: *--sp0=entries[stack-1];
467:
468: #ifdef SYSSIGNALS
469: get_winsize();
470:
471: install_signal_handlers(); /* right place? */
472:
473: if ((throw_code=setjmp(throw_jmp_buf))) {
474: static Cell signal_data_stack[8];
475: static Cell signal_return_stack[8];
476: static Float signal_fp_stack[1];
477:
478: signal_data_stack[7]=throw_code;
479:
480: #ifdef GFORTH_DEBUGGING
481: if (debug)
482: fprintf(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
483: throw_code, saved_ip, rp);
484: if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
485: /* no rstack overflow or underflow */
486: rp0 = rp;
487: *--rp0 = (Cell)saved_ip;
488: }
489: else /* I love non-syntactic ifdefs :-) */
490: rp0 = signal_return_stack+8;
491: #else /* !defined(GFORTH_DEBUGGING) */
492: if (debug)
493: fprintf(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
494: rp0 = signal_return_stack+8;
495: #endif /* !defined(GFORTH_DEBUGGING) */
496: /* fprintf(stderr, "rp=$%x\n",rp0);*/
497:
498: return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
499: rp0, signal_fp_stack, 0));
500: }
501: #endif
502:
503: return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
504: }
505:
506: #ifndef INCLUDE_IMAGE
507: void print_sizes(Cell sizebyte)
508: /* print size information */
509: {
510: static char* endianstring[]= { " big","little" };
511:
512: fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
513: endianstring[sizebyte & 1],
514: 1 << ((sizebyte >> 1) & 3),
515: 1 << ((sizebyte >> 3) & 3),
516: 1 << ((sizebyte >> 5) & 3));
517: }
518:
519: /* static superinstruction stuff */
520:
521: struct cost {
522: char loads; /* number of stack loads */
523: char stores; /* number of stack stores */
524: char updates; /* number of stack pointer updates */
525: short offset; /* offset into super2 table */
526: char length; /* number of components */
527: };
528:
529: short super2[] = {
530: #include "super2.i"
531: };
532:
533: struct cost super_costs[] = {
534: #include "costs.i"
535: };
536:
537: #define HASH_SIZE 256
538:
539: struct super_table_entry {
540: struct super_table_entry *next;
541: short *start;
542: short length;
543: short super;
544: } *super_table[HASH_SIZE];
545: int max_super=2;
546:
547: int hash_super(short *start, int length)
548: {
549: int i, r;
550:
551: for (i=0, r=0; i<length; i++) {
552: r <<= 1;
553: r += start[i];
554: }
555: return r & (HASH_SIZE-1);
556: }
557:
558: int lookup_super(short *start, int length)
559: {
560: int hash=hash_super(start,length);
561: struct super_table_entry *p = super_table[hash];
562:
563: assert(length >= 2);
564: for (; p!=NULL; p = p->next) {
565: if (length == p->length &&
566: memcmp((char *)p->start, (char *)start, length*sizeof(short))==0)
567: return p->super;
568: }
569: return -1;
570: }
571:
572: void prepare_super_table()
573: {
574: int i;
575:
576: for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
577: struct cost *c = &super_costs[i];
578: if (c->length > 1) {
579: int hash = hash_super(super2+c->offset, c->length);
580: struct super_table_entry **p = &super_table[hash];
581: struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
582: e->next = *p;
583: e->start = super2 + c->offset;
584: e->length = c->length;
585: e->super = i;
586: *p = e;
587: if (c->length > max_super)
588: max_super = c->length;
589: }
590: }
591: }
592:
593: int mycost(int prim)
594: {
595: return 1;
596: }
597:
598: /* dynamic replication/superinstruction stuff */
599:
600: #define MAX_IMMARGS 2
601:
602: #ifndef NO_DYNAMIC
603: typedef struct {
604: Label start;
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) */
607: char superend; /* true if primitive ends superinstruction, i.e.,
608: unconditional branch, execute, etc. */
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];
614: } PrimInfo;
615:
616: PrimInfo *priminfos;
617: PrimInfo **decomp_prims;
618:
619: int compare_priminfo_length(const void *_a, const void *_b)
620: {
621: PrimInfo **a = (PrimInfo **)_a;
622: PrimInfo **b = (PrimInfo **)_b;
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;
630: }
631:
632: static char superend[]={
633: #include "prim_superend.i"
634: };
635: #endif /* !defined(NO_DYNAMIC) */
636:
637: Cell npriminfos=0;
638:
639: void check_prims(Label symbols1[])
640: {
641: int i;
642: #ifndef NO_DYNAMIC
643: Label *symbols2, *symbols3, *ends1;
644: #endif
645:
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
654: for (i=DOESJUMP+1; symbols1[i+1]!=0; i++)
655: ;
656: npriminfos = i;
657:
658: #ifndef NO_DYNAMIC
659: if (no_dynamic)
660: return;
661: symbols2=engine2(0,0,0,0,0);
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;
668: priminfos = calloc(i,sizeof(PrimInfo));
669: for (i=DOESJUMP+1; symbols1[i+1]!=0; i++) {
670: int prim_len = ends1[i]-symbols1[i];
671: PrimInfo *pi=&priminfos[i];
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;
683: pi->restlength = symbols1[i+1] - symbols1[i] - pi->length;
684: pi->nimmargs = 0;
685: if (debug)
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);
688: assert(prim_len>=0);
689: while (j<(pi->length+pi->restlength)) {
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);
695: /* assert(j<prim_len); */
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);
717: /* assert(j<prim_len);*/
718: break;
719: }
720: j+=4;
721: }
722: }
723: if (debug)
724: fprintf(stderr,"\n");
725: }
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);
731: #endif
732: }
733:
734: void flush_to_here(void)
735: {
736: #ifndef NO_DYNAMIC
737: if (start_flush)
738: FLUSH_ICACHE(start_flush, code_here-start_flush);
739: start_flush=code_here;
740: #endif
741: }
742:
743: #ifndef NO_DYNAMIC
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:
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:
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) {
774: struct code_block_list *p;
775: append_jump();
776: flush_to_here();
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: }
788: old_code_here = code_here;
789: next_code_blockp = &(p->next);
790: }
791: memcpy(code_here, pi->start, pi->length);
792: code_here += pi->length;
793: return old_code_here;
794: }
795: #endif
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: }
813: return -no_dynamic;
814: #endif /* !defined(NO_DYNAMIC) */
815: }
816:
817: long dyncodesize(void)
818: {
819: #ifndef NO_DYNAMIC
820: struct code_block_list *p;
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:
832: Label decompile_code(Label _code)
833: {
834: #ifdef NO_DYNAMIC
835: return _code;
836: #else /* !defined(NO_DYNAMIC) */
837: Cell i;
838: struct code_block_list *p;
839: Address code=_code;
840:
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: }
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) */
856: }
857:
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:
872: /* definitions of N_execute etc. */
873: #include "prim_num.i"
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:
893: assert(vm_prims[p]==priminfos[p].start);
894: append_prim(p);
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;
901: PrimInfo *pi = &priminfos[N_call2];
902: Address old_code_here = append_prim(N_call2);
903:
904: next_code_target = (Cell *)(old_code_here + pi->immargs[0].offset);
905: register_branchinfo(old_code_here + pi->immargs[1].offset, targetptr);
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;
926: #endif
927: flush_to_here();
928: }
929:
930: /* compile *start into a dynamic superinstruction, updating *start */
931: void compile_prim_dyn(Cell *start)
932: {
933: #if defined(DOUBLY_INDIRECT)
934: Label prim=(Label)*start;
935: if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
936: fprintf(stderr,"compile_prim encountered xt %p\n", prim);
937: *start=(Cell)prim;
938: return;
939: } else {
940: *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
941: return;
942: }
943: #elif defined(NO_IP)
944: static Cell *last_start=NULL;
945: static Xt last_prim=NULL;
946: /* delay work by one call in order to get relocated immargs */
947:
948: if (last_start) {
949: unsigned i = last_prim-vm_prims;
950: PrimInfo *pi=&priminfos[i];
951: Cell *next_code_target=NULL;
952:
953: assert(i<npriminfos);
954: if (i==N_execute||i==N_perform||i==N_lit_perform) {
955: next_code_target = compile_prim1arg(N_set_next_code);
956: }
957: if (i==N_call) {
958: next_code_target = compile_call2(last_start[1]);
959: } else if (i==N_does_exec) {
960: struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
961: *compile_prim1arg(N_lit) = (Cell)PFA(last_start[1]);
962: /* we cannot determine the callee now (last_start[1] may be a
963: forward reference), so just register an arbitrary target, and
964: register in dei that we need to fix this before resolving
965: branches */
966: dei->branchinfo = nbranchinfos;
967: dei->xt = (Cell *)(last_start[1]);
968: next_code_target = compile_call2(NULL);
969: } else if (pi->start == NULL) { /* non-reloc */
970: next_code_target = compile_prim1arg(N_set_next_code);
971: set_rel_target(compile_prim1arg(N_abranch),*(Xt)last_prim);
972: } else {
973: unsigned j;
974: Address old_code_here = append_prim(i);
975:
976: for (j=0; j<pi->nimmargs; j++) {
977: struct immarg *ia = &(pi->immargs[j]);
978: Cell argval = last_start[pi->nimmargs - j]; /* !! specific to prims */
979: if (ia->rel) { /* !! assumption: relative refs are branches */
980: register_branchinfo(old_code_here + ia->offset, argval);
981: } else /* plain argument */
982: *(Cell *)(old_code_here + ia->offset) = argval;
983: }
984: }
985: if (next_code_target!=NULL)
986: *next_code_target = (Cell)code_here;
987: }
988: if (start) {
989: last_prim = (Xt)*start;
990: *start = (Cell)code_here;
991: }
992: last_start = start;
993: return;
994: #elif !defined(NO_DYNAMIC)
995: Label prim=(Label)*start;
996: unsigned i;
997: Address old_code_here;
998:
999: i = ((Xt)prim)-vm_prims;
1000: prim = *(Xt)prim;
1001: if (no_dynamic) {
1002: *start = (Cell)prim;
1003: return;
1004: }
1005: if (i>=npriminfos || priminfos[i].start == 0) { /* not a relocatable prim */
1006: append_jump();
1007: *start = (Cell)prim;
1008: return;
1009: }
1010: assert(priminfos[i].start = prim);
1011: #ifdef ALIGN_CODE
1012: /* ALIGN_CODE;*/
1013: #endif
1014: assert(prim==priminfos[i].start);
1015: old_code_here = append_prim(i);
1016: last_jump = (priminfos[i].superend) ? 0 : i;
1017: *start = (Cell)old_code_here;
1018: return;
1019: #else /* !defined(DOUBLY_INDIRECT), no code replication */
1020: Label prim=(Label)*start;
1021: #if !defined(INDIRECT_THREADED)
1022: prim = *(Xt)prim;
1023: #endif
1024: *start = (Cell)prim;
1025: return;
1026: #endif /* !defined(DOUBLY_INDIRECT) */
1027: }
1028:
1029: #define MAX_BB 128 /* maximum number of instructions in BB */
1030:
1031: /* use dynamic programming to find the shortest paths within the basic
1032: block origs[0..ninsts-1]; optimals[i] contains the superinstruction
1033: on the shortest path to the end of the BB */
1034: void optimize_bb(short origs[], short optimals[], int ninsts)
1035: {
1036: int i,j;
1037: static int costs[MAX_BB+1];
1038:
1039: assert(ninsts<MAX_BB);
1040: costs[ninsts]=0;
1041: for (i=ninsts-1; i>=0; i--) {
1042: optimals[i] = origs[i];
1043: costs[i] = costs[i+1] + mycost(optimals[i]);
1044: for (j=2; j<=max_super && i+j<=ninsts ; j++) {
1045: int super, jcost;
1046:
1047: super = lookup_super(origs+i,j);
1048: if (super >= 0) {
1049: jcost = costs[i+j] + mycost(super);
1050: if (jcost <= costs[i]) {
1051: optimals[i] = super;
1052: costs[i] = jcost;
1053: }
1054: }
1055: }
1056: }
1057: }
1058:
1059: /* rewrite the instructions pointed to by instps to use the
1060: superinstructions in optimals */
1061: void rewrite_bb(Cell *instps[], short *optimals, int ninsts)
1062: {
1063: int i, nextdyn;
1064:
1065: for (i=0, nextdyn=0; i<ninsts; i++) {
1066: *(instps[i]) = vm_prims[optimals[i]+DOESJUMP+1];
1067: if (i==nextdyn) {
1068: nextdyn += super_costs[optimals[i]].length;
1069: /* !! *(p->instp) = compile_prim_dyn(p->superinst); */
1070: }
1071: }
1072: }
1073:
1074: /* compile *start, possibly rewriting it into a static and/or dynamic
1075: superinstruction */
1076: void compile_prim1(Cell *start)
1077: {
1078: #if defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)
1079: compile_prim_dyn(start);
1080: #else
1081: static Cell *instps[MAX_BB];
1082: static short origs[MAX_BB];
1083: static short optimals[MAX_BB];
1084: static int ninsts=0;
1085: unsigned prim_num;
1086:
1087: if (start==NULL)
1088: goto end_bb;
1089: prim_num = ((Xt)*start)-vm_prims;
1090: if (prim_num >= npriminfos)
1091: goto end_bb;
1092: assert(ninsts<MAX_BB);
1093: instps[ninsts] = start;
1094: origs[ninsts] = prim_num-DOESJUMP-1;
1095: ninsts++;
1096: if (ninsts >= MAX_BB || superend[prim_num-DOESJUMP-1]) {
1097: end_bb:
1098: optimize_bb(origs,optimals,ninsts);
1099: rewrite_bb(instps,optimals,ninsts);
1100: ninsts=0;
1101: }
1102: #endif /* defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED) */
1103: }
1104:
1105: #if defined(PRINT_SUPER_LENGTHS) && !defined(NO_DYNAMIC)
1106: Cell prim_length(Cell prim)
1107: {
1108: return priminfos[prim+DOESJUMP+1].length;
1109: }
1110: #endif
1111:
1112: Address loader(FILE *imagefile, char* filename)
1113: /* returns the address of the image proper (after the preamble) */
1114: {
1115: ImageHeader header;
1116: Address image;
1117: Address imp; /* image+preamble */
1118: Char magic[8];
1119: char magic7; /* size byte of magic number */
1120: Cell preamblesize=0;
1121: Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1122: UCell check_sum;
1123: Cell ausize = ((RELINFOBITS == 8) ? 0 :
1124: (RELINFOBITS == 16) ? 1 :
1125: (RELINFOBITS == 32) ? 2 : 3);
1126: Cell charsize = ((sizeof(Char) == 1) ? 0 :
1127: (sizeof(Char) == 2) ? 1 :
1128: (sizeof(Char) == 4) ? 2 : 3) + ausize;
1129: Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
1130: (sizeof(Cell) == 2) ? 1 :
1131: (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1132: Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
1133: #ifdef WORDS_BIGENDIAN
1134: 0
1135: #else
1136: 1
1137: #endif
1138: ;
1139:
1140: vm_prims = engine(0,0,0,0,0);
1141: check_prims(vm_prims);
1142: prepare_super_table();
1143: #ifndef DOUBLY_INDIRECT
1144: #ifdef PRINT_SUPER_LENGTHS
1145: print_super_lengths();
1146: #endif
1147: check_sum = checksum(vm_prims);
1148: #else /* defined(DOUBLY_INDIRECT) */
1149: check_sum = (UCell)vm_prims;
1150: #endif /* defined(DOUBLY_INDIRECT) */
1151:
1152: do {
1153: if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1154: fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
1155: progname, filename);
1156: exit(1);
1157: }
1158: preamblesize+=8;
1159: } while(memcmp(magic,"Gforth3",7));
1160: magic7 = magic[7];
1161: if (debug) {
1162: magic[7]='\0';
1163: fprintf(stderr,"Magic found: %s ", magic);
1164: print_sizes(magic7);
1165: }
1166:
1167: if (magic7 != sizebyte)
1168: {
1169: fprintf(stderr,"This image is: ");
1170: print_sizes(magic7);
1171: fprintf(stderr,"whereas the machine is ");
1172: print_sizes(sizebyte);
1173: exit(-2);
1174: };
1175:
1176: fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1177:
1178: set_stack_sizes(&header);
1179:
1180: #if HAVE_GETPAGESIZE
1181: pagesize=getpagesize(); /* Linux/GNU libc offers this */
1182: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
1183: pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
1184: #elif PAGESIZE
1185: pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
1186: #endif
1187: if (debug)
1188: fprintf(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1189:
1190: image = dict_alloc_read(imagefile, preamblesize+header.image_size,
1191: preamblesize+dictsize, data_offset);
1192: imp=image+preamblesize;
1193: alloc_stacks((ImageHeader *)imp);
1194: if (clear_dictionary)
1195: memset(imp+header.image_size, 0, dictsize-header.image_size);
1196: if(header.base==0 || header.base == (Address)0x100) {
1197: Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
1198: char reloc_bits[reloc_size];
1199: fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1200: fread(reloc_bits, 1, reloc_size, imagefile);
1201: relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
1202: #if 0
1203: { /* let's see what the relocator did */
1204: FILE *snapshot=fopen("snapshot.fi","wb");
1205: fwrite(image,1,imagesize,snapshot);
1206: fclose(snapshot);
1207: }
1208: #endif
1209: }
1210: else if(header.base!=imp) {
1211: fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
1212: progname, (unsigned long)header.base, (unsigned long)imp);
1213: exit(1);
1214: }
1215: if (header.checksum==0)
1216: ((ImageHeader *)imp)->checksum=check_sum;
1217: else if (header.checksum != check_sum) {
1218: fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
1219: progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
1220: exit(1);
1221: }
1222: #ifdef DOUBLY_INDIRECT
1223: ((ImageHeader *)imp)->xt_base = xts;
1224: #endif
1225: fclose(imagefile);
1226:
1227: /* unnecessary, except maybe for CODE words */
1228: /* FLUSH_ICACHE(imp, header.image_size);*/
1229:
1230: return imp;
1231: }
1232:
1233: /* pointer to last '/' or '\' in file, 0 if there is none. */
1234: char *onlypath(char *filename)
1235: {
1236: return strrchr(filename, DIRSEP);
1237: }
1238:
1239: FILE *openimage(char *fullfilename)
1240: {
1241: FILE *image_file;
1242: char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
1243:
1244: image_file=fopen(expfilename,"rb");
1245: if (image_file!=NULL && debug)
1246: fprintf(stderr, "Opened image file: %s\n", expfilename);
1247: return image_file;
1248: }
1249:
1250: /* try to open image file concat(path[0:len],imagename) */
1251: FILE *checkimage(char *path, int len, char *imagename)
1252: {
1253: int dirlen=len;
1254: char fullfilename[dirlen+strlen(imagename)+2];
1255:
1256: memcpy(fullfilename, path, dirlen);
1257: if (fullfilename[dirlen-1]!=DIRSEP)
1258: fullfilename[dirlen++]=DIRSEP;
1259: strcpy(fullfilename+dirlen,imagename);
1260: return openimage(fullfilename);
1261: }
1262:
1263: FILE * open_image_file(char * imagename, char * path)
1264: {
1265: FILE * image_file=NULL;
1266: char *origpath=path;
1267:
1268: if(strchr(imagename, DIRSEP)==NULL) {
1269: /* first check the directory where the exe file is in !! 01may97jaw */
1270: if (onlypath(progname))
1271: image_file=checkimage(progname, onlypath(progname)-progname, imagename);
1272: if (!image_file)
1273: do {
1274: char *pend=strchr(path, PATHSEP);
1275: if (pend==NULL)
1276: pend=path+strlen(path);
1277: if (strlen(path)==0) break;
1278: image_file=checkimage(path, pend-path, imagename);
1279: path=pend+(*pend==PATHSEP);
1280: } while (image_file==NULL);
1281: } else {
1282: image_file=openimage(imagename);
1283: }
1284:
1285: if (!image_file) {
1286: fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1287: progname, imagename, origpath);
1288: exit(1);
1289: }
1290:
1291: return image_file;
1292: }
1293: #endif
1294:
1295: #ifdef HAS_OS
1296: UCell convsize(char *s, UCell elemsize)
1297: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
1298: of bytes. the letter at the end indicates the unit, where e stands
1299: for the element size. default is e */
1300: {
1301: char *endp;
1302: UCell n,m;
1303:
1304: m = elemsize;
1305: n = strtoul(s,&endp,0);
1306: if (endp!=NULL) {
1307: if (strcmp(endp,"b")==0)
1308: m=1;
1309: else if (strcmp(endp,"k")==0)
1310: m=1024;
1311: else if (strcmp(endp,"M")==0)
1312: m=1024*1024;
1313: else if (strcmp(endp,"G")==0)
1314: m=1024*1024*1024;
1315: else if (strcmp(endp,"T")==0) {
1316: #if (SIZEOF_CHAR_P > 4)
1317: m=1024L*1024*1024*1024;
1318: #else
1319: fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
1320: exit(1);
1321: #endif
1322: } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
1323: fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
1324: exit(1);
1325: }
1326: }
1327: return n*m;
1328: }
1329:
1330: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
1331: {
1332: int c;
1333:
1334: opterr=0;
1335: while (1) {
1336: int option_index=0;
1337: static struct option opts[] = {
1338: {"appl-image", required_argument, NULL, 'a'},
1339: {"image-file", required_argument, NULL, 'i'},
1340: {"dictionary-size", required_argument, NULL, 'm'},
1341: {"data-stack-size", required_argument, NULL, 'd'},
1342: {"return-stack-size", required_argument, NULL, 'r'},
1343: {"fp-stack-size", required_argument, NULL, 'f'},
1344: {"locals-stack-size", required_argument, NULL, 'l'},
1345: {"path", required_argument, NULL, 'p'},
1346: {"version", no_argument, NULL, 'v'},
1347: {"help", no_argument, NULL, 'h'},
1348: /* put something != 0 into offset_image */
1349: {"offset-image", no_argument, &offset_image, 1},
1350: {"no-offset-im", no_argument, &offset_image, 0},
1351: {"clear-dictionary", no_argument, &clear_dictionary, 1},
1352: {"die-on-signal", no_argument, &die_on_signal, 1},
1353: {"debug", no_argument, &debug, 1},
1354: {"no-super", no_argument, &no_super, 1},
1355: {"no-dynamic", no_argument, &no_dynamic, 1},
1356: {"dynamic", no_argument, &no_dynamic, 0},
1357: {"print-codesize", no_argument, &print_codesize, 1},
1358: {0,0,0,0}
1359: /* no-init-file, no-rc? */
1360: };
1361:
1362: c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1363:
1364: switch (c) {
1365: case EOF: return;
1366: case '?': optind--; return;
1367: case 'a': *imagename = optarg; return;
1368: case 'i': *imagename = optarg; break;
1369: case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
1370: case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
1371: case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
1372: case 'f': fsize = convsize(optarg,sizeof(Float)); break;
1373: case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1374: case 'p': *path = optarg; break;
1375: case 'o': offset_image = 1; break;
1376: case 'n': offset_image = 0; break;
1377: case 'c': clear_dictionary = 1; break;
1378: case 's': die_on_signal = 1; break;
1379: case 'x': debug = 1; break;
1380: case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
1381: case 'h':
1382: fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1383: Engine Options:\n\
1384: --appl-image FILE equivalent to '--image-file=FILE --'\n\
1385: --clear-dictionary Initialize the dictionary with 0 bytes\n\
1386: -d SIZE, --data-stack-size=SIZE Specify data stack size\n\
1387: --debug Print debugging information during startup\n\
1388: --die-on-signal exit instead of CATCHing some signals\n\
1389: --dynamic use dynamic native code\n\
1390: -f SIZE, --fp-stack-size=SIZE Specify floating point stack size\n\
1391: -h, --help Print this message and exit\n\
1392: -i FILE, --image-file=FILE Use image FILE instead of `gforth.fi'\n\
1393: -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
1394: -m SIZE, --dictionary-size=SIZE Specify Forth dictionary size\n\
1395: --no-dynamic Use only statically compiled primitives\n\
1396: --no-offset-im Load image at normal position\n\
1397: --no-super No dynamically formed superinstructions\n\
1398: --offset-image Load image at a different position\n\
1399: -p PATH, --path=PATH Search path for finding image and sources\n\
1400: --print-codesize Print size of generated native code on exit\n\
1401: -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
1402: -v, --version Print engine version and exit\n\
1403: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1404: `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
1405: argv[0]);
1406: optind--;
1407: return;
1408: }
1409: }
1410: }
1411: #endif
1412:
1413: #ifdef INCLUDE_IMAGE
1414: extern Cell image[];
1415: extern const char reloc_bits[];
1416: #endif
1417:
1418: int main(int argc, char **argv, char **env)
1419: {
1420: #ifdef HAS_OS
1421: char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1422: #else
1423: char *path = DEFAULTPATH;
1424: #endif
1425: #ifndef INCLUDE_IMAGE
1426: char *imagename="gforth.fi";
1427: FILE *image_file;
1428: Address image;
1429: #endif
1430: int retvalue;
1431:
1432: #if defined(i386) && defined(ALIGNMENT_CHECK)
1433: /* turn on alignment checks on the 486.
1434: * on the 386 this should have no effect. */
1435: __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
1436: /* this is unusable with Linux' libc.4.6.27, because this library is
1437: not alignment-clean; we would have to replace some library
1438: functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
1439: the stack FP-aligned. */
1440: #endif
1441:
1442: /* buffering of the user output device */
1443: #ifdef _IONBF
1444: if (isatty(fileno(stdout))) {
1445: fflush(stdout);
1446: setvbuf(stdout,NULL,_IONBF,0);
1447: }
1448: #endif
1449:
1450: progname = argv[0];
1451:
1452: #ifdef HAS_OS
1453: gforth_args(argc, argv, &path, &imagename);
1454: #endif
1455:
1456: #ifdef INCLUDE_IMAGE
1457: set_stack_sizes((ImageHeader *)image);
1458: if(((ImageHeader *)image)->base != image)
1459: relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
1460: (Label*)engine(0, 0, 0, 0, 0));
1461: alloc_stacks((ImageHeader *)image);
1462: #else
1463: image_file = open_image_file(imagename, path);
1464: image = loader(image_file, imagename);
1465: #endif
1466: gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1467:
1468: {
1469: char path2[strlen(path)+1];
1470: char *p1, *p2;
1471: Cell environ[]= {
1472: (Cell)argc-(optind-1),
1473: (Cell)(argv+(optind-1)),
1474: (Cell)strlen(path),
1475: (Cell)path2};
1476: argv[optind-1] = progname;
1477: /*
1478: for (i=0; i<environ[0]; i++)
1479: printf("%s\n", ((char **)(environ[1]))[i]);
1480: */
1481: /* make path OS-independent by replacing path separators with NUL */
1482: for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1483: if (*p1==PATHSEP)
1484: *p2 = '\0';
1485: else
1486: *p2 = *p1;
1487: *p2='\0';
1488: retvalue = go_forth(image, 4, environ);
1489: #ifdef SIGPIPE
1490: bsd_signal(SIGPIPE, SIG_IGN);
1491: #endif
1492: #ifdef VM_PROFILING
1493: vm_print_profile(stderr);
1494: #endif
1495: deprep_terminal();
1496: }
1497: if (print_codesize) {
1498: fprintf(stderr, "code size = %ld\n", dyncodesize());
1499: }
1500: return retvalue;
1501: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>