1: /* command line interpretation, image loading etc. for Gforth
2:
3:
4: Copyright (C) 1995,1996,1997,1998,2000,2003,2004 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: typedef enum prim_num {
51: /* definitions of N_execute etc. */
52: #include PRIM_NUM_I
53: N_START_SUPER
54: } PrimNum;
55:
56: /* global variables for engine.c
57: We put them here because engine.c is compiled several times in
58: different ways for the same engine. */
59: Cell *SP;
60: Float *FP;
61: Address UP=NULL;
62:
63: #ifdef HAS_FFCALL
64: Cell *RP;
65: Address LP;
66:
67: #include <callback.h>
68:
69: va_alist clist;
70:
71: void engine_callback(Xt* fcall, void * alist)
72: {
73: /* save global valiables */
74: Cell *rp = RP;
75: Cell *sp = SP;
76: Float *fp = FP;
77: Address lp = LP;
78:
79: clist = (va_alist)alist;
80:
81: engine(fcall, sp, rp, fp, lp);
82:
83: /* restore global variables */
84: RP = rp;
85: SP = sp;
86: FP = fp;
87: LP = lp;
88: }
89: #endif
90:
91: #ifdef GFORTH_DEBUGGING
92: /* define some VM registers as global variables, so they survive exceptions;
93: global register variables are not up to the task (according to the
94: GNU C manual) */
95: Xt *saved_ip;
96: Cell *rp;
97: #endif
98:
99: #ifdef NO_IP
100: Label next_code;
101: #endif
102:
103: #ifdef HAS_FILE
104: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
105: char* pfileattr[6]={"r","r","r+","r+","w","w"};
106:
107: #ifndef O_BINARY
108: #define O_BINARY 0
109: #endif
110: #ifndef O_TEXT
111: #define O_TEXT 0
112: #endif
113:
114: int ufileattr[6]= {
115: O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
116: O_RDWR |O_BINARY, O_RDWR |O_BINARY,
117: O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
118: #endif
119: /* end global vars for engine.c */
120:
121: #define PRIM_VERSION 1
122: /* increment this whenever the primitives change in an incompatible way */
123:
124: #ifndef DEFAULTPATH
125: # define DEFAULTPATH "."
126: #endif
127:
128: #ifdef MSDOS
129: jmp_buf throw_jmp_buf;
130: #endif
131:
132: #if defined(DOUBLY_INDIRECT)
133: # define CFA(n) ({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
134: #else
135: # define CFA(n) ((Cell)(symbols+((n)&~0x4000UL)))
136: #endif
137:
138: #define maxaligned(n) (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
139:
140: static UCell dictsize=0;
141: static UCell dsize=0;
142: static UCell rsize=0;
143: static UCell fsize=0;
144: static UCell lsize=0;
145: int offset_image=0;
146: int die_on_signal=0;
147: #ifndef INCLUDE_IMAGE
148: static int clear_dictionary=0;
149: UCell pagesize=1;
150: char *progname;
151: #else
152: char *progname = "gforth";
153: int optind = 1;
154: #endif
155:
156: #define CODE_BLOCK_SIZE (4096*1024) /* !! overflow handling for -native */
157: Address code_area=0;
158: Cell code_area_size = CODE_BLOCK_SIZE;
159: Address code_here=NULL+CODE_BLOCK_SIZE; /* does for code-area what HERE
160: does for the dictionary */
161: Address start_flush=NULL; /* start of unflushed code */
162: Cell last_jump=0; /* if the last prim was compiled without jump, this
163: is it's number, otherwise this contains 0 */
164:
165: static int no_super=0; /* true if compile_prim should not fuse prims */
166: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
167: dynamically */
168: static int print_metrics=0; /* if true, print metrics on exit */
169: static int static_super_number = 10000000; /* number of ss used if available */
170: #define MAX_STATE 4 /* maximum number of states */
171: static int maxstates = MAX_STATE; /* number of states for stack caching */
172: static int ss_greedy = 0; /* if true: use greedy, not optimal ss selection */
173: static int diag = 0; /* if true: print diagnostic informations */
174: static int relocs = 0;
175: static int nonrelocs = 0;
176:
177: #ifdef HAS_DEBUG
178: int debug=0;
179: # define debugp(x...) if (debug) fprintf(x);
180: #else
181: # define perror(x...)
182: # define fprintf(x...)
183: # define debugp(x...)
184: #endif
185:
186: ImageHeader *gforth_header;
187: Label *vm_prims;
188: #ifdef DOUBLY_INDIRECT
189: Label *xts; /* same content as vm_prims, but should only be used for xts */
190: #endif
191:
192: #ifndef NO_DYNAMIC
193: #define MAX_IMMARGS 2
194:
195: typedef struct {
196: Label start; /* NULL if not relocatable */
197: Cell length; /* only includes the jump iff superend is true*/
198: Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
199: char superend; /* true if primitive ends superinstruction, i.e.,
200: unconditional branch, execute, etc. */
201: Cell nimmargs;
202: struct immarg {
203: Cell offset; /* offset of immarg within prim */
204: char rel; /* true if immarg is relative */
205: } immargs[MAX_IMMARGS];
206: } PrimInfo;
207:
208: PrimInfo *priminfos;
209: PrimInfo **decomp_prims;
210:
211: const char const* const prim_names[]={
212: #include PRIM_NAMES_I
213: };
214:
215: void init_ss_cost(void);
216:
217: static int is_relocatable(int p)
218: {
219: return !no_dynamic && priminfos[p].start != NULL;
220: }
221: #else /* defined(NO_DYNAMIC) */
222: static int is_relocatable(int p)
223: {
224: return 0;
225: }
226: #endif /* defined(NO_DYNAMIC) */
227:
228: #ifdef MEMCMP_AS_SUBROUTINE
229: int gforth_memcmp(const char * s1, const char * s2, size_t n)
230: {
231: return memcmp(s1, s2, n);
232: }
233: #endif
234:
235: static Cell max(Cell a, Cell b)
236: {
237: return a>b?a:b;
238: }
239:
240: static Cell min(Cell a, Cell b)
241: {
242: return a<b?a:b;
243: }
244:
245: /* image file format:
246: * "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
247: * padding to a multiple of 8
248: * magic: "Gforth3x" means format 0.6,
249: * where x is a byte with
250: * bit 7: reserved = 0
251: * bit 6:5: address unit size 2^n octets
252: * bit 4:3: character size 2^n octets
253: * bit 2:1: cell size 2^n octets
254: * bit 0: endian, big=0, little=1.
255: * The magic are always 8 octets, no matter what the native AU/character size is
256: * padding to max alignment (no padding necessary on current machines)
257: * ImageHeader structure (see forth.h)
258: * data (size in ImageHeader.image_size)
259: * tags ((if relocatable, 1 bit/data cell)
260: *
261: * tag==1 means that the corresponding word is an address;
262: * If the word is >=0, the address is within the image;
263: * addresses within the image are given relative to the start of the image.
264: * If the word =-1 (CF_NIL), the address is NIL,
265: * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
266: * If the word =CF(DODOES), it's a DOES> CFA
267: * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
268: * possibly containing a jump to dodoes)
269: * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
270: * If the word is <CF(DOESJUMP) and bit 14 is clear,
271: * it's the threaded code of a primitive
272: * bits 13..9 of a primitive token state which group the primitive belongs to,
273: * bits 8..0 of a primitive token index into the group
274: */
275:
276: Cell groups[32] = {
277: 0,
278: 0
279: #undef GROUP
280: #undef GROUPADD
281: #define GROUPADD(n) +n
282: #define GROUP(x, n) , 0
283: #include PRIM_GRP_I
284: #undef GROUP
285: #undef GROUPADD
286: #define GROUP(x, n)
287: #define GROUPADD(n)
288: };
289:
290: unsigned char *branch_targets(Cell *image, const unsigned char *bitstring,
291: int size, Cell base)
292: /* produce a bitmask marking all the branch targets */
293: {
294: int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
295: Cell token;
296: unsigned char bits;
297: unsigned char *result=malloc(steps);
298:
299: memset(result, 0, steps);
300: for(k=0; k<steps; k++) {
301: for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
302: if(bits & (1U << (RELINFOBITS-1))) {
303: assert(i*sizeof(Cell) < size);
304: token=image[i];
305: if (token>=base) { /* relocatable address */
306: UCell bitnum=(token-base)/sizeof(Cell);
307: result[bitnum/RELINFOBITS] |= 1U << ((~bitnum)&(RELINFOBITS-1));
308: }
309: }
310: }
311: }
312: return result;
313: }
314:
315: void relocate(Cell *image, const unsigned char *bitstring,
316: int size, Cell base, Label symbols[])
317: {
318: int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
319: Cell token;
320: char bits;
321: Cell max_symbols;
322: /*
323: * A virtual start address that's the real start address minus
324: * the one in the image
325: */
326: Cell *start = (Cell * ) (((void *) image) - ((void *) base));
327: unsigned char *targets = branch_targets(image, bitstring, size, base);
328:
329: /* group index into table */
330: if(groups[31]==0) {
331: int groupsum=0;
332: for(i=0; i<32; i++) {
333: groupsum += groups[i];
334: groups[i] = groupsum;
335: /* printf("group[%d]=%d\n",i,groupsum); */
336: }
337: i=0;
338: }
339:
340: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
341:
342: for (max_symbols=0; symbols[max_symbols]!=0; max_symbols++)
343: ;
344: max_symbols--;
345:
346: for(k=0; k<steps; k++) {
347: for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
348: /* fprintf(stderr,"relocate: image[%d]\n", i);*/
349: if(bits & (1U << (RELINFOBITS-1))) {
350: assert(i*sizeof(Cell) < size);
351: /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
352: token=image[i];
353: if(token<0) {
354: int group = (-token & 0x3E00) >> 9;
355: if(group == 0) {
356: switch(token|0x4000) {
357: case CF_NIL : image[i]=0; break;
358: #if !defined(DOUBLY_INDIRECT)
359: case CF(DOCOL) :
360: case CF(DOVAR) :
361: case CF(DOCON) :
362: case CF(DOUSER) :
363: case CF(DODEFER) :
364: case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
365: case CF(DOESJUMP): image[i]=0; break;
366: #endif /* !defined(DOUBLY_INDIRECT) */
367: case CF(DODOES) :
368: MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
369: break;
370: default : /* backward compatibility */
371: /* printf("Code field generation image[%x]:=CFA(%x)\n",
372: i, CF(image[i])); */
373: if (CF((token | 0x4000))<max_symbols) {
374: image[i]=(Cell)CFA(CF(token));
375: #ifdef DIRECT_THREADED
376: if ((token & 0x4000) == 0) { /* threade code, no CFA */
377: if (targets[k] & (1U<<(RELINFOBITS-1-j)))
378: compile_prim1(0);
379: compile_prim1(&image[i]);
380: }
381: #endif
382: } else
383: fprintf(stderr,"Primitive %ld used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n",(long)CF(token),(long)&image[i], i, PACKAGE_VERSION);
384: }
385: } else {
386: int tok = -token & 0x1FF;
387: if (tok < (groups[group+1]-groups[group])) {
388: #if defined(DOUBLY_INDIRECT)
389: image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
390: #else
391: image[i]=(Cell)CFA((groups[group]+tok));
392: #endif
393: #ifdef DIRECT_THREADED
394: if ((token & 0x4000) == 0) { /* threade code, no CFA */
395: if (targets[k] & (1U<<(RELINFOBITS-1-j)))
396: compile_prim1(0);
397: compile_prim1(&image[i]);
398: }
399: #endif
400: } else
401: fprintf(stderr,"Primitive %lx, %d of group %d used in this image at $%lx (offset $%x) is not implemented by this\n engine (%s); executing this code will crash.\n", (long)-token, tok, group, (long)&image[i],i,PACKAGE_VERSION);
402: }
403: } else {
404: /* if base is > 0: 0 is a null reference so don't adjust*/
405: if (token>=base) {
406: image[i]+=(Cell)start;
407: }
408: }
409: }
410: }
411: }
412: free(targets);
413: finish_code();
414: ((ImageHeader*)(image))->base = (Address) image;
415: }
416:
417: UCell checksum(Label symbols[])
418: {
419: UCell r=PRIM_VERSION;
420: Cell i;
421:
422: for (i=DOCOL; i<=DOESJUMP; i++) {
423: r ^= (UCell)(symbols[i]);
424: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
425: }
426: #ifdef DIRECT_THREADED
427: /* we have to consider all the primitives */
428: for (; symbols[i]!=(Label)0; i++) {
429: r ^= (UCell)(symbols[i]);
430: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
431: }
432: #else
433: /* in indirect threaded code all primitives are accessed through the
434: symbols table, so we just have to put the base address of symbols
435: in the checksum */
436: r ^= (UCell)symbols;
437: #endif
438: return r;
439: }
440:
441: Address verbose_malloc(Cell size)
442: {
443: Address r;
444: /* leave a little room (64B) for stack underflows */
445: if ((r = malloc(size+64))==NULL) {
446: perror(progname);
447: exit(1);
448: }
449: r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
450: debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
451: return r;
452: }
453:
454: static Address next_address=0;
455: void after_alloc(Address r, Cell size)
456: {
457: if (r != (Address)-1) {
458: debugp(stderr, "success, address=$%lx\n", (long) r);
459: if (pagesize != 1)
460: next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
461: } else {
462: debugp(stderr, "failed: %s\n", strerror(errno));
463: }
464: }
465:
466: #ifndef MAP_FAILED
467: #define MAP_FAILED ((Address) -1)
468: #endif
469: #ifndef MAP_FILE
470: # define MAP_FILE 0
471: #endif
472: #ifndef MAP_PRIVATE
473: # define MAP_PRIVATE 0
474: #endif
475: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
476: # define MAP_ANON MAP_ANONYMOUS
477: #endif
478:
479: #if defined(HAVE_MMAP)
480: static Address alloc_mmap(Cell size)
481: {
482: Address r;
483:
484: #if defined(MAP_ANON)
485: debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
486: r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0);
487: #else /* !defined(MAP_ANON) */
488: /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
489: apparently defaults) */
490: static int dev_zero=-1;
491:
492: if (dev_zero == -1)
493: dev_zero = open("/dev/zero", O_RDONLY);
494: if (dev_zero == -1) {
495: r = MAP_FAILED;
496: debugp(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ",
497: strerror(errno));
498: } else {
499: debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
500: r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE, dev_zero, 0);
501: }
502: #endif /* !defined(MAP_ANON) */
503: after_alloc(r, size);
504: return r;
505: }
506: #endif
507:
508: Address my_alloc(Cell size)
509: {
510: #if HAVE_MMAP
511: Address r;
512:
513: r=alloc_mmap(size);
514: if (r!=(Address)MAP_FAILED)
515: return r;
516: #endif /* HAVE_MMAP */
517: /* use malloc as fallback */
518: return verbose_malloc(size);
519: }
520:
521: Address dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
522: {
523: Address image = MAP_FAILED;
524:
525: #if defined(HAVE_MMAP)
526: if (offset==0) {
527: image=alloc_mmap(dictsize);
528: if (image != (Address)MAP_FAILED) {
529: Address image1;
530: debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
531: image1 = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE, fileno(file), 0);
532: after_alloc(image1,dictsize);
533: if (image1 == (Address)MAP_FAILED)
534: goto read_image;
535: }
536: }
537: #endif /* defined(HAVE_MMAP) */
538: if (image == (Address)MAP_FAILED) {
539: image = my_alloc(dictsize+offset)+offset;
540: read_image:
541: rewind(file); /* fseek(imagefile,0L,SEEK_SET); */
542: fread(image, 1, imagesize, file);
543: }
544: return image;
545: }
546:
547: void set_stack_sizes(ImageHeader * header)
548: {
549: if (dictsize==0)
550: dictsize = header->dict_size;
551: if (dsize==0)
552: dsize = header->data_stack_size;
553: if (rsize==0)
554: rsize = header->return_stack_size;
555: if (fsize==0)
556: fsize = header->fp_stack_size;
557: if (lsize==0)
558: lsize = header->locals_stack_size;
559: dictsize=maxaligned(dictsize);
560: dsize=maxaligned(dsize);
561: rsize=maxaligned(rsize);
562: lsize=maxaligned(lsize);
563: fsize=maxaligned(fsize);
564: }
565:
566: void alloc_stacks(ImageHeader * header)
567: {
568: header->dict_size=dictsize;
569: header->data_stack_size=dsize;
570: header->fp_stack_size=fsize;
571: header->return_stack_size=rsize;
572: header->locals_stack_size=lsize;
573:
574: header->data_stack_base=my_alloc(dsize);
575: header->fp_stack_base=my_alloc(fsize);
576: header->return_stack_base=my_alloc(rsize);
577: header->locals_stack_base=my_alloc(lsize);
578: }
579:
580: #warning You can ignore the warnings about clobbered variables in go_forth
581: int go_forth(Address image, int stack, Cell *entries)
582: {
583: volatile ImageHeader *image_header = (ImageHeader *)image;
584: Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
585: Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
586: Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
587: #ifdef GFORTH_DEBUGGING
588: volatile Cell *orig_rp0=rp0;
589: #endif
590: Address lp0=image_header->locals_stack_base + lsize;
591: Xt *ip0=(Xt *)(image_header->boot_entry);
592: #ifdef SYSSIGNALS
593: int throw_code;
594: #endif
595:
596: /* ensure that the cached elements (if any) are accessible */
597: #if !(defined(GFORTH_DEBUGGING) || defined(INDIRECT_THREADED) || defined(DOUBLY_INDIRECT) || defined(VM_PROFILING))
598: sp0 -= 8; /* make stuff below bottom accessible for stack caching */
599: #endif
600: IF_fpTOS(fp0--);
601:
602: for(;stack>0;stack--)
603: *--sp0=entries[stack-1];
604:
605: #ifdef SYSSIGNALS
606: get_winsize();
607:
608: install_signal_handlers(); /* right place? */
609:
610: if ((throw_code=setjmp(throw_jmp_buf))) {
611: static Cell signal_data_stack[8];
612: static Cell signal_return_stack[8];
613: static Float signal_fp_stack[1];
614:
615: signal_data_stack[7]=throw_code;
616:
617: #ifdef GFORTH_DEBUGGING
618: debugp(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
619: throw_code, saved_ip, rp);
620: if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
621: /* no rstack overflow or underflow */
622: rp0 = rp;
623: *--rp0 = (Cell)saved_ip;
624: }
625: else /* I love non-syntactic ifdefs :-) */
626: rp0 = signal_return_stack+8;
627: #else /* !defined(GFORTH_DEBUGGING) */
628: debugp(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
629: rp0 = signal_return_stack+8;
630: #endif /* !defined(GFORTH_DEBUGGING) */
631: /* fprintf(stderr, "rp=$%x\n",rp0);*/
632:
633: return((int)(Cell)engine(image_header->throw_entry, signal_data_stack+7,
634: rp0, signal_fp_stack, 0));
635: }
636: #endif
637:
638: return((int)(Cell)engine(ip0,sp0,rp0,fp0,lp0));
639: }
640:
641: #ifndef INCLUDE_IMAGE
642: void print_sizes(Cell sizebyte)
643: /* print size information */
644: {
645: static char* endianstring[]= { " big","little" };
646:
647: fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
648: endianstring[sizebyte & 1],
649: 1 << ((sizebyte >> 1) & 3),
650: 1 << ((sizebyte >> 3) & 3),
651: 1 << ((sizebyte >> 5) & 3));
652: }
653:
654: /* static superinstruction stuff */
655:
656: struct cost { /* super_info might be a more accurate name */
657: char loads; /* number of stack loads */
658: char stores; /* number of stack stores */
659: char updates; /* number of stack pointer updates */
660: char branch; /* is it a branch (SET_IP) */
661: unsigned char state_in; /* state on entry */
662: unsigned char state_out; /* state on exit */
663: unsigned char imm_ops; /* number of immediate operands */
664: short offset; /* offset into super2 table */
665: unsigned char length; /* number of components */
666: };
667:
668: PrimNum super2[] = {
669: #include SUPER2_I
670: };
671:
672: struct cost super_costs[] = {
673: #include COSTS_I
674: };
675:
676: struct super_state {
677: struct super_state *next;
678: PrimNum super;
679: };
680:
681: #define HASH_SIZE 256
682:
683: struct super_table_entry {
684: struct super_table_entry *next;
685: PrimNum *start;
686: short length;
687: struct super_state *ss_list; /* list of supers */
688: } *super_table[HASH_SIZE];
689: int max_super=2;
690:
691: struct super_state *state_transitions=NULL;
692:
693: int hash_super(PrimNum *start, int length)
694: {
695: int i, r;
696:
697: for (i=0, r=0; i<length; i++) {
698: r <<= 1;
699: r += start[i];
700: }
701: return r & (HASH_SIZE-1);
702: }
703:
704: struct super_state **lookup_super(PrimNum *start, int length)
705: {
706: int hash=hash_super(start,length);
707: struct super_table_entry *p = super_table[hash];
708:
709: /* assert(length >= 2); */
710: for (; p!=NULL; p = p->next) {
711: if (length == p->length &&
712: memcmp((char *)p->start, (char *)start, length*sizeof(PrimNum))==0)
713: return &(p->ss_list);
714: }
715: return NULL;
716: }
717:
718: void prepare_super_table()
719: {
720: int i;
721: int nsupers = 0;
722:
723: for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
724: struct cost *c = &super_costs[i];
725: if ((c->length < 2 || nsupers < static_super_number) &&
726: c->state_in < maxstates && c->state_out < maxstates) {
727: struct super_state **ss_listp= lookup_super(super2+c->offset, c->length);
728: struct super_state *ss = malloc(sizeof(struct super_state));
729: ss->super= i;
730: if (c->offset==N_noop && i != N_noop) {
731: if (is_relocatable(i)) {
732: ss->next = state_transitions;
733: state_transitions = ss;
734: }
735: } else if (ss_listp != NULL) {
736: ss->next = *ss_listp;
737: *ss_listp = ss;
738: } else {
739: int hash = hash_super(super2+c->offset, c->length);
740: struct super_table_entry **p = &super_table[hash];
741: struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
742: ss->next = NULL;
743: e->next = *p;
744: e->start = super2 + c->offset;
745: e->length = c->length;
746: e->ss_list = ss;
747: *p = e;
748: }
749: if (c->length > max_super)
750: max_super = c->length;
751: if (c->length >= 2)
752: nsupers++;
753: }
754: }
755: debugp(stderr, "Using %d static superinsts\n", nsupers);
756: }
757:
758: /* dynamic replication/superinstruction stuff */
759:
760: #ifndef NO_DYNAMIC
761: int compare_priminfo_length(const void *_a, const void *_b)
762: {
763: PrimInfo **a = (PrimInfo **)_a;
764: PrimInfo **b = (PrimInfo **)_b;
765: Cell diff = (*a)->length - (*b)->length;
766: if (diff)
767: return diff;
768: else /* break ties by start address; thus the decompiler produces
769: the earliest primitive with the same code (e.g. noop instead
770: of (char) and @ instead of >code-address */
771: return (*b)->start - (*a)->start;
772: }
773: #endif /* !defined(NO_DYNAMIC) */
774:
775: static char MAYBE_UNUSED superend[]={
776: #include PRIM_SUPEREND_I
777: };
778:
779: Cell npriminfos=0;
780:
781: Label goto_start;
782: Cell goto_len;
783:
784: int compare_labels(const void *pa, const void *pb)
785: {
786: Label a = *(Label *)pa;
787: Label b = *(Label *)pb;
788: return a-b;
789: }
790:
791: Label bsearch_next(Label key, Label *a, UCell n)
792: /* a is sorted; return the label >=key that is the closest in a;
793: return NULL if there is no label in a >=key */
794: {
795: int mid = (n-1)/2;
796: if (n<1)
797: return NULL;
798: if (n == 1) {
799: if (a[0] < key)
800: return NULL;
801: else
802: return a[0];
803: }
804: if (a[mid] < key)
805: return bsearch_next(key, a+mid+1, n-mid-1);
806: else
807: return bsearch_next(key, a, mid+1);
808: }
809:
810: void check_prims(Label symbols1[])
811: {
812: int i;
813: #ifndef NO_DYNAMIC
814: Label *symbols2, *symbols3, *ends1, *ends1j, *ends1jsorted, *goto_p;
815: int nends1j;
816: #endif
817:
818: if (debug)
819: #ifdef __VERSION__
820: fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
821: #else
822: #define xstr(s) str(s)
823: #define str(s) #s
824: fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n");
825: #endif
826: for (i=0; symbols1[i]!=0; i++)
827: ;
828: npriminfos = i;
829:
830: #ifndef NO_DYNAMIC
831: if (no_dynamic)
832: return;
833: symbols2=engine2(0,0,0,0,0);
834: #if NO_IP
835: symbols3=engine3(0,0,0,0,0);
836: #else
837: symbols3=symbols1;
838: #endif
839: ends1 = symbols1+i+1;
840: ends1j = ends1+i;
841: goto_p = ends1j+i+1; /* goto_p[0]==before; ...[1]==after;*/
842: nends1j = i+1;
843: ends1jsorted = (Label *)alloca(nends1j*sizeof(Label));
844: memcpy(ends1jsorted,ends1j,nends1j*sizeof(Label));
845: qsort(ends1jsorted, nends1j, sizeof(Label), compare_labels);
846:
847: /* check whether the "goto *" is relocatable */
848: goto_len = goto_p[1]-goto_p[0];
849: debugp(stderr, "goto * %p %p len=%ld\n",
850: goto_p[0],symbols2[goto_p-symbols1],goto_len);
851: if (memcmp(goto_p[0],symbols2[goto_p-symbols1],goto_len)!=0) { /* unequal */
852: no_dynamic=1;
853: debugp(stderr," not relocatable, disabling dynamic code generation\n");
854: init_ss_cost();
855: return;
856: }
857: goto_start = goto_p[0];
858:
859: priminfos = calloc(i,sizeof(PrimInfo));
860: for (i=0; symbols1[i]!=0; i++) {
861: int prim_len = ends1[i]-symbols1[i];
862: PrimInfo *pi=&priminfos[i];
863: int j=0;
864: char *s1 = (char *)symbols1[i];
865: char *s2 = (char *)symbols2[i];
866: char *s3 = (char *)symbols3[i];
867: Label endlabel = bsearch_next(symbols1[i]+1,ends1jsorted,nends1j);
868:
869: pi->start = s1;
870: pi->superend = superend[i]|no_super;
871: pi->length = prim_len;
872: pi->restlength = endlabel - symbols1[i] - pi->length;
873: pi->nimmargs = 0;
874: relocs++;
875: debugp(stderr, "%-15s %3d %p %p %p len=%3ld restlen=%2ld s-end=%1d",
876: prim_names[i], i, s1, s2, s3, (long)(pi->length), (long)(pi->restlength), pi->superend);
877: if (endlabel == NULL) {
878: pi->start = NULL; /* not relocatable */
879: if (pi->length<0) pi->length=100;
880: debugp(stderr,"\n non_reloc: no J label > start found\n");
881: relocs--;
882: nonrelocs++;
883: continue;
884: }
885: if (ends1[i] > endlabel && !pi->superend) {
886: pi->start = NULL; /* not relocatable */
887: pi->length = endlabel-symbols1[i];
888: debugp(stderr,"\n non_reloc: there is a J label before the K label (restlength<0)\n");
889: relocs--;
890: nonrelocs++;
891: continue;
892: }
893: if (ends1[i] < pi->start && !pi->superend) {
894: pi->start = NULL; /* not relocatable */
895: pi->length = endlabel-symbols1[i];
896: debugp(stderr,"\n non_reloc: K label before I label (length<0)\n");
897: relocs--;
898: nonrelocs++;
899: continue;
900: }
901: assert(pi->length>=0);
902: assert(pi->restlength >=0);
903: while (j<(pi->length+pi->restlength)) {
904: if (s1[j]==s3[j]) {
905: if (s1[j] != s2[j]) {
906: pi->start = NULL; /* not relocatable */
907: debugp(stderr,"\n non_reloc: engine1!=engine2 offset %3d",j);
908: /* assert(j<prim_len); */
909: relocs--;
910: nonrelocs++;
911: break;
912: }
913: j++;
914: } else {
915: struct immarg *ia=&pi->immargs[pi->nimmargs];
916:
917: pi->nimmargs++;
918: ia->offset=j;
919: if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
920: ia->rel=0;
921: debugp(stderr,"\n absolute immarg: offset %3d",j);
922: } else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
923: symbols1[DOESJUMP+1]) {
924: ia->rel=1;
925: debugp(stderr,"\n relative immarg: offset %3d",j);
926: } else {
927: pi->start = NULL; /* not relocatable */
928: debugp(stderr,"\n non_reloc: engine1!=engine3 offset %3d",j);
929: /* assert(j<prim_len);*/
930: relocs--;
931: nonrelocs++;
932: break;
933: }
934: j+=4;
935: }
936: }
937: debugp(stderr,"\n");
938: }
939: decomp_prims = calloc(i,sizeof(PrimInfo *));
940: for (i=DOESJUMP+1; i<npriminfos; i++)
941: decomp_prims[i] = &(priminfos[i]);
942: qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
943: compare_priminfo_length);
944: #endif
945: }
946:
947: void flush_to_here(void)
948: {
949: #ifndef NO_DYNAMIC
950: if (start_flush)
951: FLUSH_ICACHE(start_flush, code_here-start_flush);
952: start_flush=code_here;
953: #endif
954: }
955:
956: #ifndef NO_DYNAMIC
957: void append_jump(void)
958: {
959: if (last_jump) {
960: PrimInfo *pi = &priminfos[last_jump];
961:
962: memcpy(code_here, pi->start+pi->length, pi->restlength);
963: code_here += pi->restlength;
964: memcpy(code_here, goto_start, goto_len);
965: code_here += goto_len;
966: last_jump=0;
967: }
968: }
969:
970: /* Gforth remembers all code blocks in this list. On forgetting (by
971: executing a marker) the code blocks are not freed (because Gforth does
972: not remember how they were allocated; hmm, remembering that might be
973: easier and cleaner). Instead, code_here etc. are reset to the old
974: value, and the "forgotten" code blocks are reused when they are
975: needed. */
976:
977: struct code_block_list {
978: struct code_block_list *next;
979: Address block;
980: Cell size;
981: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
982:
983: Address append_prim(Cell p)
984: {
985: PrimInfo *pi = &priminfos[p];
986: Address old_code_here = code_here;
987:
988: if (code_area+code_area_size < code_here+pi->length+pi->restlength) {
989: struct code_block_list *p;
990: append_jump();
991: flush_to_here();
992: if (*next_code_blockp == NULL) {
993: code_here = start_flush = code_area = my_alloc(code_area_size);
994: p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
995: *next_code_blockp = p;
996: p->next = NULL;
997: p->block = code_here;
998: p->size = code_area_size;
999: } else {
1000: p = *next_code_blockp;
1001: code_here = start_flush = code_area = p->block;
1002: }
1003: old_code_here = code_here;
1004: next_code_blockp = &(p->next);
1005: }
1006: memcpy(code_here, pi->start, pi->length);
1007: code_here += pi->length;
1008: return old_code_here;
1009: }
1010: #endif
1011:
1012: int forget_dyncode(Address code)
1013: {
1014: #ifdef NO_DYNAMIC
1015: return -1;
1016: #else
1017: struct code_block_list *p, **pp;
1018:
1019: for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
1020: if (code >= p->block && code < p->block+p->size) {
1021: next_code_blockp = &(p->next);
1022: code_here = start_flush = code;
1023: code_area = p->block;
1024: last_jump = 0;
1025: return -1;
1026: }
1027: }
1028: return -no_dynamic;
1029: #endif /* !defined(NO_DYNAMIC) */
1030: }
1031:
1032: long dyncodesize(void)
1033: {
1034: #ifndef NO_DYNAMIC
1035: struct code_block_list *p;
1036: long size=0;
1037: for (p=code_block_list; p!=NULL; p=p->next) {
1038: if (code_here >= p->block && code_here < p->block+p->size)
1039: return size + (code_here - p->block);
1040: else
1041: size += p->size;
1042: }
1043: #endif /* !defined(NO_DYNAMIC) */
1044: return 0;
1045: }
1046:
1047: Label decompile_code(Label _code)
1048: {
1049: #ifdef NO_DYNAMIC
1050: return _code;
1051: #else /* !defined(NO_DYNAMIC) */
1052: Cell i;
1053: struct code_block_list *p;
1054: Address code=_code;
1055:
1056: /* first, check if we are in code at all */
1057: for (p = code_block_list;; p = p->next) {
1058: if (p == NULL)
1059: return code;
1060: if (code >= p->block && code < p->block+p->size)
1061: break;
1062: }
1063: /* reverse order because NOOP might match other prims */
1064: for (i=npriminfos-1; i>DOESJUMP; i--) {
1065: PrimInfo *pi=decomp_prims[i];
1066: if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
1067: return vm_prims[super2[super_costs[pi-priminfos].offset]];
1068: /* return pi->start;*/
1069: }
1070: return code;
1071: #endif /* !defined(NO_DYNAMIC) */
1072: }
1073:
1074: #ifdef NO_IP
1075: int nbranchinfos=0;
1076:
1077: struct branchinfo {
1078: Label **targetpp; /* **(bi->targetpp) is the target */
1079: Cell *addressptr; /* store the target here */
1080: } branchinfos[100000];
1081:
1082: int ndoesexecinfos=0;
1083: struct doesexecinfo {
1084: int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
1085: Label *targetp; /*target for branch (because this is not in threaded code)*/
1086: Cell *xt; /* cfa of word whose does-code needs calling */
1087: } doesexecinfos[10000];
1088:
1089: void set_rel_target(Cell *source, Label target)
1090: {
1091: *source = ((Cell)target)-(((Cell)source)+4);
1092: }
1093:
1094: void register_branchinfo(Label source, Cell *targetpp)
1095: {
1096: struct branchinfo *bi = &(branchinfos[nbranchinfos]);
1097: bi->targetpp = (Label **)targetpp;
1098: bi->addressptr = (Cell *)source;
1099: nbranchinfos++;
1100: }
1101:
1102: Address compile_prim1arg(PrimNum p, Cell **argp)
1103: {
1104: Address old_code_here=append_prim(p);
1105:
1106: assert(vm_prims[p]==priminfos[p].start);
1107: *argp = (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
1108: return old_code_here;
1109: }
1110:
1111: Address compile_call2(Cell *targetpp, Cell **next_code_targetp)
1112: {
1113: PrimInfo *pi = &priminfos[N_call2];
1114: Address old_code_here = append_prim(N_call2);
1115:
1116: *next_code_targetp = (Cell *)(old_code_here + pi->immargs[0].offset);
1117: register_branchinfo(old_code_here + pi->immargs[1].offset, targetpp);
1118: return old_code_here;
1119: }
1120: #endif
1121:
1122: void finish_code(void)
1123: {
1124: #ifdef NO_IP
1125: Cell i;
1126:
1127: compile_prim1(NULL);
1128: for (i=0; i<ndoesexecinfos; i++) {
1129: struct doesexecinfo *dei = &doesexecinfos[i];
1130: dei->targetp = (Label *)DOES_CODE1((dei->xt));
1131: branchinfos[dei->branchinfo].targetpp = &(dei->targetp);
1132: }
1133: ndoesexecinfos = 0;
1134: for (i=0; i<nbranchinfos; i++) {
1135: struct branchinfo *bi=&branchinfos[i];
1136: set_rel_target(bi->addressptr, **(bi->targetpp));
1137: }
1138: nbranchinfos = 0;
1139: #else
1140: compile_prim1(NULL);
1141: #endif
1142: flush_to_here();
1143: }
1144:
1145: #ifdef NO_IP
1146: Cell compile_prim_dyn(PrimNum p, Cell *tcp)
1147: /* compile prim #p dynamically (mod flags etc.) and return start
1148: address of generated code for putting it into the threaded
1149: code. This function is only called if all the associated
1150: inline arguments of p are already in place (at tcp[1] etc.) */
1151: {
1152: PrimInfo *pi=&priminfos[p];
1153: Cell *next_code_target=NULL;
1154: Address codeaddr;
1155: Address primstart;
1156:
1157: assert(p<npriminfos);
1158: if (p==N_execute || p==N_perform || p==N_lit_perform) {
1159: codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
1160: primstart = append_prim(p);
1161: goto other_prim;
1162: } else if (p==N_call) {
1163: codeaddr = compile_call2(tcp+1, &next_code_target);
1164: } else if (p==N_does_exec) {
1165: struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
1166: Cell *arg;
1167: codeaddr = compile_prim1arg(N_lit,&arg);
1168: *arg = (Cell)PFA(tcp[1]);
1169: /* we cannot determine the callee now (last_start[1] may be a
1170: forward reference), so just register an arbitrary target, and
1171: register in dei that we need to fix this before resolving
1172: branches */
1173: dei->branchinfo = nbranchinfos;
1174: dei->xt = (Cell *)(tcp[1]);
1175: compile_call2(0, &next_code_target);
1176: } else if (!is_relocatable(p)) {
1177: Cell *branch_target;
1178: codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
1179: compile_prim1arg(N_branch,&branch_target);
1180: set_rel_target(branch_target,vm_prims[p]);
1181: } else {
1182: unsigned j;
1183:
1184: codeaddr = primstart = append_prim(p);
1185: other_prim:
1186: for (j=0; j<pi->nimmargs; j++) {
1187: struct immarg *ia = &(pi->immargs[j]);
1188: Cell *argp = tcp + pi->nimmargs - j;
1189: Cell argval = *argp; /* !! specific to prims */
1190: if (ia->rel) { /* !! assumption: relative refs are branches */
1191: register_branchinfo(primstart + ia->offset, argp);
1192: } else /* plain argument */
1193: *(Cell *)(primstart + ia->offset) = argval;
1194: }
1195: }
1196: if (next_code_target!=NULL)
1197: *next_code_target = (Cell)code_here;
1198: return (Cell)codeaddr;
1199: }
1200: #else /* !defined(NO_IP) */
1201: Cell compile_prim_dyn(PrimNum p, Cell *tcp)
1202: /* compile prim #p dynamically (mod flags etc.) and return start
1203: address of generated code for putting it into the threaded code */
1204: {
1205: Cell static_prim = (Cell)vm_prims[p];
1206: #if defined(NO_DYNAMIC)
1207: return static_prim;
1208: #else /* !defined(NO_DYNAMIC) */
1209: Address old_code_here;
1210:
1211: if (no_dynamic)
1212: return static_prim;
1213: if (p>=npriminfos || !is_relocatable(p)) {
1214: append_jump();
1215: return static_prim;
1216: }
1217: old_code_here = append_prim(p);
1218: last_jump = p;
1219: if (priminfos[p].superend)
1220: append_jump();
1221: return (Cell)old_code_here;
1222: #endif /* !defined(NO_DYNAMIC) */
1223: }
1224: #endif /* !defined(NO_IP) */
1225:
1226: #ifndef NO_DYNAMIC
1227: int cost_codesize(int prim)
1228: {
1229: return priminfos[prim].length;
1230: }
1231: #endif
1232:
1233: int cost_ls(int prim)
1234: {
1235: struct cost *c = super_costs+prim;
1236:
1237: return c->loads + c->stores;
1238: }
1239:
1240: int cost_lsu(int prim)
1241: {
1242: struct cost *c = super_costs+prim;
1243:
1244: return c->loads + c->stores + c->updates;
1245: }
1246:
1247: int cost_nexts(int prim)
1248: {
1249: return 1;
1250: }
1251:
1252: typedef int Costfunc(int);
1253: Costfunc *ss_cost = /* cost function for optimize_bb */
1254: #ifdef NO_DYNAMIC
1255: cost_lsu;
1256: #else
1257: cost_codesize;
1258: #endif
1259:
1260: struct {
1261: Costfunc *costfunc;
1262: char *metricname;
1263: long sum;
1264: } cost_sums[] = {
1265: #ifndef NO_DYNAMIC
1266: { cost_codesize, "codesize", 0 },
1267: #endif
1268: { cost_ls, "ls", 0 },
1269: { cost_lsu, "lsu", 0 },
1270: { cost_nexts, "nexts", 0 }
1271: };
1272:
1273: #ifndef NO_DYNAMIC
1274: void init_ss_cost(void) {
1275: if (no_dynamic && ss_cost == cost_codesize) {
1276: ss_cost = cost_nexts;
1277: cost_sums[0] = cost_sums[1]; /* don't use cost_codesize for print-metrics */
1278: debugp(stderr, "--no-dynamic conflicts with --ss-min-codesize, reverting to --ss-min-nexts\n");
1279: }
1280: }
1281: #endif
1282:
1283: #define MAX_BB 128 /* maximum number of instructions in BB */
1284: #define INF_COST 1000000 /* infinite cost */
1285: #define CANONICAL_STATE 0
1286:
1287: struct waypoint {
1288: int cost; /* the cost from here to the end */
1289: PrimNum inst; /* the inst used from here to the next waypoint */
1290: char relocatable; /* the last non-transition was relocatable */
1291: char no_transition; /* don't use the next transition (relocatability)
1292: * or this transition (does not change state) */
1293: };
1294:
1295: void init_waypoints(struct waypoint ws[])
1296: {
1297: int k;
1298:
1299: for (k=0; k<maxstates; k++)
1300: ws[k].cost=INF_COST;
1301: }
1302:
1303: void transitions(struct waypoint inst[], struct waypoint trans[])
1304: {
1305: int k;
1306: struct super_state *l;
1307:
1308: for (k=0; k<maxstates; k++) {
1309: trans[k] = inst[k];
1310: trans[k].no_transition = 1;
1311: }
1312: for (l = state_transitions; l != NULL; l = l->next) {
1313: PrimNum s = l->super;
1314: int jcost;
1315: struct cost *c=super_costs+s;
1316: struct waypoint *wi=&(trans[c->state_in]);
1317: struct waypoint *wo=&(inst[c->state_out]);
1318: if (wo->cost == INF_COST)
1319: continue;
1320: jcost = wo->cost + ss_cost(s);
1321: if (jcost <= wi->cost) {
1322: wi->cost = jcost;
1323: wi->inst = s;
1324: wi->relocatable = wo->relocatable;
1325: wi->no_transition = 0;
1326: /* if (ss_greedy) wi->cost = wo->cost ? */
1327: }
1328: }
1329: }
1330:
1331: /* use dynamic programming to find the shortest paths within the basic
1332: block origs[0..ninsts-1] and rewrite the instructions pointed to by
1333: instps to use it */
1334: void optimize_rewrite(Cell *instps[], PrimNum origs[], int ninsts)
1335: {
1336: int i,j;
1337: static struct waypoint inst[MAX_BB+1][MAX_STATE]; /* before instruction*/
1338: static struct waypoint trans[MAX_BB+1][MAX_STATE]; /* before transition */
1339: int nextdyn, nextstate, no_transition;
1340:
1341: init_waypoints(inst[ninsts]);
1342: inst[ninsts][CANONICAL_STATE].cost=0;
1343: transitions(inst[ninsts],trans[ninsts]);
1344: for (i=ninsts-1; i>=0; i--) {
1345: init_waypoints(inst[i]);
1346: for (j=1; j<=max_super && i+j<=ninsts; j++) {
1347: struct super_state **superp = lookup_super(origs+i, j);
1348: if (superp!=NULL) {
1349: struct super_state *supers = *superp;
1350: for (; supers!=NULL; supers = supers->next) {
1351: PrimNum s = supers->super;
1352: int jcost;
1353: struct cost *c=super_costs+s;
1354: struct waypoint *wi=&(inst[i][c->state_in]);
1355: struct waypoint *wo=&(trans[i+j][c->state_out]);
1356: int no_transition = wo->no_transition;
1357: if (!(is_relocatable(s)) && !wo->relocatable) {
1358: wo=&(inst[i+j][c->state_out]);
1359: no_transition=1;
1360: }
1361: if (wo->cost == INF_COST)
1362: continue;
1363: jcost = wo->cost + ss_cost(s);
1364: if (jcost <= wi->cost) {
1365: wi->cost = jcost;
1366: wi->inst = s;
1367: wi->relocatable = is_relocatable(s);
1368: wi->no_transition = no_transition;
1369: /* if (ss_greedy) wi->cost = wo->cost ? */
1370: }
1371: }
1372: }
1373: }
1374: transitions(inst[i],trans[i]);
1375: }
1376: /* now rewrite the instructions */
1377: nextdyn=0;
1378: nextstate=CANONICAL_STATE;
1379: no_transition = ((!trans[0][nextstate].relocatable)
1380: ||trans[0][nextstate].no_transition);
1381: for (i=0; i<ninsts; i++) {
1382: Cell tc=0, tc2;
1383: if (i==nextdyn) {
1384: if (!no_transition) {
1385: /* process trans */
1386: PrimNum p = trans[i][nextstate].inst;
1387: struct cost *c = super_costs+p;
1388: assert(trans[i][nextstate].cost != INF_COST);
1389: assert(c->state_in==nextstate);
1390: tc = compile_prim_dyn(p,NULL);
1391: nextstate = c->state_out;
1392: }
1393: {
1394: /* process inst */
1395: PrimNum p = inst[i][nextstate].inst;
1396: struct cost *c=super_costs+p;
1397: assert(c->state_in==nextstate);
1398: assert(inst[i][nextstate].cost != INF_COST);
1399: #if defined(GFORTH_DEBUGGING)
1400: assert(p == origs[i]);
1401: #endif
1402: tc2 = compile_prim_dyn(p,instps[i]);
1403: if (no_transition || !is_relocatable(p))
1404: /* !! actually what we care about is if and where
1405: * compile_prim_dyn() puts NEXTs */
1406: tc=tc2;
1407: no_transition = inst[i][nextstate].no_transition;
1408: nextstate = c->state_out;
1409: nextdyn += c->length;
1410: }
1411: } else {
1412: #if defined(GFORTH_DEBUGGING)
1413: assert(0);
1414: #endif
1415: tc=0;
1416: /* tc= (Cell)vm_prims[inst[i][CANONICAL_STATE].inst]; */
1417: }
1418: *(instps[i]) = tc;
1419: }
1420: if (!no_transition) {
1421: PrimNum p = trans[i][nextstate].inst;
1422: struct cost *c = super_costs+p;
1423: assert(c->state_in==nextstate);
1424: assert(trans[i][nextstate].cost != INF_COST);
1425: assert(i==nextdyn);
1426: (void)compile_prim_dyn(p,NULL);
1427: nextstate = c->state_out;
1428: }
1429: assert(nextstate==CANONICAL_STATE);
1430: }
1431:
1432: /* compile *start, possibly rewriting it into a static and/or dynamic
1433: superinstruction */
1434: void compile_prim1(Cell *start)
1435: {
1436: #if defined(DOUBLY_INDIRECT)
1437: Label prim;
1438:
1439: if (start==NULL)
1440: return;
1441: prim = (Label)*start;
1442: if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
1443: fprintf(stderr,"compile_prim encountered xt %p\n", prim);
1444: *start=(Cell)prim;
1445: return;
1446: } else {
1447: *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
1448: return;
1449: }
1450: #elif defined(INDIRECT_THREADED)
1451: return;
1452: #else /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1453: /* !! does not work, for unknown reasons; but something like this is
1454: probably needed to ensure that we don't call compile_prim_dyn
1455: before the inline arguments are there */
1456: static Cell *instps[MAX_BB];
1457: static PrimNum origs[MAX_BB];
1458: static int ninsts=0;
1459: PrimNum prim_num;
1460:
1461: if (start==NULL || ninsts >= MAX_BB ||
1462: (ninsts>0 && superend[origs[ninsts-1]])) {
1463: /* after bb, or at the start of the next bb */
1464: optimize_rewrite(instps,origs,ninsts);
1465: /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts); */
1466: ninsts=0;
1467: if (start==NULL)
1468: return;
1469: }
1470: prim_num = ((Xt)*start)-vm_prims;
1471: if(prim_num >= npriminfos) {
1472: optimize_rewrite(instps,origs,ninsts);
1473: /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts);*/
1474: ninsts=0;
1475: return;
1476: }
1477: assert(ninsts<MAX_BB);
1478: instps[ninsts] = start;
1479: origs[ninsts] = prim_num;
1480: ninsts++;
1481: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1482: }
1483:
1484: Address loader(FILE *imagefile, char* filename)
1485: /* returns the address of the image proper (after the preamble) */
1486: {
1487: ImageHeader header;
1488: Address image;
1489: Address imp; /* image+preamble */
1490: Char magic[8];
1491: char magic7; /* size byte of magic number */
1492: Cell preamblesize=0;
1493: Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1494: UCell check_sum;
1495: Cell ausize = ((RELINFOBITS == 8) ? 0 :
1496: (RELINFOBITS == 16) ? 1 :
1497: (RELINFOBITS == 32) ? 2 : 3);
1498: Cell charsize = ((sizeof(Char) == 1) ? 0 :
1499: (sizeof(Char) == 2) ? 1 :
1500: (sizeof(Char) == 4) ? 2 : 3) + ausize;
1501: Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
1502: (sizeof(Cell) == 2) ? 1 :
1503: (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1504: Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
1505: #ifdef WORDS_BIGENDIAN
1506: 0
1507: #else
1508: 1
1509: #endif
1510: ;
1511:
1512: vm_prims = engine(0,0,0,0,0);
1513: check_prims(vm_prims);
1514: prepare_super_table();
1515: #ifndef DOUBLY_INDIRECT
1516: #ifdef PRINT_SUPER_LENGTHS
1517: print_super_lengths();
1518: #endif
1519: check_sum = checksum(vm_prims);
1520: #else /* defined(DOUBLY_INDIRECT) */
1521: check_sum = (UCell)vm_prims;
1522: #endif /* defined(DOUBLY_INDIRECT) */
1523:
1524: do {
1525: if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1526: fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
1527: progname, filename);
1528: exit(1);
1529: }
1530: preamblesize+=8;
1531: } while(memcmp(magic,"Gforth3",7));
1532: magic7 = magic[7];
1533: if (debug) {
1534: magic[7]='\0';
1535: fprintf(stderr,"Magic found: %s ", magic);
1536: print_sizes(magic7);
1537: }
1538:
1539: if (magic7 != sizebyte)
1540: {
1541: fprintf(stderr,"This image is: ");
1542: print_sizes(magic7);
1543: fprintf(stderr,"whereas the machine is ");
1544: print_sizes(sizebyte);
1545: exit(-2);
1546: };
1547:
1548: fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1549:
1550: set_stack_sizes(&header);
1551:
1552: #if HAVE_GETPAGESIZE
1553: pagesize=getpagesize(); /* Linux/GNU libc offers this */
1554: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
1555: pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
1556: #elif PAGESIZE
1557: pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
1558: #endif
1559: debugp(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1560:
1561: image = dict_alloc_read(imagefile, preamblesize+header.image_size,
1562: preamblesize+dictsize, data_offset);
1563: imp=image+preamblesize;
1564: alloc_stacks((ImageHeader *)imp);
1565: if (clear_dictionary)
1566: memset(imp+header.image_size, 0, dictsize-header.image_size);
1567: if(header.base==0 || header.base == (Address)0x100) {
1568: Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
1569: char reloc_bits[reloc_size];
1570: fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1571: fread(reloc_bits, 1, reloc_size, imagefile);
1572: relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
1573: #if 0
1574: { /* let's see what the relocator did */
1575: FILE *snapshot=fopen("snapshot.fi","wb");
1576: fwrite(image,1,imagesize,snapshot);
1577: fclose(snapshot);
1578: }
1579: #endif
1580: }
1581: else if(header.base!=imp) {
1582: fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
1583: progname, (unsigned long)header.base, (unsigned long)imp);
1584: exit(1);
1585: }
1586: if (header.checksum==0)
1587: ((ImageHeader *)imp)->checksum=check_sum;
1588: else if (header.checksum != check_sum) {
1589: fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
1590: progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
1591: exit(1);
1592: }
1593: #ifdef DOUBLY_INDIRECT
1594: ((ImageHeader *)imp)->xt_base = xts;
1595: #endif
1596: fclose(imagefile);
1597:
1598: /* unnecessary, except maybe for CODE words */
1599: /* FLUSH_ICACHE(imp, header.image_size);*/
1600:
1601: return imp;
1602: }
1603:
1604: /* pointer to last '/' or '\' in file, 0 if there is none. */
1605: char *onlypath(char *filename)
1606: {
1607: return strrchr(filename, DIRSEP);
1608: }
1609:
1610: FILE *openimage(char *fullfilename)
1611: {
1612: FILE *image_file;
1613: char * expfilename = tilde_cstr(fullfilename, strlen(fullfilename), 1);
1614:
1615: image_file=fopen(expfilename,"rb");
1616: if (image_file!=NULL && debug)
1617: fprintf(stderr, "Opened image file: %s\n", expfilename);
1618: return image_file;
1619: }
1620:
1621: /* try to open image file concat(path[0:len],imagename) */
1622: FILE *checkimage(char *path, int len, char *imagename)
1623: {
1624: int dirlen=len;
1625: char fullfilename[dirlen+strlen(imagename)+2];
1626:
1627: memcpy(fullfilename, path, dirlen);
1628: if (fullfilename[dirlen-1]!=DIRSEP)
1629: fullfilename[dirlen++]=DIRSEP;
1630: strcpy(fullfilename+dirlen,imagename);
1631: return openimage(fullfilename);
1632: }
1633:
1634: FILE * open_image_file(char * imagename, char * path)
1635: {
1636: FILE * image_file=NULL;
1637: char *origpath=path;
1638:
1639: if(strchr(imagename, DIRSEP)==NULL) {
1640: /* first check the directory where the exe file is in !! 01may97jaw */
1641: if (onlypath(progname))
1642: image_file=checkimage(progname, onlypath(progname)-progname, imagename);
1643: if (!image_file)
1644: do {
1645: char *pend=strchr(path, PATHSEP);
1646: if (pend==NULL)
1647: pend=path+strlen(path);
1648: if (strlen(path)==0) break;
1649: image_file=checkimage(path, pend-path, imagename);
1650: path=pend+(*pend==PATHSEP);
1651: } while (image_file==NULL);
1652: } else {
1653: image_file=openimage(imagename);
1654: }
1655:
1656: if (!image_file) {
1657: fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
1658: progname, imagename, origpath);
1659: exit(1);
1660: }
1661:
1662: return image_file;
1663: }
1664: #endif
1665:
1666: #ifdef HAS_OS
1667: UCell convsize(char *s, UCell elemsize)
1668: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
1669: of bytes. the letter at the end indicates the unit, where e stands
1670: for the element size. default is e */
1671: {
1672: char *endp;
1673: UCell n,m;
1674:
1675: m = elemsize;
1676: n = strtoul(s,&endp,0);
1677: if (endp!=NULL) {
1678: if (strcmp(endp,"b")==0)
1679: m=1;
1680: else if (strcmp(endp,"k")==0)
1681: m=1024;
1682: else if (strcmp(endp,"M")==0)
1683: m=1024*1024;
1684: else if (strcmp(endp,"G")==0)
1685: m=1024*1024*1024;
1686: else if (strcmp(endp,"T")==0) {
1687: #if (SIZEOF_CHAR_P > 4)
1688: m=1024L*1024*1024*1024;
1689: #else
1690: fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
1691: exit(1);
1692: #endif
1693: } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
1694: fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
1695: exit(1);
1696: }
1697: }
1698: return n*m;
1699: }
1700:
1701: enum {
1702: ss_number = 256,
1703: ss_states,
1704: ss_min_codesize,
1705: ss_min_ls,
1706: ss_min_lsu,
1707: ss_min_nexts,
1708: };
1709:
1710: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
1711: {
1712: int c;
1713:
1714: opterr=0;
1715: while (1) {
1716: int option_index=0;
1717: static struct option opts[] = {
1718: {"appl-image", required_argument, NULL, 'a'},
1719: {"image-file", required_argument, NULL, 'i'},
1720: {"dictionary-size", required_argument, NULL, 'm'},
1721: {"data-stack-size", required_argument, NULL, 'd'},
1722: {"return-stack-size", required_argument, NULL, 'r'},
1723: {"fp-stack-size", required_argument, NULL, 'f'},
1724: {"locals-stack-size", required_argument, NULL, 'l'},
1725: {"path", required_argument, NULL, 'p'},
1726: {"version", no_argument, NULL, 'v'},
1727: {"help", no_argument, NULL, 'h'},
1728: /* put something != 0 into offset_image */
1729: {"offset-image", no_argument, &offset_image, 1},
1730: {"no-offset-im", no_argument, &offset_image, 0},
1731: {"clear-dictionary", no_argument, &clear_dictionary, 1},
1732: {"die-on-signal", no_argument, &die_on_signal, 1},
1733: {"debug", no_argument, &debug, 1},
1734: {"diag", no_argument, &diag, 1},
1735: {"no-super", no_argument, &no_super, 1},
1736: {"no-dynamic", no_argument, &no_dynamic, 1},
1737: {"dynamic", no_argument, &no_dynamic, 0},
1738: {"print-metrics", no_argument, &print_metrics, 1},
1739: {"ss-number", required_argument, NULL, ss_number},
1740: {"ss-states", required_argument, NULL, ss_states},
1741: #ifndef NO_DYNAMIC
1742: {"ss-min-codesize", no_argument, NULL, ss_min_codesize},
1743: #endif
1744: {"ss-min-ls", no_argument, NULL, ss_min_ls},
1745: {"ss-min-lsu", no_argument, NULL, ss_min_lsu},
1746: {"ss-min-nexts", no_argument, NULL, ss_min_nexts},
1747: {"ss-greedy", no_argument, &ss_greedy, 1},
1748: {0,0,0,0}
1749: /* no-init-file, no-rc? */
1750: };
1751:
1752: c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
1753:
1754: switch (c) {
1755: case EOF: return;
1756: case '?': optind--; return;
1757: case 'a': *imagename = optarg; return;
1758: case 'i': *imagename = optarg; break;
1759: case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
1760: case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
1761: case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
1762: case 'f': fsize = convsize(optarg,sizeof(Float)); break;
1763: case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
1764: case 'p': *path = optarg; break;
1765: case 'o': offset_image = 1; break;
1766: case 'n': offset_image = 0; break;
1767: case 'c': clear_dictionary = 1; break;
1768: case 's': die_on_signal = 1; break;
1769: case 'x': debug = 1; break;
1770: case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
1771: case ss_number: static_super_number = atoi(optarg); break;
1772: case ss_states: maxstates = max(min(atoi(optarg),MAX_STATE),1); break;
1773: #ifndef NO_DYNAMIC
1774: case ss_min_codesize: ss_cost = cost_codesize; break;
1775: #endif
1776: case ss_min_ls: ss_cost = cost_ls; break;
1777: case ss_min_lsu: ss_cost = cost_lsu; break;
1778: case ss_min_nexts: ss_cost = cost_nexts; break;
1779: case 'h':
1780: fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
1781: Engine Options:\n\
1782: --appl-image FILE equivalent to '--image-file=FILE --'\n\
1783: --clear-dictionary Initialize the dictionary with 0 bytes\n\
1784: -d SIZE, --data-stack-size=SIZE Specify data stack size\n\
1785: --debug Print debugging information during startup\n\
1786: --diag Print diagnostic information during startup\n\
1787: --die-on-signal exit instead of CATCHing some signals\n\
1788: --dynamic use dynamic native code\n\
1789: -f SIZE, --fp-stack-size=SIZE Specify floating point stack size\n\
1790: -h, --help Print this message and exit\n\
1791: -i FILE, --image-file=FILE Use image FILE instead of `gforth.fi'\n\
1792: -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
1793: -m SIZE, --dictionary-size=SIZE Specify Forth dictionary size\n\
1794: --no-dynamic Use only statically compiled primitives\n\
1795: --no-offset-im Load image at normal position\n\
1796: --no-super No dynamically formed superinstructions\n\
1797: --offset-image Load image at a different position\n\
1798: -p PATH, --path=PATH Search path for finding image and sources\n\
1799: --print-metrics Print some code generation metrics on exit\n\
1800: -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
1801: --ss-greedy greedy, not optimal superinst selection\n\
1802: --ss-min-codesize select superinsts for smallest native code\n\
1803: --ss-min-ls minimize loads and stores\n\
1804: --ss-min-lsu minimize loads, stores, and pointer updates\n\
1805: --ss-min-nexts minimize the number of static superinsts\n\
1806: --ss-number=N use N static superinsts (default max)\n\
1807: --ss-states=N N states for stack caching (default max)\n\
1808: -v, --version Print engine version and exit\n\
1809: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
1810: `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
1811: argv[0]);
1812: optind--;
1813: return;
1814: }
1815: }
1816: }
1817: #endif
1818:
1819: void print_diag()
1820: {
1821:
1822: #if !defined(HAVE_GETRUSAGE) || !defined(HAS_FFCALL)
1823: fprintf(stderr, "*** missing functionality ***\n"
1824: #ifndef HAVE_GETRUSAGE
1825: " no getrusage -> CPUTIME broken\n"
1826: #endif
1827: #ifndef HAS_FFCALL
1828: " no ffcall -> only old-style foreign function calls (no fflib.fs)\n"
1829: #endif
1830: );
1831: #endif
1832: if((relocs < nonrelocs) ||
1833: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
1834: 1
1835: #else
1836: 0
1837: #endif
1838: )
1839: debugp(stderr, "relocs: %d:%d\n", relocs, nonrelocs);
1840: fprintf(stderr, "*** performance problems ***\n%s"
1841: #if defined(BUGGY_LL_CMP) || defined(BUGGY_LL_MUL) || defined(BUGGY_LL_DIV) || defined(BUGGY_LL_ADD) || defined(BUGGY_LL_SHIFT) || defined(BUGGY_LL_D2F) || defined(BUGGY_LL_F2D)
1842: " double-cell integer type buggy ->\n "
1843: #ifdef BUGGY_LL_CMP
1844: "CMP, "
1845: #endif
1846: #ifdef BUGGY_LL_MUL
1847: "MUL, "
1848: #endif
1849: #ifdef BUGGY_LL_DIV
1850: "DIV, "
1851: #endif
1852: #ifdef BUGGY_LL_ADD
1853: "ADD, "
1854: #endif
1855: #ifdef BUGGY_LL_SHIFT
1856: "SHIFT, "
1857: #endif
1858: #ifdef BUGGY_LL_D2F
1859: "D2F, "
1860: #endif
1861: #ifdef BUGGY_LL_F2D
1862: "F2D, "
1863: #endif
1864: "\b\b slow\n"
1865: #endif
1866: #ifndef FORCE_REG
1867: " automatic register allocation: performance degradation possible\n"
1868: #endif
1869: #if !defined(FORCE_REG) || defined(BUGGY_LONG_LONG)
1870: "*** Suggested remedy: try ./configure"
1871: #ifndef FORCE_REG
1872: " --enable-force-reg"
1873: #endif
1874: #ifdef BUGGY_LONG_LONG
1875: " --enable-force-ll"
1876: #endif
1877: "\n"
1878: #endif
1879: ,
1880: (relocs < nonrelocs) ? " gcc PR 15242 -> no dynamic code generation (use gcc-2.95 instead)\n" : "");
1881: }
1882:
1883: #ifdef INCLUDE_IMAGE
1884: extern Cell image[];
1885: extern const char reloc_bits[];
1886: #endif
1887:
1888: int main(int argc, char **argv, char **env)
1889: {
1890: #ifdef HAS_OS
1891: char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
1892: #else
1893: char *path = DEFAULTPATH;
1894: #endif
1895: #ifndef INCLUDE_IMAGE
1896: char *imagename="gforth.fi";
1897: FILE *image_file;
1898: Address image;
1899: #endif
1900: int retvalue;
1901:
1902: #if defined(i386) && defined(ALIGNMENT_CHECK)
1903: /* turn on alignment checks on the 486.
1904: * on the 386 this should have no effect. */
1905: __asm__("pushfl; popl %eax; orl $0x40000, %eax; pushl %eax; popfl;");
1906: /* this is unusable with Linux' libc.4.6.27, because this library is
1907: not alignment-clean; we would have to replace some library
1908: functions (e.g., memcpy) to make it work. Also GCC doesn't try to keep
1909: the stack FP-aligned. */
1910: #endif
1911:
1912: /* buffering of the user output device */
1913: #ifdef _IONBF
1914: if (isatty(fileno(stdout))) {
1915: fflush(stdout);
1916: setvbuf(stdout,NULL,_IONBF,0);
1917: }
1918: #endif
1919:
1920: progname = argv[0];
1921:
1922: #ifdef HAS_OS
1923: gforth_args(argc, argv, &path, &imagename);
1924: #ifndef NO_DYNAMIC
1925: init_ss_cost();
1926: #endif /* !defined(NO_DYNAMIC) */
1927: #endif /* defined(HAS_OS) */
1928:
1929: #ifdef INCLUDE_IMAGE
1930: set_stack_sizes((ImageHeader *)image);
1931: if(((ImageHeader *)image)->base != image)
1932: relocate(image, reloc_bits, ((ImageHeader *)image)->image_size,
1933: (Label*)engine(0, 0, 0, 0, 0));
1934: alloc_stacks((ImageHeader *)image);
1935: #else
1936: image_file = open_image_file(imagename, path);
1937: image = loader(image_file, imagename);
1938: #endif
1939: gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
1940:
1941: if (diag)
1942: print_diag();
1943: {
1944: char path2[strlen(path)+1];
1945: char *p1, *p2;
1946: Cell environ[]= {
1947: (Cell)argc-(optind-1),
1948: (Cell)(argv+(optind-1)),
1949: (Cell)strlen(path),
1950: (Cell)path2};
1951: argv[optind-1] = progname;
1952: /*
1953: for (i=0; i<environ[0]; i++)
1954: printf("%s\n", ((char **)(environ[1]))[i]);
1955: */
1956: /* make path OS-independent by replacing path separators with NUL */
1957: for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
1958: if (*p1==PATHSEP)
1959: *p2 = '\0';
1960: else
1961: *p2 = *p1;
1962: *p2='\0';
1963: retvalue = go_forth(image, 4, environ);
1964: #ifdef SIGPIPE
1965: bsd_signal(SIGPIPE, SIG_IGN);
1966: #endif
1967: #ifdef VM_PROFILING
1968: vm_print_profile(stderr);
1969: #endif
1970: deprep_terminal();
1971: }
1972: if (print_metrics) {
1973: int i;
1974: fprintf(stderr, "code size = %8ld\n", dyncodesize());
1975: for (i=0; i<sizeof(cost_sums)/sizeof(cost_sums[0]); i++)
1976: fprintf(stderr, "metric %8s: %8ld\n",
1977: cost_sums[i].metricname, cost_sums[i].sum);
1978: }
1979: return retvalue;
1980: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>