1: /* command line interpretation, image loading etc. for Gforth
2:
3:
4: Copyright (C) 1995,1996,1997,1998,2000,2003,2004,2005,2006,2007,2008 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 3
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, see http://www.gnu.org/licenses/.
20: */
21:
22: #include "config.h"
23: #include "forth.h"
24: #include <errno.h>
25: #include <ctype.h>
26: #include <stdio.h>
27: #include <unistd.h>
28: #include <string.h>
29: #include <math.h>
30: #include <sys/types.h>
31: #ifdef HAVE_ALLOCA_H
32: #include <alloca.h>
33: #endif
34: #ifndef STANDALONE
35: #include <sys/stat.h>
36: #endif
37: #include <fcntl.h>
38: #include <assert.h>
39: #include <stdlib.h>
40: #include <signal.h>
41:
42: #ifndef STANDALONE
43: #if HAVE_SYS_MMAN_H
44: #include <sys/mman.h>
45: #endif
46: #endif
47: #include "io.h"
48: #include "getopt.h"
49: #ifdef STANDALONE
50: /* #include <systypes.h> */
51: #endif
52:
53: /* output rules etc. for burg with --debug and --print-sequences */
54: /* #define BURG_FORMAT*/
55:
56: typedef enum prim_num {
57: /* definitions of N_execute etc. */
58: #include PRIM_NUM_I
59: N_START_SUPER
60: } PrimNum;
61:
62: /* global variables for engine.c
63: We put them here because engine.c is compiled several times in
64: different ways for the same engine. */
65: Cell *gforth_SP;
66: Float *gforth_FP;
67: Address gforth_UP=NULL;
68: Cell *gforth_RP;
69: Address gforth_LP;
70:
71: #ifndef HAS_LINKBACK
72: void * gforth_pointers[] = {
73: (void*)&gforth_SP,
74: (void*)&gforth_FP,
75: (void*)&gforth_LP,
76: (void*)&gforth_RP,
77: (void*)&gforth_UP,
78: (void*)gforth_engine,
79: (void*)cstr,
80: (void*)tilde_cstr };
81: #endif
82:
83: #ifdef HAS_FFCALL
84:
85: #include <callback.h>
86:
87: va_alist gforth_clist;
88:
89: void gforth_callback(Xt* fcall, void * alist)
90: {
91: /* save global valiables */
92: Cell *rp = gforth_RP;
93: Cell *sp = gforth_SP;
94: Float *fp = gforth_FP;
95: Address lp = gforth_LP;
96: va_alist clist = gforth_clist;
97:
98: gforth_clist = (va_alist)alist;
99:
100: gforth_engine(fcall, sp, rp, fp, lp sr_call);
101:
102: /* restore global variables */
103: gforth_RP = rp;
104: gforth_SP = sp;
105: gforth_FP = fp;
106: gforth_LP = lp;
107: gforth_clist = clist;
108: }
109: #endif
110:
111: #ifdef GFORTH_DEBUGGING
112: /* define some VM registers as global variables, so they survive exceptions;
113: global register variables are not up to the task (according to the
114: GNU C manual) */
115: #if defined(GLOBALS_NONRELOC)
116: saved_regs saved_regs_v;
117: saved_regs *saved_regs_p = &saved_regs_v;
118: #else /* !defined(GLOBALS_NONRELOC) */
119: Xt *saved_ip;
120: Cell *rp;
121: #endif /* !defined(GLOBALS_NONRELOC) */
122: #endif /* !defined(GFORTH_DEBUGGING) */
123:
124: #ifdef NO_IP
125: Label next_code;
126: #endif
127:
128: #ifdef HAS_FILE
129: char* fileattr[6]={"rb","rb","r+b","r+b","wb","wb"};
130: char* pfileattr[6]={"r","r","r+","r+","w","w"};
131:
132: #ifndef O_BINARY
133: #define O_BINARY 0
134: #endif
135: #ifndef O_TEXT
136: #define O_TEXT 0
137: #endif
138:
139: int ufileattr[6]= {
140: O_RDONLY|O_BINARY, O_RDONLY|O_BINARY,
141: O_RDWR |O_BINARY, O_RDWR |O_BINARY,
142: O_WRONLY|O_BINARY, O_WRONLY|O_BINARY };
143: #endif
144: /* end global vars for engine.c */
145:
146: #define PRIM_VERSION 1
147: /* increment this whenever the primitives change in an incompatible way */
148:
149: #ifndef DEFAULTPATH
150: # define DEFAULTPATH "."
151: #endif
152:
153: #ifdef MSDOS
154: jmp_buf throw_jmp_buf;
155: #endif
156:
157: #if defined(DOUBLY_INDIRECT)
158: # define CFA(n) ({Cell _n = (n); ((Cell)(((_n & 0x4000) ? symbols : xts)+(_n&~0x4000UL)));})
159: #else
160: # define CFA(n) ((Cell)(symbols+((n)&~0x4000UL)))
161: #endif
162:
163: #define maxaligned(n) (typeof(n))((((Cell)n)+sizeof(Float)-1)&-sizeof(Float))
164:
165: static UCell dictsize=0;
166: static UCell dsize=0;
167: static UCell rsize=0;
168: static UCell fsize=0;
169: static UCell lsize=0;
170: int offset_image=0;
171: int die_on_signal=0;
172: int ignore_async_signals=0;
173: #ifndef INCLUDE_IMAGE
174: static int clear_dictionary=0;
175: UCell pagesize=1;
176: char *progname;
177: #else
178: char *progname = "gforth";
179: int optind = 1;
180: #endif
181: #ifndef MAP_NORESERVE
182: #define MAP_NORESERVE 0
183: #endif
184: /* IF you have an old Cygwin, this may help:
185: #ifdef __CYGWIN__
186: #define MAP_NORESERVE 0
187: #endif
188: */
189: static int map_noreserve=MAP_NORESERVE;
190:
191: #define CODE_BLOCK_SIZE (512*1024) /* !! overflow handling for -native */
192: Address code_area=0;
193: Cell code_area_size = CODE_BLOCK_SIZE;
194: Address code_here; /* does for code-area what HERE does for the dictionary */
195: Address start_flush=NULL; /* start of unflushed code */
196: Cell last_jump=0; /* if the last prim was compiled without jump, this
197: is it's number, otherwise this contains 0 */
198:
199: static int no_super=0; /* true if compile_prim should not fuse prims */
200: static int no_dynamic=NO_DYNAMIC_DEFAULT; /* if true, no code is generated
201: dynamically */
202: static int print_metrics=0; /* if true, print metrics on exit */
203: static int static_super_number = 10000; /* number of ss used if available */
204: #define MAX_STATE 9 /* maximum number of states */
205: static int maxstates = MAX_STATE; /* number of states for stack caching */
206: static int ss_greedy = 0; /* if true: use greedy, not optimal ss selection */
207: static int diag = 0; /* if true: print diagnostic informations */
208: static int tpa_noequiv = 0; /* if true: no state equivalence checking */
209: static int tpa_noautomaton = 0; /* if true: no tree parsing automaton */
210: static int tpa_trace = 0; /* if true: data for line graph of new states etc. */
211: static int print_sequences = 0; /* print primitive sequences for optimization */
212: static int relocs = 0;
213: static int nonrelocs = 0;
214:
215: #ifdef HAS_DEBUG
216: int debug=0;
217: # define debugp(x...) do { if (debug) fprintf(x); } while (0)
218: #else
219: # define perror(x...)
220: # define fprintf(x...)
221: # define debugp(x...)
222: #endif
223:
224: ImageHeader *gforth_header;
225: Label *vm_prims;
226: #ifdef DOUBLY_INDIRECT
227: Label *xts; /* same content as vm_prims, but should only be used for xts */
228: #endif
229:
230: #ifndef NO_DYNAMIC
231: #ifndef CODE_ALIGNMENT
232: #define CODE_ALIGNMENT 0
233: #endif
234:
235: #define MAX_IMMARGS 2
236:
237: typedef struct {
238: Label start; /* NULL if not relocatable */
239: Cell length; /* only includes the jump iff superend is true*/
240: Cell restlength; /* length of the rest (i.e., the jump or (on superend) 0) */
241: char superend; /* true if primitive ends superinstruction, i.e.,
242: unconditional branch, execute, etc. */
243: Cell nimmargs;
244: struct immarg {
245: Cell offset; /* offset of immarg within prim */
246: char rel; /* true if immarg is relative */
247: } immargs[MAX_IMMARGS];
248: } PrimInfo;
249:
250: PrimInfo *priminfos;
251: PrimInfo **decomp_prims;
252:
253: const char const* const prim_names[]={
254: #include PRIM_NAMES_I
255: };
256:
257: void init_ss_cost(void);
258:
259: static int is_relocatable(int p)
260: {
261: return !no_dynamic && priminfos[p].start != NULL;
262: }
263: #else /* defined(NO_DYNAMIC) */
264: static int is_relocatable(int p)
265: {
266: return 0;
267: }
268: #endif /* defined(NO_DYNAMIC) */
269:
270: #ifdef MEMCMP_AS_SUBROUTINE
271: int gforth_memcmp(const char * s1, const char * s2, size_t n)
272: {
273: return memcmp(s1, s2, n);
274: }
275: #endif
276:
277: static Cell max(Cell a, Cell b)
278: {
279: return a>b?a:b;
280: }
281:
282: static Cell min(Cell a, Cell b)
283: {
284: return a<b?a:b;
285: }
286:
287: #ifndef STANDALONE
288: /* image file format:
289: * "#! binary-path -i\n" (e.g., "#! /usr/local/bin/gforth-0.4.0 -i\n")
290: * padding to a multiple of 8
291: * magic: "Gforth3x" means format 0.6,
292: * where x is a byte with
293: * bit 7: reserved = 0
294: * bit 6:5: address unit size 2^n octets
295: * bit 4:3: character size 2^n octets
296: * bit 2:1: cell size 2^n octets
297: * bit 0: endian, big=0, little=1.
298: * The magic are always 8 octets, no matter what the native AU/character size is
299: * padding to max alignment (no padding necessary on current machines)
300: * ImageHeader structure (see forth.h)
301: * data (size in ImageHeader.image_size)
302: * tags ((if relocatable, 1 bit/data cell)
303: *
304: * tag==1 means that the corresponding word is an address;
305: * If the word is >=0, the address is within the image;
306: * addresses within the image are given relative to the start of the image.
307: * If the word =-1 (CF_NIL), the address is NIL,
308: * If the word is <CF_NIL and >CF(DODOES), it's a CFA (:, Create, ...)
309: * If the word =CF(DODOES), it's a DOES> CFA
310: * If the word =CF(DOESJUMP), it's a DOES JUMP (2 Cells after DOES>,
311: * possibly containing a jump to dodoes)
312: * If the word is <CF(DOESJUMP) and bit 14 is set, it's the xt of a primitive
313: * If the word is <CF(DOESJUMP) and bit 14 is clear,
314: * it's the threaded code of a primitive
315: * bits 13..9 of a primitive token state which group the primitive belongs to,
316: * bits 8..0 of a primitive token index into the group
317: */
318:
319: Cell groups[32] = {
320: 0,
321: 0
322: #undef GROUP
323: #undef GROUPADD
324: #define GROUPADD(n) +n
325: #define GROUP(x, n) , 0
326: #include PRIM_GRP_I
327: #undef GROUP
328: #undef GROUPADD
329: #define GROUP(x, n)
330: #define GROUPADD(n)
331: };
332:
333: static unsigned char *branch_targets(Cell *image, const unsigned char *bitstring,
334: int size, Cell base)
335: /* produce a bitmask marking all the branch targets */
336: {
337: int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
338: Cell token;
339: unsigned char bits;
340: unsigned char *result=malloc(steps);
341:
342: memset(result, 0, steps);
343: for(k=0; k<steps; k++) {
344: for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
345: if(bits & (1U << (RELINFOBITS-1))) {
346: assert(i*sizeof(Cell) < size);
347: token=image[i];
348: if (token>=base) { /* relocatable address */
349: UCell bitnum=(token-base)/sizeof(Cell);
350: if (bitnum/RELINFOBITS < (UCell)steps)
351: result[bitnum/RELINFOBITS] |= 1U << ((~bitnum)&(RELINFOBITS-1));
352: }
353: }
354: }
355: }
356: return result;
357: }
358:
359: void gforth_relocate(Cell *image, const Char *bitstring,
360: UCell size, Cell base, Label symbols[])
361: {
362: int i=0, j, k, steps=(((size-1)/sizeof(Cell))/RELINFOBITS)+1;
363: Cell token;
364: char bits;
365: Cell max_symbols;
366: /*
367: * A virtual start address that's the real start address minus
368: * the one in the image
369: */
370: Cell *start = (Cell * ) (((void *) image) - ((void *) base));
371: unsigned char *targets = branch_targets(image, bitstring, size, base);
372:
373: /* group index into table */
374: if(groups[31]==0) {
375: int groupsum=0;
376: for(i=0; i<32; i++) {
377: groupsum += groups[i];
378: groups[i] = groupsum;
379: /* printf("group[%d]=%d\n",i,groupsum); */
380: }
381: i=0;
382: }
383:
384: /* printf("relocating to %x[%x] start=%x base=%x\n", image, size, start, base); */
385:
386: for (max_symbols=0; symbols[max_symbols]!=0; max_symbols++)
387: ;
388: max_symbols--;
389:
390: for(k=0; k<steps; k++) {
391: for(j=0, bits=bitstring[k]; j<RELINFOBITS; j++, i++, bits<<=1) {
392: /* fprintf(stderr,"relocate: image[%d]\n", i);*/
393: if(bits & (1U << (RELINFOBITS-1))) {
394: assert(i*sizeof(Cell) < size);
395: /* fprintf(stderr,"relocate: image[%d]=%d of %d\n", i, image[i], size/sizeof(Cell)); */
396: token=image[i];
397: if(token<0) {
398: int group = (-token & 0x3E00) >> 9;
399: if(group == 0) {
400: switch(token|0x4000) {
401: case CF_NIL : image[i]=0; break;
402: #if !defined(DOUBLY_INDIRECT)
403: case CF(DOCOL) :
404: case CF(DOVAR) :
405: case CF(DOCON) :
406: case CF(DOVAL) :
407: case CF(DOUSER) :
408: case CF(DODEFER) :
409: case CF(DOFIELD) : MAKE_CF(image+i,symbols[CF(token)]); break;
410: case CF(DOESJUMP): image[i]=0; break;
411: #endif /* !defined(DOUBLY_INDIRECT) */
412: case CF(DODOES) :
413: MAKE_DOES_CF(image+i,(Xt *)(image[i+1]+((Cell)start)));
414: break;
415: default : /* backward compatibility */
416: /* printf("Code field generation image[%x]:=CFA(%x)\n",
417: i, CF(image[i])); */
418: if (CF((token | 0x4000))<max_symbols) {
419: image[i]=(Cell)CFA(CF(token));
420: #ifdef DIRECT_THREADED
421: if ((token & 0x4000) == 0) { /* threade code, no CFA */
422: if (targets[k] & (1U<<(RELINFOBITS-1-j)))
423: compile_prim1(0);
424: compile_prim1(&image[i]);
425: }
426: #endif
427: } else
428: 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);
429: }
430: } else {
431: int tok = -token & 0x1FF;
432: if (tok < (groups[group+1]-groups[group])) {
433: #if defined(DOUBLY_INDIRECT)
434: image[i]=(Cell)CFA(((groups[group]+tok) | (CF(token) & 0x4000)));
435: #else
436: image[i]=(Cell)CFA((groups[group]+tok));
437: #endif
438: #ifdef DIRECT_THREADED
439: if ((token & 0x4000) == 0) { /* threade code, no CFA */
440: if (targets[k] & (1U<<(RELINFOBITS-1-j)))
441: compile_prim1(0);
442: compile_prim1(&image[i]);
443: }
444: #endif
445: } else
446: 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);
447: }
448: } else {
449: /* if base is > 0: 0 is a null reference so don't adjust*/
450: if (token>=base) {
451: image[i]+=(Cell)start;
452: }
453: }
454: }
455: }
456: }
457: free(targets);
458: finish_code();
459: ((ImageHeader*)(image))->base = (Address) image;
460: }
461:
462: #ifndef DOUBLY_INDIRECT
463: static UCell checksum(Label symbols[])
464: {
465: UCell r=PRIM_VERSION;
466: Cell i;
467:
468: for (i=DOCOL; i<=DOESJUMP; i++) {
469: r ^= (UCell)(symbols[i]);
470: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
471: }
472: #ifdef DIRECT_THREADED
473: /* we have to consider all the primitives */
474: for (; symbols[i]!=(Label)0; i++) {
475: r ^= (UCell)(symbols[i]);
476: r = (r << 5) | (r >> (8*sizeof(Cell)-5));
477: }
478: #else
479: /* in indirect threaded code all primitives are accessed through the
480: symbols table, so we just have to put the base address of symbols
481: in the checksum */
482: r ^= (UCell)symbols;
483: #endif
484: return r;
485: }
486: #endif
487:
488: static Address verbose_malloc(Cell size)
489: {
490: Address r;
491: /* leave a little room (64B) for stack underflows */
492: if ((r = malloc(size+64))==NULL) {
493: perror(progname);
494: exit(1);
495: }
496: r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
497: debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
498: return r;
499: }
500:
501: static void *next_address=0;
502: static void after_alloc(Address r, Cell size)
503: {
504: if (r != (Address)-1) {
505: debugp(stderr, "success, address=$%lx\n", (long) r);
506: #if 0
507: /* not needed now that we protect the stacks with mprotect */
508: if (pagesize != 1)
509: next_address = (Address)(((((Cell)r)+size-1)&-pagesize)+2*pagesize); /* leave one page unmapped */
510: #endif
511: } else {
512: debugp(stderr, "failed: %s\n", strerror(errno));
513: }
514: }
515:
516: #ifndef MAP_FAILED
517: #define MAP_FAILED ((Address) -1)
518: #endif
519: #ifndef MAP_FILE
520: # define MAP_FILE 0
521: #endif
522: #ifndef MAP_PRIVATE
523: # define MAP_PRIVATE 0
524: #endif
525: #ifndef PROT_NONE
526: # define PROT_NONE 0
527: #endif
528: #if !defined(MAP_ANON) && defined(MAP_ANONYMOUS)
529: # define MAP_ANON MAP_ANONYMOUS
530: #endif
531:
532: #if defined(HAVE_MMAP)
533: static Address alloc_mmap(Cell size)
534: {
535: void *r;
536:
537: #if defined(MAP_ANON)
538: debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_ANON, ...); ", (long)next_address, (long)size);
539: r = mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE|map_noreserve, -1, 0);
540: #else /* !defined(MAP_ANON) */
541: /* Ultrix (at least) does not define MAP_FILE and MAP_PRIVATE (both are
542: apparently defaults) */
543: static int dev_zero=-1;
544:
545: if (dev_zero == -1)
546: dev_zero = open("/dev/zero", O_RDONLY);
547: if (dev_zero == -1) {
548: r = MAP_FAILED;
549: debugp(stderr, "open(\"/dev/zero\"...) failed (%s), no mmap; ",
550: strerror(errno));
551: } else {
552: debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FILE, dev_zero, ...); ", (long)next_address, (long)size);
553: r=mmap(next_address, size, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FILE|MAP_PRIVATE|map_noreserve, dev_zero, 0);
554: }
555: #endif /* !defined(MAP_ANON) */
556: after_alloc(r, size);
557: return r;
558: }
559:
560: static void page_noaccess(void *a)
561: {
562: /* try mprotect first; with munmap the page might be allocated later */
563: debugp(stderr, "try mprotect(%p,$%lx,PROT_NONE); ", a, (long)pagesize);
564: if (mprotect(a, pagesize, PROT_NONE)==0) {
565: debugp(stderr, "ok\n");
566: return;
567: }
568: debugp(stderr, "failed: %s\n", strerror(errno));
569: debugp(stderr, "try munmap(%p,$%lx); ", a, (long)pagesize);
570: if (munmap(a,pagesize)==0) {
571: debugp(stderr, "ok\n");
572: return;
573: }
574: debugp(stderr, "failed: %s\n", strerror(errno));
575: }
576:
577: static size_t wholepage(size_t n)
578: {
579: return (n+pagesize-1)&~(pagesize-1);
580: }
581: #endif
582:
583: Address gforth_alloc(Cell size)
584: {
585: #if HAVE_MMAP
586: Address r;
587:
588: r=alloc_mmap(size);
589: if (r!=(Address)MAP_FAILED)
590: return r;
591: #endif /* HAVE_MMAP */
592: /* use malloc as fallback */
593: return verbose_malloc(size);
594: }
595:
596: static void *dict_alloc_read(FILE *file, Cell imagesize, Cell dictsize, Cell offset)
597: {
598: void *image = MAP_FAILED;
599:
600: #if defined(HAVE_MMAP)
601: if (offset==0) {
602: image=alloc_mmap(dictsize);
603: if (image != (void *)MAP_FAILED) {
604: void *image1;
605: debugp(stderr,"try mmap($%lx, $%lx, ..., MAP_FIXED|MAP_FILE, imagefile, 0); ", (long)image, (long)imagesize);
606: image1 = mmap(image, imagesize, PROT_EXEC|PROT_READ|PROT_WRITE, MAP_FIXED|MAP_FILE|MAP_PRIVATE|map_noreserve, fileno(file), 0);
607: after_alloc(image1,dictsize);
608: if (image1 == (void *)MAP_FAILED)
609: goto read_image;
610: }
611: }
612: #endif /* defined(HAVE_MMAP) */
613: if (image == (void *)MAP_FAILED) {
614: image = gforth_alloc(dictsize+offset)+offset;
615: read_image:
616: rewind(file); /* fseek(imagefile,0L,SEEK_SET); */
617: fread(image, 1, imagesize, file);
618: }
619: return image;
620: }
621: #endif
622:
623: void set_stack_sizes(ImageHeader * header)
624: {
625: if (dictsize==0)
626: dictsize = header->dict_size;
627: if (dsize==0)
628: dsize = header->data_stack_size;
629: if (rsize==0)
630: rsize = header->return_stack_size;
631: if (fsize==0)
632: fsize = header->fp_stack_size;
633: if (lsize==0)
634: lsize = header->locals_stack_size;
635: dictsize=maxaligned(dictsize);
636: dsize=maxaligned(dsize);
637: rsize=maxaligned(rsize);
638: lsize=maxaligned(lsize);
639: fsize=maxaligned(fsize);
640: }
641:
642: #ifdef STANDALONE
643: void alloc_stacks(ImageHeader * h)
644: {
645: #define SSTACKSIZE 0x200
646: static Cell dstack[SSTACKSIZE+1];
647: static Cell rstack[SSTACKSIZE+1];
648:
649: h->dict_size=dictsize;
650: h->data_stack_size=dsize;
651: h->fp_stack_size=fsize;
652: h->return_stack_size=rsize;
653: h->locals_stack_size=lsize;
654:
655: h->data_stack_base=dstack+SSTACKSIZE;
656: // h->fp_stack_base=gforth_alloc(fsize);
657: h->return_stack_base=rstack+SSTACKSIZE;
658: // h->locals_stack_base=gforth_alloc(lsize);
659: }
660: #else
661: void alloc_stacks(ImageHeader * h)
662: {
663: h->dict_size=dictsize;
664: h->data_stack_size=dsize;
665: h->fp_stack_size=fsize;
666: h->return_stack_size=rsize;
667: h->locals_stack_size=lsize;
668:
669: #if defined(HAVE_MMAP) && !defined(STANDALONE)
670: if (pagesize > 1) {
671: size_t p = pagesize;
672: size_t totalsize =
673: wholepage(dsize)+wholepage(fsize)+wholepage(rsize)+wholepage(lsize)+5*p;
674: void *a = alloc_mmap(totalsize);
675: if (a != (void *)MAP_FAILED) {
676: page_noaccess(a); a+=p; h-> data_stack_base=a; a+=wholepage(dsize);
677: page_noaccess(a); a+=p; h-> fp_stack_base=a; a+=wholepage(fsize);
678: page_noaccess(a); a+=p; h->return_stack_base=a; a+=wholepage(rsize);
679: page_noaccess(a); a+=p; h->locals_stack_base=a; a+=wholepage(lsize);
680: page_noaccess(a);
681: debugp(stderr,"stack addresses: d=%p f=%p r=%p l=%p\n",
682: h->data_stack_base,
683: h->fp_stack_base,
684: h->return_stack_base,
685: h->locals_stack_base);
686: return;
687: }
688: }
689: #endif
690: h->data_stack_base=gforth_alloc(dsize);
691: h->fp_stack_base=gforth_alloc(fsize);
692: h->return_stack_base=gforth_alloc(rsize);
693: h->locals_stack_base=gforth_alloc(lsize);
694: }
695: #endif
696:
697: #warning You can ignore the warnings about clobbered variables in gforth_go
698: int gforth_go(void *image, int stack, Cell *entries)
699: {
700: volatile ImageHeader *image_header = (ImageHeader *)image;
701: Cell *sp0=(Cell*)(image_header->data_stack_base + dsize);
702: Cell *rp0=(Cell *)(image_header->return_stack_base + rsize);
703: Float *fp0=(Float *)(image_header->fp_stack_base + fsize);
704: #ifdef GFORTH_DEBUGGING
705: volatile Cell *orig_rp0=rp0;
706: #endif
707: Address lp0=image_header->locals_stack_base + lsize;
708: Xt *ip0=(Xt *)(image_header->boot_entry);
709: #ifdef SYSSIGNALS
710: int throw_code;
711: #endif
712:
713: /* ensure that the cached elements (if any) are accessible */
714: #if !(defined(GFORTH_DEBUGGING) || defined(INDIRECT_THREADED) || defined(DOUBLY_INDIRECT) || defined(VM_PROFILING))
715: sp0 -= 8; /* make stuff below bottom accessible for stack caching */
716: fp0--;
717: #endif
718:
719: for(;stack>0;stack--)
720: *--sp0=entries[stack-1];
721:
722: #if defined(SYSSIGNALS) && !defined(STANDALONE)
723: get_winsize();
724:
725: install_signal_handlers(); /* right place? */
726:
727: if ((throw_code=setjmp(throw_jmp_buf))) {
728: static Cell signal_data_stack[24];
729: static Cell signal_return_stack[16];
730: static Float signal_fp_stack[1];
731:
732: signal_data_stack[15]=throw_code;
733:
734: #ifdef GFORTH_DEBUGGING
735: debugp(stderr,"\ncaught signal, throwing exception %d, ip=%p rp=%p\n",
736: throw_code, saved_ip, rp);
737: if (rp <= orig_rp0 && rp > (Cell *)(image_header->return_stack_base+5)) {
738: /* no rstack overflow or underflow */
739: rp0 = rp;
740: *--rp0 = (Cell)saved_ip;
741: }
742: else /* I love non-syntactic ifdefs :-) */
743: rp0 = signal_return_stack+16;
744: #else /* !defined(GFORTH_DEBUGGING) */
745: debugp(stderr,"\ncaught signal, throwing exception %d\n", throw_code);
746: rp0 = signal_return_stack+16;
747: #endif /* !defined(GFORTH_DEBUGGING) */
748: /* fprintf(stderr, "rp=$%x\n",rp0);*/
749:
750: return((int)(Cell)gforth_engine(image_header->throw_entry, signal_data_stack+15,
751: rp0, signal_fp_stack, 0 sr_call));
752: }
753: #endif
754:
755: return((int)(Cell)gforth_engine(ip0,sp0,rp0,fp0,lp0 sr_call));
756: }
757:
758: #if !defined(INCLUDE_IMAGE) && !defined(STANDALONE)
759: static void print_sizes(Cell sizebyte)
760: /* print size information */
761: {
762: static char* endianstring[]= { " big","little" };
763:
764: fprintf(stderr,"%s endian, cell=%d bytes, char=%d bytes, au=%d bytes\n",
765: endianstring[sizebyte & 1],
766: 1 << ((sizebyte >> 1) & 3),
767: 1 << ((sizebyte >> 3) & 3),
768: 1 << ((sizebyte >> 5) & 3));
769: }
770:
771: /* static superinstruction stuff */
772:
773: struct cost { /* super_info might be a more accurate name */
774: char loads; /* number of stack loads */
775: char stores; /* number of stack stores */
776: char updates; /* number of stack pointer updates */
777: char branch; /* is it a branch (SET_IP) */
778: unsigned char state_in; /* state on entry */
779: unsigned char state_out; /* state on exit */
780: unsigned char imm_ops; /* number of immediate operands */
781: short offset; /* offset into super2 table */
782: unsigned char length; /* number of components */
783: };
784:
785: PrimNum super2[] = {
786: #include SUPER2_I
787: };
788:
789: struct cost super_costs[] = {
790: #include COSTS_I
791: };
792:
793: struct super_state {
794: struct super_state *next;
795: PrimNum super;
796: };
797:
798: #define HASH_SIZE 256
799:
800: struct super_table_entry {
801: struct super_table_entry *next;
802: PrimNum *start;
803: short length;
804: struct super_state *ss_list; /* list of supers */
805: } *super_table[HASH_SIZE];
806: int max_super=2;
807:
808: struct super_state *state_transitions=NULL;
809:
810: static int hash_super(PrimNum *start, int length)
811: {
812: int i, r;
813:
814: for (i=0, r=0; i<length; i++) {
815: r <<= 1;
816: r += start[i];
817: }
818: return r & (HASH_SIZE-1);
819: }
820:
821: static struct super_state **lookup_super(PrimNum *start, int length)
822: {
823: int hash=hash_super(start,length);
824: struct super_table_entry *p = super_table[hash];
825:
826: /* assert(length >= 2); */
827: for (; p!=NULL; p = p->next) {
828: if (length == p->length &&
829: memcmp((char *)p->start, (char *)start, length*sizeof(PrimNum))==0)
830: return &(p->ss_list);
831: }
832: return NULL;
833: }
834:
835: static void prepare_super_table()
836: {
837: int i;
838: int nsupers = 0;
839:
840: for (i=0; i<sizeof(super_costs)/sizeof(super_costs[0]); i++) {
841: struct cost *c = &super_costs[i];
842: if ((c->length < 2 || nsupers < static_super_number) &&
843: c->state_in < maxstates && c->state_out < maxstates) {
844: struct super_state **ss_listp= lookup_super(super2+c->offset, c->length);
845: struct super_state *ss = malloc(sizeof(struct super_state));
846: ss->super= i;
847: if (c->offset==N_noop && i != N_noop) {
848: if (is_relocatable(i)) {
849: ss->next = state_transitions;
850: state_transitions = ss;
851: }
852: } else if (ss_listp != NULL) {
853: ss->next = *ss_listp;
854: *ss_listp = ss;
855: } else {
856: int hash = hash_super(super2+c->offset, c->length);
857: struct super_table_entry **p = &super_table[hash];
858: struct super_table_entry *e = malloc(sizeof(struct super_table_entry));
859: ss->next = NULL;
860: e->next = *p;
861: e->start = super2 + c->offset;
862: e->length = c->length;
863: e->ss_list = ss;
864: *p = e;
865: }
866: if (c->length > max_super)
867: max_super = c->length;
868: if (c->length >= 2)
869: nsupers++;
870: }
871: }
872: debugp(stderr, "Using %d static superinsts\n", nsupers);
873: if (nsupers>0 && !tpa_noautomaton && !tpa_noequiv) {
874: /* Currently these two things don't work together; see Section 3.2
875: of <http://www.complang.tuwien.ac.at/papers/ertl+06pldi.ps.gz>,
876: in particular Footnote 6 for the reason; hmm, we should be able
877: to use an automaton without state equivalence, but that costs
878: significant space so we only do it if the user explicitly
879: disables state equivalence. */
880: debugp(stderr, "Disabling tpa-automaton, because nsupers>0 and state equivalence is enabled.\n");
881: tpa_noautomaton = 1;
882: }
883: }
884:
885: /* dynamic replication/superinstruction stuff */
886:
887: #ifndef NO_DYNAMIC
888: static int compare_priminfo_length(const void *_a, const void *_b)
889: {
890: PrimInfo **a = (PrimInfo **)_a;
891: PrimInfo **b = (PrimInfo **)_b;
892: Cell diff = (*a)->length - (*b)->length;
893: if (diff)
894: return diff;
895: else /* break ties by start address; thus the decompiler produces
896: the earliest primitive with the same code (e.g. noop instead
897: of (char) and @ instead of >code-address */
898: return (*b)->start - (*a)->start;
899: }
900: #endif /* !defined(NO_DYNAMIC) */
901:
902: static char MAYBE_UNUSED superend[]={
903: #include PRIM_SUPEREND_I
904: };
905:
906: Cell npriminfos=0;
907:
908: Label goto_start;
909: Cell goto_len;
910:
911: #ifndef NO_DYNAMIC
912: static int compare_labels(const void *pa, const void *pb)
913: {
914: Label a = *(Label *)pa;
915: Label b = *(Label *)pb;
916: return a-b;
917: }
918: #endif
919:
920: static Label bsearch_next(Label key, Label *a, UCell n)
921: /* a is sorted; return the label >=key that is the closest in a;
922: return NULL if there is no label in a >=key */
923: {
924: int mid = (n-1)/2;
925: if (n<1)
926: return NULL;
927: if (n == 1) {
928: if (a[0] < key)
929: return NULL;
930: else
931: return a[0];
932: }
933: if (a[mid] < key)
934: return bsearch_next(key, a+mid+1, n-mid-1);
935: else
936: return bsearch_next(key, a, mid+1);
937: }
938:
939: static void check_prims(Label symbols1[])
940: {
941: int i;
942: #ifndef NO_DYNAMIC
943: Label *symbols2, *symbols3, *ends1, *ends1j, *ends1jsorted, *goto_p;
944: int nends1j;
945: #endif
946:
947: if (debug)
948: #ifdef __VERSION__
949: fprintf(stderr, "Compiled with gcc-" __VERSION__ "\n");
950: #else
951: #define xstr(s) str(s)
952: #define str(s) #s
953: fprintf(stderr, "Compiled with gcc-" xstr(__GNUC__) "." xstr(__GNUC_MINOR__) "\n");
954: #endif
955: for (i=0; symbols1[i]!=0; i++)
956: ;
957: npriminfos = i;
958:
959: #ifndef NO_DYNAMIC
960: if (no_dynamic)
961: return;
962: symbols2=gforth_engine2(0,0,0,0,0 sr_call);
963: #if NO_IP
964: symbols3=gforth_engine3(0,0,0,0,0 sr_call);
965: #else
966: symbols3=symbols1;
967: #endif
968: ends1 = symbols1+i+1;
969: ends1j = ends1+i;
970: goto_p = ends1j+i+1; /* goto_p[0]==before; ...[1]==after;*/
971: nends1j = i+1;
972: ends1jsorted = (Label *)alloca(nends1j*sizeof(Label));
973: memcpy(ends1jsorted,ends1j,nends1j*sizeof(Label));
974: qsort(ends1jsorted, nends1j, sizeof(Label), compare_labels);
975:
976: /* check whether the "goto *" is relocatable */
977: goto_len = goto_p[1]-goto_p[0];
978: debugp(stderr, "goto * %p %p len=%ld\n",
979: goto_p[0],symbols2[goto_p-symbols1],(long)goto_len);
980: if (memcmp(goto_p[0],symbols2[goto_p-symbols1],goto_len)!=0) { /* unequal */
981: no_dynamic=1;
982: debugp(stderr," not relocatable, disabling dynamic code generation\n");
983: init_ss_cost();
984: return;
985: }
986: goto_start = goto_p[0];
987:
988: priminfos = calloc(i,sizeof(PrimInfo));
989: for (i=0; symbols1[i]!=0; i++) {
990: int prim_len = ends1[i]-symbols1[i];
991: PrimInfo *pi=&priminfos[i];
992: struct cost *sc=&super_costs[i];
993: int j=0;
994: char *s1 = (char *)symbols1[i];
995: char *s2 = (char *)symbols2[i];
996: char *s3 = (char *)symbols3[i];
997: Label endlabel = bsearch_next(symbols1[i]+1,ends1jsorted,nends1j);
998:
999: pi->start = s1;
1000: pi->superend = superend[i]|no_super;
1001: pi->length = prim_len;
1002: pi->restlength = endlabel - symbols1[i] - pi->length;
1003: pi->nimmargs = 0;
1004: relocs++;
1005: #if defined(BURG_FORMAT)
1006: { /* output as burg-style rules */
1007: int p=super_costs[i].offset;
1008: if (p==N_noop)
1009: debugp(stderr, "S%d: S%d = %d (%d);", sc->state_in, sc->state_out, i+1, pi->length);
1010: else
1011: debugp(stderr, "S%d: op%d(S%d) = %d (%d);", sc->state_in, p, sc->state_out, i+1, pi->length);
1012: }
1013: #else
1014: debugp(stderr, "%-15s %d-%d %4d %p %p %p len=%3ld rest=%2ld send=%1d",
1015: prim_names[i], sc->state_in, sc->state_out,
1016: i, s1, s2, s3, (long)(pi->length), (long)(pi->restlength),
1017: pi->superend);
1018: #endif
1019: if (endlabel == NULL) {
1020: pi->start = NULL; /* not relocatable */
1021: if (pi->length<0) pi->length=100;
1022: #ifndef BURG_FORMAT
1023: debugp(stderr,"\n non_reloc: no J label > start found\n");
1024: #endif
1025: relocs--;
1026: nonrelocs++;
1027: continue;
1028: }
1029: if (ends1[i] > endlabel && !pi->superend) {
1030: pi->start = NULL; /* not relocatable */
1031: pi->length = endlabel-symbols1[i];
1032: #ifndef BURG_FORMAT
1033: debugp(stderr,"\n non_reloc: there is a J label before the K label (restlength<0)\n");
1034: #endif
1035: relocs--;
1036: nonrelocs++;
1037: continue;
1038: }
1039: if (ends1[i] < pi->start && !pi->superend) {
1040: pi->start = NULL; /* not relocatable */
1041: pi->length = endlabel-symbols1[i];
1042: #ifndef BURG_FORMAT
1043: debugp(stderr,"\n non_reloc: K label before I label (length<0)\n");
1044: #endif
1045: relocs--;
1046: nonrelocs++;
1047: continue;
1048: }
1049: assert(pi->length>=0);
1050: assert(pi->restlength >=0);
1051: while (j<(pi->length+pi->restlength)) {
1052: if (s1[j]==s3[j]) {
1053: if (s1[j] != s2[j]) {
1054: pi->start = NULL; /* not relocatable */
1055: #ifndef BURG_FORMAT
1056: debugp(stderr,"\n non_reloc: engine1!=engine2 offset %3d",j);
1057: #endif
1058: /* assert(j<prim_len); */
1059: relocs--;
1060: nonrelocs++;
1061: break;
1062: }
1063: j++;
1064: } else {
1065: struct immarg *ia=&pi->immargs[pi->nimmargs];
1066:
1067: pi->nimmargs++;
1068: ia->offset=j;
1069: if ((~*(Cell *)&(s1[j]))==*(Cell *)&(s3[j])) {
1070: ia->rel=0;
1071: debugp(stderr,"\n absolute immarg: offset %3d",j);
1072: } else if ((&(s1[j]))+(*(Cell *)&(s1[j]))+4 ==
1073: symbols1[DOESJUMP+1]) {
1074: ia->rel=1;
1075: debugp(stderr,"\n relative immarg: offset %3d",j);
1076: } else {
1077: pi->start = NULL; /* not relocatable */
1078: #ifndef BURG_FORMAT
1079: debugp(stderr,"\n non_reloc: engine1!=engine3 offset %3d",j);
1080: #endif
1081: /* assert(j<prim_len);*/
1082: relocs--;
1083: nonrelocs++;
1084: break;
1085: }
1086: j+=4;
1087: }
1088: }
1089: debugp(stderr,"\n");
1090: }
1091: decomp_prims = calloc(i,sizeof(PrimInfo *));
1092: for (i=DOESJUMP+1; i<npriminfos; i++)
1093: decomp_prims[i] = &(priminfos[i]);
1094: qsort(decomp_prims+DOESJUMP+1, npriminfos-DOESJUMP-1, sizeof(PrimInfo *),
1095: compare_priminfo_length);
1096: #endif
1097: }
1098:
1099: static void flush_to_here(void)
1100: {
1101: #ifndef NO_DYNAMIC
1102: if (start_flush)
1103: FLUSH_ICACHE((caddr_t)start_flush, code_here-start_flush);
1104: start_flush=code_here;
1105: #endif
1106: }
1107:
1108: static void MAYBE_UNUSED align_code(void)
1109: /* align code_here on some platforms */
1110: {
1111: #ifndef NO_DYNAMIC
1112: #if defined(CODE_PADDING)
1113: Cell alignment = CODE_ALIGNMENT;
1114: static char nops[] = CODE_PADDING;
1115: UCell maxpadding=MAX_PADDING;
1116: UCell offset = ((UCell)code_here)&(alignment-1);
1117: UCell length = alignment-offset;
1118: if (length <= maxpadding) {
1119: memcpy(code_here,nops+offset,length);
1120: code_here += length;
1121: }
1122: #endif /* defined(CODE_PADDING) */
1123: #endif /* defined(NO_DYNAMIC */
1124: }
1125:
1126: #ifndef NO_DYNAMIC
1127: static void append_jump(void)
1128: {
1129: if (last_jump) {
1130: PrimInfo *pi = &priminfos[last_jump];
1131:
1132: memcpy(code_here, pi->start+pi->length, pi->restlength);
1133: code_here += pi->restlength;
1134: memcpy(code_here, goto_start, goto_len);
1135: code_here += goto_len;
1136: align_code();
1137: last_jump=0;
1138: }
1139: }
1140:
1141: /* Gforth remembers all code blocks in this list. On forgetting (by
1142: executing a marker) the code blocks are not freed (because Gforth does
1143: not remember how they were allocated; hmm, remembering that might be
1144: easier and cleaner). Instead, code_here etc. are reset to the old
1145: value, and the "forgotten" code blocks are reused when they are
1146: needed. */
1147:
1148: struct code_block_list {
1149: struct code_block_list *next;
1150: Address block;
1151: Cell size;
1152: } *code_block_list=NULL, **next_code_blockp=&code_block_list;
1153:
1154: static void reserve_code_space(UCell size)
1155: {
1156: if (code_area+code_area_size < code_here+size) {
1157: struct code_block_list *p;
1158: append_jump();
1159: debugp(stderr,"Did not use %ld bytes in code block\n",
1160: (long)(code_area+code_area_size-code_here));
1161: flush_to_here();
1162: if (*next_code_blockp == NULL) {
1163: code_here = start_flush = code_area = gforth_alloc(code_area_size);
1164: p = (struct code_block_list *)malloc(sizeof(struct code_block_list));
1165: *next_code_blockp = p;
1166: p->next = NULL;
1167: p->block = code_here;
1168: p->size = code_area_size;
1169: } else {
1170: p = *next_code_blockp;
1171: code_here = start_flush = code_area = p->block;
1172: }
1173: next_code_blockp = &(p->next);
1174: }
1175: }
1176:
1177: static Address append_prim(Cell p)
1178: {
1179: PrimInfo *pi = &priminfos[p];
1180: Address old_code_here;
1181: reserve_code_space(pi->length+pi->restlength+goto_len+CODE_ALIGNMENT-1);
1182: memcpy(code_here, pi->start, pi->length);
1183: old_code_here = code_here;
1184: code_here += pi->length;
1185: return old_code_here;
1186: }
1187:
1188: static void reserve_code_super(PrimNum origs[], int ninsts)
1189: {
1190: int i;
1191: UCell size = CODE_ALIGNMENT-1; /* alignment may happen first */
1192: if (no_dynamic)
1193: return;
1194: /* use size of the original primitives as an upper bound for the
1195: size of the superinstruction. !! This is only safe if we
1196: optimize for code size (the default) */
1197: for (i=0; i<ninsts; i++) {
1198: PrimNum p = origs[i];
1199: PrimInfo *pi = &priminfos[p];
1200: if (is_relocatable(p))
1201: size += pi->length;
1202: else
1203: if (i>0)
1204: size += priminfos[origs[i-1]].restlength+goto_len+CODE_ALIGNMENT-1;
1205: }
1206: size += priminfos[origs[i-1]].restlength+goto_len;
1207: reserve_code_space(size);
1208: }
1209: #endif
1210:
1211: int forget_dyncode(Address code)
1212: {
1213: #ifdef NO_DYNAMIC
1214: return -1;
1215: #else
1216: struct code_block_list *p, **pp;
1217:
1218: for (pp=&code_block_list, p=*pp; p!=NULL; pp=&(p->next), p=*pp) {
1219: if (code >= p->block && code < p->block+p->size) {
1220: next_code_blockp = &(p->next);
1221: code_here = start_flush = code;
1222: code_area = p->block;
1223: last_jump = 0;
1224: return -1;
1225: }
1226: }
1227: return -no_dynamic;
1228: #endif /* !defined(NO_DYNAMIC) */
1229: }
1230:
1231: static long dyncodesize(void)
1232: {
1233: #ifndef NO_DYNAMIC
1234: struct code_block_list *p;
1235: long size=0;
1236: for (p=code_block_list; p!=NULL; p=p->next) {
1237: if (code_here >= p->block && code_here < p->block+p->size)
1238: return size + (code_here - p->block);
1239: else
1240: size += p->size;
1241: }
1242: #endif /* !defined(NO_DYNAMIC) */
1243: return 0;
1244: }
1245:
1246: Label decompile_code(Label _code)
1247: {
1248: #ifdef NO_DYNAMIC
1249: return _code;
1250: #else /* !defined(NO_DYNAMIC) */
1251: Cell i;
1252: struct code_block_list *p;
1253: Address code=_code;
1254:
1255: /* first, check if we are in code at all */
1256: for (p = code_block_list;; p = p->next) {
1257: if (p == NULL)
1258: return code;
1259: if (code >= p->block && code < p->block+p->size)
1260: break;
1261: }
1262: /* reverse order because NOOP might match other prims */
1263: for (i=npriminfos-1; i>DOESJUMP; i--) {
1264: PrimInfo *pi=decomp_prims[i];
1265: if (pi->start==code || (pi->start && memcmp(code,pi->start,pi->length)==0))
1266: return vm_prims[super2[super_costs[pi-priminfos].offset]];
1267: /* return pi->start;*/
1268: }
1269: return code;
1270: #endif /* !defined(NO_DYNAMIC) */
1271: }
1272:
1273: #ifdef NO_IP
1274: int nbranchinfos=0;
1275:
1276: struct branchinfo {
1277: Label **targetpp; /* **(bi->targetpp) is the target */
1278: Cell *addressptr; /* store the target here */
1279: } branchinfos[100000];
1280:
1281: int ndoesexecinfos=0;
1282: struct doesexecinfo {
1283: int branchinfo; /* fix the targetptr of branchinfos[...->branchinfo] */
1284: Label *targetp; /*target for branch (because this is not in threaded code)*/
1285: Cell *xt; /* cfa of word whose does-code needs calling */
1286: } doesexecinfos[10000];
1287:
1288: static void set_rel_target(Cell *source, Label target)
1289: {
1290: *source = ((Cell)target)-(((Cell)source)+4);
1291: }
1292:
1293: static void register_branchinfo(Label source, Cell *targetpp)
1294: {
1295: struct branchinfo *bi = &(branchinfos[nbranchinfos]);
1296: bi->targetpp = (Label **)targetpp;
1297: bi->addressptr = (Cell *)source;
1298: nbranchinfos++;
1299: }
1300:
1301: static Address compile_prim1arg(PrimNum p, Cell **argp)
1302: {
1303: Address old_code_here=append_prim(p);
1304:
1305: assert(vm_prims[p]==priminfos[p].start);
1306: *argp = (Cell*)(old_code_here+priminfos[p].immargs[0].offset);
1307: return old_code_here;
1308: }
1309:
1310: static Address compile_call2(Cell *targetpp, Cell **next_code_targetp)
1311: {
1312: PrimInfo *pi = &priminfos[N_call2];
1313: Address old_code_here = append_prim(N_call2);
1314:
1315: *next_code_targetp = (Cell *)(old_code_here + pi->immargs[0].offset);
1316: register_branchinfo(old_code_here + pi->immargs[1].offset, targetpp);
1317: return old_code_here;
1318: }
1319: #endif
1320:
1321: void finish_code(void)
1322: {
1323: #ifdef NO_IP
1324: Cell i;
1325:
1326: compile_prim1(NULL);
1327: for (i=0; i<ndoesexecinfos; i++) {
1328: struct doesexecinfo *dei = &doesexecinfos[i];
1329: dei->targetp = (Label *)DOES_CODE1((dei->xt));
1330: branchinfos[dei->branchinfo].targetpp = &(dei->targetp);
1331: }
1332: ndoesexecinfos = 0;
1333: for (i=0; i<nbranchinfos; i++) {
1334: struct branchinfo *bi=&branchinfos[i];
1335: set_rel_target(bi->addressptr, **(bi->targetpp));
1336: }
1337: nbranchinfos = 0;
1338: #else
1339: compile_prim1(NULL);
1340: #endif
1341: flush_to_here();
1342: }
1343:
1344: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1345: #ifdef NO_IP
1346: static Cell compile_prim_dyn(PrimNum p, Cell *tcp)
1347: /* compile prim #p dynamically (mod flags etc.) and return start
1348: address of generated code for putting it into the threaded
1349: code. This function is only called if all the associated
1350: inline arguments of p are already in place (at tcp[1] etc.) */
1351: {
1352: PrimInfo *pi=&priminfos[p];
1353: Cell *next_code_target=NULL;
1354: Address codeaddr;
1355: Address primstart;
1356:
1357: assert(p<npriminfos);
1358: if (p==N_execute || p==N_perform || p==N_lit_perform) {
1359: codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
1360: primstart = append_prim(p);
1361: goto other_prim;
1362: } else if (p==N_call) {
1363: codeaddr = compile_call2(tcp+1, &next_code_target);
1364: } else if (p==N_does_exec) {
1365: struct doesexecinfo *dei = &doesexecinfos[ndoesexecinfos++];
1366: Cell *arg;
1367: codeaddr = compile_prim1arg(N_lit,&arg);
1368: *arg = (Cell)PFA(tcp[1]);
1369: /* we cannot determine the callee now (last_start[1] may be a
1370: forward reference), so just register an arbitrary target, and
1371: register in dei that we need to fix this before resolving
1372: branches */
1373: dei->branchinfo = nbranchinfos;
1374: dei->xt = (Cell *)(tcp[1]);
1375: compile_call2(0, &next_code_target);
1376: } else if (!is_relocatable(p)) {
1377: Cell *branch_target;
1378: codeaddr = compile_prim1arg(N_set_next_code, &next_code_target);
1379: compile_prim1arg(N_branch,&branch_target);
1380: set_rel_target(branch_target,vm_prims[p]);
1381: } else {
1382: unsigned j;
1383:
1384: codeaddr = primstart = append_prim(p);
1385: other_prim:
1386: for (j=0; j<pi->nimmargs; j++) {
1387: struct immarg *ia = &(pi->immargs[j]);
1388: Cell *argp = tcp + pi->nimmargs - j;
1389: Cell argval = *argp; /* !! specific to prims */
1390: if (ia->rel) { /* !! assumption: relative refs are branches */
1391: register_branchinfo(primstart + ia->offset, argp);
1392: } else /* plain argument */
1393: *(Cell *)(primstart + ia->offset) = argval;
1394: }
1395: }
1396: if (next_code_target!=NULL)
1397: *next_code_target = (Cell)code_here;
1398: return (Cell)codeaddr;
1399: }
1400: #else /* !defined(NO_IP) */
1401: static Cell compile_prim_dyn(PrimNum p, Cell *tcp)
1402: /* compile prim #p dynamically (mod flags etc.) and return start
1403: address of generated code for putting it into the threaded code */
1404: {
1405: Cell static_prim = (Cell)vm_prims[p];
1406: #if defined(NO_DYNAMIC)
1407: return static_prim;
1408: #else /* !defined(NO_DYNAMIC) */
1409: Address old_code_here;
1410:
1411: if (no_dynamic)
1412: return static_prim;
1413: if (p>=npriminfos || !is_relocatable(p)) {
1414: append_jump();
1415: return static_prim;
1416: }
1417: old_code_here = append_prim(p);
1418: last_jump = p;
1419: if (priminfos[p].superend)
1420: append_jump();
1421: return (Cell)old_code_here;
1422: #endif /* !defined(NO_DYNAMIC) */
1423: }
1424: #endif /* !defined(NO_IP) */
1425: #endif
1426:
1427: #ifndef NO_DYNAMIC
1428: static int cost_codesize(int prim)
1429: {
1430: return priminfos[prim].length;
1431: }
1432: #endif
1433:
1434: static int cost_ls(int prim)
1435: {
1436: struct cost *c = super_costs+prim;
1437:
1438: return c->loads + c->stores;
1439: }
1440:
1441: static int cost_lsu(int prim)
1442: {
1443: struct cost *c = super_costs+prim;
1444:
1445: return c->loads + c->stores + c->updates;
1446: }
1447:
1448: static int cost_nexts(int prim)
1449: {
1450: return 1;
1451: }
1452:
1453: typedef int Costfunc(int);
1454: Costfunc *ss_cost = /* cost function for optimize_bb */
1455: #ifdef NO_DYNAMIC
1456: cost_lsu;
1457: #else
1458: cost_codesize;
1459: #endif
1460:
1461: struct {
1462: Costfunc *costfunc;
1463: char *metricname;
1464: long sum;
1465: } cost_sums[] = {
1466: #ifndef NO_DYNAMIC
1467: { cost_codesize, "codesize", 0 },
1468: #endif
1469: { cost_ls, "ls", 0 },
1470: { cost_lsu, "lsu", 0 },
1471: { cost_nexts, "nexts", 0 }
1472: };
1473:
1474: #ifndef NO_DYNAMIC
1475: void init_ss_cost(void) {
1476: if (no_dynamic && ss_cost == cost_codesize) {
1477: ss_cost = cost_nexts;
1478: cost_sums[0] = cost_sums[1]; /* don't use cost_codesize for print-metrics */
1479: debugp(stderr, "--no-dynamic conflicts with --ss-min-codesize, reverting to --ss-min-nexts\n");
1480: }
1481: }
1482: #endif
1483:
1484: #define MAX_BB 128 /* maximum number of instructions in BB */
1485: #define INF_COST 1000000 /* infinite cost */
1486: #define CANONICAL_STATE 0
1487:
1488: struct waypoint {
1489: int cost; /* the cost from here to the end */
1490: PrimNum inst; /* the inst used from here to the next waypoint */
1491: char relocatable; /* the last non-transition was relocatable */
1492: char no_transition; /* don't use the next transition (relocatability)
1493: * or this transition (does not change state) */
1494: };
1495:
1496: struct tpa_state { /* tree parsing automaton (like) state */
1497: /* labeling is back-to-front */
1498: struct waypoint *inst; /* in front of instruction */
1499: struct waypoint *trans; /* in front of instruction and transition */
1500: };
1501:
1502: struct tpa_state *termstate = NULL; /* initialized in loader() */
1503:
1504: /* statistics about tree parsing (lazyburg) stuff */
1505: long lb_basic_blocks = 0;
1506: long lb_labeler_steps = 0;
1507: long lb_labeler_automaton = 0;
1508: long lb_labeler_dynprog = 0;
1509: long lb_newstate_equiv = 0;
1510: long lb_newstate_new = 0;
1511: long lb_applicable_base_rules = 0;
1512: long lb_applicable_chain_rules = 0;
1513:
1514: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1515: static void init_waypoints(struct waypoint ws[])
1516: {
1517: int k;
1518:
1519: for (k=0; k<maxstates; k++)
1520: ws[k].cost=INF_COST;
1521: }
1522:
1523: static struct tpa_state *empty_tpa_state()
1524: {
1525: struct tpa_state *s = malloc(sizeof(struct tpa_state));
1526:
1527: s->inst = calloc(maxstates,sizeof(struct waypoint));
1528: init_waypoints(s->inst);
1529: s->trans = calloc(maxstates,sizeof(struct waypoint));
1530: /* init_waypoints(s->trans);*/
1531: return s;
1532: }
1533:
1534: static void transitions(struct tpa_state *t)
1535: {
1536: int k;
1537: struct super_state *l;
1538:
1539: for (k=0; k<maxstates; k++) {
1540: t->trans[k] = t->inst[k];
1541: t->trans[k].no_transition = 1;
1542: }
1543: for (l = state_transitions; l != NULL; l = l->next) {
1544: PrimNum s = l->super;
1545: int jcost;
1546: struct cost *c=super_costs+s;
1547: struct waypoint *wi=&(t->trans[c->state_in]);
1548: struct waypoint *wo=&(t->inst[c->state_out]);
1549: lb_applicable_chain_rules++;
1550: if (wo->cost == INF_COST)
1551: continue;
1552: jcost = wo->cost + ss_cost(s);
1553: if (jcost <= wi->cost) {
1554: wi->cost = jcost;
1555: wi->inst = s;
1556: wi->relocatable = wo->relocatable;
1557: wi->no_transition = 0;
1558: /* if (ss_greedy) wi->cost = wo->cost ? */
1559: }
1560: }
1561: }
1562:
1563: static struct tpa_state *make_termstate()
1564: {
1565: struct tpa_state *s = empty_tpa_state();
1566:
1567: s->inst[CANONICAL_STATE].cost = 0;
1568: transitions(s);
1569: return s;
1570: }
1571: #endif
1572:
1573: #define TPA_SIZE 16384
1574:
1575: struct tpa_entry {
1576: struct tpa_entry *next;
1577: PrimNum inst;
1578: struct tpa_state *state_behind; /* note: brack-to-front labeling */
1579: struct tpa_state *state_infront; /* note: brack-to-front labeling */
1580: } *tpa_table[TPA_SIZE];
1581:
1582: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1583: static Cell hash_tpa(PrimNum p, struct tpa_state *t)
1584: {
1585: UCell it = (UCell )t;
1586: return (p+it+(it>>14))&(TPA_SIZE-1);
1587: }
1588:
1589: static struct tpa_state **lookup_tpa(PrimNum p, struct tpa_state *t2)
1590: {
1591: int hash=hash_tpa(p, t2);
1592: struct tpa_entry *te = tpa_table[hash];
1593:
1594: if (tpa_noautomaton) {
1595: static struct tpa_state *t;
1596: t = NULL;
1597: return &t;
1598: }
1599: for (; te!=NULL; te = te->next) {
1600: if (p == te->inst && t2 == te->state_behind)
1601: return &(te->state_infront);
1602: }
1603: te = (struct tpa_entry *)malloc(sizeof(struct tpa_entry));
1604: te->next = tpa_table[hash];
1605: te->inst = p;
1606: te->state_behind = t2;
1607: te->state_infront = NULL;
1608: tpa_table[hash] = te;
1609: return &(te->state_infront);
1610: }
1611:
1612: static void tpa_state_normalize(struct tpa_state *t)
1613: {
1614: /* normalize so cost of canonical state=0; this may result in
1615: negative costs for some states */
1616: int d = t->inst[CANONICAL_STATE].cost;
1617: int i;
1618:
1619: for (i=0; i<maxstates; i++) {
1620: if (t->inst[i].cost != INF_COST)
1621: t->inst[i].cost -= d;
1622: if (t->trans[i].cost != INF_COST)
1623: t->trans[i].cost -= d;
1624: }
1625: }
1626:
1627: static int tpa_state_equivalent(struct tpa_state *t1, struct tpa_state *t2)
1628: {
1629: return (memcmp(t1->inst, t2->inst, maxstates*sizeof(struct waypoint)) == 0 &&
1630: memcmp(t1->trans,t2->trans,maxstates*sizeof(struct waypoint)) == 0);
1631: }
1632: #endif
1633:
1634: struct tpa_state_entry {
1635: struct tpa_state_entry *next;
1636: struct tpa_state *state;
1637: } *tpa_state_table[TPA_SIZE];
1638:
1639: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1640: static Cell hash_tpa_state(struct tpa_state *t)
1641: {
1642: int *ti = (int *)(t->inst);
1643: int *tt = (int *)(t->trans);
1644: int r=0;
1645: int i;
1646:
1647: for (i=0; ti+i < (int *)(t->inst+maxstates); i++)
1648: r += ti[i]+tt[i];
1649: return (r+(r>>14)+(r>>22)) & (TPA_SIZE-1);
1650: }
1651:
1652: static struct tpa_state *lookup_tpa_state(struct tpa_state *t)
1653: {
1654: Cell hash = hash_tpa_state(t);
1655: struct tpa_state_entry *te = tpa_state_table[hash];
1656: struct tpa_state_entry *tn;
1657:
1658: if (!tpa_noequiv) {
1659: for (; te!=NULL; te = te->next) {
1660: if (tpa_state_equivalent(t, te->state)) {
1661: lb_newstate_equiv++;
1662: free(t->inst);
1663: free(t->trans);
1664: free(t);
1665: return te->state;
1666: }
1667: }
1668: tn = (struct tpa_state_entry *)malloc(sizeof(struct tpa_state_entry));
1669: tn->next = te;
1670: tn->state = t;
1671: tpa_state_table[hash] = tn;
1672: }
1673: lb_newstate_new++;
1674: if (tpa_trace)
1675: fprintf(stderr, "%ld %ld lb_states\n", lb_labeler_steps, lb_newstate_new);
1676: return t;
1677: }
1678:
1679: /* use dynamic programming to find the shortest paths within the basic
1680: block origs[0..ninsts-1] and rewrite the instructions pointed to by
1681: instps to use it */
1682: static void optimize_rewrite(Cell *instps[], PrimNum origs[], int ninsts)
1683: {
1684: int i,j;
1685: struct tpa_state *ts[ninsts+1];
1686: int nextdyn, nextstate, no_transition;
1687: Address old_code_area;
1688:
1689: lb_basic_blocks++;
1690: ts[ninsts] = termstate;
1691: #ifndef NO_DYNAMIC
1692: if (print_sequences) {
1693: for (i=0; i<ninsts; i++)
1694: #if defined(BURG_FORMAT)
1695: fprintf(stderr, "op%d ", super_costs[origs[i]].offset);
1696: #else
1697: fprintf(stderr, "%s ", prim_names[origs[i]]);
1698: #endif
1699: fprintf(stderr, "\n");
1700: }
1701: #endif
1702: for (i=ninsts-1; i>=0; i--) {
1703: struct tpa_state **tp = lookup_tpa(origs[i],ts[i+1]);
1704: struct tpa_state *t = *tp;
1705: lb_labeler_steps++;
1706: if (t) {
1707: ts[i] = t;
1708: lb_labeler_automaton++;
1709: }
1710: else {
1711: lb_labeler_dynprog++;
1712: ts[i] = empty_tpa_state();
1713: for (j=1; j<=max_super && i+j<=ninsts; j++) {
1714: struct super_state **superp = lookup_super(origs+i, j);
1715: if (superp!=NULL) {
1716: struct super_state *supers = *superp;
1717: for (; supers!=NULL; supers = supers->next) {
1718: PrimNum s = supers->super;
1719: int jcost;
1720: struct cost *c=super_costs+s;
1721: struct waypoint *wi=&(ts[i]->inst[c->state_in]);
1722: struct waypoint *wo=&(ts[i+j]->trans[c->state_out]);
1723: int no_transition = wo->no_transition;
1724: lb_applicable_base_rules++;
1725: if (!(is_relocatable(s)) && !wo->relocatable) {
1726: wo=&(ts[i+j]->inst[c->state_out]);
1727: no_transition=1;
1728: }
1729: if (wo->cost == INF_COST)
1730: continue;
1731: jcost = wo->cost + ss_cost(s);
1732: if (jcost <= wi->cost) {
1733: wi->cost = jcost;
1734: wi->inst = s;
1735: wi->relocatable = is_relocatable(s);
1736: wi->no_transition = no_transition;
1737: /* if (ss_greedy) wi->cost = wo->cost ? */
1738: }
1739: }
1740: }
1741: }
1742: transitions(ts[i]);
1743: tpa_state_normalize(ts[i]);
1744: *tp = ts[i] = lookup_tpa_state(ts[i]);
1745: if (tpa_trace)
1746: fprintf(stderr, "%ld %ld lb_table_entries\n", lb_labeler_steps, lb_labeler_dynprog);
1747: }
1748: }
1749: /* now rewrite the instructions */
1750: reserve_code_super(origs,ninsts);
1751: old_code_area = code_area;
1752: nextdyn=0;
1753: nextstate=CANONICAL_STATE;
1754: no_transition = ((!ts[0]->trans[nextstate].relocatable)
1755: ||ts[0]->trans[nextstate].no_transition);
1756: for (i=0; i<ninsts; i++) {
1757: Cell tc=0, tc2;
1758: if (i==nextdyn) {
1759: if (!no_transition) {
1760: /* process trans */
1761: PrimNum p = ts[i]->trans[nextstate].inst;
1762: struct cost *c = super_costs+p;
1763: assert(ts[i]->trans[nextstate].cost != INF_COST);
1764: assert(c->state_in==nextstate);
1765: tc = compile_prim_dyn(p,NULL);
1766: nextstate = c->state_out;
1767: }
1768: {
1769: /* process inst */
1770: PrimNum p = ts[i]->inst[nextstate].inst;
1771: struct cost *c=super_costs+p;
1772: assert(c->state_in==nextstate);
1773: assert(ts[i]->inst[nextstate].cost != INF_COST);
1774: #if defined(GFORTH_DEBUGGING)
1775: assert(p == origs[i]);
1776: #endif
1777: tc2 = compile_prim_dyn(p,instps[i]);
1778: if (no_transition || !is_relocatable(p))
1779: /* !! actually what we care about is if and where
1780: * compile_prim_dyn() puts NEXTs */
1781: tc=tc2;
1782: no_transition = ts[i]->inst[nextstate].no_transition;
1783: nextstate = c->state_out;
1784: nextdyn += c->length;
1785: }
1786: } else {
1787: #if defined(GFORTH_DEBUGGING)
1788: assert(0);
1789: #endif
1790: tc=0;
1791: /* tc= (Cell)vm_prims[ts[i]->inst[CANONICAL_STATE].inst]; */
1792: }
1793: *(instps[i]) = tc;
1794: }
1795: if (!no_transition) {
1796: PrimNum p = ts[i]->trans[nextstate].inst;
1797: struct cost *c = super_costs+p;
1798: assert(c->state_in==nextstate);
1799: assert(ts[i]->trans[nextstate].cost != INF_COST);
1800: assert(i==nextdyn);
1801: (void)compile_prim_dyn(p,NULL);
1802: nextstate = c->state_out;
1803: }
1804: assert(nextstate==CANONICAL_STATE);
1805: assert(code_area==old_code_area); /* does reserve_code_super() work? */
1806: }
1807: #endif
1808:
1809: /* compile *start, possibly rewriting it into a static and/or dynamic
1810: superinstruction */
1811: void compile_prim1(Cell *start)
1812: {
1813: #if defined(DOUBLY_INDIRECT)
1814: Label prim;
1815:
1816: if (start==NULL)
1817: return;
1818: prim = (Label)*start;
1819: if (prim<((Label)(xts+DOESJUMP)) || prim>((Label)(xts+npriminfos))) {
1820: fprintf(stderr,"compile_prim encountered xt %p\n", prim);
1821: *start=(Cell)prim;
1822: return;
1823: } else {
1824: *start = (Cell)(prim-((Label)xts)+((Label)vm_prims));
1825: return;
1826: }
1827: #elif defined(INDIRECT_THREADED)
1828: return;
1829: #else /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1830: /* !! does not work, for unknown reasons; but something like this is
1831: probably needed to ensure that we don't call compile_prim_dyn
1832: before the inline arguments are there */
1833: static Cell *instps[MAX_BB];
1834: static PrimNum origs[MAX_BB];
1835: static int ninsts=0;
1836: PrimNum prim_num;
1837:
1838: if (start==NULL || ninsts >= MAX_BB ||
1839: (ninsts>0 && superend[origs[ninsts-1]])) {
1840: /* after bb, or at the start of the next bb */
1841: optimize_rewrite(instps,origs,ninsts);
1842: /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts); */
1843: ninsts=0;
1844: if (start==NULL) {
1845: align_code();
1846: return;
1847: }
1848: }
1849: prim_num = ((Xt)*start)-vm_prims;
1850: if(prim_num >= npriminfos) {
1851: optimize_rewrite(instps,origs,ninsts);
1852: /* fprintf(stderr,"optimize_rewrite(...,%d)\n",ninsts);*/
1853: ninsts=0;
1854: return;
1855: }
1856: assert(ninsts<MAX_BB);
1857: instps[ninsts] = start;
1858: origs[ninsts] = prim_num;
1859: ninsts++;
1860: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1861: }
1862:
1863: #ifndef STANDALONE
1864: Address gforth_loader(FILE *imagefile, char* filename)
1865: /* returns the address of the image proper (after the preamble) */
1866: {
1867: ImageHeader header;
1868: Address image;
1869: Address imp; /* image+preamble */
1870: Char magic[8];
1871: char magic7; /* size byte of magic number */
1872: Cell preamblesize=0;
1873: Cell data_offset = offset_image ? 56*sizeof(Cell) : 0;
1874: UCell check_sum;
1875: Cell ausize = ((RELINFOBITS == 8) ? 0 :
1876: (RELINFOBITS == 16) ? 1 :
1877: (RELINFOBITS == 32) ? 2 : 3);
1878: Cell charsize = ((sizeof(Char) == 1) ? 0 :
1879: (sizeof(Char) == 2) ? 1 :
1880: (sizeof(Char) == 4) ? 2 : 3) + ausize;
1881: Cell cellsize = ((sizeof(Cell) == 1) ? 0 :
1882: (sizeof(Cell) == 2) ? 1 :
1883: (sizeof(Cell) == 4) ? 2 : 3) + ausize;
1884: Cell sizebyte = (ausize << 5) + (charsize << 3) + (cellsize << 1) +
1885: #ifdef WORDS_BIGENDIAN
1886: 0
1887: #else
1888: 1
1889: #endif
1890: ;
1891:
1892: vm_prims = gforth_engine(0,0,0,0,0 sr_call);
1893: check_prims(vm_prims);
1894: prepare_super_table();
1895: #ifndef DOUBLY_INDIRECT
1896: #ifdef PRINT_SUPER_LENGTHS
1897: print_super_lengths();
1898: #endif
1899: check_sum = checksum(vm_prims);
1900: #else /* defined(DOUBLY_INDIRECT) */
1901: check_sum = (UCell)vm_prims;
1902: #endif /* defined(DOUBLY_INDIRECT) */
1903: #if !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED))
1904: termstate = make_termstate();
1905: #endif /* !(defined(DOUBLY_INDIRECT) || defined(INDIRECT_THREADED)) */
1906:
1907: do {
1908: if(fread(magic,sizeof(Char),8,imagefile) < 8) {
1909: fprintf(stderr,"%s: image %s doesn't seem to be a Gforth (>=0.6) image.\n",
1910: progname, filename);
1911: exit(1);
1912: }
1913: preamblesize+=8;
1914: } while(memcmp(magic,"Gforth3",7));
1915: magic7 = magic[7];
1916: if (debug) {
1917: magic[7]='\0';
1918: fprintf(stderr,"Magic found: %s ", magic);
1919: print_sizes(magic7);
1920: }
1921:
1922: if (magic7 != sizebyte)
1923: {
1924: fprintf(stderr,"This image is: ");
1925: print_sizes(magic7);
1926: fprintf(stderr,"whereas the machine is ");
1927: print_sizes(sizebyte);
1928: exit(-2);
1929: };
1930:
1931: fread((void *)&header,sizeof(ImageHeader),1,imagefile);
1932:
1933: set_stack_sizes(&header);
1934:
1935: #if HAVE_GETPAGESIZE
1936: pagesize=getpagesize(); /* Linux/GNU libc offers this */
1937: #elif HAVE_SYSCONF && defined(_SC_PAGESIZE)
1938: pagesize=sysconf(_SC_PAGESIZE); /* POSIX.4 */
1939: #elif PAGESIZE
1940: pagesize=PAGESIZE; /* in limits.h according to Gallmeister's POSIX.4 book */
1941: #endif
1942: debugp(stderr,"pagesize=%ld\n",(unsigned long) pagesize);
1943:
1944: image = dict_alloc_read(imagefile, preamblesize+header.image_size,
1945: dictsize, data_offset);
1946: imp=image+preamblesize;
1947:
1948: alloc_stacks((ImageHeader *)imp);
1949: if (clear_dictionary)
1950: memset(imp+header.image_size, 0, dictsize-header.image_size);
1951: if(header.base==0 || header.base == (Address)0x100) {
1952: Cell reloc_size=((header.image_size-1)/sizeof(Cell))/8+1;
1953: Char reloc_bits[reloc_size];
1954: fseek(imagefile, preamblesize+header.image_size, SEEK_SET);
1955: fread(reloc_bits, 1, reloc_size, imagefile);
1956: gforth_relocate((Cell *)imp, reloc_bits, header.image_size, (Cell)header.base, vm_prims);
1957: #if 0
1958: { /* let's see what the relocator did */
1959: FILE *snapshot=fopen("snapshot.fi","wb");
1960: fwrite(image,1,imagesize,snapshot);
1961: fclose(snapshot);
1962: }
1963: #endif
1964: }
1965: else if(header.base!=imp) {
1966: fprintf(stderr,"%s: Cannot load nonrelocatable image (compiled for address $%lx) at address $%lx\n",
1967: progname, (unsigned long)header.base, (unsigned long)imp);
1968: exit(1);
1969: }
1970: if (header.checksum==0)
1971: ((ImageHeader *)imp)->checksum=check_sum;
1972: else if (header.checksum != check_sum) {
1973: fprintf(stderr,"%s: Checksum of image ($%lx) does not match the executable ($%lx)\n",
1974: progname, (unsigned long)(header.checksum),(unsigned long)check_sum);
1975: exit(1);
1976: }
1977: #ifdef DOUBLY_INDIRECT
1978: ((ImageHeader *)imp)->xt_base = xts;
1979: #endif
1980: fclose(imagefile);
1981:
1982: /* unnecessary, except maybe for CODE words */
1983: /* FLUSH_ICACHE(imp, header.image_size);*/
1984:
1985: return imp;
1986: }
1987: #endif
1988:
1989: /* pointer to last '/' or '\' in file, 0 if there is none. */
1990: static char *onlypath(char *filename)
1991: {
1992: return strrchr(filename, DIRSEP);
1993: }
1994:
1995: static FILE *openimage(char *fullfilename)
1996: {
1997: FILE *image_file;
1998: char * expfilename = tilde_cstr((Char *)fullfilename, strlen(fullfilename), 1);
1999:
2000: image_file=fopen(expfilename,"rb");
2001: if (image_file!=NULL && debug)
2002: fprintf(stderr, "Opened image file: %s\n", expfilename);
2003: return image_file;
2004: }
2005:
2006: /* try to open image file concat(path[0:len],imagename) */
2007: static FILE *checkimage(char *path, int len, char *imagename)
2008: {
2009: int dirlen=len;
2010: char fullfilename[dirlen+strlen((char *)imagename)+2];
2011:
2012: memcpy(fullfilename, path, dirlen);
2013: if (fullfilename[dirlen-1]!=DIRSEP)
2014: fullfilename[dirlen++]=DIRSEP;
2015: strcpy(fullfilename+dirlen,imagename);
2016: return openimage(fullfilename);
2017: }
2018:
2019: static FILE * open_image_file(char * imagename, char * path)
2020: {
2021: FILE * image_file=NULL;
2022: char *origpath=path;
2023:
2024: if(strchr(imagename, DIRSEP)==NULL) {
2025: /* first check the directory where the exe file is in !! 01may97jaw */
2026: if (onlypath(progname))
2027: image_file=checkimage(progname, onlypath(progname)-progname, imagename);
2028: if (!image_file)
2029: do {
2030: char *pend=strchr(path, PATHSEP);
2031: if (pend==NULL)
2032: pend=path+strlen(path);
2033: if (strlen(path)==0) break;
2034: image_file=checkimage(path, pend-path, imagename);
2035: path=pend+(*pend==PATHSEP);
2036: } while (image_file==NULL);
2037: } else {
2038: image_file=openimage(imagename);
2039: }
2040:
2041: if (!image_file) {
2042: fprintf(stderr,"%s: cannot open image file %s in path %s for reading\n",
2043: progname, imagename, origpath);
2044: exit(1);
2045: }
2046:
2047: return image_file;
2048: }
2049: #endif
2050:
2051: #ifdef STANDALONE_ALLOC
2052: Address gforth_alloc(Cell size)
2053: {
2054: Address r;
2055: /* leave a little room (64B) for stack underflows */
2056: if ((r = malloc(size+64))==NULL) {
2057: perror(progname);
2058: exit(1);
2059: }
2060: r = (Address)((((Cell)r)+(sizeof(Float)-1))&(-sizeof(Float)));
2061: debugp(stderr, "malloc succeeds, address=$%lx\n", (long)r);
2062: return r;
2063: }
2064: #endif
2065:
2066: #ifdef HAS_OS
2067: static UCell convsize(char *s, UCell elemsize)
2068: /* converts s of the format [0-9]+[bekMGT]? (e.g. 25k) into the number
2069: of bytes. the letter at the end indicates the unit, where e stands
2070: for the element size. default is e */
2071: {
2072: char *endp;
2073: UCell n,m;
2074:
2075: m = elemsize;
2076: n = strtoul(s,&endp,0);
2077: if (endp!=NULL) {
2078: if (strcmp(endp,"b")==0)
2079: m=1;
2080: else if (strcmp(endp,"k")==0)
2081: m=1024;
2082: else if (strcmp(endp,"M")==0)
2083: m=1024*1024;
2084: else if (strcmp(endp,"G")==0)
2085: m=1024*1024*1024;
2086: else if (strcmp(endp,"T")==0) {
2087: #if (SIZEOF_CHAR_P > 4)
2088: m=1024L*1024*1024*1024;
2089: #else
2090: fprintf(stderr,"%s: size specification \"%s\" too large for this machine\n", progname, endp);
2091: exit(1);
2092: #endif
2093: } else if (strcmp(endp,"e")!=0 && strcmp(endp,"")!=0) {
2094: fprintf(stderr,"%s: cannot grok size specification %s: invalid unit \"%s\"\n", progname, s, endp);
2095: exit(1);
2096: }
2097: }
2098: return n*m;
2099: }
2100:
2101: enum {
2102: ss_number = 256,
2103: ss_states,
2104: ss_min_codesize,
2105: ss_min_ls,
2106: ss_min_lsu,
2107: ss_min_nexts,
2108: };
2109:
2110: #ifndef STANDALONE
2111: void gforth_args(int argc, char ** argv, char ** path, char ** imagename)
2112: {
2113: int c;
2114:
2115: opterr=0;
2116: while (1) {
2117: int option_index=0;
2118: static struct option opts[] = {
2119: {"appl-image", required_argument, NULL, 'a'},
2120: {"image-file", required_argument, NULL, 'i'},
2121: {"dictionary-size", required_argument, NULL, 'm'},
2122: {"data-stack-size", required_argument, NULL, 'd'},
2123: {"return-stack-size", required_argument, NULL, 'r'},
2124: {"fp-stack-size", required_argument, NULL, 'f'},
2125: {"locals-stack-size", required_argument, NULL, 'l'},
2126: {"vm-commit", no_argument, &map_noreserve, 0},
2127: {"path", required_argument, NULL, 'p'},
2128: {"version", no_argument, NULL, 'v'},
2129: {"help", no_argument, NULL, 'h'},
2130: /* put something != 0 into offset_image */
2131: {"offset-image", no_argument, &offset_image, 1},
2132: {"no-offset-im", no_argument, &offset_image, 0},
2133: {"clear-dictionary", no_argument, &clear_dictionary, 1},
2134: {"debug", no_argument, &debug, 1},
2135: {"diag", no_argument, &diag, 1},
2136: {"die-on-signal", no_argument, &die_on_signal, 1},
2137: {"ignore-async-signals", no_argument, &ignore_async_signals, 1},
2138: {"no-super", no_argument, &no_super, 1},
2139: {"no-dynamic", no_argument, &no_dynamic, 1},
2140: {"dynamic", no_argument, &no_dynamic, 0},
2141: {"print-metrics", no_argument, &print_metrics, 1},
2142: {"print-sequences", no_argument, &print_sequences, 1},
2143: {"ss-number", required_argument, NULL, ss_number},
2144: {"ss-states", required_argument, NULL, ss_states},
2145: #ifndef NO_DYNAMIC
2146: {"ss-min-codesize", no_argument, NULL, ss_min_codesize},
2147: #endif
2148: {"ss-min-ls", no_argument, NULL, ss_min_ls},
2149: {"ss-min-lsu", no_argument, NULL, ss_min_lsu},
2150: {"ss-min-nexts", no_argument, NULL, ss_min_nexts},
2151: {"ss-greedy", no_argument, &ss_greedy, 1},
2152: {"tpa-noequiv", no_argument, &tpa_noequiv, 1},
2153: {"tpa-noautomaton", no_argument, &tpa_noautomaton, 1},
2154: {"tpa-trace", no_argument, &tpa_trace, 1},
2155: {0,0,0,0}
2156: /* no-init-file, no-rc? */
2157: };
2158:
2159: c = getopt_long(argc, argv, "+i:m:d:r:f:l:p:vhoncsx", opts, &option_index);
2160:
2161: switch (c) {
2162: case EOF: return;
2163: case '?': optind--; return;
2164: case 'a': *imagename = optarg; return;
2165: case 'i': *imagename = optarg; break;
2166: case 'm': dictsize = convsize(optarg,sizeof(Cell)); break;
2167: case 'd': dsize = convsize(optarg,sizeof(Cell)); break;
2168: case 'r': rsize = convsize(optarg,sizeof(Cell)); break;
2169: case 'f': fsize = convsize(optarg,sizeof(Float)); break;
2170: case 'l': lsize = convsize(optarg,sizeof(Cell)); break;
2171: case 'p': *path = optarg; break;
2172: case 'o': offset_image = 1; break;
2173: case 'n': offset_image = 0; break;
2174: case 'c': clear_dictionary = 1; break;
2175: case 's': die_on_signal = 1; break;
2176: case 'x': debug = 1; break;
2177: case 'v': fputs(PACKAGE_STRING"\n", stderr); exit(0);
2178: case ss_number: static_super_number = atoi(optarg); break;
2179: case ss_states: maxstates = max(min(atoi(optarg),MAX_STATE),1); break;
2180: #ifndef NO_DYNAMIC
2181: case ss_min_codesize: ss_cost = cost_codesize; break;
2182: #endif
2183: case ss_min_ls: ss_cost = cost_ls; break;
2184: case ss_min_lsu: ss_cost = cost_lsu; break;
2185: case ss_min_nexts: ss_cost = cost_nexts; break;
2186: case 'h':
2187: fprintf(stderr, "Usage: %s [engine options] ['--'] [image arguments]\n\
2188: Engine Options:\n\
2189: --appl-image FILE Equivalent to '--image-file=FILE --'\n\
2190: --clear-dictionary Initialize the dictionary with 0 bytes\n\
2191: -d SIZE, --data-stack-size=SIZE Specify data stack size\n\
2192: --debug Print debugging information during startup\n\
2193: --diag Print diagnostic information during startup\n\
2194: --die-on-signal Exit instead of THROWing some signals\n\
2195: --dynamic Use dynamic native code\n\
2196: -f SIZE, --fp-stack-size=SIZE Specify floating point stack size\n\
2197: -h, --help Print this message and exit\n\
2198: --ignore-async-signals Ignore instead of THROWing async. signals\n\
2199: -i FILE, --image-file=FILE Use image FILE instead of `gforth.fi'\n\
2200: -l SIZE, --locals-stack-size=SIZE Specify locals stack size\n\
2201: -m SIZE, --dictionary-size=SIZE Specify Forth dictionary size\n\
2202: --no-dynamic Use only statically compiled primitives\n\
2203: --no-offset-im Load image at normal position\n\
2204: --no-super No dynamically formed superinstructions\n\
2205: --offset-image Load image at a different position\n\
2206: -p PATH, --path=PATH Search path for finding image and sources\n\
2207: --print-metrics Print some code generation metrics on exit\n\
2208: --print-sequences Print primitive sequences for optimization\n\
2209: -r SIZE, --return-stack-size=SIZE Specify return stack size\n\
2210: --ss-greedy Greedy, not optimal superinst selection\n\
2211: --ss-min-codesize Select superinsts for smallest native code\n\
2212: --ss-min-ls Minimize loads and stores\n\
2213: --ss-min-lsu Minimize loads, stores, and pointer updates\n\
2214: --ss-min-nexts Minimize the number of static superinsts\n\
2215: --ss-number=N Use N static superinsts (default max)\n\
2216: --ss-states=N N states for stack caching (default max)\n\
2217: --tpa-noequiv Automaton without state equivalence\n\
2218: --tpa-noautomaton Dynamic programming only\n\
2219: --tpa-trace Report new states etc.\n\
2220: -v, --version Print engine version and exit\n\
2221: --vm-commit Use OS default for memory overcommit\n\
2222: SIZE arguments consist of an integer followed by a unit. The unit can be\n\
2223: `b' (byte), `e' (element; default), `k' (KB), `M' (MB), `G' (GB) or `T' (TB).\n",
2224: argv[0]);
2225: optind--;
2226: return;
2227: }
2228: }
2229: }
2230: #endif
2231: #endif
2232:
2233: static void print_diag()
2234: {
2235:
2236: #if !defined(HAVE_GETRUSAGE)
2237: fprintf(stderr, "*** missing functionality ***\n"
2238: #ifndef HAVE_GETRUSAGE
2239: " no getrusage -> CPUTIME broken\n"
2240: #endif
2241: );
2242: #endif
2243: if((relocs < nonrelocs) ||
2244: #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)
2245: 1
2246: #else
2247: 0
2248: #endif
2249: )
2250: debugp(stderr, "relocs: %d:%d\n", relocs, nonrelocs);
2251: fprintf(stderr, "*** %sperformance problems ***\n%s%s",
2252: #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) || !(defined(FORCE_REG) || defined(FORCE_REG_UNNECESSARY)) || defined(BUGGY_LONG_LONG)
2253: "",
2254: #else
2255: "no ",
2256: #endif
2257: #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)
2258: " double-cell integer type buggy ->\n "
2259: #ifdef BUGGY_LL_CMP
2260: "double comparisons, "
2261: #endif
2262: #ifdef BUGGY_LL_MUL
2263: "*/MOD */ M* UM* "
2264: #endif
2265: #ifdef BUGGY_LL_DIV
2266: /* currently nothing is affected */
2267: #endif
2268: #ifdef BUGGY_LL_ADD
2269: "M+ D+ D- DNEGATE "
2270: #endif
2271: #ifdef BUGGY_LL_SHIFT
2272: "D2/ "
2273: #endif
2274: #ifdef BUGGY_LL_D2F
2275: "D>F "
2276: #endif
2277: #ifdef BUGGY_LL_F2D
2278: "F>D "
2279: #endif
2280: "\b\b slow\n"
2281: #endif
2282: #if !(defined(FORCE_REG) || defined(FORCE_REG_UNNECESSARY))
2283: " automatic register allocation: performance degradation possible\n"
2284: #endif
2285: "",
2286: (relocs < nonrelocs) ? "no dynamic code generation (--debug for details) -> factor 2 slowdown\n" : "");
2287: }
2288:
2289: #ifdef STANDALONE
2290: Cell data_abort_pc;
2291:
2292: void data_abort_C(void)
2293: {
2294: while(1) {
2295: }
2296: }
2297: #endif
2298:
2299: int main(int argc, char **argv, char **env)
2300: {
2301: #ifdef HAS_OS
2302: char *path = getenv("GFORTHPATH") ? : DEFAULTPATH;
2303: #else
2304: char *path = DEFAULTPATH;
2305: #endif
2306: #ifndef INCLUDE_IMAGE
2307: char *imagename="gforth.fi";
2308: FILE *image_file;
2309: Address image;
2310: #endif
2311: int retvalue;
2312: #if 0 && defined(__i386)
2313: /* disabled because the drawbacks may be worse than the benefits */
2314: /* set 387 precision control to use 53-bit mantissae to avoid most
2315: cases of double rounding */
2316: short fpu_control = 0x027f ;
2317: asm("fldcw %0" : : "m"(fpu_control));
2318: #endif /* defined(__i386) */
2319:
2320: code_here = ((void *)0)+CODE_BLOCK_SIZE; /* llvm-gcc does not like this as
2321: initializer, so we do it here */
2322: #ifdef MACOSX_DEPLOYMENT_TARGET
2323: setenv("MACOSX_DEPLOYMENT_TARGET", MACOSX_DEPLOYMENT_TARGET, 0);
2324: #endif
2325: #ifdef LTDL_LIBRARY_PATH
2326: setenv("LTDL_LIBRARY_PATH", LTDL_LIBRARY_PATH, 0);
2327: #endif
2328: #ifndef STANDALONE
2329: /* buffering of the user output device */
2330: #ifdef _IONBF
2331: if (isatty(fileno(stdout))) {
2332: fflush(stdout);
2333: setvbuf(stdout,NULL,_IONBF,0);
2334: }
2335: #endif
2336: #else
2337: prep_terminal();
2338: #endif
2339:
2340: progname = argv[0];
2341:
2342: #ifndef STANDALONE
2343: #ifdef HAVE_LIBLTDL
2344: if (lt_dlinit()!=0) {
2345: fprintf(stderr,"%s: lt_dlinit failed", progname);
2346: exit(1);
2347: }
2348: #endif
2349:
2350: #ifdef HAS_OS
2351: gforth_args(argc, argv, &path, &imagename);
2352: #ifndef NO_DYNAMIC
2353: init_ss_cost();
2354: #endif /* !defined(NO_DYNAMIC) */
2355: #endif /* defined(HAS_OS) */
2356: #endif
2357:
2358: #ifdef STANDALONE
2359: image = gforth_engine(0, 0, 0, 0, 0 sr_call);
2360: alloc_stacks((ImageHeader *)image);
2361: #else
2362: image_file = open_image_file(imagename, path);
2363: image = gforth_loader(image_file, imagename);
2364: #endif
2365: gforth_header=(ImageHeader *)image; /* used in SIGSEGV handler */
2366:
2367: if (diag)
2368: print_diag();
2369: {
2370: char path2[strlen(path)+1];
2371: char *p1, *p2;
2372: Cell environ[]= {
2373: (Cell)argc-(optind-1),
2374: (Cell)(argv+(optind-1)),
2375: (Cell)strlen(path),
2376: (Cell)path2};
2377: argv[optind-1] = progname;
2378: /*
2379: for (i=0; i<environ[0]; i++)
2380: printf("%s\n", ((char **)(environ[1]))[i]);
2381: */
2382: /* make path OS-independent by replacing path separators with NUL */
2383: for (p1=path, p2=path2; *p1!='\0'; p1++, p2++)
2384: if (*p1==PATHSEP)
2385: *p2 = '\0';
2386: else
2387: *p2 = *p1;
2388: *p2='\0';
2389: retvalue = gforth_go(image, 4, environ);
2390: #if defined(SIGPIPE) && !defined(STANDALONE)
2391: bsd_signal(SIGPIPE, SIG_IGN);
2392: #endif
2393: #ifdef VM_PROFILING
2394: vm_print_profile(stderr);
2395: #endif
2396: deprep_terminal();
2397: #ifndef STANDALONE
2398: #ifdef HAVE_LIBLTDL
2399: if (lt_dlexit()!=0)
2400: fprintf(stderr,"%s: lt_dlexit failed", progname);
2401: #endif
2402: #endif
2403: }
2404: if (print_metrics) {
2405: int i;
2406: fprintf(stderr, "code size = %8ld\n", dyncodesize());
2407: #ifndef STANDALONE
2408: for (i=0; i<sizeof(cost_sums)/sizeof(cost_sums[0]); i++)
2409: fprintf(stderr, "metric %8s: %8ld\n",
2410: cost_sums[i].metricname, cost_sums[i].sum);
2411: #endif
2412: fprintf(stderr,"lb_basic_blocks = %ld\n", lb_basic_blocks);
2413: fprintf(stderr,"lb_labeler_steps = %ld\n", lb_labeler_steps);
2414: fprintf(stderr,"lb_labeler_automaton = %ld\n", lb_labeler_automaton);
2415: fprintf(stderr,"lb_labeler_dynprog = %ld\n", lb_labeler_dynprog);
2416: fprintf(stderr,"lb_newstate_equiv = %ld\n", lb_newstate_equiv);
2417: fprintf(stderr,"lb_newstate_new = %ld\n", lb_newstate_new);
2418: fprintf(stderr,"lb_applicable_base_rules = %ld\n", lb_applicable_base_rules);
2419: fprintf(stderr,"lb_applicable_chain_rules = %ld\n", lb_applicable_chain_rules);
2420: }
2421: if (tpa_trace) {
2422: fprintf(stderr, "%ld %ld lb_states\n", lb_labeler_steps, lb_newstate_new);
2423: fprintf(stderr, "%ld %ld lb_table_entries\n", lb_labeler_steps, lb_labeler_dynprog);
2424: }
2425: return retvalue;
2426: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>