Debian Codegraph @

terps/tads/tads3/tct3img.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/TCT3IMG.CPP,v 1.1 1999/07/11 00:46:57 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1999, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 tct3.cpp - TADS 3 Compiler - T3 VM Code Generator - image writing functions
15 Function
16 Image writing routines for the T3-specific code generator
17 Notes
18
19 Modified
20 05/08/99 MJRoberts - Creation
21 */
22
23 #include <stdio.h>
24 #include <stdlib.h>
25
26 #include "t3std.h"
27 #include "os.h"
28 #include "tcprs.h"
29 #include "tct3.h"
30 #include "tcgen.h"
31 #include "vmtype.h"
32 #include "vmwrtimg.h"
33 #include "vmgram.h"
34 #include "vmfile.h"
35 #include "tcmain.h"
36 #include "tcerr.h"
37 #include "tcmake.h"
38 #include "tctok.h"
39
40
41 /* ------------------------------------------------------------------------ */
42 /*
43 * Object file signature. The numerical suffix in the first part is the
44 * format version number: whenever we make an incompatible change to the
45 * format, we'll increment this number so that the linker will recognize an
46 * incompatible file format and require a full rebuild.
47 */
48 static const char obj_file_sig[] = "TADS3.Object.0011\n\r\032";
49
50
51 /* ------------------------------------------------------------------------ */
52 /*
53 * Write an object file. The object file contains the raw byte streams
54 * with the generated code; the fixup lists for the streams; the global
55 * symbol table; and the function and metaclass dependency lists.
56 */
57 void CTcGenTarg::write_to_object_file(CVmFile *fp, CTcMake *)
58 {
59 ulong flags;
60
61 /* write the signature */
62 fp->write_bytes(obj_file_sig, sizeof(obj_file_sig) - 1);
63
64 /* compute the object file flags */
65 flags = 0;
66 if (G_debug)
67 flags |= TCT3_OBJHDR_DEBUG;
68
69 /* write the flags */
70 fp->write_uint4(flags);
71
72 /* write the constant and code pool indivisible object maxima */
73 fp->write_uint4(max_str_len_);
74 fp->write_uint4(max_list_cnt_);
75 fp->write_uint4(max_bytecode_len_);
76
77 /*
78 * Write the maximum object and property ID's. When we load this
79 * object file, we'll need to generate a translated ID number for
80 * each object ID and for each property ID, to translate from the
81 * numbering system in the object file to the final image file
82 * numbering system. It is helpful if we know early on how many of
83 * each there are, so that we can allocate table space accordingly.
84 */
85 fp->write_uint4(next_obj_);
86 fp->write_uint4(next_prop_);
87 fp->write_uint4(G_prs->get_enum_count());
88
89 /* write the function set dependency table */
90 write_funcdep_to_object_file(fp);
91
92 /*
93 * write the metaclass dependency table - note that we must do this
94 * before writing the global symbol table, because upon loading the
95 * object file, we must have the dependency table loaded before we
96 * can load the symbols (so that any metaclass symbols can be
97 * resolved to their dependency table indices)
98 */
99 write_metadep_to_object_file(fp);
100
101 /* write the global symbol table */
102 G_prs->write_to_object_file(fp);
103
104 /* write the main code stream and its fixup list */
105 G_cs_main->write_to_object_file(fp);
106
107 /* write the static code stream and its fixup list */
108 G_cs_static->write_to_object_file(fp);
109
110 /* write the data stream and its fixup list */
111 G_ds->write_to_object_file(fp);
112
113 /* write the object stream and its fixup list */
114 G_os->write_to_object_file(fp);
115
116 /* write the intrinsic class modifier stream */
117 G_icmod_stream->write_to_object_file(fp);
118
119 /* write the BigNumber stream and its fixup list */
120 G_bignum_stream->write_to_object_file(fp);
121
122 /* write the RexPattern stream and its fixup list */
123 G_rexpat_stream->write_to_object_file(fp);
124
125 /* write the static initializer ID stream */
126 G_static_init_id_stream->write_to_object_file(fp);
127
128 /* write the local variable symbol stream */
129 G_lcl_stream->write_to_object_file(fp);
130
131 /* write the object ID fixup list */
132 CTcIdFixup::write_to_object_file(fp, G_objfixup);
133
134 /* write the property ID fixup list */
135 CTcIdFixup::write_to_object_file(fp, G_propfixup);
136
137 /* write the enumerator ID fixup list */
138 CTcIdFixup::write_to_object_file(fp, G_enumfixup);
139
140 /* write debugging information if we're compiling for the debugger */
141 if (G_debug)
142 {
143 tct3_debug_line_page *pg;
144
145 /* write the source file list */
146 write_sources_to_object_file(fp);
147
148 /*
149 * Write the pointers to the debug line records in the code
150 * stream, so that we can fix up the line records on re-loading
151 * the object file (they'll need to be adjusted for the new
152 * numbering system for the source file descriptors). First,
153 * write the total number of pointers.
154 */
155 fp->write_uint4(debug_line_cnt_);
156
157 /* now write the pointers, one page at a time */
158 for (pg = debug_line_head_ ; pg != 0 ; pg = pg->nxt)
159 {
160 size_t pgcnt;
161
162 /*
163 * if this is the last entry, it might only be partially
164 * full; otherwise, it's completely full, because we always
165 * fill a page before allocating a new one
166 */
167 if (pg->nxt == 0)
168 pgcnt = (size_t)(debug_line_cnt_ % TCT3_DEBUG_LINE_PAGE_SIZE);
169 else
170 pgcnt = TCT3_DEBUG_LINE_PAGE_SIZE;
171
172 /*
173 * Write the data - we prepared it in portable format, so we
174 * can just copy it directly to the file. Note that each
175 * entry is four bytes.
176 */
177 fp->write_bytes((char *)pg->line_ofs,
178 pgcnt * TCT3_DEBUG_LINE_REC_SIZE);
179 }
180 }
181
182 /* write the #define symbols */
183 G_tok->write_macros_to_file_for_debug(fp);
184 }
185
186 /* ------------------------------------------------------------------------ */
187 /*
188 * Write the function-set dependency table to an object file
189 */
190 void CTcGenTarg::write_funcdep_to_object_file(CVmFile *fp)
191 {
192 tc_fnset_entry *cur;
193
194 /* write the count */
195 fp->write_uint2(fnset_cnt_);
196
197 /* write the entries */
198 for (cur = fnset_head_ ; cur != 0 ; cur = cur->nxt)
199 {
200 size_t len;
201
202 len = strlen(cur->nm);
203 fp->write_uint2(len);
204 fp->write_bytes(cur->nm, len);
205 }
206 }
207
208 /*
209 * Write the metaclass dependency table to an object file
210 */
211 void CTcGenTarg::write_metadep_to_object_file(CVmFile *fp)
212 {
213 tc_meta_entry *cur;
214
215 /* write the count */
216 fp->write_uint2(meta_cnt_);
217
218 /* write the entries */
219 for (cur = meta_head_ ; cur != 0 ; cur = cur->nxt)
220 {
221 size_t len;
222
223 len = strlen(cur->nm);
224 fp->write_uint2(len);
225 fp->write_bytes(cur->nm, len);
226 }
227 }
228
229
230 /* ------------------------------------------------------------------------ */
231 /*
232 * Error handler for CTcTokenizer::load_macros_from_file()
233 */
234 class MyLoadMacErr: public CTcTokLoadMacErr
235 {
236 public:
237 MyLoadMacErr(const char *fname) { fname_ = fname; }
238
239 /* log an error */
240 virtual void log_error(int err)
241 {
242 /* check the error code */
243 switch(err)
244 {
245 case 1:
246 case 2:
247 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
248 TCERR_OBJFILE_MACRO_SYM_TOO_LONG, fname_);
249 break;
250 }
251 }
252
253 private:
254 /* the name of the object file we're loading */
255 const char *fname_;
256 };
257
258 /* ------------------------------------------------------------------------ */
259 /*
260 * Load an object file. We'll read the file, load its data into memory
261 * (creating global symbol table entries and writing to the code and
262 * data streams), fix up the fixups to the new base offsets in the
263 * streams, and translate object and property ID values from the object
264 * file numbering system to our in-memory numbering system (which will
265 * usually differ after more than one object file is loaded, because the
266 * numbering systems in the different files must be reconciled).
267 *
268 * Returns zero on success; logs errors and returns non-zero on error.
269 */
270 int CTcGenTarg::load_object_file(CVmFile *fp, const textchar_t *fname)
271 {
272 char buf[128];
273 ulong obj_cnt;
274 ulong prop_cnt;
275 ulong enum_cnt;
276 vm_obj_id_t *obj_xlat = 0;
277 vm_prop_id_t *prop_xlat = 0;
278 ulong *enum_xlat = 0;
279 int err;
280 ulong hdr_flags;
281 ulong siz;
282 ulong main_cs_start_ofs;
283 ulong static_cs_start_ofs;
284
285 /*
286 * Before loading anything from the file, go through all of the
287 * streams and set their object file base offset. All stream
288 * offsets that we read from the object file will be relative to the
289 * these values, since the object file stream data will be loaded in
290 * after any data currently in the streams.
291 */
292 G_cs_main->set_object_file_start_ofs();
293 G_cs_static->set_object_file_start_ofs();
294 G_ds->set_object_file_start_ofs();
295 G_os->set_object_file_start_ofs();
296 G_icmod_stream->set_object_file_start_ofs();
297 G_bignum_stream->set_object_file_start_ofs();
298 G_rexpat_stream->set_object_file_start_ofs();
299 G_static_init_id_stream->set_object_file_start_ofs();
300 G_lcl_stream->set_object_file_start_ofs();
301
302 /*
303 * note the main code stream's start offset, since we'll need this
304 * later in order to process the debug line records; likewise, note
305 * the static stream's start offset
306 */
307 main_cs_start_ofs = G_cs_main->get_ofs();
308 static_cs_start_ofs = G_cs_static->get_ofs();
309
310 /* read the signature, and make sure it matches */
311 fp->read_bytes(buf, sizeof(obj_file_sig) - 1);
312 if (memcmp(buf, obj_file_sig, sizeof(obj_file_sig) - 1) != 0)
313 {
314 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_OBJFILE_INV_SIG);
315 return 1;
316 }
317
318 /* read the file header flags */
319 hdr_flags = fp->read_uint4();
320
321 /*
322 * If we're linking with debugging information, but this object file
323 * wasn't compiled with debugging information, we won't be able to
324 * produce a complete debuggable image - log an error to that
325 * effect.
326 */
327 if (G_debug && (hdr_flags & TCT3_OBJHDR_DEBUG) == 0)
328 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
329 TCERR_OBJFILE_NO_DBG, fname);
330
331 /*
332 * Read the constant and code pool indivisible object maxima. Note
333 * each maximum that exceeds the current maximum, since we must keep
334 * track of the largest indivisible object of each type in the
335 * entire program.
336 */
337
338 /* read and note the maximum string constant length */
339 siz = fp->read_uint4();
340 if (siz > max_str_len_)
341 max_str_len_ = siz;
342
343 /* read and note the maximum list size */
344 siz = fp->read_uint4();
345 if (siz > max_list_cnt_)
346 max_list_cnt_ = siz;
347
348 /* read and note the maximum code pool object size */
349 siz = fp->read_uint4();
350 if (siz > max_bytecode_len_)
351 max_bytecode_len_ = siz;
352
353 /*
354 * read the object, property, and enumerator ID counts from the file
355 * - these give the highest ID values that are assigned anywhere in
356 * the object file's numbering system
357 */
358 obj_cnt = fp->read_uint4();
359 prop_cnt = fp->read_uint4();
360 enum_cnt = fp->read_uint4();
361
362 /*
363 * Allocate object and property ID translation tables. These are
364 * simply arrays of ID's. Each element of an array gives the global
365 * ID number assigned to the object whose local ID is the array
366 * index. So, obj_xlat[local_id] = global_id. We need one element
367 * in the object ID translation array for each local ID in the
368 * object file, which is obj_cnt; likewise for properties and
369 * prop_cnt.
370 *
371 * We're being a bit lazy here by using flat arrays. This could be
372 * a problem for very large object files on 16-bit machines: if a
373 * single object file has more than 16k object ID's (which means
374 * that it defines and imports more than 16k unique objects), or
375 * more than 32k property ID's, we'll go over the 64k allocation
376 * limit on these machines. This seems unlikely to become a problem
377 * in practice, but to ensure a graceful failure in such cases,
378 * check the allocation requirement to make sure we don't go over
379 * the present platform's architectural limits.
380 */
381 if (obj_cnt * sizeof(obj_xlat[0]) > OSMALMAX
382 || prop_cnt * sizeof(prop_xlat[0]) > OSMALMAX
383 || enum_cnt * sizeof(enum_xlat[0]) > OSMALMAX)
384 {
385 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_OBJFILE_TOO_MANY_IDS);
386 return 2;
387 }
388
389 /* allocate the translation arrays */
390 obj_xlat = (vm_obj_id_t *)
391 t3malloc((size_t)(obj_cnt * sizeof(obj_xlat[0])));
392 prop_xlat = (vm_prop_id_t *)
393 t3malloc((size_t)(prop_cnt * sizeof(prop_xlat[0])));
394 enum_xlat = (ulong *)
395 t3malloc((size_t)(enum_cnt * sizeof(enum_xlat[0])));
396
397 err_try
398 {
399 /* check to make sure we got the memory */
400 if (obj_xlat == 0 || prop_xlat == 0 || enum_xlat == 0)
401 {
402 /* log an error and return failure */
403 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_OBJFILE_OUT_OF_MEM);
404 err = 3;
405 goto done;
406 }
407
408 /*
409 * Clear out the translation arrays initially. We should, in the
410 * course of loading the symbol table, assign a translation value
411 * for every entry. If anything is left at zero (which is invalid
412 * as an object or property ID), something must be wrong.
413 */
414 memset(obj_xlat, 0, (size_t)(obj_cnt * sizeof(obj_xlat[0])));
415 memset(prop_xlat, 0, (size_t)(prop_cnt * sizeof(prop_xlat[0])));
416 memset(enum_xlat, 0, (size_t)(enum_cnt * sizeof(enum_xlat[0])));
417
418 /* read the function set dependency table */
419 load_funcdep_from_object_file(fp, fname);
420
421 /* read the metaclass dependency table */
422 load_metadep_from_object_file(fp, fname);
423
424 /*
425 * Read the symbol table. This will create translation entries for
426 * the object and property names found in the symbol table.
427 */
428 if ((err = G_prs->load_object_file(fp, fname, obj_xlat, prop_xlat,
429 enum_xlat)) != 0)
430 {
431 /* that failed - abort the load */
432 goto done;
433 }
434
435 /* read the main code stream and its fixup list */
436 G_cs_main->load_object_file(fp, fname);
437
438 /* read the static code stream and its fixup list */
439 G_cs_static->load_object_file(fp, fname);
440
441 /* read the data stream and its fixup list */
442 G_ds->load_object_file(fp, fname);
443
444 /* read the object data stream and its fixup list */
445 G_os->load_object_file(fp, fname);
446
447 /* read the intrinsic class modifier stream */
448 G_icmod_stream->load_object_file(fp, fname);
449
450 /* read the BigNumber stream and its fixup list */
451 G_bignum_stream->load_object_file(fp, fname);
452
453 /* read the RexPattern stream and its fixup list */
454 G_rexpat_stream->load_object_file(fp, fname);
455
456 /* read the static initializer ID stream */
457 G_static_init_id_stream->load_object_file(fp, fname);
458
459 /* read the local variable symbol stream */
460 G_lcl_stream->load_object_file(fp, fname);
461
462 /* read the object ID fixup list */
463 CTcIdFixup::load_object_file(
464 fp, obj_xlat, obj_cnt, TCGEN_XLAT_OBJ, 4,
465 fname, G_keep_objfixups ? &G_objfixup : 0);
466
467 /* read the property ID fixup list */
468 CTcIdFixup::load_object_file(
469 fp, prop_xlat, prop_cnt, TCGEN_XLAT_PROP, 2,
470 fname, G_keep_propfixups ? &G_propfixup : 0);
471
472 /* read the enum ID fixup list */
473 CTcIdFixup::load_object_file(
474 fp, enum_xlat, enum_cnt, TCGEN_XLAT_ENUM, 2,
475 fname, G_keep_enumfixups ? &G_enumfixup : 0);
476
477 /* if the object file contains debugging information, read that */
478 if ((hdr_flags & TCT3_OBJHDR_DEBUG) != 0)
479 {
480 /* load the debug records */
481 load_debug_records_from_object_file(
482 fp, fname, main_cs_start_ofs, static_cs_start_ofs);
483 }
484
485 /* read the macro definitions */
486 {
487 CVmFileStream str(fp);
488 MyLoadMacErr err_handler(fname);
489 G_tok->load_macros_from_file(&str, &err_handler);
490 }
491
492 done: ;
493 }
494 err_finally
495 {
496 /*
497 * free the ID translation arrays - we no longer need them after
498 * loading the object file, because we translate everything in the
499 * course of loading, so what's left in memory when we're done uses
500 * the new global numbering system
501 */
502 if (obj_xlat != 0)
503 t3free(obj_xlat);
504 if (prop_xlat != 0)
505 t3free(prop_xlat);
506 if (enum_xlat != 0)
507 t3free(enum_xlat);
508 }
509 err_end;
510
511 /* return the result */
512 return err;
513 }
514
515
516 /* ------------------------------------------------------------------------ */
517 /*
518 * Add a debug line table to our list
519 */
520 void CTcGenTarg::add_debug_line_table(ulong ofs)
521 {
522 size_t idx;
523 uchar *p;
524
525 /* calculate the index of the next free entry on its page */
526 idx = (size_t)(debug_line_cnt_ % TCT3_DEBUG_LINE_PAGE_SIZE);
527
528 /*
529 * if we've completely filled the last page, allocate a new one - we
530 * know we've exhausted the page if we're at the start of a new page
531 * (i.e., the index is zero)
532 */
533 if (idx == 0)
534 {
535 tct3_debug_line_page *pg;
536
537 /* allocate the new page */
538 pg = (tct3_debug_line_page *)t3malloc(sizeof(*pg));
539
540 /* link it in at the end of the list */
541 pg->nxt = 0;
542 if (debug_line_tail_ == 0)
543 debug_line_head_ = pg;
544 else
545 debug_line_tail_->nxt = pg;
546 debug_line_tail_ = pg;
547 }
548
549 /* get a pointer to the entry */
550 p = debug_line_tail_->line_ofs + (idx * TCT3_DEBUG_LINE_REC_SIZE);
551
552 /*
553 * set this entry - one byte for the code stream ID, then a UINT4 with
554 * the offset in the stream
555 */
556 *p = G_cs->get_stream_id();
557 oswp4(p + 1, ofs);
558
559 /* count it */
560 ++debug_line_cnt_;
561 }
562
563 /*
564 * Load the debug records from an object file
565 */
566 void CTcGenTarg::load_debug_records_from_object_file(
567 CVmFile *fp, const textchar_t *fname,
568 ulong main_cs_start_ofs, ulong static_cs_start_ofs)
569 {
570 int first_filedesc;
571 ulong line_table_cnt;
572
573 /*
574 * Note the starting number of our file descriptors - in the file,
575 * we started numbering them at zero, but if we have already loaded
576 * other object files before this one, we'll be numbering ours after
577 * the ones previously loaded. So, we'll need to fix up the
578 * references to the file descriptor indices accordingly.
579 */
580 first_filedesc = G_tok->get_next_filedesc_index();
581
582 /* read the source file list */
583 read_sources_from_object_file(fp);
584
585 /*
586 * Read the line record pointers. For each line record table, we
587 * must fix up the line records to reflect the file descriptor
588 * numbering system.
589 */
590 for (line_table_cnt = fp->read_uint4() ; line_table_cnt != 0 ;
591 --line_table_cnt)
592 {
593 uchar stream_id;
594 ulong ofs;
595 CTcCodeStream *cs;
596 ulong start_ofs;
597
598 /* read the stream ID */
599 stream_id = fp->read_byte();
600
601 /* find the appropriate code stream */
602 cs = (CTcCodeStream *)
603 CTcDataStream::get_stream_from_id(stream_id, fname);
604
605 /* get the appropriate starting offset */
606 start_ofs = (cs == G_cs_main ? main_cs_start_ofs
607 : static_cs_start_ofs);
608
609 /*
610 * Read the next line table offset - this is the offset in the
611 * code stream of the next debug line table. Add our starting
612 * offset to get the true offset.
613 */
614 ofs = fp->read_uint4() + start_ofs;
615
616 /* update this table */
617 fix_up_debug_line_table(cs, ofs, first_filedesc);
618 }
619 }
620
621 /*
622 * Fix up a debug line record table for the current object file
623 */
624 void CTcGenTarg::fix_up_debug_line_table(CTcCodeStream *cs,
625 ulong line_table_ofs,
626 int first_filedesc)
627 {
628 uint cnt;
629 ulong ofs;
630
631 /* read the number of line records in the table */
632 cnt = cs->readu2_at(line_table_ofs);
633
634 /* adjust each entry */
635 for (ofs = line_table_ofs + 2 ; cnt != 0 ; --cnt, ofs += G_sizes.dbg_line)
636 {
637 uint filedesc;
638
639 /* read the old file descriptor ID */
640 filedesc = cs->readu2_at(ofs + 2);
641
642 /* adjust it to the new numbering system */
643 filedesc += first_filedesc;
644
645 /* write it back */
646 cs->write2_at(ofs + 2, filedesc);
647 }
648 }
649
650 /* ------------------------------------------------------------------------ */
651 /*
652 * Load a function set dependency table from the object file. We can
653 * add to the existing set of functions, but if we have N function sets
654 * defined already, the first N in the file must match the ones we have
655 * loaded exactly.
656 */
657 void CTcGenTarg::load_funcdep_from_object_file(class CVmFile *fp,
658 const textchar_t *fname)
659 {
660 int cnt;
661 tc_fnset_entry *cur;
662
663 /* read the count */
664 cnt = fp->read_int2();
665
666 /* read the entries */
667 for (cur = fnset_head_ ; cnt != 0 ; --cnt)
668 {
669 char buf[128];
670 size_t len;
671
672 /* read this entry */
673 len = fp->read_uint2();
674 if (len + 1 > sizeof(buf))
675 {
676 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
677 TCERR_OBJFILE_INV_FN_OR_META, fname);
678 return;
679 }
680
681 /* read the name and null-terminate it */
682 fp->read_bytes(buf, len);
683 buf[len] = '\0';
684
685 /*
686 * if we are still scanning existing entries, make sure it
687 * matches; otherwise, add it
688 */
689 if (cur != 0)
690 {
691 const char *vsn;
692 char *ent_vsn;
693 size_t name_len;
694 size_t ent_name_len;
695
696 /* get the version suffixes, if any */
697 vsn = lib_find_vsn_suffix(buf, '/', 0, &name_len);
698 ent_vsn = (char *)
699 lib_find_vsn_suffix(cur->nm, '/', 0, &ent_name_len);
700
701 /* if it doesn't match, it's an error */
702 if (name_len != ent_name_len
703 || memcmp(cur->nm, buf, name_len) != 0)
704 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
705 TCERR_OBJFILE_FNSET_CONFLICT,
706 buf, fname);
707
708 /*
709 * if the new version string is higher than the old version
710 * string, keep the new version string
711 */
712 if (vsn != 0 && ent_vsn != 0 && strcmp(vsn, ent_vsn) > 0
713 && strlen(vsn) <= strlen(ent_vsn))
714 {
715 /*
716 * the new version is newer than the version in the
717 * table - overwrite the table version with the new
718 * version, so that the table keeps the newest version
719 * mentioned anywhere (newer versions are upwardly
720 * compatible with older versions, so the code that uses
721 * the older version will be equally happy with the
722 * newer version)
723 */
724 strcpy(ent_vsn, vsn);
725 }
726
727 /* move on to the next one */
728 cur = cur->nxt;
729 }
730 else
731 {
732 /* we're past the existing list - add the new function set */
733 add_fnset(buf, len);
734 }
735 }
736 }
737
738 /*
739 * Load a metaclass dependency table from the object file. We can add
740 * to the existing set of metaclasses, but if we have N metaclasses
741 * defined already, the first N in the file must match the ones we have
742 * loaded exactly.
743 */
744 void CTcGenTarg::load_metadep_from_object_file(class CVmFile *fp,
745 const textchar_t *fname)
746 {
747 int cnt;
748 tc_meta_entry *cur;
749
750 /* read the count */
751 cnt = fp->read_int2();
752
753 /* read the entries */
754 for (cur = meta_head_ ; cnt != 0 ; --cnt)
755 {
756 char buf[128];
757 size_t len;
758
759 /* read this entry */
760 len = fp->read_uint2();
761 if (len + 1 > sizeof(buf))
762 {
763 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
764 TCERR_OBJFILE_INV_FN_OR_META, fname);
765 return;
766 }
767
768 /* read the name and null-terminate it */
769 fp->read_bytes(buf, len);
770 buf[len] = '\0';
771
772 /*
773 * if we are still scanning existing entries, make sure it
774 * matches; otherwise, add it
775 */
776 if (cur != 0)
777 {
778 const char *vsn;
779 char *ent_vsn;
780 size_t name_len;
781 size_t ent_name_len;
782
783 /* find the version suffix, if any */
784 vsn = lib_find_vsn_suffix(buf, '/', 0, &name_len);
785
786 /* find the version suffix in this entry's name */
787 ent_vsn = (char *)
788 lib_find_vsn_suffix(cur->nm, '/', 0, &ent_name_len);
789
790 /* if it doesn't match the entry name, it's an error */
791 if (name_len != ent_name_len
792 || memcmp(cur->nm, buf, name_len) != 0)
793 {
794 /* log a mis-matched metaclass error */
795 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
796 TCERR_OBJFILE_META_CONFLICT, buf, fname);
797 }
798
799 /*
800 * if the new version string is higher than the old version
801 * string, keep the new version string
802 */
803 if (vsn != 0 && ent_vsn != 0 && strcmp(vsn, ent_vsn) > 0
804 && strlen(vsn) <= strlen(ent_vsn))
805 {
806 /*
807 * the new version is newer than the version in the
808 * table - overwrite the table version with the new
809 * version, so that the table keeps the newest version
810 * mentioned anywhere (newer versions are upwardly
811 * compatible with older versions, so the code that uses
812 * the older version will be equally happy with the
813 * newer version)
814 */
815 strcpy(ent_vsn, vsn);
816 }
817
818 /* move on to the next one */
819 cur = cur->nxt;
820 }
821 else
822 {
823 /* we're past the existing list - add the new metaclass */
824 add_meta(buf, len, 0);
825 }
826 }
827 }
828
829
830 /* ------------------------------------------------------------------------ */
831 /*
832 * Write the source file list to an object file
833 */
834 void CTcGenTarg::write_sources_to_object_file(CVmFile *fp)
835 {
836 CTcTokFileDesc *desc;
837
838 /* write the number of entries */
839 fp->write_uint2(G_tok->get_filedesc_count());
840
841 /* write the entries */
842 for (desc = G_tok->get_first_filedesc() ; desc != 0 ;
843 desc = desc->get_next())
844 {
845 size_t len;
846 const char *fname;
847
848 /* get the filename - use the resolved local filename */
849 fname = desc->get_fname();
850
851 /* write the length of the filename */
852 len = strlen(fname);
853 fp->write_uint2(len);
854
855 /* write the filename */
856 fp->write_bytes(fname, len);
857 }
858 }
859
860 /*
861 * Read a source file list from an object file
862 */
863 void CTcGenTarg::read_sources_from_object_file(CVmFile *fp)
864 {
865 uint cnt;
866 uint i;
867
868 /* read the number of entries */
869 cnt = fp->read_uint2();
870
871 /* read the entries */
872 for (i = 0 ; i < cnt ; ++i)
873 {
874 size_t len;
875 char fname[OSFNMAX];
876
877 /* read the length of the entry */
878 len = fp->read_uint2();
879
880 /* see if it fits in our buffer */
881 if (len <= sizeof(fname))
882 {
883 /* read it */
884 fp->read_bytes(fname, len);
885 }
886 else
887 {
888 /* it's too long - truncate to the buffer size */
889 fp->read_bytes(fname, sizeof(fname));
890
891 /* skip the rest */
892 fp->set_pos(fp->get_pos() + len - sizeof(fname));
893
894 /* note the truncated length */
895 len = sizeof(fname);
896 }
897
898 /*
899 * Add it to the tokenizer list. Always create a new entry,
900 * rather than re-using an existing entry. When loading
901 * multiple object files, this might result in the same file
902 * appearing as multiple different descriptors, but it's a small
903 * price to pay (it doesn't add too much redundant space to the
904 * image file, and in any case the information is only retained
905 * when we're compiling for debugging) for a big gain in
906 * simplicity (the source references in the object file can be
907 * fixed up simply by adding the object file's base index to all
908 * of the reference indices).
909 */
910 G_tok->create_file_desc(fname, len);
911 }
912 }
913
914 /* ------------------------------------------------------------------------ */
915 /*
916 * Calculate pool layouts. This is called at the start of the link
917 * phase: at this point, we know the sizes of the largest constant pool
918 * and code pool objects, so we can figure the layouts of the pools.
919 */
920 void CTcGenTarg::calc_pool_layouts(size_t *first_static_page)
921 {
922 size_t max_str;
923 size_t max_list;
924 size_t max_item;
925
926 /*
927 * We've parsed the entire program, so we now know the lengths of
928 * the longest string constant and the longest list constant. From
929 * this, we can figure the size of our constant pool pages: since
930 * each list or string must be contained entirely in a single page,
931 * the minimum page size is the length of the longest string or list.
932 *
933 * We must pick a power of two for our page size. We don't want to
934 * make the page size too small; each page requires a small amount
935 * of overhead, hence the more pages for a given total constant pool
936 * size, the more overhead. We also don't want to make the page
937 * size too large, because smaller page sizes will give us better
938 * performance on small machines that will have to swap pages in and
939 * out (the smaller a page, the less time it will take to load a
940 * page).
941 *
942 * Start at 2k, which is big enough that the data part will
943 * overwhelm the per-page overhead, but small enough that it can be
944 * loaded quickly on a small machine. If that's at least twice the
945 * length of the longest string or list, use it; otherwise, double
946 * it and try again.
947 */
948
949 /*
950 * find the length in bytes of the longest string - we require the
951 * length prefix in addition to the bytes of the string
952 */
953 max_str = max_str_len_ + VMB_LEN;
954
955 /*
956 * find the length in bytes of the longest list - we require one
957 * data holder per element, plus the length prefix
958 */
959 max_list = (max_list_cnt_ * VMB_DATAHOLDER) + VMB_LEN;
960
961 /* get the larger of the two - this will be our minimum size */
962 max_item = max_str;
963 if (max_list > max_item)
964 max_item = max_list;
965
966 /*
967 * if the maximum item size is under 16k, look for a size that will
968 * hold twice the maximum item size; otherwise, relax this
969 * requirement, since the pages are getting big, and look for
970 * something that merely fits the largest element
971 */
972 if (max_item < 16*1024)
973 max_item <<= 1;
974
975 /* calculate the constant pool layout */
976 const_layout_.calc_layout(G_ds, max_item, TRUE);
977
978 /* calculate the main code pool layout */
979 code_layout_.calc_layout(G_cs_main, max_bytecode_len_, TRUE);
980
981 /* note the number of pages of regular code */
982 *first_static_page = code_layout_.page_cnt_;
983
984 /*
985 * add the static pool into the code pool layout, since we'll
986 * ultimately write the static code as part of the plain code pages
987 */
988 code_layout_.calc_layout(G_cs_static, max_bytecode_len_, FALSE);
989 }
990
991
992 /* ------------------------------------------------------------------------ */
993 /*
994 * Write the image file
995 */
996 void CTcGenTarg::write_to_image(CVmFile *fp, uchar data_xor_mask,
997 const char tool_data[4])
998 {
999 tc_meta_entry *meta;
1000 CTcSymbol *sym;
1001 unsigned long main_ofs;
1002 vm_prop_id_t construct_prop = VM_INVALID_PROP;
1003 vm_prop_id_t finalize_prop = VM_INVALID_PROP;
1004 vm_prop_id_t graminfo_prop = VM_INVALID_PROP;
1005 vm_prop_id_t gramtag_prop = VM_INVALID_PROP;
1006 vm_prop_id_t miscvocab_prop = VM_INVALID_PROP;
1007 tc_fnset_entry *fnset;
1008 CVmImageWriter *image_writer;
1009 int bignum_idx;
1010 int rexpat_idx;
1011 int int_class_idx;
1012 CTcPrsExport *exp;
1013 CTcDataStream *cs_list[2];
1014 size_t first_static_code_page;
1015
1016 /*
1017 * if we have any BigNumber data, get the BigNumber metaclass index
1018 * (or define it, if the program didn't do so itself)
1019 */
1020 if (G_bignum_stream->get_ofs() != 0)
1021 bignum_idx = find_or_add_meta("bignumber", 9, 0);
1022
1023 /* if we have any RexPattern data, get the RexPattern metaclass index */
1024 if (G_rexpat_stream->get_ofs() != 0)
1025 rexpat_idx = find_or_add_meta("regex-pattern", 13, 0);
1026
1027 /* apply internal object/property ID fixups in the symbol table */
1028 G_prs->apply_internal_fixups();
1029
1030 /* build the grammar productions */
1031 G_prs->build_grammar_productions();
1032
1033 /*
1034 * Build the dictionaries. We must wait until after applying the
1035 * internal fixups to build the dictionaries, so that we have the
1036 * final, fully-resolved form of each object's vocabulary list before
1037 * we build the dictionaries. We must also wait until after we build
1038 * the grammar productions, because the grammar productions can add
1039 * dictionary entries for their literal token matchers.
1040 */
1041 G_prs->build_dictionaries();
1042
1043 /*
1044 * Build the multi-method static initializers. Note: this must be done
1045 * before we generate the intrinsic class objects, because we might add
1046 * intrinsic class modifiers in the course of building the mm
1047 * initializers.
1048 */
1049 build_multimethod_initializers();
1050
1051 /* make sure the the IntrinsicClass intrinsic class is itself defined */
1052 int_class_idx = find_or_add_meta("intrinsic-class", 15, 0);
1053
1054 /* build the IntrinsicClass objects */
1055 build_intrinsic_class_objs(G_int_class_stream);
1056
1057 /*
1058 * Apply fixups for the local variable stream. This stream isn't
1059 * written to the image file, but we need to do the layout in order to
1060 * apply its fixups.
1061 */
1062 CTcStreamLayout vpl;
1063 vpl.calc_layout(G_lcl_stream, 65535, TRUE);
1064
1065 /*
1066 * Build the local symbol records. We need to do this before
1067 * calculating the code pool layout, because this writes more data to
1068 * the constant pool. We need to build the symbol records separately
1069 * for the regular and static code pools, since they haven't been
1070 * merged yet.
1071 */
1072 CVmHashTable *lcltab = new CVmHashTable(1024, new CVmHashFuncCS(), TRUE);
1073 build_local_symbol_records(G_cs_main, lcltab);
1074 build_local_symbol_records(G_cs_static, lcltab);
1075
1076 /* we're done with the local symbol hash table */
1077 delete lcltab;
1078
1079 /* calculate the final pool layouts */
1080 calc_pool_layouts(&first_static_code_page);
1081
1082 /* build the source line location maps, if debugging */
1083 if (G_debug)
1084 build_source_line_maps();
1085
1086 /* look up the "_main" symbol in the global symbol table */
1087 sym = G_prs->get_global_symtab()->find("_main");
1088
1089 /*
1090 * if there's no "_main" symbol, or it's not a function, it's an
1091 * error
1092 */
1093 if (sym == 0)
1094 {
1095 /* "_main" isn't defined - log an error and abort */
1096 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_MAIN_NOT_DEFINED);
1097 return;
1098 }
1099 else if (sym->get_type() != TC_SYM_FUNC)
1100 {
1101 /* "_main" isn't a function - log an error and abort */
1102 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_MAIN_NOT_FUNC);
1103 return;
1104 }
1105 else
1106 {
1107 /*
1108 * Get the "_main" symbol's code pool address - this is the
1109 * program's entrypoint. We can ask for this information at
1110 * this point because we don't start writing the image file
1111 * until after the final fixup pass, which is where this address
1112 * is finally calculated.
1113 */
1114 main_ofs = ((CTcSymFunc *)sym)->get_code_pool_addr();
1115 }
1116
1117 /* get the constructor and finalizer property ID's */
1118 construct_prop = (tctarg_prop_id_t)G_prs->get_constructor_prop();
1119 finalize_prop = (tctarg_prop_id_t)G_prs->get_finalize_prop();
1120
1121 /* get the special generated GrammarProd property IDs */
1122 graminfo_prop = (tctarg_prop_id_t)G_prs->get_grammarInfo_prop();
1123 gramtag_prop = (tctarg_prop_id_t)G_prs->get_grammarTag_prop();
1124 miscvocab_prop = (tctarg_prop_id_t)G_prs->get_miscvocab_prop();
1125
1126 /* create our image writer */
1127 image_writer = new CVmImageWriter(fp);
1128
1129 /* prepare the image file - use file format version 1 */
1130 image_writer->prepare(1, tool_data);
1131
1132 /* write the entrypoint offset and data structure parameters */
1133 image_writer->write_entrypt(main_ofs, G_sizes.mhdr,
1134 G_sizes.exc_entry, G_sizes.dbg_line,
1135 G_sizes.dbg_hdr, G_sizes.lcl_hdr,
1136 G_sizes.dbg_frame,
1137 G_sizes.dbg_fmt_vsn);
1138
1139 /* begin writing the symbolic items */
1140 image_writer->begin_sym_block();
1141
1142 /* run through the list of exports in the parser */
1143 for (exp = G_prs->get_exp_head() ; exp != 0 ; exp = exp->get_next())
1144 {
1145 CTcPrsExport *exp2;
1146 int dup_err_cnt;
1147
1148 /*
1149 * if this one's external name is null, it means that we've
1150 * previously encountered it as a duplicate and marked it as such
1151 * - in this case, simply skip it
1152 */
1153 if (exp->get_ext_name() == 0)
1154 continue;
1155
1156 /* make sure it's not one of our special ones */
1157 if (exp->ext_name_matches("LastProp")
1158 || exp->ext_name_matches("Constructor")
1159 || exp->ext_name_matches("Destructor")
1160 || exp->ext_name_starts_with("operator "))
1161 {
1162 /* it's a reserved export - flag an error */
1163 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
1164 TCERR_RESERVED_EXPORT,
1165 (int)exp->get_ext_len(),
1166 exp->get_ext_name());
1167 }
1168
1169
1170 /* look up the symbol, defining as a property if undefined */
1171 sym = G_prs->get_global_symtab()
1172 ->find_or_def_prop(exp->get_sym(), exp->get_sym_len(), FALSE);
1173
1174 /*
1175 * Scan the rest of the export list for duplicates. If we find
1176 * the symbol external name exported with a different value, it's
1177 * an error.
1178 */
1179 for (dup_err_cnt = 0, exp2 = exp->get_next() ; exp2 != 0 ;
1180 exp2 = exp2->get_next())
1181 {
1182 /* if this one has already been marked as a duplicate, skip it */
1183 if (exp2->get_ext_name() == 0)
1184 continue;
1185
1186 /* check for a match of the external name */
1187 if (exp->ext_name_matches(exp2))
1188 {
1189 /*
1190 * This one matches, so it's a redundant export for the
1191 * same name. If it's being exported as the same internal
1192 * symbol as the other one, this is fine; otherwise it's
1193 * an error, since the same external name can't be given
1194 * two different meanings.
1195 */
1196 if (!exp->sym_matches(exp2))
1197 {
1198 /*
1199 * It doesn't match - log an error. If we've already
1200 * logged an error, show a continuation error;
1201 * otherwise show the first error for the symbol.
1202 */
1203 ++dup_err_cnt;
1204 if (dup_err_cnt == 1)
1205 {
1206 /* it's the first error - show the long form */
1207 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
1208 TCERR_DUP_EXPORT,
1209 (int)exp->get_ext_len(),
1210 exp->get_ext_name(),
1211 (int)exp->get_sym_len(),
1212 exp->get_sym(),
1213 (int)exp2->get_sym_len(),
1214 exp2->get_sym());
1215 }
1216 else
1217 {
1218 /* it's a follow-up error */
1219 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
1220 TCERR_DUP_EXPORT_AGAIN,
1221 (int)exp->get_ext_len(),
1222 exp->get_ext_name(),
1223 (int)exp2->get_sym_len(),
1224 exp2->get_sym());
1225 }
1226 }
1227
1228 /*
1229 * Regardless of whether this one matches or not, remove
1230 * it from the list by setting its external name to null -
1231 * we only want to include each symbol in the export list
1232 * once.
1233 */
1234 exp2->set_extern_name(0, 0);
1235 }
1236 }
1237
1238 /* write it out according to its type */
1239 switch(sym->get_type())
1240 {
1241 case TC_SYM_OBJ:
1242 /* write the object symbol */
1243 image_writer->write_sym_item_objid(
1244 exp->get_ext_name(), exp->get_ext_len(),
1245 ((CTcSymObj *)sym)->get_obj_id());
1246 break;
1247
1248 case TC_SYM_PROP:
1249 /* write the property symbol */
1250 image_writer->write_sym_item_propid(
1251 exp->get_ext_name(), exp->get_ext_len(),
1252 ((CTcSymProp *)sym)->get_prop());
1253 break;
1254
1255 case TC_SYM_FUNC:
1256 /* write the function symbol */
1257 image_writer->write_sym_item_func(
1258 exp->get_ext_name(), exp->get_ext_len(),
1259 ((CTcSymFunc *)sym)->get_code_pool_addr());
1260 break;
1261
1262 default:
1263 /* can't export other types */
1264 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
1265 TCERR_INVALID_TYPE_FOR_EXPORT,
1266 (int)exp->get_sym_len(), exp->get_sym());
1267 break;
1268 }
1269 }
1270
1271 /*
1272 * write the last property ID - this is a special synthetic export
1273 * that we provide automatically
1274 */
1275 image_writer->write_sym_item_propid("LastProp", next_prop_);
1276
1277 /* write our Constructor and Destructor property ID's */
1278 if (construct_prop != VM_INVALID_PROP)
1279 image_writer->write_sym_item_propid("Constructor", construct_prop);
1280 if (finalize_prop != VM_INVALID_PROP)
1281 image_writer->write_sym_item_propid("Destructor", finalize_prop);
1282
1283 /* the compiler generates grammarTag and grammarInfo properties */
1284 if (graminfo_prop != VM_INVALID_PROP)
1285 image_writer->write_sym_item_propid(
1286 "GrammarProd.grammarInfo", graminfo_prop);
1287 if (gramtag_prop != VM_INVALID_PROP)
1288 image_writer->write_sym_item_propid(
1289 "GrammarProd.grammarTag", gramtag_prop);
1290
1291 /* likewise miscVocab */
1292 if (miscvocab_prop != VM_INVALID_PROP)
1293 image_writer->write_sym_item_propid(
1294 "GrammarProd.miscVocab", miscvocab_prop);
1295
1296 /* write the operator properties */
1297 write_op_export(image_writer, G_prs->ov_op_add_);
1298 write_op_export(image_writer, G_prs->ov_op_sub_);
1299 write_op_export(image_writer, G_prs->ov_op_mul_);
1300 write_op_export(image_writer, G_prs->ov_op_div_);
1301 write_op_export(image_writer, G_prs->ov_op_mod_);
1302 write_op_export(image_writer, G_prs->ov_op_xor_);
1303 write_op_export(image_writer, G_prs->ov_op_shl_);
1304 write_op_export(image_writer, G_prs->ov_op_ashr_);
1305 write_op_export(image_writer, G_prs->ov_op_lshr_);
1306 write_op_export(image_writer, G_prs->ov_op_bnot_);
1307 write_op_export(image_writer, G_prs->ov_op_bor_);
1308 write_op_export(image_writer, G_prs->ov_op_band_);
1309 write_op_export(image_writer, G_prs->ov_op_neg_);
1310 write_op_export(image_writer, G_prs->ov_op_idx_);
1311 write_op_export(image_writer, G_prs->ov_op_setidx_);
1312
1313 /* done with the symbolic names */
1314 image_writer->end_sym_block();
1315
1316 /* write the function-set dependency table */
1317 image_writer->begin_func_dep(fnset_cnt_);
1318 for (fnset = fnset_head_ ; fnset != 0 ; fnset = fnset->nxt)
1319 image_writer->write_func_dep_item(fnset->nm);
1320 image_writer->end_func_dep();
1321
1322 /* start the metaclass dependency table */
1323 image_writer->begin_meta_dep(meta_cnt_);
1324
1325 /* write the metaclass dependency items */
1326 for (meta = meta_head_ ; meta != 0 ; meta = meta->nxt)
1327 {
1328 /* write the dependency item */
1329 image_writer->write_meta_dep_item(meta->nm);
1330
1331 /* if there's an associated symbol, write the property list */
1332 if (meta->sym != 0)
1333 {
1334 CTcSymMetaProp *prop;
1335
1336 /* scan the list of properties and write each one */
1337 for (prop = meta->sym->get_prop_head() ; prop != 0 ;
1338 prop = prop->nxt_)
1339 {
1340 /* write this item's property */
1341 image_writer->write_meta_item_prop(prop->prop_->get_prop());
1342 }
1343 }
1344 }
1345
1346 /* end the metaclass dependency table */
1347 image_writer->end_meta_dep();
1348
1349 /* write the code pool streams (don't bother masking the code bytes) */
1350 cs_list[0] = G_cs_main;
1351 cs_list[1] = G_cs_static;
1352 code_layout_.write_to_image(cs_list, 2, image_writer, 1, 0);
1353
1354 /*
1355 * write the constant pool (applying the constant pool data mask to
1356 * obscure any text strings in the data)
1357 */
1358 const_layout_.write_to_image(&G_ds, 1, image_writer, 2, data_xor_mask);
1359
1360 /* write the "TADS object" data */
1361 write_tads_objects_to_image(G_os, image_writer, TCT3_METAID_TADSOBJ);
1362
1363 /* write the intrinsic class modifier object data */
1364 write_tads_objects_to_image(G_icmod_stream, image_writer,
1365 TCT3_METAID_ICMOD);
1366
1367 /* write the dictionary data - this is a stream of dictionary objects */
1368 write_nontads_objs_to_image(G_dict_stream, image_writer,
1369 TCT3_METAID_DICT, TRUE);
1370
1371 /* write the grammar data - this is a stream of production objects */
1372 write_nontads_objs_to_image(G_gramprod_stream, image_writer,
1373 TCT3_METAID_GRAMPROD, TRUE);
1374
1375 /* if we have any BigNumber data, write it out */
1376 if (G_bignum_stream->get_ofs() != 0)
1377 write_nontads_objs_to_image(G_bignum_stream,
1378 image_writer, bignum_idx, FALSE);
1379
1380 /* if we have any RexPattern data, write it out */
1381 if (G_rexpat_stream->get_ofs() != 0)
1382 write_nontads_objs_to_image(G_rexpat_stream,
1383 image_writer, rexpat_idx, FALSE);
1384
1385 /* if we have any IntrinsicClass data, write it out */
1386 if (G_int_class_stream->get_ofs() != 0)
1387 write_nontads_objs_to_image(G_int_class_stream, image_writer,
1388 int_class_idx, FALSE);
1389
1390 /* write the static initializer list */
1391 write_static_init_list(image_writer,
1392 first_static_code_page * code_layout_.page_size_);
1393
1394 /* write debug information if desired */
1395 if (G_debug)
1396 {
1397 /* write the source file table */
1398 write_sources_to_image(image_writer);
1399
1400 /* write the global symbol table to the image file */
1401 write_global_symbols_to_image(image_writer);
1402
1403 /* write the method header list */
1404 write_method_list_to_image(image_writer);
1405
1406 /* write the macro records */
1407 write_macros_to_image(image_writer);
1408 }
1409
1410 /* finish the image file */
1411 image_writer->finish();
1412
1413 /* delete our image writer */
1414 delete image_writer;
1415 image_writer = 0;
1416 }
1417
1418 /* ------------------------------------------------------------------------ */
1419 /*
1420 * Write an export record for an operator overload property
1421 */
1422 void CTcGenTarg::write_op_export(CVmImageWriter *image_writer,
1423 CTcSymProp *prop)
1424 {
1425 if (prop != 0 && prop->get_prop() != VM_INVALID_PROP)
1426 {
1427 image_writer->write_sym_item_propid(
1428 prop->get_sym(), prop->get_sym_len(), prop->get_prop());
1429 }
1430 }
1431
1432 /* ------------------------------------------------------------------------ */
1433 /*
1434 * Write the static initializer ID list
1435 */
1436 void CTcGenTarg::write_static_init_list(CVmImageWriter *image_writer,
1437 ulong main_cs_size)
1438 {
1439 ulong rem;
1440 ulong ofs;
1441 ulong init_cnt;
1442
1443 /*
1444 * calculate the number of initializers - this is simply the size of
1445 * the stream divided by the size of each record (4 bytes for object
1446 * ID, 2 bytes for property ID)
1447 */
1448 init_cnt = G_static_init_id_stream->get_ofs() / 6;
1449
1450 /* add the multi-method initializer object, if there is one */
1451 if (mminit_obj_ != VM_INVALID_OBJ)
1452 init_cnt += 1;
1453
1454 /* start the block */
1455 image_writer->begin_sini_block(main_cs_size, init_cnt);
1456
1457 /* write the multi-method initializer object, if applicable */
1458 if (mminit_obj_ != VM_INVALID_OBJ)
1459 {
1460 /* write the object data */
1461 char buf[6];
1462 oswp4(buf, mminit_obj_); /* the object ID */
1463 oswp2(buf+4, 1); /* our arbitrary initializer property ID */
1464 image_writer->write_bytes(buf, 6);
1465 }
1466
1467 /* write the bytes */
1468 for (ofs = 0, rem = G_static_init_id_stream->get_ofs() ; rem != 0 ; )
1469 {
1470 const char *ptr;
1471 ulong cur;
1472
1473 /* get the next chunk */
1474 ptr = G_static_init_id_stream->get_block_ptr(ofs, rem, &cur);
1475
1476 /* write this chunk */
1477 image_writer->write_bytes(ptr, cur);
1478
1479 /* advance past this chunk */
1480 ofs += cur;
1481 rem -= cur;
1482 }
1483
1484 /* end the block */
1485 image_writer->end_sini_block();
1486 }
1487
1488 /* ------------------------------------------------------------------------ */
1489 /*
1490 * Build synthesized code. This is called after all of the object files
1491 * are loaded and before we generate the final image file, to give the
1492 * linker a chance to generate any automatically generated code. We use
1493 * this to generate the stub base functions for multi-methods.
1494 */
1495 struct mmstub_ctx
1496 {
1497 mmstub_ctx()
1498 {
1499 mmc = 0;
1500 cnt = 0;
1501 }
1502
1503 /* _multiMethodCall function symbol */
1504 CTcSymFunc *mmc;
1505
1506 /* number of multi-method stubs we generated */
1507 int cnt;
1508 };
1509
1510 void CTcGenTarg::build_synthesized_code()
1511 {
1512 mmstub_ctx ctx;
1513
1514 /* look up the _multiMethodCall function */
1515 ctx.mmc = (CTcSymFunc *)G_prs->get_global_symtab()->find(
1516 "_multiMethodCall", 16);
1517
1518 /*
1519 * our generated code isn't part of any object file - flag a new object
1520 * file so that we don't get confused into thinking this came from the
1521 * last object file loaded
1522 */
1523 G_cs_static->set_object_file_start_ofs();
1524 G_os->set_object_file_start_ofs();
1525
1526 /* build out the stubs for the multi-method base functions */
1527 G_prs->get_global_symtab()->enum_entries(&multimethod_stub_cb, &ctx);
1528
1529 /*
1530 * if we generated any stubs, we definitely need _multiMethodCall to be
1531 * defined - if it's not, it's an error
1532 */
1533 if (ctx.cnt != 0 && (ctx.mmc == 0 || ctx.mmc->get_type() != TC_SYM_FUNC))
1534 {
1535 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_MISSING_MMREG,
1536 "_multiMethodCall");
1537 }
1538 }
1539
1540 /* callback context - build multi-method base function stubs */
1541 void CTcGenTarg::multimethod_stub_cb(void *ctx0, CTcSymbol *sym)
1542 {
1543 mmstub_ctx *ctx = (mmstub_ctx *)ctx0;
1544
1545 /* if this is a function, check to see if it's a multi-method stub */
1546 if (sym->get_type() == TC_SYM_FUNC)
1547 {
1548 CTcSymFunc *fsym = (CTcSymFunc *)sym;
1549
1550 /*
1551 * It's a base function if it's marked as a multi-method and it
1552 * doesn't have a '*' in its name. (If there's a '*', it's a
1553 * concrete multi-method rather than a base function.)
1554 */
1555 if (fsym->is_multimethod())
1556 {
1557 /* it's marked as a multi-method - check for a decorated name */
1558 const char *p = sym->getstr();
1559 size_t rem = sym->getlen();
1560 for ( ; rem != 0 && *p != '*' ; ++p, --rem) ;
1561 if (rem == 0)
1562 {
1563 tct3_method_gen_ctx gen_ctx;
1564
1565 /*
1566 * It's a multi-method base function - build out its stub.
1567 * The stub function is a varargs function with no fixed
1568 * parameters - i.e., funcName(...). Its body simply calls
1569 * _multiMethodCall with a pointer to itself as the base
1570 * function.
1571 */
1572 G_cg->open_method(G_cs_main,
1573 fsym, fsym->get_fixup_list_anchor(),
1574 0, 0, 0, 0, TRUE, FALSE, FALSE, FALSE,
1575 &gen_ctx);
1576
1577 /* set the anchor in the function symbol */
1578 fsym->set_anchor(gen_ctx.anchor);
1579
1580 /*
1581 * turn the arguments into a list, leaving this on the
1582 * stack as the second argument for _multiMethodCall
1583 */
1584 G_cg->write_op(OPC_PUSHPARLST);
1585 G_cs->write(0);
1586 G_cg->note_push();
1587
1588 /* push the function address argument */
1589 CTcConstVal funcval;
1590 funcval.set_funcptr(fsym);
1591 CTPNConst cfunc(&funcval);
1592 cfunc.gen_code(FALSE, FALSE);
1593 G_cg->note_push();
1594
1595 /*
1596 * call _multiMethodCall, if it's defined (if not, the
1597 * caller will flag it as an error, so we don't need to
1598 * worry about that here - just skip generating the call)
1599 */
1600 if (ctx->mmc != 0)
1601 ctx->mmc->gen_code_call(FALSE, 2, FALSE, FALSE);
1602
1603 /* return the result */
1604 G_cg->write_op(OPC_RETVAL);
1605 G_cg->note_pop();
1606
1607 /* finish the method */
1608 G_cg->close_method(0, 0, 0, 0, &gen_ctx, 0);
1609 G_cg->close_method_cleanup(&gen_ctx);
1610
1611 /* the stub symbol now has a definition */
1612 fsym->set_extern(FALSE);
1613
1614 /* count it */
1615 ctx->cnt += 1;
1616 }
1617 }
1618 }
1619 }
1620
1621 /* ------------------------------------------------------------------------ */
1622 /*
1623 * Start a OBJS header for a TadsObject to a given stream. This only
1624 * writes the fixed part; the caller must then write the superclass list
1625 * and the property table. After the contents have been written, call
1626 * close_tadsobj() to finalize the header data.
1627 */
1628 void CTcGenTarg::open_tadsobj(tct3_tadsobj_ctx *ctx,
1629 CTcDataStream *stream,
1630 vm_obj_id_t obj_id,
1631 int sc_cnt, int prop_cnt,
1632 unsigned int internal_flags,
1633 unsigned int vm_flags)
1634 {
1635 /* remember the stream in the context */
1636 ctx->stream = stream;
1637
1638 /* write the internal header */
1639 stream->write2(internal_flags);
1640
1641 /* note the start of the VM object data */
1642 ctx->obj_ofs = stream->get_ofs();
1643
1644 /* write the fixed header data */
1645 stream->write_obj_id(obj_id); /* object ID */
1646 stream->write2(0); /* byte size placeholder - we'll fix up at "close" */
1647 stream->write2(sc_cnt); /* superclass count */
1648 stream->write2(prop_cnt); /* property count */
1649 stream->write2(vm_flags); /* object flags */
1650 }
1651
1652 /*
1653 * Close a TadsObject header. This must be called after the object's
1654 * contents have been written so that we can fix up the header with the
1655 * actual data size.
1656 */
1657 void CTcGenTarg::close_tadsobj(tct3_tadsobj_ctx *ctx)
1658 {
1659 /* fix up the object size data */
1660 ctx->stream->write2_at(ctx->obj_ofs + 4,
1661 ctx->stream->get_ofs() - ctx->obj_ofs - 6);
1662 }
1663
1664
1665 /* ------------------------------------------------------------------------ */
1666 /*
1667 * Linker support: ensure that the given intrinsic class has a modifier
1668 * object. If there's no modifier, we'll create one and add the code for
1669 * it to the object stream.
1670 *
1671 * This should only be called during the linking phase, after code
1672 * generation is completed. If you want to create a modifier during
1673 * compilation, you should instead use CTcParser::find_or_def_obj(), since
1674 * that creates the necessary structures for object file generation and
1675 * later linking.
1676 */
1677 void CTcGenTarg::linker_ensure_mod_obj(CTcSymMetaclass *mc)
1678 {
1679 /* if there's no modifier object, create one */
1680 if (mc->get_mod_obj() == 0)
1681 {
1682 /* create a modifier object */
1683 CTcSymObj *mod_sym = CTcSymObj::synthesize_modified_obj_sym(FALSE);
1684
1685 /* set it to be an IntrinsicClassModifier object */
1686 mod_sym->set_metaclass(TC_META_ICMOD);
1687
1688 /* link the modifier to the metaclass */
1689 mc->set_mod_obj(mod_sym);
1690
1691 /*
1692 * generate the object data - this is simply an empty object with
1693 * no superclasses, and it goes in the intrinsic class modifier
1694 * stream
1695 */
1696 tct3_tadsobj_ctx obj_ctx;
1697 G_cg->open_tadsobj(
1698 &obj_ctx, G_icmod_stream,
1699 mod_sym->get_obj_id(), 0, 0, 0, 0);
1700 G_cg->close_tadsobj(&obj_ctx);
1701 }
1702 }
1703
1704 /*
1705 * Ensure that the given intrinsic class has a modifier object, by name.
1706 */
1707 void CTcGenTarg::linker_ensure_mod_obj(const char *name, size_t len)
1708 {
1709 /* look up the symbol */
1710 CTcSymMetaclass *mc = (CTcSymMetaclass *)G_prs->get_global_symtab()
1711 ->find(name, len);
1712
1713 /* if we found the metaclass symbol, add a modifier if needed */
1714 if (mc != 0 && mc->get_type() == TC_SYM_METACLASS)
1715 linker_ensure_mod_obj(mc);
1716 }
1717
1718
1719 /* ------------------------------------------------------------------------ */
1720 /*
1721 * Build the multi-method initializers
1722 */
1723
1724 /* enumerator callback context */
1725 struct mminit_ctx
1726 {
1727 mminit_ctx()
1728 {
1729 mmr = 0;
1730 cnt = 0;
1731 }
1732
1733 /* _multiMethodRegister function symbol */
1734 CTcSymFunc *mmr;
1735
1736 /* number of multi-method registrations we generated */
1737 int cnt;
1738 };
1739
1740 /* main initializer builder */
1741 void CTcGenTarg::build_multimethod_initializers()
1742 {
1743 tct3_method_gen_ctx genctx;
1744 mminit_ctx ctx;
1745
1746 /* look up the _multiMethodRegister function */
1747 ctx.mmr = (CTcSymFunc *)G_prs->get_global_symtab()->find(
1748 "_multiMethodRegister", 20);
1749
1750 /*
1751 * open the method - it's a static initializer, so write it to the
1752 * static stream
1753 */
1754 G_cg->open_method(G_cs_static, 0, 0, 0, 0, 0, 0, FALSE,
1755 FALSE, FALSE, FALSE, &genctx);
1756
1757 /* scan the symbol table for multimethods and generate initializers */
1758 G_prs->get_global_symtab()->enum_entries(&multimethod_init_cb, &ctx);
1759
1760 /*
1761 * if we found any multi-methods, generate a call to
1762 * _multiMethodBuildBindings
1763 */
1764 if (ctx.cnt != 0)
1765 {
1766 /* look up the function - it's an error if it's not defined */
1767 CTcSymFunc *mmb = (CTcSymFunc *)G_prs->get_global_symtab()->find(
1768 "_multiMethodBuildBindings", 25);
1769 if (mmb == 0 || mmb->get_type() != TC_SYM_FUNC)
1770 {
1771 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_MISSING_MMREG,
1772 "_multiMethodBuildBindings");
1773 return;
1774 }
1775
1776 /* write the call instruction */
1777 G_cg->write_op(OPC_CALL);
1778 G_cs->write(0); /* argument count */
1779 mmb->add_abs_fixup(G_cs); /* function address fixup */
1780 G_cs->write4(0); /* fixup placeholder */
1781 }
1782
1783 /* close the method and clean up */
1784 G_cg->close_method(0, 0, 0, 0, &genctx, 0);
1785 G_cg->close_method_cleanup(&genctx);
1786
1787 /*
1788 * if we generated any registrations, create the initializer object -
1789 * this will go in the static initializer block to trigger invocation
1790 * of the registration routine at load time
1791 */
1792 if (ctx.cnt != 0)
1793 {
1794 /* we have multi-methods, so we definitely need _multiMethodRegister */
1795 if (ctx.mmr == 0 || ctx.mmr->get_type() != TC_SYM_FUNC)
1796 {
1797 G_tcmain->log_error(0, 0, TC_SEV_ERROR, TCERR_MISSING_MMREG,
1798 "_multiMethodRegister");
1799 return;
1800 }
1801
1802 /* create an anonymous object to hold the initializer code */
1803 mminit_obj_ = G_cg->new_obj_id();
1804
1805 /* add a debugging symbol for it */
1806 G_prs->get_global_symtab()->add_entry(new CTcSymObj(
1807 "<multiMethodInit>", 17, FALSE, mminit_obj_, TRUE,
1808 TC_META_TADSOBJ, 0));
1809
1810 /* write the object header: no superclasses, 1 property */
1811 tct3_tadsobj_ctx obj_ctx;
1812 open_tadsobj(&obj_ctx, G_os, mminit_obj_, 0, 1, 0, 0);
1813
1814 /* write the static initializer property */
1815 G_os->write2(1); /* arbitrary property ID */
1816 G_os->write(VM_CODEOFS); /* offset of the code we just generated */
1817 CTcAbsFixup::add_abs_fixup(
1818 &genctx.anchor->fixup_info_.internal_fixup_head_,
1819 G_os, G_os->get_ofs());
1820 G_os->write4(0); /* placeholder */
1821
1822 /* fix up the object size data */
1823 close_tadsobj(&obj_ctx);
1824 }
1825
1826 /* switch back to the main stream */
1827 G_cs = G_cs_main;
1828 }
1829
1830 /* callback context - build multi-method registration calls */
1831 void CTcGenTarg::multimethod_init_cb(void *ctx0, CTcSymbol *sym)
1832 {
1833 mminit_ctx *ctx = (mminit_ctx *)ctx0;
1834
1835 /* if this is a function, check to see if it's a multi-method instance */
1836 if (sym->get_type() == TC_SYM_FUNC)
1837 {
1838 CTcSymFunc *fsym = (CTcSymFunc *)sym;
1839
1840 /*
1841 * multi-method instances have names of the form
1842 * "name*type1,type2", so check the name to see if it fits the
1843 * pattern
1844 */
1845 const char *p = sym->getstr();
1846 size_t rem = sym->getlen();
1847 int is_mm = FALSE;
1848 for ( ; rem != 0 ; ++p, --rem)
1849 {
1850 /*
1851 * if we found a '*', it's a multimethod; otherwise, if it's
1852 * anything other than a symbol character, it's not a
1853 * multimethod
1854 */
1855 if (*p == '*')
1856 {
1857 is_mm = TRUE;
1858 break;
1859 }
1860 else if (!is_sym(*p))
1861 break;
1862 }
1863
1864 /*
1865 * If it's a multi-method symbol, build the initializer. If it's
1866 * the base function for a multi-method, build out the stub
1867 * function.
1868 */
1869 if (is_mm)
1870 {
1871 int argc;
1872
1873 /* note the function base name - it's the part up to the '*' */
1874 const char *funcname = sym->getstr();
1875 size_t funclen = (size_t)(p - funcname);
1876
1877 /* look up the base function symbol */
1878 CTcSymFunc *base_sym = (CTcSymFunc *)G_prs->get_global_symtab()
1879 ->find(funcname, funclen);
1880
1881 /* if it's not defined as a function, ignore it */
1882 if (base_sym == 0 || base_sym->get_type() != TC_SYM_FUNC)
1883 return;
1884
1885 /*
1886 * skip to the end of the string, and remove the '*' from the
1887 * length count
1888 */
1889 p += rem;
1890 --rem;
1891
1892 /*
1893 * Run through the decorated name and look up each mentioned
1894 * class. We need to push the parameters onto the stack in
1895 * reverse order to match the VM calling conventions.
1896 */
1897 for (argc = 0 ; rem != 0 ; ++argc)
1898 {
1899 /* remember where the current name starts */
1900 size_t plen;
1901
1902 /* skip the terminator for this item */
1903 --p, --rem;
1904
1905 /* scan backwards to the previous delimiter */
1906 for (plen = 0 ; rem != 0 && *(p-1) != ';' ;
1907 --p, --rem, ++plen) ;
1908
1909 /* look up this name */
1910 if (plen == 0)
1911 {
1912 /*
1913 * empty name - this slot accepts any type; represent
1914 * this in the run-time formal list with 'nil'
1915 */
1916 G_cg->write_op(OPC_PUSHNIL);
1917
1918 /*
1919 * An untyped slot is implicitly an Object slot, so we
1920 * need to make sure that Object can participate in the
1921 * binding property system by ensuring that it has a
1922 * modifier object.
1923 */
1924 G_cg->linker_ensure_mod_obj("Object", 6);
1925 }
1926 else if (plen == 3 && memcmp(p, "...", 3) == 0)
1927 {
1928 /*
1929 * varargs indicator - represent this in the list with
1930 * the literal string '...'
1931 */
1932 CTcConstVal val;
1933 val.set_sstr("...", 3);
1934 CTPNConst cval(&val);
1935 cval.gen_code(FALSE, FALSE);
1936
1937 /*
1938 * a varargs slot is implicitly an Object slot, so make
1939 * sure Object has a modifier object
1940 */
1941 G_cg->linker_ensure_mod_obj("Object", 6);
1942 }
1943 else
1944 {
1945 /* class name - look it up */
1946 CTcSymbol *cl = G_prs->get_global_symtab()->find(p, plen);
1947 CTcConstVal val;
1948
1949 /*
1950 * if it's missing, unresolved, or not an object, flag
1951 * an error
1952 */
1953 if (cl == 0
1954 || (cl->get_type() == TC_SYM_OBJ
1955 && ((CTcSymObj *)cl)->is_extern()))
1956 {
1957 G_tcmain->log_error(
1958 0, 0, TC_SEV_ERROR, TCERR_UNDEF_SYM,
1959 (int)plen, p);
1960 return;
1961 }
1962 else if (cl->get_type() == TC_SYM_OBJ)
1963 {
1964 /* get the object information */
1965 CTcSymObj *co = (CTcSymObj *)cl;
1966 val.set_obj(co->get_obj_id(), co->get_metaclass());
1967 }
1968 else if (cl->get_type() == TC_SYM_METACLASS)
1969 {
1970 /* get the metaclass information */
1971 CTcSymMetaclass *cm = (CTcSymMetaclass *)cl;
1972 val.set_obj(cm->get_class_obj(), TC_META_UNKNOWN);
1973
1974 /*
1975 * If this metaclass doesn't have a modifier
1976 * object, create one for it. This is needed
1977 * because the run-time library's multi-method
1978 * implementation stores the method binding
1979 * information in properties of the parameter
1980 * objects. Since we're using this metaclass as a
1981 * parameter type, we'll need to write at least one
1982 * property to it. We can only write properties to
1983 * intrinsic class objects when they're equipped
1984 * with modifier objects.
1985 *
1986 * The presence of a modifier object has no effect
1987 * at all on performance for ordinary method call
1988 * operations on the intrinsic class, and the
1989 * modifier itself is just a bare object, so the
1990 * cost of creating this extra object is trivial.
1991 */
1992 G_cg->linker_ensure_mod_obj(cm);
1993 }
1994 else
1995 {
1996 /* it's not a valid object type */
1997 G_tcmain->log_error(
1998 0, 0, TC_SEV_ERROR, TCERR_MMPARAM_NOT_OBJECT,
1999 (int)plen, p, (int)funclen, funcname);
2000 return;
2001 }
2002
2003 /*
2004 * represent the object or class in the parameter list
2005 * with the object reference
2006 */
2007 CTPNConst cval(&val);
2008 cval.gen_code(FALSE, FALSE);
2009 }
2010
2011 /* note the value we pushed */
2012 G_cg->note_push();
2013 }
2014
2015 /* build and push the list from the parameters */
2016 if (argc <= 255)
2017 {
2018 G_cg->write_op(OPC_NEW1);
2019 G_cs->write((char)argc);
2020 }
2021 else
2022 {
2023 G_cg->write_op(OPC_NEW2);
2024 G_cs->write2(argc);
2025 }
2026 G_cs->write((char)G_cg->get_predef_meta_idx(TCT3_METAID_LIST));
2027 G_cg->write_op(OPC_GETR0);
2028 G_cg->note_pop(argc);
2029 G_cg->note_push();
2030
2031 /* push the function pointer argument */
2032 fsym->gen_code(FALSE);
2033
2034 /* push the base function pointer argument */
2035 base_sym->gen_code(FALSE);
2036
2037 /*
2038 * call _multiMethodRegister, if it's available (if it's not,
2039 * our caller will flag this as an error, so just skip the code
2040 * generation here)
2041 */
2042 if (ctx->mmr != 0)
2043 {
2044 G_cg->write_op(OPC_CALL);
2045 G_cs->write(3); /* argument count */
2046 ctx->mmr->add_abs_fixup(G_cs); /* function address fixup */
2047 G_cs->write4(0); /* fixup placeholder */
2048 }
2049
2050 /* the 3 arguments will be gone on return */
2051 G_cg->note_pop(3);
2052
2053 /* count the registration */
2054 ctx->cnt += 1;
2055 }
2056 }
2057 }
2058
2059 /* ------------------------------------------------------------------------ */
2060 /*
2061 * Build the IntrinsicClass objects
2062 */
2063 void CTcGenTarg::build_intrinsic_class_objs(CTcDataStream *str)
2064 {
2065 tc_meta_entry *meta;
2066 uint idx;
2067
2068 /*
2069 * run through the dependency table, and create an IntrinsicClass
2070 * object for each entry
2071 */
2072 for (idx = 0, meta = meta_head_ ; meta != 0 ; meta = meta->nxt, ++idx)
2073 {
2074 /*
2075 * if we have a symbol for this class, add the object to the
2076 * intrinsic class stream
2077 */
2078 if (meta->sym != 0)
2079 {
2080 /* write the OBJS header */
2081 str->write4(meta->sym->get_class_obj());
2082 str->write2(8);
2083
2084 /*
2085 * write the data - the data length (8), followed by the
2086 * intrinsic class index that this object is associated
2087 * with, followed by the modifier object
2088 */
2089 str->write2(8);
2090 str->write2(idx);
2091 str->write4(meta->sym->get_mod_obj() == 0
2092 ? VM_INVALID_OBJ
2093 : meta->sym->get_mod_obj()->get_obj_id());
2094
2095 /*
2096 * fix up the inheritance chain in the modifier objects, if
2097 * necessary
2098 */
2099 meta->sym->fix_mod_obj_sc_list();
2100 }
2101 }
2102 }
2103
2104 /* ------------------------------------------------------------------------ */
2105 /*
2106 * symbol table entry for a local variable debug entry
2107 */
2108 class dbglcl: public CVmHashEntryCS
2109 {
2110 public:
2111 dbglcl(const char *str, size_t len, CTcStreamAnchor *anchor, ulong ofs)
2112 : CVmHashEntryCS(str, len, TRUE)
2113 {
2114 this->anchor = anchor;
2115 this->ofs = ofs;
2116 }
2117
2118 CTcStreamAnchor *anchor;
2119 ulong ofs;
2120 };
2121
2122 /*
2123 * Build the local symbol records.
2124 */
2125 void CTcGenTarg::build_local_symbol_records(CTcCodeStream *cs,
2126 CVmHashTable *tab)
2127 {
2128 CTcStreamAnchor *anchor;
2129
2130 /* this only applies for debug format 2+ */
2131 if (G_sizes.dbg_fmt_vsn < 2)
2132 return;
2133
2134 /* go through the list of anchors in the code stream */
2135 for (anchor = cs->get_first_anchor() ; anchor != 0 ;
2136 anchor = anchor->nxt_)
2137 {
2138 ulong start_ofs;
2139 ulong dbg_ofs;
2140 uint cnt;
2141 ulong ofs;
2142
2143 /* get the anchor's stream offset */
2144 start_ofs = anchor->get_ofs();
2145
2146 /* read the debug table offset from the method header */
2147 dbg_ofs = start_ofs + cs->readu2_at(start_ofs + 8);
2148
2149 /* if there's no debug table for this method, go on to the next */
2150 if (dbg_ofs == start_ofs)
2151 continue;
2152
2153 /* read the number of line entries */
2154 ofs = dbg_ofs + G_sizes.dbg_hdr;
2155 cnt = cs->readu2_at(ofs);
2156 ofs += 2;
2157
2158 /* skip past the line entries */
2159 ofs += cnt * G_sizes.dbg_line;
2160
2161 /* skip the end offset */
2162 ofs += 2;
2163
2164 /* read the frame count */
2165 uint frame_cnt = cs->readu2_at(ofs);
2166 ofs += 2;
2167
2168 /* skip the frame index */
2169 ofs += 2 * frame_cnt;
2170
2171 /* go through the individual frames */
2172 for (uint fi = 0 ; fi < frame_cnt ; ++fi)
2173 {
2174 /* get the number of entries */
2175 cnt = cs->readu2_at(ofs + 2);
2176
2177 /* skip to the first entry */
2178 ofs += G_sizes.dbg_frame;
2179
2180 /* parse each entry */
2181 for (uint i = 0 ; i < cnt ; ++i)
2182 {
2183 /* read the flags */
2184 uint flags = cs->readu2_at(ofs + 2);
2185 ofs += G_sizes.lcl_hdr;
2186
2187 /*
2188 * If this is an out-of-line entry, we currently have a
2189 * pointer to the local variable stream, and we need to
2190 * move it to the constant pool instead. If it's in-line,
2191 * there's nothing to do - we just skip the record.
2192 */
2193 if (flags & 0x0004)
2194 {
2195 /*
2196 * It's a constant pool entry. Read the name from the
2197 * local variable pool.
2198 */
2199 ulong lofs = cs->readu4_at(ofs);
2200 size_t nlen = G_lcl_stream->readu2_at(lofs);
2201 if (nlen <= TOK_SYM_MAX_LEN)
2202 {
2203 /* read the name */
2204 char nbuf[TOK_SYM_MAX_LEN + 1];
2205 G_lcl_stream->copy_to_buf(nbuf, lofs + 2, nlen);
2206
2207 /*
2208 * Look up the name in our symbol table, to see if
2209 * we've already defined it. If so, re-use the
2210 * same name. A few local variable names tend to
2211 * be used over and over, so it saves a lot of
2212 * space to share one copy for each instance of a
2213 * reused name.
2214 */
2215 dbglcl *l = (dbglcl *)tab->find(nbuf, nlen);
2216 if (l == 0)
2217 {
2218 /* add an anchor for the constant pool entry */
2219 CTcStreamAnchor *anchor = G_ds->add_anchor(0, 0);
2220
2221 /*
2222 * It's not already defined. Add a new symbol
2223 * table entry for it. The entry will go at
2224 * the current constant pool stream offset.
2225 */
2226 l = new dbglcl(nbuf, nlen, anchor,
2227 G_ds->get_ofs());
2228 tab->add(l);
2229
2230 /* copy the name to the constant pool stream */
2231 G_ds->write2(nlen);
2232 G_ds->write(nbuf, nlen);
2233 }
2234
2235 /* add a fixup for this pointer in the code stream */
2236 CTcAbsFixup::add_abs_fixup(
2237 l->anchor->fixup_list_head_, cs, ofs);
2238
2239 /*
2240 * Overwrite the local stream offset with the
2241 * constant pool offset of the symbol.
2242 */
2243 cs->write4_at(ofs, l->ofs);
2244 }
2245
2246 /* skip the record */
2247 ofs += 4;
2248 }
2249 else
2250 {
2251 /* it's in-line - just skip to the next record */
2252 ofs += cs->readu2_at(ofs) + 2;
2253 }
2254 }
2255 }
2256 }
2257 }
2258
2259 /* ------------------------------------------------------------------------ */
2260 /*
2261 * Build the source file line maps. These maps provide listings from
2262 * the source location to the executable location, so the debugger can
2263 * do things such as set a breakpoint at a given source file location.
2264 */
2265 void CTcGenTarg::build_source_line_maps()
2266 {
2267 CTcStreamAnchor *anchor;
2268
2269 /* go through the list of anchors in the code stream */
2270 for (anchor = G_cs->get_first_anchor() ; anchor != 0 ;
2271 anchor = anchor->nxt_)
2272 {
2273 ulong start_ofs;
2274 ulong start_addr;
2275 ulong dbg_ofs;
2276 uint cnt;
2277 ulong ofs;
2278
2279 /* get the anchor's stream offset */
2280 start_ofs = anchor->get_ofs();
2281
2282 /* get the anchor's absolute address in the image file */
2283 start_addr = anchor->get_addr();
2284
2285 /* read the debug table offset from the method header */
2286 dbg_ofs = start_ofs + G_cs->readu2_at(start_ofs + 8);
2287
2288 /* if there's no debug table for this method, go on to the next */
2289 if (dbg_ofs == start_ofs)
2290 continue;
2291
2292 /* read the number of line entries */
2293 cnt = G_cs->readu2_at(dbg_ofs + G_sizes.dbg_hdr);
2294
2295 /* go through the individual line entries */
2296 for (ofs = dbg_ofs + G_sizes.dbg_hdr + 2 ; cnt != 0 ;
2297 --cnt, ofs += G_sizes.dbg_line)
2298 {
2299 uint file_id;
2300 ulong linenum;
2301 uint method_ofs;
2302 ulong line_addr;
2303 CTcTokFileDesc *file_desc;
2304
2305 /*
2306 * get the file position, and the byte-code offset from the
2307 * start of the method of the executable code for the line
2308 */
2309 method_ofs = G_cs->readu2_at(ofs);
2310 file_id = G_cs->readu2_at(ofs + 2);
2311 linenum = G_cs->readu4_at(ofs + 4);
2312
2313 /* calculate the absolute address of the line in the image file */
2314 line_addr = start_addr + method_ofs;
2315
2316 /* find the given file descriptor */
2317 file_desc = G_tok->get_filedesc(file_id);
2318
2319 /*
2320 * get the original file descriptor, since we always want to
2321 * add to the original, not to the duplicates, if the file
2322 * appears more than once (because this is a one-way mapping
2323 * from file to byte-code location - we thus require a
2324 * single index)
2325 */
2326 if (file_desc->get_orig() != 0)
2327 file_desc = file_desc->get_orig();
2328
2329 /* add this line to the file descriptor */
2330 file_desc->add_source_line(linenum, line_addr);
2331 }
2332 }
2333 }
2334
2335
2336 /* ------------------------------------------------------------------------ */
2337 /*
2338 * Callback to write enumerated source lines to an image file
2339 */
2340 static void write_source_lines_cb(void *ctx, ulong linenum, ulong code_addr)
2341 {
2342 CVmImageWriter *image_writer;
2343
2344 /* get the image writer */
2345 image_writer = (CVmImageWriter *)ctx;
2346
2347 /* write the data */
2348 image_writer->write_srcf_line_entry(linenum, code_addr);
2349 }
2350
2351 /*
2352 * Write the list of source file descriptors to an image file
2353 */
2354 void CTcGenTarg::write_sources_to_image(CVmImageWriter *image_writer)
2355 {
2356 CTcTokFileDesc *desc;
2357
2358 /* write the block prefix */
2359 image_writer->begin_srcf_block(G_tok->get_filedesc_count());
2360
2361 /* write the entries */
2362 for (desc = G_tok->get_first_filedesc() ; desc != 0 ;
2363 desc = desc->get_next())
2364 {
2365 const char *fname;
2366
2367 /*
2368 * Get the filename. Use the fully resolved local filename, so
2369 * that the debugger can correlate the resolved file back to the
2370 * project configuration. This ties the debug records to the local
2371 * directory structure, but the only drawback of this is that the
2372 * program must be recompiled wherever it's to be used with the
2373 * debugger.
2374 */
2375 fname = desc->get_fname();
2376
2377 /*
2378 * if we're in test reporting mode, write only the root name, not
2379 * the full name - this insulates test logs from the details of
2380 * local pathname conventions and the local directory structure,
2381 * allowing for more portable test logs
2382 */
2383 if (G_tcmain->get_test_report_mode())
2384 fname = os_get_root_name((char *)fname);
2385
2386 /* begin this entry */
2387 image_writer->begin_srcf_entry(desc->get_orig_index(), fname);
2388
2389 /* write the source lines */
2390 desc->enum_source_lines(write_source_lines_cb, image_writer);
2391
2392 /* end this entry */
2393 image_writer->end_srcf_entry();
2394 }
2395
2396 /* end the block */
2397 image_writer->end_srcf_block();
2398 }
2399
2400 /*
2401 * Write the method header list to the image file
2402 */
2403 void CTcGenTarg::write_method_list_to_image(CVmImageWriter *image_writer)
2404 {
2405 CTcStreamAnchor *anchor;
2406
2407 /* begin the method header list block in the image file */
2408 image_writer->begin_mhls_block();
2409
2410 /* go through the list of anchors in the code stream */
2411 for (anchor = G_cs->get_first_anchor() ; anchor != 0 ;
2412 anchor = anchor->nxt_)
2413 {
2414 /* write this entry's code pool address */
2415 image_writer->write_mhls_entry(anchor->get_addr());
2416 }
2417
2418 /* end the block */
2419 image_writer->end_mhls_block();
2420 }
2421
2422 /*
2423 * Write the preprocessor macros to the image file, for debugger use
2424 */
2425 void CTcGenTarg::write_macros_to_image(CVmImageWriter *image_writer)
2426 {
2427 /* begin the macro block */
2428 image_writer->begin_macr_block();
2429
2430 /*
2431 * ask the tokenizer to dump the data directly to the file underlying
2432 * the image writer
2433 */
2434 G_tok->write_macros_to_file_for_debug(image_writer->get_fp());
2435
2436 /* end the macro block */
2437 image_writer->end_macr_block();
2438 }
2439
2440 /* ------------------------------------------------------------------------ */
2441 /*
2442 * Callback context for global symbol table writer
2443 */
2444 struct write_sym_to_image_cb
2445 {
2446 /* number of symbols written */
2447 ulong count;
2448
2449 /* the image writer */
2450 CVmImageWriter *image_writer;
2451 };
2452
2453 /*
2454 * Callback for writing the global symbol table to an object file
2455 */
2456 static void write_sym_to_image(void *ctx0, CTcSymbol *sym)
2457 {
2458 write_sym_to_image_cb *ctx;
2459
2460 /* cast the context */
2461 ctx = (write_sym_to_image_cb *)ctx0;
2462
2463 /*
2464 * If the symbol's name starts with a period, don't write it - the
2465 * compiler constructs certain private symbol names for its own
2466 * internal use, and marks them as such by starting the name with a
2467 * period. These symbols cannot be used to evaluate expressions, so
2468 * they're of no use in teh global symbol table in the image file.
2469 */
2470 if (sym->get_sym()[0] == '.')
2471 return;
2472
2473 /* ask the symbol to do the work */
2474 if (sym->write_to_image_file_global(ctx->image_writer))
2475 {
2476 /* we wrote the symbol - count it */
2477 ++(ctx->count);
2478 }
2479 }
2480
2481 /*
2482 * Write the global symbol table to an object file
2483 */
2484 void CTcGenTarg::write_global_symbols_to_image(CVmImageWriter *image_writer)
2485 {
2486 write_sym_to_image_cb ctx;
2487
2488 /* set up the callback context */
2489 ctx.count = 0;
2490 ctx.image_writer = image_writer;
2491
2492 /* start the block */
2493 image_writer->begin_gsym_block();
2494
2495 /* ask the symbol table to enumerate itself through our symbol writer */
2496 G_prs->get_global_symtab()->enum_entries(&write_sym_to_image, &ctx);
2497
2498 /* end the block */
2499 image_writer->end_gsym_block(ctx.count);
2500 }
2501
2502 /* ------------------------------------------------------------------------ */
2503 /*
2504 * Look up a property
2505 */
2506 vm_prop_id_t CTcGenTarg::look_up_prop(const char *propname, int required,
2507 int err_if_undef, int err_if_not_prop)
2508 {
2509 /* look up the symbol */
2510 CTcSymbol *sym = G_prs->get_global_symtab()->find(propname);
2511
2512 /* check to see if it's defined and of the proper type */
2513 if (sym == 0)
2514 {
2515 /* log the 'undefined' error */
2516 G_tcmain->log_error(0, 0, required ? TC_SEV_ERROR : TC_SEV_PEDANTIC,
2517 err_if_undef);
2518 }
2519 else if (sym->get_type() != TC_SYM_PROP)
2520 {
2521 /* log the 'not a property' error */
2522 G_tcmain->log_error(0, 0, required ? TC_SEV_ERROR : TC_SEV_PEDANTIC,
2523 err_if_not_prop);
2524 }
2525 else
2526 {
2527 /* return the property ID */
2528 return ((CTcSymProp *)sym)->get_prop();
2529 }
2530
2531 /* if we got here, we didn't find a valid property */
2532 return VM_INVALID_PROP;
2533 }
2534
2535
2536 /* ------------------------------------------------------------------------ */
2537 /*
2538 * Write a TADS object stream to the image file. We'll write blocks of
2539 * size up to somewhat less than 64k, to ensure that the file is usable on
2540 * 16-bit machines.
2541 */
2542 void CTcGenTarg::write_tads_objects_to_image(CTcDataStream *os,
2543 CVmImageWriter *image_writer,
2544 int meta_idx)
2545 {
2546 /* write the persistent (non-transient) objects */
2547 write_tads_objects_to_image(os, image_writer, meta_idx, FALSE);
2548
2549 /* write the transient objects */
2550 write_tads_objects_to_image(os, image_writer, meta_idx, TRUE);
2551 }
2552
2553 /*
2554 * Write the TADS object stream to the image file, writing only persistent
2555 * or transient objects.
2556 */
2557 void CTcGenTarg::write_tads_objects_to_image(CTcDataStream *os,
2558 CVmImageWriter *image_writer,
2559 int meta_idx, int trans)
2560 {
2561 ulong start_ofs;
2562
2563 /* keep going until we've written the whole file */
2564 for (start_ofs = 0 ; start_ofs < os->get_ofs() ; )
2565 {
2566 ulong ofs;
2567 uint siz;
2568 uint cnt;
2569 uint block_size;
2570
2571 /*
2572 * Scan the stream. Each entry in the stream is a standard
2573 * object record, which means that it starts with the object ID
2574 * (UINT4) and the length (UINT2) of the metaclass-specific
2575 * data, which is then followed by the metaclass data. Skip as
2576 * many objects as we can while staying within our approximately
2577 * 64k limit.
2578 */
2579 for (block_size = 0, ofs = start_ofs, cnt = 0 ; ; )
2580 {
2581 uint flags;
2582 ulong rem_len;
2583 size_t orig_prop_cnt;
2584 size_t write_prop_cnt;
2585 size_t write_size;
2586 ulong next_ofs;
2587 ulong orig_ofs;
2588
2589 /* if we've reached the end of the stream, we're done */
2590 if (ofs >= os->get_ofs())
2591 break;
2592
2593 /* remember the starting offset */
2594 orig_ofs = ofs;
2595
2596 /* read our internal flags */
2597 flags = os->readu2_at(ofs + TCT3_OBJ_INTERNHDR_FLAGS_OFS);
2598
2599 /*
2600 * get the size of this block - this is the
2601 * metaclass-specific data size at offset 4 in the T3
2602 * metaclass header, plus the size of the T3 metaclass
2603 * header, plus the size of our internal header
2604 */
2605 siz = TCT3_OBJ_INTERNHDR_SIZE
2606 + TCT3_META_HEADER_SIZE
2607 + os->readu2_at(ofs + TCT3_META_HEADER_OFS + 4);
2608
2609 /*
2610 * Calculate the offset of the next block. Note that this is
2611 * the current offset plus the original block size; the amount
2612 * of data we end up writing might be less than the original
2613 * block size because we might have deleted property slots
2614 * when we sorted and compressed the property table.
2615 */
2616 next_ofs = ofs + siz;
2617
2618 /* if this object was deleted, skip it */
2619 if ((flags & TCT3_OBJ_REPLACED) != 0)
2620 {
2621 ofs = next_ofs;
2622 continue;
2623 }
2624
2625 /*
2626 * if this object is of the wrong persistent/transient type,
2627 * skip it
2628 */
2629 if (((flags & TCT3_OBJ_TRANSIENT) != 0) != (trans != 0))
2630 {
2631 ofs = next_ofs;
2632 continue;
2633 }
2634
2635 /*
2636 * if this would push us over the limit, stop here and start a
2637 * new block
2638 */
2639 if (block_size + siz > 64000L)
2640 break;
2641
2642 /*
2643 * We must sort the property table, in order of ascending
2644 * property ID, before we write the image file. We had to
2645 * wait until now to do this, because the final property ID
2646 * assignments aren't made until link time.
2647 */
2648 write_prop_cnt = sort_object_prop_table(os, ofs);
2649
2650 /* note the original property count */
2651 orig_prop_cnt = CTPNStmObject::get_stream_prop_cnt(os, ofs);
2652
2653 /*
2654 * Then temporarily pdate the property count in the stream, in
2655 * case we changed it in the sorting process.
2656 *
2657 * Calculate the new size of the data to write. Note that we
2658 * must add in the size of the T3 metaclass header, since this
2659 * isn't reflected in the data size.
2660 */
2661 write_size =
2662 CTPNStmObject::set_stream_prop_cnt(os, ofs, write_prop_cnt)
2663 + TCT3_META_HEADER_SIZE;
2664
2665 /*
2666 * if this is the first object in this block, write the
2667 * block header
2668 */
2669 if (cnt == 0)
2670 image_writer->begin_objs_block(meta_idx, FALSE, trans);
2671
2672 /*
2673 * skip past our internal header - we don't want to write
2674 * our internal header to the image file, since this was
2675 * purely for our own use in the compiler and linker
2676 */
2677 ofs += TCT3_OBJ_INTERNHDR_SIZE;
2678
2679 /*
2680 * write the object data; write the size returned from
2681 * sorting the property table, which might be different than
2682 * the original block data size in the stream, because we
2683 * might have compressed the property table
2684 */
2685 for (rem_len = write_size ; rem_len != 0 ; )
2686 {
2687 const char *p;
2688 ulong avail_len;
2689
2690 /* get the next block */
2691 p = os->get_block_ptr(ofs, rem_len, &avail_len);
2692
2693 /* write it out */
2694 image_writer->write_objs_bytes(p, avail_len);
2695
2696 /* move past this block */
2697 ofs += avail_len;
2698 rem_len -= avail_len;
2699 }
2700
2701 /* count the object */
2702 ++cnt;
2703
2704 /* restore the original stream property count */
2705 CTPNStmObject::set_stream_prop_cnt(os, orig_ofs, orig_prop_cnt);
2706
2707 /* move on to the next block */
2708 ofs = next_ofs;
2709 }
2710
2711 /* if we wrote any objects, end the block */
2712 if (cnt != 0)
2713 image_writer->end_objs_block(cnt);
2714
2715 /* move on to the next block */
2716 start_ofs = ofs;
2717 }
2718 }
2719
2720 /* ------------------------------------------------------------------------ */
2721 /*
2722 * Write an object stream of non-TADS objects to the image file
2723 */
2724 void CTcGenTarg::write_nontads_objs_to_image(CTcDataStream *os,
2725 CVmImageWriter *image_writer,
2726 int meta_idx, int large_objs)
2727 {
2728 /* keep going until we've written the whole file */
2729 for (ulong start_ofs = 0 ; start_ofs < os->get_ofs() ; )
2730 {
2731 ulong ofs;
2732 uint siz;
2733 uint cnt;
2734 uint block_size;
2735
2736 /*
2737 * Scan the stream. Each entry in the stream is either a small or
2738 * large object record, which means that it starts with the object
2739 * ID (UINT4) and the length (UINT2 for small, UINT4 for large) of
2740 * the metaclass-specific data, which is then followed by the
2741 * metaclass data.
2742 *
2743 * Include as many objects as we can while staying within our
2744 * approximately 64k limit, if this is a small-format block; fill
2745 * the block without limit if this is a large-format block.
2746 */
2747 for (block_size = 0, ofs = start_ofs, cnt = 0 ; ; )
2748 {
2749 ulong rem_len;
2750 ulong next_ofs;
2751
2752 /* if we've reached the end of the stream, we're done */
2753 if (ofs >= os->get_ofs())
2754 break;
2755
2756 /*
2757 * get the size of this block - this is the
2758 * metaclass-specific data size at offset 4 in the T3
2759 * metaclass header, plus the size of the T3 metaclass
2760 * header
2761 */
2762 if (large_objs)
2763 {
2764 /*
2765 * Get the 32-bit size value. Note that we don't worry
2766 * about limiting the overall block size to 64k when we're
2767 * writing a "large" object block.
2768 */
2769 siz = (ulong)os->readu4_at(ofs + 4)
2770 + TCT3_LARGE_META_HEADER_SIZE;
2771 }
2772 else
2773 {
2774 /* get the 16-bit size value */
2775 siz = (ulong)os->read2_at(ofs + 4)
2776 + TCT3_META_HEADER_SIZE;
2777
2778 /*
2779 * Since this is a small-object block, limit the aggregate
2780 * size of the entire block to 64k. So, if this block
2781 * would push us over the 64k aggregate for the block,
2782 * start a new OBJS block with this object.
2783 */
2784 if (cnt != 0 && block_size + siz > 64000L)
2785 break;
2786 }
2787
2788 /*
2789 * if this is the first object in this block, write the
2790 * block header - the dictionary uses large object headers,
2791 * so note that
2792 */
2793 if (cnt == 0)
2794 image_writer->begin_objs_block(meta_idx, large_objs, FALSE);
2795
2796 /* calculate the offset of the next block */
2797 next_ofs = ofs + siz;
2798
2799 /* write the object data */
2800 for (rem_len = siz ; rem_len != 0 ; )
2801 {
2802 const char *p;
2803 ulong avail_len;
2804
2805 /* get the next block */
2806 p = os->get_block_ptr(ofs, rem_len, &avail_len);
2807
2808 /* write it out */
2809 image_writer->write_objs_bytes(p, avail_len);
2810
2811 /* move past this block */
2812 ofs += avail_len;
2813 rem_len -= avail_len;
2814 }
2815
2816 /* count the object */
2817 ++cnt;
2818
2819 /* move on to the next block */
2820 ofs = next_ofs;
2821 }
2822
2823 /* if we wrote any objects, end the block */
2824 if (cnt != 0)
2825 image_writer->end_objs_block(cnt);
2826
2827 /* move on to the next block */
2828 start_ofs = ofs;
2829 }
2830 }
2831
2832
2833 /* ------------------------------------------------------------------------ */
2834 /*
2835 * Property comparison callback function for qsort() when invoked from
2836 * sort_object_prop_table()
2837 */
2838 //extern "C" int prop_compare(const void *p1, const void *p2);
2839 extern "C" {
2840 static int prop_compare(const void *p1, const void *p2)
2841 {
2842 uint id1, id2;
2843
2844 /* get the ID's */
2845 id1 = osrp2(p1);
2846 id2 = osrp2(p2);
2847
2848 /* compare them and return the result */
2849 return (id1 < id2 ? -1 : id1 == id2 ? 0 : 1);
2850 }
2851 }
2852
2853 /*
2854 * Sort an object's property table. This puts the property table into
2855 * order of ascending property ID, and deletes any unused properties from
2856 * the table.
2857 *
2858 * Note that we do NOT update the stream to indicate the reduced number of
2859 * properties if we delete any properties. Instead, we simply return the
2860 * new number of properties.
2861 */
2862 size_t CTcGenTarg::sort_object_prop_table(CTcDataStream *os, ulong start_ofs)
2863 {
2864 /* read the number of properties from the header */
2865 uint prop_cnt = CTPNStmObject::get_stream_prop_cnt(os, start_ofs);
2866
2867 /* calculate the property table size */
2868 uint prop_table_size = prop_cnt * TCT3_TADSOBJ_PROP_SIZE;
2869
2870 /* get the offset of the first property */
2871 ulong prop_ofs = CTPNStmObject::get_stream_first_prop_ofs(os, start_ofs);
2872
2873 /* reallocate the sort buffer if necessary */
2874 if (prop_table_size > sort_buf_size_)
2875 {
2876 /* increase the sort buffer size to the next 4k increment */
2877 sort_buf_size_ = (prop_table_size + 4095) & ~4096;
2878
2879 /* reallocate the buffer */
2880 sort_buf_ = (char *)t3realloc(sort_buf_, sort_buf_size_);
2881 if (sort_buf_ == 0 || sort_buf_size_ < prop_table_size)
2882 G_tok->throw_internal_error(TCERR_CODEGEN_NO_MEM);
2883 }
2884
2885 /* extract the table into our buffer */
2886 os->copy_to_buf(sort_buf_, prop_ofs, prop_table_size);
2887
2888 /*
2889 * Compress the table by removing any properties that have been
2890 * marked as deleted -- if we had any 'modify + replace' properties
2891 * that we resolved at link time, we will have marked those
2892 * properties for deletion by setting their property ID's to zero in
2893 * the table. Scan the table for any such properties and remove
2894 * them now.
2895 */
2896 size_t src, dst;
2897 for (src = dst = 0, prop_cnt = 0 ; src < prop_table_size ;
2898 src += TCT3_TADSOBJ_PROP_SIZE)
2899 {
2900 /* if this property isn't marked for deletion, keep it */
2901 if (osrp2(sort_buf_ + src) != VM_INVALID_PROP)
2902 {
2903 /*
2904 * we're keeping it - if we can move it to a lower table
2905 * position, copy the data to the new position, otherwise
2906 * leave it alone
2907 */
2908 if (src != dst)
2909 memcpy(sort_buf_ + dst, sort_buf_ + src,
2910 TCT3_TADSOBJ_PROP_SIZE);
2911
2912 /*
2913 * advance the destination pointer past this slot, since
2914 * we're going to keep the data in the slot
2915 */
2916 dst += TCT3_TADSOBJ_PROP_SIZE;
2917
2918 /* count this property, since we're keeping it */
2919 ++prop_cnt;
2920 }
2921 }
2922
2923 /* sort the table */
2924 qsort(sort_buf_, prop_cnt, TCT3_TADSOBJ_PROP_SIZE, &prop_compare);
2925
2926 /* add back any unused slots after all of the sorted slots */
2927 for ( ; dst < prop_table_size ; dst += TCT3_TADSOBJ_PROP_SIZE)
2928 oswp2(sort_buf_ + dst, VM_INVALID_PROP);
2929
2930 /* put the sorted table back in the buffer */
2931 os->write_at(prop_ofs, sort_buf_, prop_table_size);
2932
2933 /* return the (possibly reduced) number of properties */
2934 return prop_cnt;
2935 }
2936
2937
2938 /*
2939 * callback context for enumerating a dictionary
2940 */
2941 struct enum_dict_ctx
2942 {
2943 /* number of entries written so far */
2944 uint cnt;
2945 };
2946
2947 /*
2948 * Generate code for a dictionary object
2949 */
2950 void CTcGenTarg::gen_code_for_dict(CTcDictEntry *dict)
2951 {
2952 long size_ofs;
2953 long entry_cnt_ofs;
2954 long end_ofs;
2955 enum_dict_ctx ctx;
2956
2957 /*
2958 * Write the OBJS header - object ID plus byte count for
2959 * metaclass-specific data (use a placeholder length for now)
2960 */
2961 G_dict_stream->write4(dict->get_sym()->get_obj_id());
2962 size_ofs = G_dict_stream->get_ofs();
2963 G_dict_stream->write4(0);
2964
2965 /*
2966 * Write the metaclass-specific data for the 'dictionary' metaclass
2967 */
2968
2969 /* write a nil comparator object initially */
2970 G_dict_stream->write4(0);
2971
2972 /* write a placeholder for the entry count */
2973 entry_cnt_ofs = G_dict_stream->get_ofs();
2974 G_dict_stream->write2(0);
2975
2976 /* write the dictionary entries */
2977 ctx.cnt = 0;
2978 dict->get_hash_table()->enum_entries(&enum_dict_gen_cb, &ctx);
2979
2980 /* remember the ending offset of the table */
2981 end_ofs = G_dict_stream->get_ofs();
2982
2983 /* go back and fix up the total size of the object data */
2984 G_dict_stream->write4_at(size_ofs, end_ofs - size_ofs - 4);
2985
2986 /* fix up the dictionary entry count */
2987 G_dict_stream->write2_at(entry_cnt_ofs, ctx.cnt);
2988 }
2989
2990 /*
2991 * Callback - enumerate dictionary entries for code generation
2992 */
2993 void CTcGenTarg::enum_dict_gen_cb(void *ctx0, CVmHashEntry *entry0)
2994 {
2995 enum_dict_ctx *ctx = (enum_dict_ctx *)ctx0;
2996 CVmHashEntryPrsDict *entry = (CVmHashEntryPrsDict *)entry0;
2997 char buf[255];
2998 size_t len;
2999 char *p;
3000 size_t rem;
3001 uint cnt;
3002 CTcPrsDictItem *item;
3003
3004 /* count this entry */
3005 ++(ctx->cnt);
3006
3007 /* limit the key length to 255 bytes */
3008 len = entry->getlen();
3009 if (len > 255)
3010 len = 255;
3011
3012 /* copy the entry to our buffer */
3013 memcpy(buf, entry->getstr(), len);
3014
3015 /* apply the XOR obfuscation to the key text */
3016 for (p = buf, rem = len ; rem != 0 ; ++p, --rem)
3017 *p ^= 0xBD;
3018
3019 /* write the length of the key followed by the key string */
3020 G_dict_stream->write((uchar)len);
3021 G_dict_stream->write(buf, len);
3022
3023 /* count the items in this entry */
3024 for (cnt = 0, item = entry->get_list() ; item != 0 ;
3025 ++cnt, item = item->nxt_) ;
3026
3027 /* write the number of entries */
3028 G_dict_stream->write2(cnt);
3029
3030 /* write the entries */
3031 for (item = entry->get_list() ; item != 0 ; item = item->nxt_)
3032 {
3033 /* write the object ID and property ID of this entry */
3034 G_dict_stream->write4(item->obj_);
3035 G_dict_stream->write2(item->prop_);
3036 }
3037 }
3038
3039 /*
3040 * Generate code for a grammar production
3041 */
3042 void CTcGenTarg::gen_code_for_gramprod(CTcGramProdEntry *prod)
3043 {
3044 long size_ofs;
3045 long end_ofs;
3046 uint cnt;
3047 CTcGramProdAlt *alt;
3048 CTcDataStream *str = G_gramprod_stream;
3049
3050 /*
3051 * write the OBJS header - object ID plus byte count for
3052 * metaclass-specific data (use a placeholder length for now)
3053 */
3054 str->write4(prod->get_prod_sym()->get_obj_id());
3055 size_ofs = str->get_ofs();
3056 str->write4(0);
3057
3058 /*
3059 * Write the metaclass-specific data for the 'grammar-production'
3060 * metaclass
3061 */
3062
3063 /* count the alternatives */
3064 for (cnt = 0, alt = prod->get_alt_head() ; alt != 0 ;
3065 ++cnt, alt = alt->get_next()) ;
3066
3067 /*
3068 * If this production has no alternatives and was not explicitly
3069 * declared, flag an error indicating that the production is
3070 * undeclared. We treat this as an error because there's a good chance
3071 * that the an alternative referring to the production misspelled the
3072 * name. If the production was explicitly declared, then we have
3073 * sufficient confirmation that the name is correct, so no error is
3074 * indicated.
3075 */
3076 if (cnt == 0 && !prod->is_declared())
3077 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
3078 TCERR_GRAMPROD_HAS_NO_ALTS,
3079 (int)prod->get_prod_sym()->get_sym_len(),
3080 prod->get_prod_sym()->get_sym());
3081
3082 /*
3083 * The count has to fit in 16 bits; it's surprisingly easy to exceed
3084 * this by using the power of permutation (with nested '|'
3085 * alternatives), so check for overflow and flag an error. Even though
3086 * it's not hard to exceed the limit, it's not desirable to create so
3087 * many permutations, so the limit isn't really in need of being
3088 * raised; it's better to rewrite a rule with a huge number of
3089 * permutations using sub-productions.
3090 */
3091 if (cnt > 65535)
3092 G_tcmain->log_error(0, 0, TC_SEV_ERROR,
3093 TCERR_GRAMPROD_TOO_MANY_ALTS,
3094 (int)prod->get_prod_sym()->get_sym_len(),
3095 prod->get_prod_sym()->get_sym());
3096
3097 /* write the number of alternatives */
3098 str->write2(cnt);
3099
3100 /* write the alternatives */
3101 for (alt = prod->get_alt_head() ; alt != 0 ; alt = alt->get_next())
3102 {
3103 CTcGramProdTok *tok;
3104
3105 /* write the score and badness for the alternative */
3106 str->write2(alt->get_score());
3107 str->write2(alt->get_badness());
3108
3109 /* write the processor object ID for this alternative */
3110 str->write4(alt->get_processor_obj()->get_obj_id());
3111
3112 /* count the tokens in this alternative */
3113 for (cnt = 0, tok = alt->get_tok_head() ; tok != 0 ;
3114 ++cnt, tok = tok->get_next()) ;
3115
3116 /* write the token count */
3117 str->write2(cnt);
3118
3119 /* write the tokens */
3120 for (tok = alt->get_tok_head() ; tok != 0 ; tok = tok->get_next())
3121 {
3122 size_t idx;
3123
3124 /* write the property association */
3125 str->write2((uint)tok->get_prop_assoc());
3126
3127 /* write the token data */
3128 switch(tok->get_type())
3129 {
3130 case TCGRAM_PROD:
3131 /* write the type */
3132 str->write((uchar)VMGRAM_MATCH_PROD);
3133
3134 /* write the sub-production object ID */
3135 str->write4((ulong)tok->getval_prod()->get_obj_id());
3136 break;
3137
3138 case TCGRAM_PART_OF_SPEECH:
3139 /* write the type */
3140 str->write((uchar)VMGRAM_MATCH_SPEECH);
3141
3142 /* write the part-of-speech property */
3143 str->write2((uint)tok->getval_part_of_speech());
3144 break;
3145
3146 case TCGRAM_PART_OF_SPEECH_LIST:
3147 /* write the type */
3148 str->write((uchar)VMGRAM_MATCH_NSPEECH);
3149
3150 /* write the number of elements in the property list */
3151 str->write2((uint)tok->getval_part_list_len());
3152
3153 /* write each element */
3154 for (idx = 0 ; idx < tok->getval_part_list_len() ; ++idx)
3155 str->write2((uint)tok->getval_part_list_ele(idx));
3156
3157 /* done */
3158 break;
3159
3160 case TCGRAM_LITERAL:
3161 /* write the type */
3162 str->write((uchar)VMGRAM_MATCH_LITERAL);
3163
3164 /* write the string length prefix */
3165 str->write2(tok->getval_literal_len());
3166
3167 /* write the string text */
3168 str->write(tok->getval_literal_txt(),
3169 tok->getval_literal_len());
3170
3171 /*
3172 * add the word to the dictionary that was active when the
3173 * alternative was defined
3174 */
3175 if (alt->get_dict() != 0)
3176 {
3177 /*
3178 * there's a dictionary - add the word, associating it
3179 * with the production object and with the parser's
3180 * miscVocab property
3181 */
3182 alt->get_dict()->add_word(
3183 tok->getval_literal_txt(), tok->getval_literal_len(),
3184 FALSE, prod->get_prod_sym()->get_obj_id(),
3185 G_prs->get_miscvocab_prop());
3186 }
3187 break;
3188
3189 case TCGRAM_TOKEN_TYPE:
3190 /* write the type */
3191 str->write((uchar)VMGRAM_MATCH_TOKTYPE);
3192
3193 /* write the enum ID of the token */
3194 str->write4(tok->getval_token_type());
3195 break;
3196
3197 case TCGRAM_STAR:
3198 /* write the type - there's no additional data */
3199 str->write((uchar)VMGRAM_MATCH_STAR);
3200 break;
3201
3202 default:
3203 assert(FALSE);
3204 break;
3205 }
3206 }
3207 }
3208
3209 /* remember the ending offset of the object data */
3210 end_ofs = str->get_ofs();
3211
3212 /* go back and fix up the total size of the object data */
3213 str->write4_at(size_ofs, end_ofs - size_ofs - 4);
3214 }
3215
3216
3217 /* ------------------------------------------------------------------------ */
3218 /*
3219 * Data Stream Layout Manager
3220 */
3221
3222 /*
3223 * calculate the size of the pool pages, given the size of the largest
3224 * single item
3225 */
3226 void CTcStreamLayout::calc_layout(CTcDataStream *ds, ulong max_len,
3227 int is_first)
3228 {
3229 ulong rem;
3230 ulong free_ofs;
3231 CTcStreamAnchor *anchor;
3232
3233 /* if this is the first page, handle some things specially */
3234 if (is_first)
3235 {
3236 ulong pgsiz;
3237
3238 /*
3239 * Starting at 2k, look for a page size that will fit the
3240 * desired minimum size.
3241 */
3242 for (pgsiz = 2048 ; pgsiz < max_len ; pgsiz <<= 1) ;
3243
3244 /* remember our selected page size */
3245 page_size_ = pgsiz;
3246
3247 /* start at the bottom of the first page */
3248 rem = pgsiz;
3249 free_ofs = 0;
3250 page_cnt_ = 1;
3251 }
3252 else
3253 {
3254 /*
3255 * this isn't the first page - if there are no anchors, don't
3256 * bother adding anything
3257 */
3258 if (ds->get_first_anchor() == 0)
3259 return;
3260
3261 /*
3262 * start at the end of the last existing page - this will ensure
3263 * that everything added from the new stream will go onto a
3264 * brand new page after everything from the previous stream
3265 */
3266 rem = 0;
3267 free_ofs = page_size_ * page_cnt_;
3268 }
3269
3270 /*
3271 * Run through the list of stream anchors and calculate the layout.
3272 * For each item, assign its final pool address and apply its
3273 * fixups.
3274 */
3275 for (anchor = ds->get_first_anchor() ; anchor != 0 ;
3276 anchor = anchor->nxt_)
3277 {
3278 ulong len;
3279
3280 /*
3281 * if this anchor has been marked as replaced, don't include it
3282 * in our calculations, because we don't want to include this
3283 * block in the image file
3284 */
3285 if (anchor->is_replaced())
3286 continue;
3287
3288 /*
3289 * if this item fits on the current page, assign it the next
3290 * sequential address; otherwise, go to the next page
3291 *
3292 * if this anchor is at the dividing point, put it on the next
3293 * page, unless we just started a new page
3294 */
3295 len = anchor->get_len(ds);
3296 if (len > rem)
3297 {
3298 /*
3299 * we must start the next page - skip to the next page by
3300 * moving past the remaining free space on this page
3301 */
3302 free_ofs += rem;
3303
3304 /* count the new page */
3305 ++page_cnt_;
3306
3307 /* the whole next page is available to us now */
3308 rem = page_size_;
3309 }
3310
3311 /*
3312 * set the anchor's final address, which will apply fixups for
3313 * the object's fixup list
3314 */
3315 anchor->set_addr(free_ofs);
3316
3317 /* advance past this block */
3318 free_ofs += len;
3319 rem -= len;
3320 }
3321
3322 /* if there's no data at all, we have zero pages */
3323 if (free_ofs == 0)
3324 page_cnt_ = 0;
3325 }
3326
3327
3328 /*
3329 * Write our stream to an image file
3330 */
3331 void CTcStreamLayout::write_to_image(CTcDataStream **ds_arr, size_t ds_cnt,
3332 CVmImageWriter *image_writer,
3333 int pool_id, uchar xor_mask)
3334 {
3335 CTcStreamAnchor *anchor;
3336 ulong free_ofs;
3337 ulong next_page_start;
3338 int pgnum;
3339
3340 /* write the constant pool definition block - the pool's ID is 2 */
3341 image_writer->write_pool_def(pool_id, page_cnt_, page_size_, TRUE);
3342
3343 /*
3344 * start out before the first page - the next page starts with the
3345 * item at offset zero
3346 */
3347 pgnum = 0;
3348 next_page_start = 0;
3349
3350 /* run through each stream */
3351 for ( ; ds_cnt != 0 ; ++ds_arr, --ds_cnt)
3352 {
3353 CTcDataStream *ds;
3354
3355 /* get the current stream */
3356 ds = *ds_arr;
3357
3358 /* run through the anchor list for this stream */
3359 for (anchor = ds->get_first_anchor() ; anchor != 0 ;
3360 anchor = anchor->nxt_)
3361 {
3362 ulong len;
3363 ulong stream_ofs;
3364 ulong addr;
3365
3366 /*
3367 * if this anchor is marked as replaced, skip it entirely -
3368 * we omit replaced blocks from the image file, because
3369 * they're completely unreachable
3370 */
3371 if (anchor->is_replaced())
3372 continue;
3373
3374 /*
3375 * if this item's assigned address is on the next page, move
3376 * to the next page
3377 */
3378 len = anchor->get_len(ds);
3379 addr = anchor->get_addr();
3380 if (addr == next_page_start)
3381 {
3382 /* if this isn't the first page, close the previous page */
3383 if (pgnum != 0)
3384 image_writer->end_pool_page();
3385
3386 /* start the new page */
3387 image_writer->begin_pool_page(pool_id, pgnum, TRUE, xor_mask);
3388
3389 /* this item is at the start of the new page */
3390 free_ofs = next_page_start;
3391
3392 /* count the new page */
3393 ++pgnum;
3394
3395 /* calculate the address of the start of the next page */
3396 next_page_start += page_size_;
3397 }
3398
3399 /* advance past this block */
3400 free_ofs += len;
3401
3402 /*
3403 * write the data from the stream to the image file - we
3404 * must iterate over the chunks the code stream returns,
3405 * since it might not be able to return the entire block in
3406 * a single operation
3407 */
3408 for (stream_ofs = anchor->get_ofs() ; len != 0 ; )
3409 {
3410 ulong cur;
3411 const char *ptr;
3412
3413 /* get the pointer to this chunk */
3414 ptr = ds->get_block_ptr(stream_ofs, len, &cur);
3415
3416 /* write this chunk */
3417 image_writer->write_pool_page_bytes(ptr, cur, xor_mask);
3418
3419 /* advance our pointers past this chunk */
3420 len -= cur;
3421 stream_ofs += cur;
3422 }
3423 }
3424 }
3425
3426 /* if we started a page, end it */
3427 if (pgnum != 0)
3428 image_writer->end_pool_page();
3429 }
3430
3431 /* ------------------------------------------------------------------------ */
3432 /*
3433 * Object Symbol subclass - image-file functions
3434 */
3435
3436 /*
3437 * mark the compiled data for the object as a 'class' object
3438 */
3439 void CTcSymObj::mark_compiled_as_class()
3440 {
3441 uint flags;
3442 CTcDataStream *str;
3443
3444 /* get the appropriate stream for generating the data */
3445 str = get_stream();
3446
3447 /* get my original object flags */
3448 flags = CTPNStmObject::get_stream_obj_flags(str, stream_ofs_);
3449
3450 /* add in the 'class' flag */
3451 flags |= TCT3_OBJFLG_CLASS;
3452
3453 /* set the updated flags */
3454 CTPNStmObject::set_stream_obj_flags(str, stream_ofs_, flags);
3455 }
3456
3457 /*
3458 * Delete a property from our modified base classes
3459 */
3460 void CTcSymObj::delete_prop_from_mod_base(tctarg_prop_id_t prop_id)
3461 {
3462 uint prop_cnt;
3463 uint i;
3464 CTcDataStream *str;
3465
3466 /* get the correct data stream */
3467 str = get_stream();
3468
3469 /* get the number of properties in the object */
3470 prop_cnt = CTPNStmObject::get_stream_prop_cnt(str, stream_ofs_);
3471
3472 /* find the property in our property table */
3473 for (i = 0 ; i < prop_cnt ; ++i)
3474 {
3475 /* if this property ID matches, delete it */
3476 if (CTPNStmObject::get_stream_prop_id(str, stream_ofs_, i)
3477 == prop_id)
3478 {
3479 /* delete the object by setting its ID to 'invalid' */
3480 CTPNStmObject::set_stream_prop_id(str, stream_ofs_, i,
3481 VM_INVALID_PROP);
3482
3483 /*
3484 * there's no need to look any further - a property can
3485 * occur only once in an object
3486 */
3487 break;
3488 }
3489 }
3490 }
3491
3492 /*
3493 * Build the dictionary
3494 */
3495 void CTcSymObj::build_dictionary()
3496 {
3497 uint prop_cnt;
3498 uint i;
3499
3500 /*
3501 * Inherit the default handling - this will explicitly add all
3502 * superclass dictionary data into my own internal dictionary list,
3503 * so that we don't have to worry at all about superclasses here.
3504 * This will also add our words to my associated dictionary object.
3505 */
3506 CTcSymObjBase::build_dictionary();
3507
3508 /* if I'm not a regular tads object, there's nothing to do here */
3509 if (metaclass_ != TC_META_TADSOBJ)
3510 return;
3511
3512 /*
3513 * Examine my properties. Each time we find a property whose value
3514 * is set to vocab-list, replace it with an actual list of strings
3515 * for my vocabulary words associated with the property.
3516 */
3517
3518 /* get the number of properties in the object */
3519 prop_cnt = CTPNStmObject::get_stream_prop_cnt(G_os, stream_ofs_);
3520
3521 /* find the property in our property table */
3522 for (i = 0 ; i < prop_cnt ; ++i)
3523 {
3524 CTcConstVal val;
3525 vm_datatype_t prop_type;
3526
3527 /* get this property value */
3528 prop_type = CTPNStmObject::get_stream_prop_type(G_os, stream_ofs_, i);
3529
3530 /*
3531 * if it's a vocabulary list placeholder, replace it with the
3532 * actual list of vocabulary strings
3533 */
3534 if (prop_type == VM_VOCAB_LIST)
3535 {
3536 vm_prop_id_t prop_id;
3537 CTcVocabEntry *entry;
3538 CTPNList *lst;
3539 ulong prop_val_ofs;
3540
3541 /* get the property ID */
3542 prop_id = CTPNStmObject::get_stream_prop_id(G_os, stream_ofs_, i);
3543
3544 /* get the value offset of this property */
3545 prop_val_ofs = CTPNStmObject::
3546 get_stream_prop_val_ofs(G_os, stream_ofs_, i);
3547
3548 /* create a list */
3549 lst = new CTPNList();
3550
3551 /*
3552 * scan my internal vocabulary list and add the entries
3553 * associated with this property
3554 */
3555 for (entry = vocab_ ; entry != 0 ; entry = entry->nxt_)
3556 {
3557 /* if this one matches our property, add it */
3558 if (entry->prop_ == prop_id)
3559 {
3560 CTcConstVal str_val;
3561 CTcPrsNode *ele;
3562
3563 /* create a string element */
3564 str_val.set_sstr(entry->txt_, entry->len_);
3565 ele = new CTPNConst(&str_val);
3566
3567 /* add it to the list */
3568 lst->add_element(ele);
3569 }
3570 }
3571
3572 /*
3573 * Overwrite the original property value with the new list.
3574 * If the list is empty, this object doesn't define or
3575 * inherit any vocabulary of this property at all, so we can
3576 * clear the property entirely.
3577 */
3578 if (lst->get_count() == 0)
3579 {
3580 /*
3581 * delete the property from the object by setting its
3582 * property ID to 'invalid'
3583 */
3584 CTPNStmObject::
3585 set_stream_prop_id(G_os, stream_ofs_, i, VM_INVALID_PROP);
3586 }
3587 else
3588 {
3589 /* write the list value to the property */
3590 val.set_list(lst);
3591 G_cg->write_const_as_dh(G_os, prop_val_ofs, &val);
3592 }
3593 }
3594 }
3595 }
3596
3597
3598 /* ------------------------------------------------------------------------ */
3599 /*
3600 * Symbol table entry routines for writing a symbol to the global symbol
3601 * table in the debug records in the image file
3602 */
3603
3604 /*
3605 * write the symbol to an image file's global symbol table
3606 */
3607 int CTcSymFunc::write_to_image_file_global(class CVmImageWriter *image_writer)
3608 {
3609 char buf[128];
3610
3611 /* build our extra data buffer */
3612 oswp4(buf, get_code_pool_addr());
3613 oswp2(buf + 4, get_argc());
3614 buf[6] = (is_varargs() != 0);
3615 buf[7] = (has_retval() != 0);
3616 oswp2(buf + 8, get_opt_argc());
3617
3618 /* write the data */
3619 image_writer->write_gsym_entry(get_sym(), get_sym_len(),
3620 (int)TC_SYM_FUNC, buf, 10);
3621
3622 /* we wrote the symbol */
3623 return TRUE;
3624 }
3625
3626 /*
3627 * write the symbol to an image file's global symbol table
3628 */
3629 int CTcSymObj::write_to_image_file_global(class CVmImageWriter *image_writer)
3630 {
3631 char buf[128];
3632
3633 /* store our object ID in the extra data buffer */
3634 oswp4(buf, obj_id_);
3635
3636 /* add our modifying object ID, if we have a modifying object */
3637 if (get_modifying_sym() != 0)
3638 oswp4(buf + 4, get_modifying_sym()->get_obj_id());
3639 else
3640 oswp4(buf + 4, 0);
3641
3642 /* write the data */
3643 image_writer->write_gsym_entry(get_sym(), get_sym_len(),
3644 (int)TC_SYM_OBJ, buf, 8);
3645
3646 /* we wrote the symbol */
3647 return TRUE;
3648 }
3649
3650 /*
3651 * write the symbol to an image file's global symbol table
3652 */
3653 int CTcSymProp::write_to_image_file_global(class CVmImageWriter *image_writer)
3654 {
3655 char buf[128];
3656
3657 /* build our extra data buffer */
3658 oswp2(buf, (uint)get_prop());
3659
3660 /* build our flags byte */
3661 buf[2] = 0;
3662 if (vocab_)
3663 buf[2] |= 0x01;
3664
3665 /* write the data */
3666 image_writer->write_gsym_entry(get_sym(), get_sym_len(),
3667 (int)TC_SYM_PROP, buf, 3);
3668
3669 /* we wrote the symbol */
3670 return TRUE;
3671 }
3672
3673 /*
3674 * write the symbol to an image file's global symbol table
3675 */
3676 int CTcSymEnum::write_to_image_file_global(class CVmImageWriter *image_writer)
3677 {
3678 char buf[128];
3679
3680 /* build our extra data buffer */
3681 oswp4(buf, get_enum_id());
3682
3683 /* build our flags */
3684 buf[4] = 0;
3685 if (is_token_)
3686 buf[4] |= 0x01;
3687
3688 /* write the data */
3689 image_writer->write_gsym_entry(get_sym(), get_sym_len(),
3690 (int)TC_SYM_ENUM, buf, 5);
3691
3692 /* we wrote the symbol */
3693 return TRUE;
3694 }
3695
3696 /*
3697 * write the symbol to an image file's global symbol table
3698 */
3699 int CTcSymMetaclass::
3700 write_to_image_file_global(class CVmImageWriter *image_writer)
3701 {
3702 char buf[128];
3703
3704 /* build our extra data buffer */
3705 oswp2(buf, meta_idx_);
3706 oswp4(buf + 2, class_obj_);
3707
3708 /* write the data */
3709 image_writer->write_gsym_entry(get_sym(), get_sym_len(),
3710 (int)TC_SYM_METACLASS, buf, 6);
3711
3712 /* we wrote the symbol */
3713 return TRUE;
3714 }
3715
3716 /*
3717 * Fix up the inheritance chain in the modifier objects
3718 */
3719 void CTcSymMetaclass::fix_mod_obj_sc_list()
3720 {
3721 CTcSymObj *obj;
3722 CTcSymObj *obj_base;
3723
3724 /*
3725 * go through our chain of modifier objects, and make sure the
3726 * stream data for each object points to its correct superclass
3727 */
3728 for (obj = mod_obj_ ; obj != 0 ; obj = obj_base)
3729 {
3730 CTcDataStream *str;
3731
3732 /* get the correct data stream */
3733 str = obj->get_stream();
3734
3735 /* get the base object for this symbol */
3736 obj_base = obj->get_mod_base_sym();
3737
3738 /*
3739 * if there's no base object, there's no superclass entry to
3740 * adjust for this object
3741 */
3742 if (obj_base == 0)
3743 break;
3744
3745 /*
3746 * set the superclass in this object to point to this base
3747 * object
3748 */
3749 CTPNStmObject::set_stream_sc(str, obj->get_stream_ofs(),
3750 0, obj_base->get_obj_id());
3751 }
3752 }
3753
3754 /*
3755 * write the symbol to an image file's global symbol table
3756 */
3757 int CTcSymBif::write_to_image_file_global(class CVmImageWriter *image_writer)
3758 {
3759 char buf[128];
3760
3761 /* build our extra data buffer */
3762 oswp2(buf, get_func_idx());
3763 oswp2(buf + 2, get_func_set_id());
3764 buf[4] = (has_retval() != 0);
3765 oswp2(buf + 5, get_min_argc());
3766 oswp2(buf + 7, get_max_argc());
3767 buf[9] = (is_varargs() != 0);
3768
3769 /* write the data */
3770 image_writer->write_gsym_entry(get_sym(), get_sym_len(),
3771 (int)TC_SYM_BIF, buf, 10);
3772
3773 /* we wrote the symbol */
3774 return TRUE;
3775 }
3776
3777 /*
3778 * write the symbol to an image file's global symbol table
3779 */
3780 int CTcSymExtfn::write_to_image_file_global(class CVmImageWriter *iw)
3781 {
3782 //$$$ to be implemented
3783 assert(FALSE);
3784 return FALSE;
3785 }
3786
3787 /* ------------------------------------------------------------------------ */
3788 /*
3789 * Object properties
3790 */
3791
3792 /*
3793 * Check locals
3794 */
3795 void CTPNObjProp::check_locals()
3796 {
3797 /* check locals in our code body */
3798 if (code_body_ != 0)
3799 code_body_->check_locals();
3800 }