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