Debian Codegraph @

terps/tads/tads3/vmobj.cpp

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/tads3/VMOBJ.CPP,v 1.4 1999/07/11 00:46:58 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1998, 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 vmobj.cpp - VM object manager
15 Function
16
17 Notes
18
19 Modified
20 10/28/98 MJRoberts - Creation
21 */
22
23 #include <stdlib.h>
24 #include <memory.h>
25 #include <assert.h>
26
27 #include "t3std.h"
28 #include "vmtype.h"
29 #include "vmobj.h"
30 #include "vmstack.h"
31 #include "vmundo.h"
32 #include "vmrun.h"
33 #include "vmfile.h"
34 #include "vmmeta.h"
35 #include "vmlst.h"
36 #include "vmstr.h"
37 #include "vmintcls.h"
38 #include "vmpool.h"
39 #include "vmfunc.h"
40 #include "vmpredef.h"
41 #include "vmhash.h"
42 #include "vmtobj.h"
43 #include "vmanonfn.h"
44 #include "vmdynfunc.h"
45
46
47
48 /* ------------------------------------------------------------------------ */
49 /*
50 * Statistics gathering
51 */
52 #ifdef VMOBJ_GC_STATS
53 # define IF_GC_STATS(x) x
54
55 struct
56 {
57 void gc_stats()
58 {
59 runs = 0;
60 tot_freed = 0;
61 cur_freed = 0;
62 max_freed = 0;
63 t = 0;
64 }
65
66 void begin_pass()
67 {
68 t0 = os_get_sys_clock_ms();
69 runs++;
70 pass_start_bytes = cur_bytes;
71 cur_freed = 0;
72 }
73
74 void end_pass()
75 {
76 t += os_get_sys_clock_ms() - t0;
77 if (cur_freed > max_freed)
78 max_freed = cur_freed;
79 long garbage_bytes = pass_start_bytes - cur_bytes;
80 if (garbage_bytes > max_garbage_bytes)
81 max_garbage_bytes = garbage_bytes;
82 }
83
84 void count_free()
85 {
86 ++cur_freed;
87 ++tot_freed;
88 }
89
90 void count_alloc_bytes(size_t siz)
91 {
92 cur_bytes += siz;
93 if (cur_bytes > max_bytes)
94 max_bytes = cur_bytes;
95 }
96
97 void count_realloc_bytes(size_t oldsiz, size_t newsiz)
98 {
99 count_alloc_bytes(newsiz);
100 count_free_bytes(oldsiz);
101 }
102
103 void count_free_bytes(size_t siz)
104 {
105 cur_bytes -= siz;
106 }
107
108 void display()
109 {
110 printf("Garbage collection statistics:\n"
111 " collection runs: %ld\n"
112 " objects freed: %ld\n"
113 " average freed per run: %ld\n"
114 " max freed in one run: %ld\n"
115 " peak heap bytes: %ld\n"
116 " peak garbage bytes: %ld\n"
117 " total gc time (ms): %ld\n"
118 " average gc time (ms): %ld\n",
119 runs,
120 tot_freed,
121 runs != 0 ? tot_freed/runs : 0,
122 max_freed,
123 max_bytes,
124 max_garbage_bytes,
125 t,
126 runs != 0 ? t/runs : 0);
127 }
128
129 /* number of times the gc has run */
130 long runs;
131
132 /* total number of objects collected */
133 long tot_freed;
134
135 /* number of objects collected on this pass */
136 long cur_freed;
137
138 /* maximum number collected on any one pass */
139 long max_freed;
140
141 /* current total heap manager allocated bytes */
142 long cur_bytes;
143
144 /* allocated bytes at start of last gc pass */
145 long pass_start_bytes;
146
147 /* peak allocated bytes */
148 long max_bytes;
149
150 /* peak garbage bytes */
151 long max_garbage_bytes;
152
153 /* elapsed time in garbage collector */
154 long t;
155
156 /* starting time in ticks of current run */
157 long t0;
158
159 } gc_stats;
160
161 #else /* VMOBJ_GC_STATS */
162 # define IF_GC_STATS(x)
163 #endif /* VMOBJ_GC_STATS */
164
165
166 /* ------------------------------------------------------------------------ */
167 /*
168 * Base fixed-size object entry implementation
169 */
170
171 /*
172 * Metaclass registration object for the root object class. Note that a
173 * root object can never be instantiated; this entry is purely for the
174 * use of the type system.
175 */
176 static CVmMetaclassRoot metaclass_reg_obj;
177 CVmMetaclass *CVmObject::metaclass_reg_ = &metaclass_reg_obj;
178
179 /* function table */
180 int (CVmObject::
181 *CVmObject::func_table_[])(VMG_ vm_obj_id_t self,
182 vm_val_t *retval, uint *argc,
183 vm_prop_id_t prop, vm_obj_id_t *source_obj) =
184 {
185 &CVmObject::getp_undef,
186 &CVmObject::getp_of_kind,
187 &CVmObject::getp_sclist,
188 &CVmObject::getp_propdef,
189 &CVmObject::getp_proptype,
190 &CVmObject::getp_get_prop_list,
191 &CVmObject::getp_get_prop_params,
192 &CVmObject::getp_is_class,
193 &CVmObject::getp_propinh,
194 &CVmObject::getp_is_transient
195 };
196
197 /*
198 * Allocate space for an object from a page table, given the object ID.
199 * The caller must allocate the object ID prior to new'ing the object;
200 * operator new will store the memory for the new object in the object
201 * slot the caller allocated.
202 */
203 void *CVmObject::operator new(size_t siz, VMG_ vm_obj_id_t obj_id)
204 {
205 /*
206 * The size must be the size of an object entry. This size never
207 * changes, even for subclasses of the object type, since all
208 * variable-size data must be stored in the variable-size portion of
209 * the object. Here we are only concerned with allocating the
210 * fixed-size object descriptor.
211 */
212 assert(siz == sizeof(CVmObject));
213
214 /* return the memory contained in the object entry */
215 return G_obj_table->get_obj(obj_id);
216 }
217
218 /*
219 * Determine if this object is an instance of the given object. By
220 * default, we will simply check to see if the given object is the
221 * IntrinsicClass instance that represents our metaclass or one of its
222 * superclasses.
223 */
224 int CVmObject::is_instance_of(VMG_ vm_obj_id_t obj)
225 {
226 vm_meta_entry_t *entry;
227
228 /*
229 * we can only be an instance of the object if the object is an
230 * IntrinsicClass instance, since by default we have only intrinsic
231 * classes among our superclasses
232 */
233 if (!CVmObjClass::is_intcls_obj(vmg_ obj))
234 return FALSE;
235
236 /*
237 * look up my metaclass in the metaclass dependency table, and
238 * determine if my dependency table entry's record of the
239 * IntrinsicClass object for the metaclass matches the given object
240 */
241 entry = (G_meta_table
242 ->get_entry_from_reg(get_metaclass_reg()->get_reg_idx()));
243
244 /*
245 * if we have an entry, ask our superclass object if it is an
246 * instance of the given object; otherwise, we must not be an
247 * instance
248 */
249 if (entry != 0)
250 {
251 /* if this is our direct superclass, we're an instance */
252 if (entry->class_obj_ == obj)
253 return TRUE;
254
255 /* if there's no intrinsic class object, return false */
256 if (entry->class_obj_ == VM_INVALID_OBJ)
257 return FALSE;
258
259 /* ask the superclass if it inherits from the given object */
260 return vm_objp(vmg_ entry->class_obj_)->is_instance_of(vmg_ obj);
261 }
262 else
263 {
264 /*
265 * no metaclass table entry - we can't really make any
266 * determination, so indicate that we're not an instance
267 */
268 return FALSE;
269 }
270 }
271
272 /*
273 * Get the nth superclass. By default, an object's superclass is
274 * represented by the intrinsic class object for the metaclass.
275 */
276 vm_obj_id_t CVmObject::get_superclass(VMG_ vm_obj_id_t /*self*/,
277 int sc_idx) const
278 {
279 vm_meta_entry_t *entry;
280
281 /* we only have one superclass */
282 if (sc_idx != 0)
283 return VM_INVALID_OBJ;
284
285 /* look up the metaclass entry */
286 entry = (G_meta_table
287 ->get_entry_from_reg(get_metaclass_reg()->get_reg_idx()));
288
289 /* return the IntrinsicClass object that represents this metaclass */
290 return (entry != 0 ? entry->class_obj_ : VM_INVALID_OBJ);
291 }
292
293 /*
294 * Get a property
295 */
296 int CVmObject::get_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
297 vm_obj_id_t self, vm_obj_id_t *source_obj, uint *argc)
298 {
299 uint func_idx;
300
301 /* translate the property index to an index into our function table */
302 func_idx = G_meta_table
303 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
304
305 /* if we find it, the source object is the 'Object' intrinsic class */
306 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
307
308 /* call the appropriate function */
309 return (this->*func_table_[func_idx])(vmg_ self, retval, argc,
310 prop, source_obj);
311 }
312
313 /*
314 * Inherit a property
315 */
316 int CVmObject::inh_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
317 vm_obj_id_t self, vm_obj_id_t orig_target_obj,
318 vm_obj_id_t defining_obj, vm_obj_id_t *source_obj,
319 uint *argc)
320 {
321 uint func_idx;
322
323 /*
324 * We're inheriting. This is never called from native code, as native
325 * code does its inheriting directly through C++ calls to base class
326 * native code; hence, we can only be called from a byte-code modifier
327 * object.
328 *
329 * First, try looking for a native implementation. We can reach this
330 * point if a byte-code object overrides an intrinsic method, then
331 * inherits from the byte-code override.
332 */
333 func_idx = G_meta_table
334 ->prop_to_vector_idx(metaclass_reg_->get_reg_idx(), prop);
335 if (func_idx != 0)
336 {
337 /* the source object is the 'Object' intrinsic class */
338 *source_obj = metaclass_reg_->get_class_obj(vmg0_);
339
340 /* call the native implementation */
341 return (this->*func_table_[func_idx])(vmg_ self, retval, argc,
342 prop, source_obj);
343 }
344
345 /*
346 * We didn't find it among the intrinsic methods, so look at the
347 * modifier objects.
348 */
349 return find_modifier_prop(vmg_ prop, retval, self, orig_target_obj,
350 defining_obj, source_obj, argc);
351 }
352
353 /*
354 * Cast the object to a string. If we got here, it means that there's no
355 * metaclass override, so use reflection services if available, or the
356 * basic "object#xxx" template.
357 */
358 const char *CVmObject::cast_to_string(VMG_ vm_obj_id_t self,
359 vm_val_t *new_str) const
360 {
361 /* set up a vm_val_t for 'self' */
362 vm_val_t val;
363 val.set_obj(self);
364
365 /* try calling self.objToString */
366 vm_prop_id_t objToString = G_predef->objToString;
367 if (objToString != VM_INVALID_PROP)
368 {
369 /* call self.objToString */
370 G_interpreter->get_prop(vmg_ 0, &val, objToString, &val, 0, 0);
371
372 /* if that yielded a string, return it */
373 const char *str = G_interpreter->get_r0()->get_as_string(vmg0_);
374 if (str != 0)
375 {
376 /* set the return value */
377 *new_str = *G_interpreter->get_r0();
378
379 /* return the string buffer */
380 return str;
381 }
382 }
383
384 /* try getting a symbolic name, otherwise use the object#xxx template */
385 return CVmObjString::reflect_to_str(
386 vmg_ new_str, 0, 0, &val, "object#%ld", (long)self);
387 }
388
389
390 /*
391 * Any object can be listlike, even if it doesn't natively implement
392 * indexing, if it defines operator[] and 'length' as user-code methods.
393 */
394 int CVmObject::is_listlike(VMG_ vm_obj_id_t self)
395 {
396 vm_val_t v;
397 vm_obj_id_t o;
398 int minargs, optargs, varargs;
399
400 /* check for the required imports */
401 if (G_predef->operator_idx == VM_INVALID_PROP
402 || G_predef->length_prop == VM_INVALID_PROP)
403 return FALSE;
404
405 /* check for operator [] */
406 if (!get_prop(vmg_ G_predef->operator_idx, &v, self, &o, 0))
407 return FALSE;
408
409 /* check for a 'length' method taking no arguments */
410 if (!get_prop_interface(vmg_ self, G_predef->length_prop,
411 minargs, optargs, varargs)
412 || minargs > 0)
413 return FALSE;
414
415 /* it's list-like */
416 return TRUE;
417 }
418
419 /*
420 * An object that doesn't have a native list-like interface can still
421 * provide list-like operations by defining operator[] and 'length' in user
422 * code.
423 */
424 int CVmObject::ll_length(VMG_ vm_obj_id_t self)
425 {
426 /* make a recursive call to 'length' */
427 vm_val_t vself;
428 vself.set_obj(self);
429 vm_rcdesc rc("Object.ll_length");
430 G_interpreter->get_prop(vmg_ 0, &vself, G_predef->length_prop,
431 &vself, 0, &rc);
432
433 /* the return value in R0 is the length */
434 vm_val_t *r0 = G_interpreter->get_r0();
435 if (r0->typ == VM_INT)
436 return r0->val.intval;
437 else
438 return -1;
439 }
440
441 /*
442 * Index the object, with overloading if there's no native implementation.
443 */
444 void CVmObject::index_val_ov(VMG_ vm_val_t *result, vm_obj_id_t self,
445 const vm_val_t *index_val)
446 {
447 /* try the native operation first */
448 if (!index_val_q(vmg_ result, self, index_val))
449 {
450 /* no native indexing - try the operator[] overload */
451 vm_val_t vself;
452 vself.set_obj(self);
453 G_stk->push(index_val);
454 G_interpreter->op_overload(vmg_ 0, -1, &vself, G_predef->operator_idx,
455 1, VMERR_CANNOT_INDEX_TYPE);
456
457 /* return the result from R0 */
458 *result = *G_interpreter->get_r0();
459 }
460 }
461
462 /*
463 * Index the object, with overloading if there's no native implementation.
464 */
465 void CVmObject::set_index_val_ov(VMG_ vm_val_t *new_container,
466 vm_obj_id_t self,
467 const vm_val_t *index_val,
468 const vm_val_t *new_val)
469 {
470 /* try the native indexing first */
471 if (!set_index_val_q(vmg_ new_container, self, index_val, new_val))
472 {
473 /* no native indexing - try the operator[]= overload */
474 vm_val_t vself;
475 vself.set_obj(self);
476 G_stk->push(new_val);
477 G_stk->push(index_val);
478 G_interpreter->op_overload(vmg_ 0, -1,
479 &vself, G_predef->operator_setidx,
480 2, VMERR_CANNOT_INDEX_TYPE);
481
482 /* return the new container result from R0 */
483 *new_container = *G_interpreter->get_r0();
484 }
485 }
486
487 /*
488 * Get the next value from an iteration
489 */
490 int CVmObject::iter_next(VMG_ vm_obj_id_t selfobj, vm_val_t *val)
491 {
492 /* check that the iterator properties are defined by the program */
493 if (G_iter_next_avail == VM_INVALID_PROP
494 || G_iter_get_next == VM_INVALID_PROP)
495 return FALSE;
496
497 /* call isNextAvailable */
498 vm_rcdesc rc("for..in");
499 vm_val_t self;
500 self.set_obj(selfobj);
501 G_interpreter->get_prop(vmg_ 0, &self, G_iter_next_avail, &self, 0, &rc);
502
503 /* if that returned false (nil or 0), return false */
504 vm_val_t *ret = G_interpreter->get_r0();
505 if (ret->typ == VM_NIL || (ret->typ == VM_INT && ret->val.intval == 0))
506 return FALSE;
507
508 /* call getNext and return the result */
509 G_interpreter->get_prop(vmg_ 0, &self, G_iter_get_next, &self, 0, &rc);
510 *val = *G_interpreter->get_r0();
511 return TRUE;
512 }
513
514
515 /*
516 * Get a property that isn't defined in our property table
517 */
518 int CVmObject::getp_undef(VMG_ vm_obj_id_t self,
519 vm_val_t *retval, uint *argc,
520 vm_prop_id_t prop, vm_obj_id_t *source_obj)
521 {
522 /*
523 * We didn't find a native implementation of the method, but there's
524 * still one more place to look: the "modifier" object for our class
525 * tree. Modifier objects are byte-code objects that can provide
526 * implementations of methods that add to intrinsic classes (modifiers
527 * can't override intrinsic methods, but they can add new methods).
528 *
529 * Since we're looking for a property on an initial get-property call
530 * (not an inheritance call), we don't yet have a defining object to
531 * find and skip in the inheritance tree, so use VM_INVALID_OBJ as the
532 * defining object. In addition, we're directly calling the method, so
533 * the target object is the same as the 'self' object.
534 */
535 return find_modifier_prop(vmg_ prop, retval, self, self,
536 VM_INVALID_OBJ, source_obj, argc);
537 }
538
539 /*
540 * Find a modifier property.
541 */
542 int CVmObject::find_modifier_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
543 vm_obj_id_t self,
544 vm_obj_id_t orig_target_obj,
545 vm_obj_id_t defining_obj,
546 vm_obj_id_t *source_obj,
547 uint *argc)
548 {
549 vm_meta_entry_t *entry;
550 int found_def_obj;
551
552 /* we haven't yet found the defining superclass */
553 found_def_obj = FALSE;
554
555 /* get my metaclass from the dependency table */
556 entry = (G_meta_table
557 ->get_entry_from_reg(get_metaclass_reg()->get_reg_idx()));
558
559 /*
560 * if there's an associated intrinsic class object, check to see if
561 * it provides a user modifier object for this intrinsic class
562 */
563 while (entry != 0 && entry->class_obj_ != VM_INVALID_OBJ)
564 {
565 vm_obj_id_t mod_obj;
566
567 /* ask the intrinsic class object for the user modifier object */
568 mod_obj = ((CVmObjClass *)vm_objp(vmg_ entry->class_obj_))
569 ->get_mod_obj();
570
571 /*
572 * If we have a defining object, we must ignore objects in the
573 * superclass tree until we find the defining object. Therefore,
574 * scan up the superclass tree for mod_obj and see if we can find
575 * the defining object; when we find it, we can start looking at
576 * objects for real at the defining object's superclass.
577 *
578 * (Superclasses in modifier objects aren't real superclasses,
579 * because modifier objects are classless. Instead, the superclass
580 * list simply implements the 'modify' chain.)
581 */
582 if (mod_obj != VM_INVALID_OBJ
583 && defining_obj != VM_INVALID_OBJ && !found_def_obj)
584 {
585 /*
586 * if the defining object isn't among the byte-code
587 * superclasses of the modifier object, we must skip this
588 * entire intrinsic class and move to the intrinsic superclass
589 */
590 if (mod_obj == defining_obj
591 || vm_objp(vmg_ mod_obj)->is_instance_of(vmg_ defining_obj))
592 {
593 /*
594 * the defining object is among my modifier family - this
595 * means that this is the intrinsic superclass where we
596 * found the modifier method
597 */
598 found_def_obj = TRUE;
599 }
600 else
601 {
602 /*
603 * The current defining object is not part of the modifier
604 * chain for this intrinsic class, so we've already skipped
605 * past this point in the intrinsic superclass tree on past
606 * inheritances. Simply move to the next intrinsic class
607 * and look at its modifier.
608 */
609 goto next_intrinsic_sc;
610 }
611 }
612
613 /*
614 * If there's a modifier object, send the property request to it.
615 * We are effectively delegating the method call to the modifier
616 * object, so we must use the "inherited property" call, not the
617 * plain get_prop() call: 'self' is the original self, but the
618 * target object is the intrinsic class modifier object.
619 */
620 if (mod_obj != VM_INVALID_OBJ
621 && vm_objp(vmg_ mod_obj)->inh_prop(
622 vmg_ prop, retval, self, mod_obj, defining_obj,
623 source_obj, argc))
624 return TRUE;
625
626 /* we didn't find it in this object, so look at its super-metaclass */
627 next_intrinsic_sc:
628 if (entry->meta_->get_supermeta_reg() != 0)
629 {
630 /* get the super-metaclass ID */
631 entry = (G_meta_table
632 ->get_entry_from_reg(entry->meta_
633 ->get_supermeta_reg()
634 ->get_reg_idx()));
635
636 /*
637 * if we've already found the previous defining intrinsic
638 * class, we can forget about the previous defining modifier
639 * object now: since we're moving to a new intrinsic
640 * superclass, we will have no superclass relation to the
641 * previous defining object in the new modifier family, so we
642 * can simply use the next definition of the property we find
643 */
644 if (found_def_obj)
645 defining_obj = VM_INVALID_OBJ;
646 }
647 else
648 {
649 /* no super-metaclass - give up */
650 break;
651 }
652 }
653
654 /* we don't have a modifier object, so the property is undefined */
655 return FALSE;
656 }
657
658 /*
659 * property evaluator - ofKind
660 */
661 int CVmObject::getp_of_kind(VMG_ vm_obj_id_t self,
662 vm_val_t *retval, uint *argc,
663 vm_prop_id_t, vm_obj_id_t *)
664 {
665 vm_val_t sc;
666 static CVmNativeCodeDesc desc(1);
667
668 /* check arguments */
669 if (get_prop_check_argc(retval, argc, &desc))
670 return TRUE;
671
672 /* pop the superclass, and make sure it's an object */
673 G_stk->pop(&sc);
674 if (sc.typ != VM_OBJ)
675 err_throw(VMERR_OBJ_VAL_REQD);
676
677 /* check for an identity test */
678 if (sc.val.obj == self)
679 {
680 /* x.ofKind(x) == true */
681 retval->set_true();
682 }
683 else
684 {
685 /* check to see if the object is a superclass of ours */
686 retval->set_logical(is_instance_of(vmg_ sc.val.obj));
687 }
688
689 /* handled */
690 return TRUE;
691 }
692
693 /*
694 * property evaluator - isClass
695 */
696 int CVmObject::getp_is_class(VMG_ vm_obj_id_t self,
697 vm_val_t *retval, uint *argc,
698 vm_prop_id_t, vm_obj_id_t *)
699 {
700 static CVmNativeCodeDesc desc(0);
701
702 /* check arguments */
703 if (get_prop_check_argc(retval, argc, &desc))
704 return TRUE;
705
706 /* indicate whether or not we're a class object */
707 retval->set_logical(is_class_object(vmg_ self));
708
709 /* handled */
710 return TRUE;
711 }
712
713 /*
714 * property evaluator - isTransient
715 */
716 int CVmObject::getp_is_transient(VMG_ vm_obj_id_t self,
717 vm_val_t *retval, uint *argc,
718 vm_prop_id_t, vm_obj_id_t *)
719 {
720 static CVmNativeCodeDesc desc(0);
721
722 /* check arguments */
723 if (get_prop_check_argc(retval, argc, &desc))
724 return TRUE;
725
726 /* indicate whether or not we're transient */
727 retval->set_logical(G_obj_table->is_obj_transient(self));
728
729 /* handled */
730 return TRUE;
731 }
732
733 /*
734 * property evaluator - getSuperclassList
735 */
736 int CVmObject::getp_sclist(VMG_ vm_obj_id_t self,
737 vm_val_t *retval, uint *argc,
738 vm_prop_id_t, vm_obj_id_t *)
739 {
740 size_t sc_cnt;
741 vm_obj_id_t lst_obj;
742 CVmObjList *lstp;
743 size_t i;
744 static CVmNativeCodeDesc desc(0);
745
746 /* check arguments */
747 if (get_prop_check_argc(retval, argc, &desc))
748 return TRUE;
749
750 /* push a self-reference for GC protection */
751 G_interpreter->push_obj(vmg_ self);
752
753 /* get the number of superclasses */
754 sc_cnt = get_superclass_count(vmg_ self);
755
756 /* allocate a list for the results */
757 lst_obj = CVmObjList::create(vmg_ FALSE, sc_cnt);
758 lstp = (CVmObjList *)vm_objp(vmg_ lst_obj);
759
760 /* build the superclass list */
761 for (i = 0 ; i < sc_cnt ; ++i)
762 {
763 vm_val_t ele_val;
764
765 /* get this superclass */
766 ele_val.set_obj(get_superclass(vmg_ self, i));
767
768 /* set the list element */
769 lstp->cons_set_element(i, &ele_val);
770 }
771
772 /* discard our GC protection */
773 G_stk->discard();
774
775 /* return the list */
776 retval->set_obj(lst_obj);
777
778 /* handled */
779 return TRUE;
780 }
781
782 /*
783 * property evaluator - propDefined
784 */
785 int CVmObject::getp_propdef(VMG_ vm_obj_id_t self,
786 vm_val_t *retval, uint *in_argc,
787 vm_prop_id_t, vm_obj_id_t *)
788 {
789 uint argc = (in_argc != 0 ? *in_argc : 0);
790 vm_val_t val;
791 int flags;
792 int found;
793 vm_prop_id_t prop;
794 vm_obj_id_t source_obj;
795 static CVmNativeCodeDesc desc(1, 1);
796
797 /* check arguments */
798 if (get_prop_check_argc(retval, in_argc, &desc))
799 return TRUE;
800
801 /* pop the property address to test */
802 G_interpreter->pop_prop(vmg_ &val);
803 prop = val.val.prop;
804
805 /* if we have the flag argument, get it; otherwise, use the default */
806 if (argc >= 2)
807 {
808 /* get the flag value */
809 G_interpreter->pop_int(vmg_ &val);
810 flags = (int)val.val.intval;
811 }
812 else
813 {
814 /* use the default flags */
815 flags = VMOBJ_PROPDEF_ANY;
816 }
817
818 /* presume we won't find a valid source object */
819 source_obj = VM_INVALID_OBJ;
820
821 /* look up the property */
822 found = get_prop(vmg_ prop, &val, self, &source_obj, 0);
823
824 /*
825 * If we found a result, check to see if it's an intrinsic class
826 * modifier object. If it is, replace it with its intrinsic class:
827 * modifier objects are invisible through the reflection mechanism, and
828 * appear to be the actual intrinsic classes they modify.
829 */
830 if (found && CVmObjIntClsMod::is_intcls_mod_obj(vmg_ source_obj))
831 source_obj = find_intcls_for_mod(vmg_ self, source_obj);
832
833 /* check the flags */
834 switch(flags)
835 {
836 case VMOBJ_PROPDEF_ANY:
837 /* return true if the property is defined */
838 retval->set_logical(found);
839 break;
840
841 case VMOBJ_PROPDEF_DIRECTLY:
842 /* return true if the property is defined directly */
843 retval->set_logical(found && source_obj == self);
844 break;
845
846 case VMOBJ_PROPDEF_INHERITS:
847 /* return true if the property is inherited only */
848 retval->set_logical(found && source_obj != self);
849 break;
850
851 case VMOBJ_PROPDEF_GET_CLASS:
852 /* return the defining class, or nil if it's not defined */
853 if (found)
854 {
855 /*
856 * If we got a valid source object, return it. If we didn't
857 * get a valid source object, but we found the property,
858 * return 'self' as the result; this isn't exactly right, but
859 * this should only be possible when the source object is an
860 * intrinsic class for which no intrinsic class object is
861 * defined, in which case the best we can do is provide 'self'
862 * as the answer.
863 */
864 retval->set_obj(source_obj != VM_INVALID_OBJ ? source_obj : self);
865 }
866 else
867 {
868 /* didn't find it - the return value is nil */
869 retval->set_nil();
870 }
871 break;
872
873 default:
874 /* other flags are invalid */
875 err_throw(VMERR_BAD_VAL_BIF);
876 break;
877 }
878
879 /* handled */
880 return TRUE;
881 }
882
883 /*
884 * Find the intrinsic class which the given modifier object modifies. This
885 * can only be used with a modifier that modifies my intrinsic class or one
886 * of its intrinsic superclasses.
887 */
888 vm_obj_id_t CVmObject::find_intcls_for_mod(VMG_ vm_obj_id_t self,
889 vm_obj_id_t mod_obj)
890 {
891 /* get my metaclass from the dependency table */
892 vm_meta_entry_t *entry = (G_meta_table
893 ->get_entry_from_reg(get_metaclass_reg()->get_reg_idx()));
894
895 /*
896 * if there's an intrinsic class object for the metaclass, ask it to do
897 * the work
898 */
899 if (entry != 0 && entry->class_obj_ != VM_INVALID_OBJ)
900 return (((CVmObjClass *)vm_objp(vmg_ entry->class_obj_))
901 ->find_mod_src_obj(vmg_ entry->class_obj_, mod_obj));
902
903 /* there's no intrinsic metaclass, so we can't find what we need */
904 return VM_INVALID_OBJ;
905 }
906
907 /*
908 * property evaluator - propInherited
909 */
910 int CVmObject::getp_propinh(VMG_ vm_obj_id_t self,
911 vm_val_t *retval, uint *in_argc,
912 vm_prop_id_t, vm_obj_id_t *)
913 {
914 uint argc = (in_argc != 0 ? *in_argc : 0);
915 vm_val_t val;
916 int flags;
917 int found;
918 vm_prop_id_t prop;
919 vm_obj_id_t source_obj;
920 vm_obj_id_t orig_target_obj;
921 vm_obj_id_t defining_obj;
922 static CVmNativeCodeDesc desc(3, 1);
923
924 /* check arguments */
925 if (get_prop_check_argc(retval, in_argc, &desc))
926 return TRUE;
927
928 /* pop the property address to test */
929 G_interpreter->pop_prop(vmg_ &val);
930 prop = val.val.prop;
931
932 /* get the original target object */
933 G_interpreter->pop_obj(vmg_ &val);
934 orig_target_obj = val.val.obj;
935
936 /* get the defining object */
937 G_interpreter->pop_obj(vmg_ &val);
938 defining_obj = val.val.obj;
939
940 /* if we have the flag argument, get it; otherwise, use the default */
941 if (argc >= 4)
942 {
943 /* get the flag value */
944 G_interpreter->pop_int(vmg_ &val);
945 flags = (int)val.val.intval;
946 }
947 else
948 {
949 /* use the default flags */
950 flags = VMOBJ_PROPDEF_ANY;
951 }
952
953 /* presume we won't find a valid source object */
954 source_obj = VM_INVALID_OBJ;
955
956 /* look up the property */
957 found = inh_prop(vmg_ prop, &val, self, orig_target_obj, defining_obj,
958 &source_obj, 0);
959
960 /* check the flags */
961 switch(flags)
962 {
963 case VMOBJ_PROPDEF_ANY:
964 /* return true if the property is defined */
965 retval->set_logical(found);
966 break;
967
968 case VMOBJ_PROPDEF_GET_CLASS:
969 /* return the defining class, or nil if it's not defined */
970 if (found)
971 {
972 /* return the source object, or 'self' if we didn't find one */
973 retval->set_obj(source_obj != VM_INVALID_OBJ ? source_obj : self);
974 }
975 else
976 {
977 /* didn't find it - the return value is nil */
978 retval->set_nil();
979 }
980 break;
981
982 default:
983 /* other flags are invalid */
984 err_throw(VMERR_BAD_VAL_BIF);
985 break;
986 }
987
988 /* handled */
989 return TRUE;
990 }
991
992 /*
993 * property evaluator - propType
994 */
995 int CVmObject::getp_proptype(VMG_ vm_obj_id_t self,
996 vm_val_t *retval, uint *argc,
997 vm_prop_id_t, vm_obj_id_t *)
998 {
999 vm_val_t val;
1000 vm_prop_id_t prop;
1001 vm_obj_id_t source_obj;
1002 static CVmNativeCodeDesc desc(1);
1003
1004 /* check arguments */
1005 if (get_prop_check_argc(retval, argc, &desc))
1006 return TRUE;
1007
1008 /* pop the property address to test */
1009 G_interpreter->pop_prop(vmg_ &val);
1010 prop = val.val.prop;
1011
1012 /* get the property value */
1013 if (!get_prop(vmg_ prop, &val, self, &source_obj, 0))
1014 {
1015 /* the property isn't defined on the object - the result is nil */
1016 retval->set_nil();
1017 }
1018 else
1019 {
1020 /*
1021 * Fix up OBJX (execute-on-eval object reference) and BIFPTRX
1022 * (execute-on-eval built-in function pointer) values to reflect
1023 * the underlying datatype. Treat an anonymous function or dynamic
1024 * function as a CODEOFS value; treat a string object as a DSTRING
1025 * value.
1026 */
1027 if (val.typ == VM_OBJX)
1028 {
1029 if (CVmObjAnonFn::is_anonfn_obj(vmg_ val.val.obj)
1030 || CVmDynamicFunc::is_dynfunc_obj(vmg_ val.val.obj))
1031 val.typ = VM_CODEOFS;
1032 else if (CVmObjString::is_string_obj(vmg_ val.val.obj))
1033 val.typ = VM_DSTRING;
1034 else
1035 val.typ = VM_OBJ;
1036 }
1037 else if (val.typ == VM_BIFPTRX)
1038 val.typ = VM_BIFPTR;
1039
1040 /* set the return value to the property's datatype value */
1041 retval->set_datatype(vmg_ &val);
1042 }
1043
1044 /* handled */
1045 return TRUE;
1046 }
1047
1048 /*
1049 * property evaluator - getPropList
1050 */
1051 int CVmObject::getp_get_prop_list(VMG_ vm_obj_id_t self,
1052 vm_val_t *retval, uint *argc,
1053 vm_prop_id_t, vm_obj_id_t *)
1054 {
1055 static CVmNativeCodeDesc desc(0);
1056
1057 /* check arguments */
1058 if (get_prop_check_argc(retval, argc, &desc))
1059 return TRUE;
1060
1061 /* push a self-reference for gc protection */
1062 G_stk->push()->set_obj(self);
1063
1064 /* build my property list */
1065 build_prop_list(vmg_ self, retval);
1066
1067 /* discard the gc protection */
1068 G_stk->discard();
1069
1070 /* handled */
1071 return TRUE;
1072 }
1073
1074 /*
1075 * Build a list of properties directly defined by this instance
1076 */
1077 void CVmObject::build_prop_list(VMG_ vm_obj_id_t /*self*/, vm_val_t *retval)
1078 {
1079 /*
1080 * by default, object instances have no directly defined properties,
1081 * so create and return an empty list
1082 */
1083 retval->set_obj(CVmObjList::create(vmg_ FALSE, (size_t)0));
1084 }
1085
1086 /*
1087 * property evaluator - getPropParams
1088 */
1089 int CVmObject::getp_get_prop_params(VMG_ vm_obj_id_t self,
1090 vm_val_t *retval, uint *argc,
1091 vm_prop_id_t, vm_obj_id_t *)
1092 {
1093 vm_val_t val;
1094 vm_prop_id_t prop;
1095 int min_args, opt_args, varargs;
1096 static CVmNativeCodeDesc desc(1);
1097 CVmObjList *lst;
1098
1099 /* check arguments */
1100 if (get_prop_check_argc(retval, argc, &desc))
1101 return TRUE;
1102
1103 /* pop the property address to test */
1104 G_interpreter->pop_prop(vmg_ &val);
1105 prop = val.val.prop;
1106
1107 /* push a self-reference while we're working */
1108 G_stk->push()->set_obj(self);
1109
1110 /* get the property information */
1111 get_prop_interface(vmg_ self, prop, min_args, opt_args, varargs);
1112
1113 /*
1114 * Allocate our return list. We need three elements: [minArgs,
1115 * optionalArgs, isVarargs].
1116 */
1117 retval->set_obj(CVmObjList::create(vmg_ FALSE, 3));
1118
1119 /* get the list object, properly cast */
1120 lst = (CVmObjList *)vm_objp(vmg_ retval->val.obj);
1121
1122 /* set the minimum argument count */
1123 val.set_int(min_args);
1124 lst->cons_set_element(0, &val);
1125
1126 /* set the optional argument count */
1127 val.set_int(opt_args);
1128 lst->cons_set_element(1, &val);
1129
1130 /* set the varargs flag */
1131 val.set_logical(varargs);
1132 lst->cons_set_element(2, &val);
1133
1134 /* discard our self-reference */
1135 G_stk->discard();
1136
1137 /* handled */
1138 return TRUE;
1139 }
1140
1141 /*
1142 * Get the method interface to a given object property
1143 */
1144 int CVmObject::get_prop_interface(VMG_ vm_obj_id_t self, vm_prop_id_t prop,
1145 int &min_args, int &opt_args, int &varargs)
1146 {
1147 vm_val_t val;
1148 vm_obj_id_t source_obj;
1149
1150 /* presume we won't find an argument interface */
1151 min_args = opt_args = 0;
1152 varargs = FALSE;
1153
1154 /* get the property value */
1155 if (!get_prop(vmg_ prop, &val, self, &source_obj, 0))
1156 {
1157 /* we didn't find the property at all */
1158 return FALSE;
1159 }
1160 else if (val.typ == VM_CODEOFS
1161 || val.typ == VM_OBJX
1162 || val.typ == VM_BIFPTRX)
1163 {
1164 /*
1165 * It's a direct pointer to static code, an object that we execute
1166 * on evaluation, or a built-in function pointer. Try getting a
1167 * pointer to the method header. CODEOFS and BIFPTRX values always
1168 * have method headers; OBJX values do if the underlying object is
1169 * invokable. If the object *isn't* invokable, it won't have a
1170 * method header; the only way this can happen is that we have a
1171 * String object as an OBJX property, which acts like a DSTRING
1172 * when evaluated. That has the default zero-argument interface,
1173 * so we can simply leave the return value with the defaults we've
1174 * already set up in this case.
1175 */
1176 CVmFuncPtr func;
1177 if (func.set(vmg_ &val))
1178 {
1179 /* it's an invokable - get the interface info from the header */
1180 min_args = func.get_min_argc();
1181 opt_args = func.get_opt_argc();
1182 varargs = func.is_varargs();
1183 }
1184
1185 /* got it */
1186 return TRUE;
1187 }
1188 else if (val.typ == VM_NATIVE_CODE)
1189 {
1190 /* get the arguments from the native code descriptor */
1191 min_args = val.val.native_desc->min_argc_;
1192 opt_args = val.val.native_desc->opt_argc_;
1193 varargs = val.val.native_desc->varargs_;
1194
1195 /* we found the property */
1196 return TRUE;
1197 }
1198 else
1199 {
1200 /*
1201 * it's not a function, so there are no arguments, but we did find
1202 * the property
1203 */
1204 return TRUE;
1205 }
1206 }
1207
1208 /*
1209 * Call a static property
1210 */
1211 int CVmObject::call_stat_prop(VMG_ vm_val_t *retval, const uchar **pc_ptr,
1212 uint *argc, vm_prop_id_t prop)
1213 {
1214 /* not handled */
1215 return FALSE;
1216 }
1217
1218 /*
1219 * Get my image file version string
1220 */
1221 const char *CVmObject::get_image_file_version(VMG0_) const
1222 {
1223 /* get the metaclass table entry */
1224 vm_meta_entry_t *entry = G_meta_table->get_entry_from_reg(
1225 get_metaclass_reg()->get_reg_idx());
1226
1227 /* if we found it, get the image metaclass string from the entry */
1228 if (entry != 0)
1229 {
1230 /* get the image metaclass name - "name/version" */
1231 const char *n = entry->image_meta_name_;
1232
1233 /* scan for the version slash */
1234 n = strchr(n, '/');
1235
1236 /* if we found it, the version follows the slash */
1237 if (n != 0)
1238 return n + 1;
1239 }
1240
1241 /* we couldn't find the version data, so return an empty string */
1242 return "";
1243 }
1244
1245
1246 /* ------------------------------------------------------------------------ */
1247 /*
1248 * CVmMetaclass implementation
1249 */
1250
1251 /*
1252 * Get a metaclass's super-metaclass. We'll look up our super-metaclass
1253 * in the metaclass registration table and return the IntrinsicClass
1254 * object we find referenced there.
1255 */
1256 vm_obj_id_t CVmMetaclass::get_supermeta(VMG_ int idx) const
1257 {
1258 vm_meta_entry_t *entry;
1259
1260 /* we only have one supermetaclass */
1261 if (idx != 0)
1262 return VM_INVALID_OBJ;
1263
1264 /* if I don't have a supermetaclass at all, return nil */
1265 if (get_supermeta_reg() == 0)
1266 return VM_INVALID_OBJ;
1267
1268 /* look up my supermetaclass entry */
1269 entry = (G_meta_table->get_entry_from_reg(
1270 get_supermeta_reg()->get_reg_idx()));
1271
1272 /* return the IntrinsicClass object that represents this metaclass */
1273 return (entry != 0 ? entry->class_obj_ : VM_INVALID_OBJ);
1274 }
1275
1276 /*
1277 * Determine if I'm an instance of the given object. Most metaclasses
1278 * inherit directly from CVmObject, so we'll return true only if the
1279 * object is the CVmObject IntrinsicClass object
1280 */
1281 int CVmMetaclass::is_meta_instance_of(VMG_ vm_obj_id_t obj) const
1282 {
1283 /* iterate over my supermetaclasses */
1284 for (CVmMetaclass *sc = get_supermeta_reg() ; sc != 0 ;
1285 sc = sc->get_supermeta_reg())
1286 {
1287 /* look up the metaclass entry for this supermetaclass */
1288 vm_meta_entry_t *entry =
1289 (G_meta_table->get_entry_from_reg(sc->get_reg_idx()));
1290
1291 /*
1292 * if the object matches the current superclass's IntrinsicClass
1293 * object, we're a subclass of that object; otherwise we're not
1294 */
1295 if (entry != 0 && entry->class_obj_ == obj)
1296 return TRUE;
1297 }
1298
1299 /* it's not one of my superclasses */
1300 return FALSE;
1301 }
1302
1303 /*
1304 * Get my intrinsic class object
1305 */
1306 vm_obj_id_t CVmMetaclass::get_class_obj(VMG0_) const
1307 {
1308 /* get my metacalss entry */
1309 vm_meta_entry_t *entry = G_meta_table->get_entry_from_reg(get_reg_idx());
1310
1311 /* if we found our entry, return the class from the entry */
1312 return (entry != 0 ? entry->class_obj_ : VM_INVALID_OBJ);
1313 }
1314
1315 /* ------------------------------------------------------------------------ */
1316 /*
1317 * The nil object. This is a special pseudo-object we create for object
1318 * #0, to provide graceful error handling if byte code tries to dereference
1319 * nil in any way.
1320 */
1321 class CVmObjNil: public CVmObject
1322 {
1323 public:
1324 virtual class CVmMetaclass *get_metaclass_reg() const
1325 {
1326 err_throw(VMERR_NIL_DEREF);
1327 AFTER_ERR_THROW(return 0;)
1328 }
1329
1330 virtual void set_prop(VMG_ class CVmUndo *, vm_obj_id_t, vm_prop_id_t,
1331 const vm_val_t *)
1332 { err_throw(VMERR_NIL_DEREF); }
1333 virtual int get_prop(VMG_ vm_prop_id_t, vm_val_t *,
1334 vm_obj_id_t, vm_obj_id_t *, uint *)
1335 {
1336 err_throw(VMERR_NIL_DEREF);
1337 AFTER_ERR_THROW(return FALSE;)
1338 }
1339 virtual int is_instance_of(VMG_ vm_obj_id_t)
1340 {
1341 err_throw(VMERR_NIL_DEREF);
1342 AFTER_ERR_THROW(return FALSE;)
1343 }
1344 virtual int get_superclass_count(VMG_ vm_obj_id_t) const
1345 {
1346 err_throw(VMERR_NIL_DEREF);
1347 AFTER_ERR_THROW(return 0;)
1348 }
1349 virtual vm_obj_id_t get_superclass(VMG_ vm_obj_id_t, int) const
1350 {
1351 err_throw(VMERR_NIL_DEREF);
1352 AFTER_ERR_THROW(return VM_INVALID_OBJ;)
1353 }
1354 virtual void enum_props(VMG_ vm_obj_id_t,
1355 void (*cb)(VMG_ void *, vm_obj_id_t,
1356 vm_prop_id_t, const vm_val_t *),
1357 void *)
1358 { err_throw(VMERR_NIL_DEREF); }
1359 virtual int get_prop_interface(VMG_ vm_obj_id_t, vm_prop_id_t,
1360 int &, int &, int &)
1361 {
1362 err_throw(VMERR_NIL_DEREF);
1363 AFTER_ERR_THROW(return FALSE;)
1364 }
1365 virtual int inh_prop(VMG_ vm_prop_id_t prop, vm_val_t *retval,
1366 vm_obj_id_t self, vm_obj_id_t orig_target_obj,
1367 vm_obj_id_t defining_obj, vm_obj_id_t *source_obj,
1368 uint *argc)
1369 {
1370 err_throw(VMERR_NIL_DEREF);
1371 AFTER_ERR_THROW(return FALSE;)
1372 }
1373 virtual void build_prop_list(VMG_ vm_obj_id_t, vm_val_t *)
1374 { err_throw(VMERR_NIL_DEREF); }
1375
1376 virtual void notify_delete(VMG_ int) { }
1377 virtual void mark_refs(VMG_ uint) { }
1378 virtual void remove_stale_weak_refs(VMG0_) { }
1379 virtual void notify_new_savept() { }
1380 virtual void apply_undo(VMG_ struct CVmUndoRecord *) { }
1381 virtual void mark_undo_ref(VMG_ struct CVmUndoRecord *) { }
1382 virtual void remove_stale_undo_weak_ref(VMG_ struct CVmUndoRecord *) { }
1383 virtual void load_from_image(VMG_ vm_obj_id_t, const char *, size_t) { }
1384 virtual void save_to_file(VMG_ class CVmFile *) { }
1385 virtual void restore_from_file(VMG_ vm_obj_id_t, class CVmFile *,
1386 class CVmObjFixup *) { }
1387
1388 };
1389
1390
1391 /* ------------------------------------------------------------------------ */
1392 /*
1393 * object table implementation
1394 */
1395
1396 /*
1397 * construction - create an empty table
1398 */
1399 CVmObjTable::CVmObjTable()
1400 {
1401 pages_ = 0;
1402 page_slots_ = 0;
1403 pages_used_ = 0;
1404 image_ptr_head_ = 0;
1405 globals_ = 0;
1406 global_var_head_ = 0;
1407 post_load_init_table_ = 0;
1408 }
1409
1410 /*
1411 * allocate object table
1412 */
1413 void CVmObjTable::init(VMG0_)
1414 {
1415 /* allocate the initial set of page slots */
1416 page_slots_ = 10;
1417 pages_ = (CVmObjPageEntry **)t3malloc(page_slots_ * sizeof(*pages_));
1418
1419 /* if that failed, throw an error */
1420 if (pages_ == 0)
1421 err_throw(VMERR_OUT_OF_MEMORY);
1422
1423 /* no pages are in use yet */
1424 pages_used_ = 0;
1425
1426 /* there are no free objects yet */
1427 first_free_ = 0;
1428
1429 /* there's nothing in the GC work queue yet */
1430 gc_queue_head_ = VM_INVALID_OBJ;
1431
1432 /* nothing in the finalizer work queue yet */
1433 finalize_queue_head_ = VM_INVALID_OBJ;
1434
1435 /* we haven't allocated anything yet */
1436 allocs_since_gc_ = 0;
1437 bytes_since_gc_ = 0;
1438
1439 /*
1440 * Set the upper limit for new objects and allocated bytes between
1441 * garbage collection passes.
1442 *
1443 * In choosing these parameters, there's a trade-off. Running more
1444 * frequently reduces GC "stall time" of each pass (the time that the
1445 * system is unresponsive while scanning for unreachable objects),
1446 * because the total scanning on each pass will be smaller. More
1447 * frequent GC'ing also minimizes the working memory size by freeing
1448 * garbage objects sooner after they become unreachable. But running
1449 * more frequently reduces *overall* program speed, since we spend more
1450 * time in the collector in aggregate. We have to scan the reachable
1451 * objects on every pass, so the more frequently we run, the more
1452 * unproductive time we'll spend scanning the same reachable objects
1453 * over and over.
1454 *
1455 * TADS is specialized for highly interactive programs, so minimizing
1456 * stall time is the overriding priority. In practical testing, the
1457 * stall time is imperceptible up to at least 30,000 objects between
1458 * passes. (It stays below 5 ms per run on an average 2007 desktop.
1459 * The usual threshold of perceptibility is about 50-100 ms.) Overall
1460 * throughput seems to level out at about 20,000 objects between
1461 * passes. Beyond that, decreasing the frequency of gc runs yields
1462 * diminishing returns. The knee is the point where we're waiting long
1463 * enough between passes that unreachable objects dominate. Once
1464 * you're at that frequency, going longer between passes won't improve
1465 * speed much because you're typically just adding more garbage for the
1466 * next pass. The time you save by not doing a pass now gets canceled
1467 * out by making the next pass longer by giving it more garbage to
1468 * collect. This is in contrast to running too frequently, where
1469 * scanning reachable objects dominates: this time typically plateaus
1470 * the longer you go between passes, since the reachable set itself
1471 * tends to plateau in size over time, so while we're still in this
1472 * zone, the longer you go between passes the better.)
1473 *
1474 * Although 20,000 allocations seems to be the best frequency for
1475 * throughput for our test set, we currently set a somewhat more
1476 * conservative limit (i.e., collect garbage more frequently). This is
1477 * because the assumptions in our test set don't apply to all programs.
1478 * Some programs might allocate larger objects more frequently than our
1479 * tests, and in those cases we don't want the working set to grow too
1480 * quickly. More frequenty GC will help avoid this.
1481 *
1482 * In addition to the simple object allocation count, we also count
1483 * bytes allocated between passes, and collect garbage if we go above a
1484 * byte threshold independently of the object count. This is to ensure
1485 * that we collect garbage more frequently when very large objects are
1486 * being used, to keep the working set from growing too fast. Very
1487 * large working sets can hurt performance by reducing locality of
1488 * reference (for CPU caching) and even triggering OS-level disk
1489 * swapping.
1490 */
1491 // max_allocs_between_gc_ = 17500;
1492 max_allocs_between_gc_ = 10000;
1493 max_bytes_between_gc_ = 6*1024*1024;
1494
1495 /* enable the garbage collector */
1496 gc_enabled_ = TRUE;
1497
1498 /* there are no saved image data pointers yet */
1499 image_ptr_head_ = 0;
1500 image_ptr_tail_ = 0;
1501 image_ptr_last_cnt_ = 0;
1502
1503 /* no global pages yet */
1504 globals_ = 0;
1505
1506 /* no global variables yet */
1507 global_var_head_ = 0;
1508
1509 /* create the post_load_init() request table */
1510 post_load_init_table_ = new CVmHashTable(128, new CVmHashFuncCS(), TRUE);
1511
1512 /* allocate the first object page */
1513 alloc_new_page();
1514
1515 /*
1516 * Initialize object #0 with the nil pseudo-object. This isn't an
1517 * actual object, but it provides graceful error handling if the byte
1518 * code attempts to invoke any methods on nil.
1519 */
1520 new (vmg_ VM_INVALID_OBJ) CVmObjNil;
1521 CVmObjPageEntry *obj0 = get_entry(0);
1522 obj0->free_ = TRUE;
1523 obj0->in_root_set_ = TRUE;
1524 obj0->reachable_ = VMOBJ_REACHABLE;
1525 obj0->finalize_state_ = VMOBJ_UNFINALIZABLE;
1526 obj0->in_undo_ = FALSE;
1527 obj0->transient_ = FALSE;
1528 obj0->requested_post_load_init_ = FALSE;
1529 obj0->can_have_refs_ = FALSE;
1530 obj0->can_have_weak_refs_ = FALSE;
1531 }
1532
1533 /*
1534 * delete object table
1535 */
1536 CVmObjTable::~CVmObjTable()
1537 {
1538 /* show statistics if applicable */
1539 IF_GC_STATS(gc_stats.display());
1540 }
1541
1542 /*
1543 * Clear the object table. This deletes all garbage-collected objects in
1544 * preparation for VM shutdown.
1545 */
1546 void CVmObjTable::clear_obj_table(VMG0_)
1547 {
1548 /* delete all entries in the post-load initialization table */
1549 post_load_init_table_->delete_all_entries();
1550
1551 /* go through the pages and delete the entries */
1552 for (size_t i = 0 ; i < pages_used_ ; ++i)
1553 {
1554 /* delete all of the objects on the page */
1555 int j;
1556 CVmObjPageEntry *entry;
1557 for (j = 0, entry = pages_[i] ; j < VM_OBJ_PAGE_CNT ; ++j, ++entry)
1558 {
1559 /* if this entry is still in use, delete it */
1560 if (!entry->free_)
1561 entry->get_vm_obj()->notify_delete(vmg_ entry->in_root_set_);
1562 }
1563 }
1564
1565 }
1566
1567 /*
1568 * Delete the table. (We need to separate this out into a method so
1569 * that we can get access to the global variables.)
1570 */
1571 void CVmObjTable::delete_obj_table(VMG0_)
1572 {
1573 /* delete each page we've allocated */
1574 for (size_t i = 0 ; i < pages_used_ ; ++i)
1575 t3free(pages_[i]);
1576
1577 /* free the master page table */
1578 t3free(pages_);
1579
1580 /* we no longer have any pages */
1581 pages_ = 0;
1582 page_slots_ = 0;
1583 pages_used_ = 0;
1584
1585 /* empty out the object lists */
1586 first_free_ = VM_INVALID_OBJ;
1587 gc_queue_head_ = VM_INVALID_OBJ;
1588 finalize_queue_head_ = VM_INVALID_OBJ;
1589
1590 /* clear the gc statistics */
1591 allocs_since_gc_ = 0;
1592 bytes_since_gc_ = 0;
1593
1594 /* delete each object image data pointer page */
1595 for (vm_image_ptr_page *ip_page = image_ptr_head_, *ip_next = 0 ;
1596 ip_page != 0 ; ip_page = ip_next)
1597 {
1598 /* remember the next page (before we delete this one) */
1599 ip_next = ip_page->next_;
1600
1601 /* delete this page */
1602 t3free(ip_page);
1603 }
1604
1605 /* there's nothing left in the image data list */
1606 image_ptr_head_ = image_ptr_tail_ = 0;
1607
1608 /* delete the linked list of globals */
1609 if (globals_ != 0)
1610 {
1611 delete globals_;
1612 globals_ = 0;
1613 }
1614
1615 /*
1616 * delete any left-over global variables (these should always be
1617 * deleted by subsystems before we get here, but this is the last
1618 * chance, so clean them up manually)
1619 */
1620 while (global_var_head_ != 0)
1621 delete_global_var(global_var_head_);
1622
1623 /* delete the post-load initialization table */
1624 delete post_load_init_table_;
1625 post_load_init_table_ = 0;
1626 }
1627
1628 /*
1629 * Enable or disable garbage collection
1630 */
1631 int CVmObjTable::enable_gc(VMG_ int enable)
1632 {
1633 /* remember the old status for returning */
1634 int old_enable = gc_enabled_;
1635
1636 /* set the new status */
1637 gc_enabled_ = enable;
1638
1639 /*
1640 * if we're enabling GC after it was previously disabled, check to
1641 * see if we should perform a GC pass now (but don't count this as a
1642 * separate allocation)
1643 */
1644 if (!old_enable && enable)
1645 alloc_check_gc(vmg_ FALSE);
1646
1647 /* return the previous status */
1648 return old_enable;
1649 }
1650
1651 /*
1652 * allocate a new object ID
1653 */
1654 vm_obj_id_t CVmObjTable::alloc_obj(VMG_ int in_root_set,
1655 int can_have_refs, int can_have_weak_refs)
1656 {
1657 /* count the allocation and maybe perform garbage collection */
1658 alloc_check_gc(vmg_ TRUE);
1659
1660 /* if the free list is empty, allocate a new page of object entries */
1661 if (first_free_ == VM_INVALID_OBJ)
1662 alloc_new_page();
1663
1664 /* remember the first item in the free list - this is our result */
1665 vm_obj_id_t ret = first_free_;
1666
1667 /* get the object table entry for the ID */
1668 CVmObjPageEntry *entry = get_entry(ret);
1669
1670 /* unlink new entry from the free list */
1671 first_free_ = entry->next_obj_;
1672 if (entry->next_obj_ != VM_INVALID_OBJ)
1673 get_entry(entry->next_obj_)->ptr_.prev_free_ = entry->ptr_.prev_free_;
1674
1675 /* initialize the entry */
1676 init_entry_for_alloc(ret, entry, in_root_set,
1677 can_have_refs, can_have_weak_refs);
1678
1679 /* return the free object */
1680 return ret;
1681 }
1682
1683 /*
1684 * Run garbage collection before allocating an object
1685 */
1686 void CVmObjTable::gc_before_alloc(VMG0_)
1687 {
1688 /* count it if in statistics mode */
1689 IF_GC_STATS(gc_stats.begin_pass());
1690
1691 /* run a full garbage collection pass */
1692 gc_pass_init(vmg0_);
1693 gc_pass_finish(vmg0_);
1694
1695 /* count it if in statistics mode */
1696 IF_GC_STATS(gc_stats.end_pass());
1697 }
1698
1699 /*
1700 * Allocate an object with a particular ID
1701 */
1702 void CVmObjTable::alloc_obj_with_id(vm_obj_id_t id, int in_root_set,
1703 int can_have_refs, int can_have_weak_refs)
1704 {
1705 CVmObjPageEntry *entry;
1706
1707 /*
1708 * if the page containing the given object ID hasn't been allocated,
1709 * allocate pages until it's available
1710 */
1711 while (id >= pages_used_ * VM_OBJ_PAGE_CNT)
1712 alloc_new_page();
1713
1714 /* get the object table entry for the ID */
1715 entry = get_entry(id);
1716
1717 /* if the desired object ID is already taken, it's an error */
1718 if (!entry->free_)
1719 err_throw(VMERR_OBJ_IN_USE);
1720
1721 /* unlink the item - set the previous item's forward pointer... */
1722 if (entry->ptr_.prev_free_ == VM_INVALID_OBJ)
1723 first_free_ = entry->next_obj_;
1724 else
1725 get_entry(entry->ptr_.prev_free_)->next_obj_ = entry->next_obj_;
1726
1727 /* ...and the next items back pointer */
1728 if (entry->next_obj_ != VM_INVALID_OBJ)
1729 get_entry(entry->next_obj_)->ptr_.prev_free_ = entry->ptr_.prev_free_;
1730
1731 /* initialize the entry for allocation */
1732 init_entry_for_alloc(id, entry, in_root_set,
1733 can_have_refs, can_have_weak_refs);
1734 }
1735
1736 /*
1737 * Initialize an object table entry that we've just allocated
1738 */
1739 void CVmObjTable::init_entry_for_alloc(vm_obj_id_t id,
1740 CVmObjPageEntry *entry,
1741 int in_root_set,
1742 int can_have_refs,
1743 int can_have_weak_refs)
1744 {
1745 /* mark the entry as in use */
1746 entry->free_ = FALSE;
1747
1748 /* no undo savepoint has been created since the object was created */
1749 entry->in_undo_ = FALSE;
1750
1751 /* mark the object as being in the root set if appropriate */
1752 entry->in_root_set_ = in_root_set;
1753
1754 /* presume it's an ordinary persistent object */
1755 entry->transient_ = FALSE;
1756
1757 /* presume it won't need post-load initialization */
1758 entry->requested_post_load_init_ = FALSE;
1759
1760 /* set the GC characteristics as requested */
1761 entry->can_have_refs_ = can_have_refs;
1762 entry->can_have_weak_refs_ = can_have_weak_refs;
1763
1764 /*
1765 * Mark the object as initially unreachable and unfinalizable. It's
1766 * not necessarily really unreachable at this point, but we mark it
1767 * as such because the garbage collector hasn't explicitly traced
1768 * the object to be reachable. The initial conditions for garbage
1769 * collection are that all objects not in the root set and not
1770 * finalizable are marked as unreachable; since we're not in a gc
1771 * pass right now (we can't be - memory cannot be allocated during a
1772 * gc pass), we know that we must establish initial gc conditions
1773 * for the next time we start a gc pass.
1774 */
1775 entry->reachable_ = VMOBJ_UNREACHABLE;
1776 entry->finalize_state_ = VMOBJ_UNFINALIZABLE;
1777
1778 /* add it to the GC work queue for the next GC pass */
1779 if (in_root_set)
1780 add_to_gc_queue(id, entry, VMOBJ_REACHABLE);
1781 }
1782
1783 #if 0 // moved to in-line in header, since it's called *a lot*
1784 /*
1785 * get the page entry for a given ID
1786 */
1787 CVmObjPageEntry *CVmObjTable::get_entry(vm_obj_id_t id) const
1788 {
1789 size_t main_idx;
1790 size_t page_idx;
1791
1792 /* get the index of the page in the main array */
1793 main_idx = (size_t)(id >> VM_OBJ_PAGE_CNT_LOG2);
1794
1795 /* get the index within the page */
1796 page_idx = (size_t)(id & (VM_OBJ_PAGE_CNT - 1));
1797
1798 /* get the object */
1799 return &pages_[main_idx][page_idx];
1800 }
1801 #endif
1802
1803 /*
1804 * Delete an object, given the object table entry.
1805 */
1806 void CVmObjTable::delete_entry(VMG_ vm_obj_id_t id, CVmObjPageEntry *entry)
1807 {
1808 /* mark the object table entry as free */
1809 entry->free_ = TRUE;
1810
1811 /* it's not in the root set if it's free */
1812 entry->in_root_set_ = FALSE;
1813
1814 /*
1815 * notify the object that it's being deleted - this will let the
1816 * object release any additional resources (such as variable-size
1817 * heap space) that it's holding
1818 */
1819 entry->get_vm_obj()->notify_delete(vmg_ FALSE);
1820
1821 /*
1822 * remove any post-load initialization request for the object, if it
1823 * ever requested post-load initialization
1824 */
1825 if (entry->requested_post_load_init_)
1826 remove_post_load_init(id);
1827
1828 /* link this object into the head of the free list */
1829 entry->next_obj_ = first_free_;
1830
1831 /* link the previous head back to this object */
1832 if (first_free_ != VM_INVALID_OBJ)
1833 get_entry(first_free_)->ptr_.prev_free_ = id;
1834
1835 /* this object doesn't have a previous entry */
1836 entry->ptr_.prev_free_ = VM_INVALID_OBJ;
1837
1838 /* it's now the first entry in the list */
1839 first_free_ = id;
1840 }
1841
1842
1843 /*
1844 * allocate a new page of objects
1845 */
1846 void CVmObjTable::alloc_new_page()
1847 {
1848 size_t i;
1849 vm_obj_id_t id;
1850 CVmObjPageEntry *entry;
1851
1852 /* first, make sure we have room in the master page list */
1853 if (pages_used_ == page_slots_)
1854 {
1855 /* increase the number of page slots */
1856 page_slots_ += 10;
1857
1858 /* allocate space for the increased number of slots */
1859 pages_ = (CVmObjPageEntry **)t3realloc(
1860 pages_, page_slots_ * sizeof(*pages_));
1861 }
1862
1863 /* allocate a new page */
1864 pages_[pages_used_] =
1865 (CVmObjPageEntry *)t3malloc(VM_OBJ_PAGE_CNT * sizeof(*pages_[0]));
1866
1867 /* if that failed, throw an error */
1868 if (pages_[pages_used_] == 0)
1869 err_throw(VMERR_OUT_OF_MEMORY);
1870
1871 /*
1872 * initialize the new page to be entirely free - add each element of
1873 * the page to the free list
1874 */
1875 entry = pages_[pages_used_];
1876 i = 0;
1877 id = pages_used_ * VM_OBJ_PAGE_CNT;
1878
1879 /*
1880 * if this is the start of the very first page, leave off the first
1881 * object, since its ID is invalid
1882 */
1883 if (id == VM_INVALID_OBJ)
1884 {
1885 /* mark the object as free so we don't try to free it later */
1886 entry->free_ = TRUE;
1887
1888 /* ...and it's certainly not a collectable object */
1889 entry->in_root_set_ = TRUE;
1890
1891 /* skip it for the impending free list construction */
1892 ++i;
1893 ++entry;
1894 ++id;
1895 }
1896
1897 /* loop over each object in this page */
1898 for ( ; i < VM_OBJ_PAGE_CNT ; ++i, ++entry, ++id)
1899 {
1900 /* set the forward pointer in this object */
1901 entry->next_obj_ = first_free_;
1902
1903 /* set the back pointer in the previous object in the list */
1904 if (first_free_ != VM_INVALID_OBJ)
1905 get_entry(first_free_)->ptr_.prev_free_ = id;
1906
1907 /* there's nothing before this entry yet */
1908 entry->ptr_.prev_free_ = VM_INVALID_OBJ;
1909
1910 /* this is now the head of the list */
1911 first_free_ = id;
1912
1913 /* mark it free */
1914 entry->free_ = TRUE;
1915
1916 /* presume it's not part of the root set */
1917 entry->in_root_set_ = FALSE;
1918
1919 /*
1920 * mark it initially unreachable and finalized, since it's not
1921 * even allocated yet
1922 */
1923 entry->reachable_ = VMOBJ_UNREACHABLE;
1924 entry->finalize_state_ = VMOBJ_FINALIZED;
1925 }
1926
1927 /* count the new page we've allocated */
1928 ++pages_used_;
1929 }
1930
1931 /*
1932 * Add an object to the list of machine globals.
1933 */
1934 void CVmObjTable::add_to_globals(vm_obj_id_t obj)
1935 {
1936 CVmObjGlobPage *pg;
1937
1938 /*
1939 * if this is a root set object, there is no need to mark it as
1940 * global, since it is inherently uncollectable as an image file
1941 * object to begin with
1942 */
1943 if (get_entry(obj)->in_root_set_)
1944 return;
1945
1946 /* if we have any global pages allocated, try adding to the head page */
1947 if (globals_ != 0 && globals_->add_entry(obj))
1948 {
1949 /* we successfully added it to the head page - we're done */
1950 return;
1951 }
1952
1953 /*
1954 * either the head page is full, or we haven't allocated any global
1955 * pages at all yet; in either case, allocate a new page and link it
1956 * at the head of our list
1957 */
1958 pg = new CVmObjGlobPage();
1959 pg->nxt_ = globals_;
1960 globals_ = pg;
1961
1962 /*
1963 * add the object to the new page - it must fit, since the new page is
1964 * empty
1965 */
1966 globals_->add_entry(obj);
1967 }
1968
1969 /*
1970 * Collect all garbage. This does a complete garbage collection pass,
1971 * returning only after all unreachable objects have been collected. If
1972 * incremental garbage collection is not required, the caller can simply
1973 * invoke this routine to do the entire operation in a single call.
1974 */
1975 void CVmObjTable::gc_full(VMG0_)
1976 {
1977 /* count it if in statistics mode */
1978 IF_GC_STATS(gc_stats.begin_pass());
1979
1980 /*
1981 * run the initial pass to mark globally-reachable objects, then run
1982 * the garbage collector to completion
1983 */
1984 gc_pass_init(vmg0_);
1985 gc_pass_finish(vmg0_);
1986
1987 /* count it if in statistics mode */
1988 IF_GC_STATS(gc_stats.end_pass());
1989 }
1990
1991 /*
1992 * Garbage collector - initialize. Add all globally-reachable objects
1993 * to the work queue.
1994 *
1995 * We assume that the following initial conditions hold: all objects
1996 * except root set objects are marked as unreferenced, and all root set
1997 * objects are marked as referenced; all root set objects are in the GC
1998 * work queue. So, we don't need to worry about finding root objects or
1999 * initializing the other objects at this point.
2000 */
2001 void CVmObjTable::gc_pass_init(VMG0_)
2002 {
2003 /*
2004 * reset the allocations-since-gc counter, since this is now the
2005 * last gc pass, and we obviously haven't performed any allocations
2006 * since this gc pass yet
2007 */
2008 allocs_since_gc_ = 0;
2009 bytes_since_gc_ = 0;
2010
2011 /* trace objects reachable from the stack */
2012 gc_trace_stack(vmg0_);
2013
2014 /* trace objects reachable from imports */
2015 gc_trace_imports(vmg0_);
2016
2017 /* trace objects reachable from machine globals */
2018 gc_trace_globals(vmg0_);
2019
2020 /*
2021 * Process undo records - for each undo record, mark any referenced
2022 * objects as reachable. Undo records are part of the root set.
2023 */
2024 G_undo->gc_mark_refs(vmg0_);
2025 }
2026
2027 /*
2028 * Garbage collection - continue processing the work queue. This
2029 * processes a set of entries from the work queue. This routine can be
2030 * used for incremental garbage collection: after calling
2031 * gc_pass_init(), the caller can repeatedly invoke this routine until
2032 * it returns false. Since this routine will return after a short time
2033 * even if there's more work left to do, other operations (such as
2034 * processing user input) can be interleaved in a single thread with
2035 * garbage collection.
2036 *
2037 * The actual number of entries that we process is configurable at VM
2038 * compile-time via VM_GC_WORK_INCREMENT. The point of running the GC
2039 * incrementally is to allow GC work to be interleaved with long-running
2040 * user I/O operations (such as reading a line of text from the
2041 * keyboard) in the foreground thread, so the work increment should be
2042 * chosen so that each call to this routine completes quickly enough
2043 * that the user will perceive no delay.
2044 *
2045 * Returns true if more work remains to be done, false if not. The
2046 * caller should invoke this routine repeatedly until it returns false.
2047 */
2048 int CVmObjTable::gc_pass_continue(VMG_ int trace_transient)
2049 {
2050 int cnt;
2051
2052 /*
2053 * keep going until we exhaust the queue or run for our maximum
2054 * number of iterations
2055 */
2056 for (cnt = VM_GC_WORK_INCREMENT ;
2057 cnt != 0 && gc_queue_head_ != VM_INVALID_OBJ ; --cnt)
2058 {
2059 vm_obj_id_t cur;
2060 CVmObjPageEntry *entry;
2061
2062 /* get the next item from the work queue */
2063 cur = gc_queue_head_;
2064
2065 /* get this object's entry */
2066 entry = get_entry(cur);
2067
2068 /* remove this entry from the work queue */
2069 gc_queue_head_ = entry->next_obj_;
2070
2071 /*
2072 * Tell this object to mark its references. Mark the referenced
2073 * objects with the same state as this object, if they're not
2074 * already marked with a stronger state.
2075 *
2076 * If we're not tracing transients, do not trace this object if
2077 * it's transient.
2078 */
2079 if (trace_transient || !entry->transient_)
2080 entry->get_vm_obj()->mark_refs(vmg_ entry->reachable_);
2081 }
2082
2083 /*
2084 * return true if there's more work to do; there's more work to do
2085 * if we have any objects left in the gc work queue
2086 */
2087 return gc_queue_head_ != VM_INVALID_OBJ;
2088 }
2089
2090 /*
2091 * Finish garbage collection. We'll finish any work remaining in the
2092 * work queue, so this is safe to call at any time after gc_pass_init(),
2093 * after any number of calls (even zero) to gc_pass_continue().
2094 */
2095 void CVmObjTable::gc_pass_finish(VMG0_)
2096 {
2097 CVmObjPageEntry **pg;
2098 CVmObjPageEntry *entry;
2099 size_t i;
2100 size_t j;
2101 vm_obj_id_t id;
2102
2103 /*
2104 * Make sure we're done processing the work queue -- keep calling
2105 * gc_pass_continue() until it indicates that it's finished. If
2106 * we're skipping finalizers, stop as soon as the state structure
2107 * indicates that we've started running finalizers.
2108 */
2109 gc_trace_work_queue(vmg_ TRUE);
2110
2111 /*
2112 * We've now marked everything that's reachable from the root set as
2113 * VMOBJ_REACHABLE. We can therefore determine the set of objects
2114 * that are newly 'finalizable' - an object becomes finalizable when
2115 * it was previously 'unfinalizable' and is not reachable, because we
2116 * can finalize an object any time after it first becomes unreachable.
2117 * So, scan all objects for eligibility for the 'finalizable'
2118 * transition, and make the transition in those objects.
2119 */
2120 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2121 {
2122 /* go through each entry on this page */
2123 for (j = VM_OBJ_PAGE_CNT, entry = *pg ; j > 0 ; --j, ++entry, ++id)
2124 {
2125 /*
2126 * if this entry is not free and is not in the root set, check
2127 * to see if its finalization status is changing
2128 */
2129 if (!entry->free_ && !entry->in_root_set_)
2130 {
2131 /*
2132 * If the entry is not reachable, and was previously
2133 * unfinalizable, it is now finalizable.
2134 *
2135 * Note that an object must actually be reachable to avoid
2136 * become finalizable at this point. Not only do
2137 * unreachable objects become finalizable, but
2138 * 'f-reachable' objects do, too, since these are only
2139 * reachable from other finalizable objects.
2140 */
2141 if (entry->reachable_ != VMOBJ_REACHABLE
2142 && entry->finalize_state_ == VMOBJ_UNFINALIZABLE)
2143 {
2144 /*
2145 * This object is newly finalizable. If it has no
2146 * finalizer, the object can go directly to the
2147 * 'finalized' state; otherwise, add it to the queue
2148 * of objects with pending finalizers.
2149 */
2150 if (entry->get_vm_obj()->has_finalizer(vmg_ id))
2151 {
2152 /*
2153 * This object is not reachable from the root set
2154 * and was previously unfinalizable. Make the
2155 * object finalizable.
2156 */
2157 entry->finalize_state_ = VMOBJ_FINALIZABLE;
2158 }
2159 else
2160 {
2161 /*
2162 * the entry has no finalizer, so we can make this
2163 * object 'finalized' immediately
2164 */
2165 entry->finalize_state_ = VMOBJ_FINALIZED;
2166 }
2167
2168 /* count it as a collected object */
2169 IF_GC_STATS(gc_stats.count_free());
2170 }
2171
2172 /*
2173 * If this object is finalizable, add it to the work queue
2174 * in state "f-reachable." We must mark everything this
2175 * object references, directly or indirectly, as
2176 * f-reachable, which we'll do with another pass through
2177 * the gc queue momentarily.
2178 */
2179 if (entry->finalize_state_ == VMOBJ_FINALIZABLE)
2180 {
2181 /*
2182 * this object and all of the objects it references
2183 * are "f-reachable"
2184 */
2185 add_to_gc_queue(id, entry, VMOBJ_F_REACHABLE);
2186 }
2187 }
2188 }
2189 }
2190
2191 /*
2192 * During the scan above, we put all of the finalizable objects in the
2193 * work queue in reachability state 'f-reachable'. (Actually,
2194 * finalizable objects that were fully reachable were not put in the
2195 * work queue, because they are in a stronger reachability state that
2196 * we've already fully scanned.) Trace the work queue so that we mark
2197 * everything reachable indirectly from an f-reachable object as also
2198 * being at least f-reachable.
2199 */
2200 gc_trace_work_queue(vmg_ TRUE);
2201
2202 /*
2203 * We have now marked everything that's fully reachable as being in
2204 * state 'reachable', and everything that's reachable from a
2205 * finalizable object as being in state 'f-reachable'. Anything that
2206 * is still in state 'unreachable' is garbage and can be collected.
2207 */
2208 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2209 {
2210 /* go through each entry on this page */
2211 for (j = VM_OBJ_PAGE_CNT, entry = *pg ; j > 0 ; --j, ++entry, ++id)
2212 {
2213 /* if it's not already free, process it */
2214 if (!entry->free_)
2215 {
2216 /* if the object is deletable, delete it */
2217 if (entry->is_deletable())
2218 {
2219 /*
2220 * This object is completely unreachable, and it has
2221 * already been finalized. This means there is no
2222 * possibility that the object could ever become
2223 * reachable again, hence we can discard the object.
2224 */
2225 delete_entry(vmg_ id, entry);
2226 }
2227 else
2228 {
2229 /*
2230 * The object is reachable, so keep it around. Since
2231 * it's staying around, and since we know which
2232 * objects we're deleting and which are staying, we
2233 * can ask this object to remove all of its "stale
2234 * weak references" - that is, weak references to
2235 * objects that we're about to delete. Don't bother
2236 * notifying the object if it's incapable of keeping
2237 * weak references.
2238 */
2239 if (entry->can_have_weak_refs_)
2240 entry->get_vm_obj()->remove_stale_weak_refs(vmg0_);
2241
2242 /*
2243 * If this object is finalizable, put it in the
2244 * finalizer queue, so that we can run its finalizer
2245 * when we're done scanning the table.
2246 */
2247 if (entry->finalize_state_ == VMOBJ_FINALIZABLE)
2248 add_to_finalize_queue(id, entry);
2249
2250 /*
2251 * restore initial conditions for this object, so that
2252 * we're properly set up for the next GC pass
2253 */
2254 gc_set_init_conditions(id, entry);
2255 }
2256 }
2257 }
2258 }
2259
2260 /*
2261 * Go through the undo records and clear any stale weak references
2262 * contained in the undo list.
2263 */
2264 G_undo->gc_remove_stale_weak_refs(vmg0_);
2265
2266 /*
2267 * All of the finalizable objects are now in the finalizer queue. Run
2268 * through the finalizer queue and run each such object's finalizer.
2269 */
2270 run_finalizers(vmg0_);
2271 }
2272
2273 /*
2274 * Trace all objects reachable from the work queue.
2275 */
2276 void CVmObjTable::gc_trace_work_queue(VMG_ int trace_transient)
2277 {
2278 /*
2279 * trace everything reachable directly from the work queue, until we
2280 * exhaust the queue
2281 */
2282 while (gc_pass_continue(vmg_ trace_transient)) ;
2283 }
2284
2285 /*
2286 * Garbage collection: trace objects reachable from the stack
2287 */
2288 void CVmObjTable::gc_trace_stack(VMG0_)
2289 {
2290 size_t i;
2291 size_t depth;
2292 vm_val_t *val;
2293
2294 /*
2295 * Process the stack. For each stack element that refers to an
2296 * object, mark the object as referenced and add it to the work
2297 * queue.
2298 *
2299 * Note that it makes no difference in what order we process the
2300 * stack elements; we go from depth down to 0 merely as a trivial
2301 * micro-optimization to avoid evaluating the stack depth on every
2302 * iteration of the loop.
2303 */
2304 for (i = 0, depth = G_stk->get_depth() ; i < depth ; ++i)
2305 {
2306 /*
2307 * If this element refers to an object, and the object hasn't
2308 * already been marked as referenced, mark it as reachable and
2309 * add it to the work queue.
2310 *
2311 * Note that we only have to worry about objects here. We don't
2312 * have to worry about constant lists, even though they can
2313 * contain object references, because any object reference in a
2314 * constant list must be a root set object, and we've already
2315 * processed all root set objects.
2316 */
2317 val = G_stk->get(i);
2318 if (val->typ == VM_OBJ && val->val.obj != VM_INVALID_OBJ)
2319 add_to_gc_queue(val->val.obj, VMOBJ_REACHABLE);
2320 }
2321 }
2322
2323 /*
2324 * Trace objects reachable from imports
2325 */
2326 void CVmObjTable::gc_trace_imports(VMG0_)
2327 {
2328 /*
2329 * generate the list of object imports; for each one, if we have a
2330 * valid object for the import, mark it as reachable
2331 */
2332 #define VM_IMPORT_OBJ(sym, mem) \
2333 if (G_predef->mem != VM_INVALID_OBJ) \
2334 add_to_gc_queue(G_predef->mem, VMOBJ_REACHABLE);
2335 #define VM_NOIMPORT_OBJ(sym, mem) VM_IMPORT_OBJ(sym, mem)
2336 #include "vmimport.h"
2337 }
2338
2339 /*
2340 * Garbage collection: trace objects reachable from the machine globals
2341 */
2342 void CVmObjTable::gc_trace_globals(VMG0_)
2343 {
2344 CVmObjGlobPage *pg;
2345 vm_val_t *val;
2346 vm_globalvar_t *var;
2347
2348 /* trace each page of globals */
2349 for (pg = globals_ ; pg != 0 ; pg = pg->nxt_)
2350 {
2351 size_t i;
2352 vm_obj_id_t *objp;
2353
2354 /* trace each item on this page */
2355 for (objp = pg->objs_, i = pg->used_ ; i != 0 ; ++objp, --i)
2356 {
2357 /* trace this global */
2358 add_to_gc_queue(*objp, VMOBJ_REACHABLE);
2359 }
2360 }
2361
2362 /* the return value register (R0) is a machine global */
2363 val = G_interpreter->get_r0();
2364 if (val->typ == VM_OBJ && val->val.obj != VM_INVALID_OBJ)
2365 add_to_gc_queue(val->val.obj, VMOBJ_REACHABLE);
2366
2367 /* trace the global variables defined by other subsystems */
2368 for (var = global_var_head_ ; var != 0 ; var = var->nxt)
2369 {
2370 /* if this global variable contains an object, trace it */
2371 if (var->val.typ == VM_OBJ && var->val.val.obj != VM_INVALID_OBJ)
2372 add_to_gc_queue(var->val.val.obj, VMOBJ_REACHABLE);
2373 }
2374 }
2375
2376 #if 0 // moved inline, as it's small and is called a fair amount
2377 /*
2378 * Set the initial conditions for an object, in preparation for the next
2379 * GC pass.
2380 */
2381 void CVmObjTable::gc_set_init_conditions(vm_obj_id_t id,
2382 CVmObjPageEntry *entry)
2383 {
2384 /*
2385 * Mark the object as unreachable -- at the start of each GC pass,
2386 * all non-root-set objects must be marked unreachable.
2387 */
2388 entry->reachable_ = VMOBJ_UNREACHABLE;
2389
2390 /*
2391 * If it's in the root set, add it to the GC work queue -- all
2392 * root-set objects must be in the work queue and marked as reachable
2393 * at the start of each GC pass.
2394 *
2395 * If the object is not in the root set, check to see if it's
2396 * finalizable. If so, add it to the finalizer queue, so that we
2397 * eventually run its finalizer.
2398 */
2399 if (entry->in_root_set_)
2400 add_to_gc_queue(id, entry, VMOBJ_REACHABLE);
2401 }
2402 #endif
2403
2404 /*
2405 * Run finalizers
2406 */
2407 void CVmObjTable::run_finalizers(VMG0_)
2408 {
2409 /* keep going until we run out of work or reach our work limit */
2410 while (finalize_queue_head_ != VM_INVALID_OBJ)
2411 {
2412 CVmObjPageEntry *entry;
2413 vm_obj_id_t id;
2414
2415 /* get the next object from the queue */
2416 id = finalize_queue_head_;
2417
2418 /* get the entry */
2419 entry = get_entry(id);
2420
2421 /* remove the entry form the queue */
2422 finalize_queue_head_ = entry->next_obj_;
2423
2424 /* mark the object as finalized */
2425 entry->finalize_state_ = VMOBJ_FINALIZED;
2426
2427 /*
2428 * the entry is no longer in any queue, so we must mark it as
2429 * unreachable -- this ensures that the initial conditions are
2430 * correct for the next garbage collection pass, since all
2431 * objects not in the work queue must be marked as unreachable
2432 * (it doesn't matter whether the object is actually reachable;
2433 * the garbage collector will make that determination when it
2434 * next runs)
2435 */
2436 entry->reachable_ = VMOBJ_UNREACHABLE;
2437
2438 /* invoke its finalizer */
2439 entry->get_vm_obj()->invoke_finalizer(vmg_ id);
2440 }
2441 }
2442
2443
2444 /*
2445 * Receive notification that we're creating a new undo savepoint
2446 */
2447 void CVmObjTable::notify_new_savept()
2448 {
2449 CVmObjPageEntry **pg;
2450 CVmObjPageEntry *entry;
2451 size_t i;
2452 size_t j;
2453 vm_obj_id_t id;
2454
2455 /* go through each page of objects */
2456 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2457 {
2458 /* go through each entry on this page */
2459 for (j = VM_OBJ_PAGE_CNT, entry = *pg ; j > 0 ; --j, ++entry, ++id)
2460 {
2461 /* if this entry is active, tell it about the new savepoint */
2462 if (!entry->free_)
2463 {
2464 /*
2465 * the object existed at the start of this savepoint, so
2466 * it must keep undo information throughout the savepoint
2467 */
2468 entry->in_undo_ = TRUE;
2469
2470 /* notify the object of the new savepoint */
2471 entry->get_vm_obj()->notify_new_savept();
2472 }
2473 }
2474 }
2475 }
2476
2477 /*
2478 * Call a callback for each object in the table
2479 */
2480 void CVmObjTable::for_each(VMG_ void (*func)(VMG_ vm_obj_id_t, void *),
2481 void *ctx)
2482 {
2483 CVmObjPageEntry **pg;
2484 size_t i;
2485 vm_obj_id_t id;
2486
2487 /* go through each page in the object table */
2488 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2489 {
2490 /* start at the start of the page */
2491 size_t j = VM_OBJ_PAGE_CNT;
2492 CVmObjPageEntry *entry = *pg;
2493
2494 /* go through each entry on this page */
2495 for ( ; j > 0 ; --j, ++entry, ++id)
2496 {
2497 /* if this entry is in use, invoke the callback */
2498 if (!entry->free_)
2499 (*func)(vmg_ id, ctx);
2500 }
2501 }
2502 }
2503
2504 /*
2505 * Apply undo
2506 */
2507 void CVmObjTable::apply_undo(VMG_ CVmUndoRecord *rec)
2508 {
2509 /* tell the object to apply the undo */
2510 if (rec->obj != VM_INVALID_OBJ)
2511 get_obj(rec->obj)->apply_undo(vmg_ rec);
2512 }
2513
2514
2515 /*
2516 * Scan all objects and add metaclass entries to the metaclass
2517 * dependency table for any metaclasses of which there are existing
2518 * instances.
2519 */
2520 void CVmObjTable::add_metadeps_for_instances(VMG0_)
2521 {
2522 CVmObjPageEntry **pg;
2523 size_t i;
2524 vm_obj_id_t id;
2525
2526 /* go through each page in the object table */
2527 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2528 {
2529 size_t j;
2530 CVmObjPageEntry *entry;
2531
2532 /* start at the start of the page, but skip object ID = 0 */
2533 j = VM_OBJ_PAGE_CNT;
2534 entry = *pg;
2535
2536 /* go through each entry on this page */
2537 for ( ; j > 0 ; --j, ++entry, ++id)
2538 {
2539 /* if this entry is in use, add its metaclass if necessary */
2540 if (!entry->free_)
2541 G_meta_table->add_entry_if_new(
2542 entry->get_vm_obj()->get_metaclass_reg()->get_reg_idx(),
2543 0, VM_INVALID_PROP, VM_INVALID_PROP);
2544 }
2545 }
2546 }
2547
2548
2549 /* ------------------------------------------------------------------------ */
2550 /*
2551 * creation
2552 */
2553 CVmObjFixup::CVmObjFixup(ulong entry_cnt)
2554 {
2555 uint i;
2556
2557 /* remember the number of entries */
2558 cnt_ = entry_cnt;
2559
2560 /* no entries are used yet */
2561 used_ = 0;
2562
2563 /* if we have no entries, there's nothing to do */
2564 if (cnt_ == 0)
2565 {
2566 arr_ = 0;
2567 pages_ = 0;
2568 return;
2569 }
2570
2571 /* calculate the number of subarrays we need */
2572 pages_ = (entry_cnt + VMOBJFIXUP_SUB_SIZE - 1) / VMOBJFIXUP_SUB_SIZE;
2573
2574 /* allocate the necessary number of subarrays */
2575 arr_ = (obj_fixup_entry **)t3malloc(pages_ * sizeof(arr_[0]));
2576
2577 /* allocate the subarrays */
2578 for (i = 0 ; i < pages_ ; ++i)
2579 {
2580 size_t cur_cnt;
2581
2582 /*
2583 * allocate a full page, except for the last page, which might be
2584 * only partially used
2585 */
2586 cur_cnt = VMOBJFIXUP_SUB_SIZE;
2587 if (i + 1 == pages_)
2588 cur_cnt = ((entry_cnt - 1) % VMOBJFIXUP_SUB_SIZE) + 1;
2589
2590 /* allocate it */
2591 arr_[i] = (obj_fixup_entry *)t3malloc(cur_cnt * sizeof(arr_[i][i]));
2592 }
2593 }
2594
2595 /*
2596 * deletion
2597 */
2598 CVmObjFixup::~CVmObjFixup()
2599 {
2600 uint i;
2601
2602 /* if we never allocated an array, there's nothing to do */
2603 if (arr_ == 0)
2604 return;
2605
2606 /* delete each subarray */
2607 for (i = 0 ; i < pages_ ; ++i)
2608 t3free(arr_[i]);
2609
2610 /* delete the main array */
2611 t3free(arr_);
2612 }
2613
2614 /*
2615 * add a fixup
2616 */
2617 void CVmObjFixup::add_fixup(vm_obj_id_t old_id, vm_obj_id_t new_id)
2618 {
2619 obj_fixup_entry *entry;
2620
2621 /* allocate the next available entry */
2622 entry = get_entry(used_++);
2623
2624 /* store it */
2625 entry->old_id = old_id;
2626 entry->new_id = new_id;
2627 }
2628
2629 /*
2630 * translate an ID
2631 */
2632 vm_obj_id_t CVmObjFixup::get_new_id(VMG_ vm_obj_id_t old_id)
2633 {
2634 /*
2635 * if it's a root-set object, don't bother even trying to translate
2636 * it, because root-set objects have stable ID's that never change on
2637 * saving or restoring
2638 */
2639 if (G_obj_table->is_obj_id_valid(old_id)
2640 && G_obj_table->is_obj_in_root_set(old_id))
2641 return old_id;
2642
2643 /* find the entry by the object ID */
2644 obj_fixup_entry *entry = find_entry(old_id);
2645
2646 /*
2647 * if we found it, return the new ID; otherwise, return the old ID
2648 * unchanged, since the ID evidently doesn't require mapping
2649 */
2650 return (entry != 0 ? entry->new_id : old_id);
2651 }
2652
2653 /*
2654 * find an entry given the old object ID
2655 */
2656 obj_fixup_entry *CVmObjFixup::find_entry(vm_obj_id_t old_id)
2657 {
2658 /* do a binary search for the entry */
2659 ulong cur;
2660 ulong lo = 0;
2661 ulong hi = cnt_ - 1;
2662 while (lo <= hi)
2663 {
2664 /* split the difference */
2665 cur = lo + (hi - lo)/2;
2666 obj_fixup_entry *entry = get_entry(cur);
2667
2668 /* is it the one we're looking for? */
2669 if (entry->old_id == old_id)
2670 {
2671 /* it's the one - return the entry */
2672 return entry;
2673 }
2674 else if (old_id > entry->old_id)
2675 {
2676 /* we need to go higher */
2677 lo = (cur == lo ? cur + 1 : cur);
2678 }
2679 else
2680 {
2681 /* we need to go lower */
2682 hi = (cur == hi ? cur - 1 : cur);
2683 }
2684 }
2685
2686 /* didn't find it */
2687 return 0;
2688 }
2689
2690 /*
2691 * Fix a DATAHOLDER value
2692 */
2693 void CVmObjFixup::fix_dh(VMG_ char *dh)
2694 {
2695 /* if it's an object, translate the ID */
2696 if (vmb_get_dh_type(dh) == VM_OBJ)
2697 {
2698 vm_obj_id_t id;
2699
2700 /* get the object value */
2701 id = vmb_get_dh_obj(dh);
2702
2703 /* translate it */
2704 id = get_new_id(vmg_ id);
2705
2706 /*
2707 * if it's invalid, set the dataholder value to nil; otherwise,
2708 * set it to the new object ID
2709 */
2710 if (id == VM_INVALID_OBJ)
2711 vmb_put_dh_nil(dh);
2712 else
2713 vmb_put_dh_obj(dh, id);
2714 }
2715 }
2716
2717 /*
2718 * Fix up an array of DATAHOLDER values.
2719 */
2720 void CVmObjFixup::fix_dh_array(VMG_ char *arr, size_t cnt)
2721 {
2722 /* scan the array of dataholders */
2723 for ( ; cnt != 0 ; --cnt, arr += VMB_DATAHOLDER)
2724 fix_dh(vmg_ arr);
2725 }
2726
2727 /*
2728 * Fix a portable VMB_OBJECT_ID field
2729 */
2730 void CVmObjFixup::fix_vmb_obj(VMG_ char *p)
2731 {
2732 vm_obj_id_t id;
2733
2734 /* get the old ID */
2735 id = vmb_get_objid(p);
2736
2737 /* fix it up */
2738 id = get_new_id(vmg_ id);
2739
2740 /* store it back */
2741 vmb_put_objid(p, id);
2742 }
2743
2744 /*
2745 * Fix an array of portable VMB_OBJECT_ID fields
2746 */
2747 void CVmObjFixup::fix_vmb_obj_array(VMG_ char *p, size_t cnt)
2748 {
2749 /* scan the array */
2750 for ( ; cnt != 0 ; --cnt, p += VMB_OBJECT_ID)
2751 fix_vmb_obj(vmg_ p);
2752 }
2753
2754
2755 /* ------------------------------------------------------------------------ */
2756 /*
2757 * Save/restore
2758 */
2759
2760 /*
2761 * table-of-contents flags
2762 */
2763
2764 /* object is transient (so the object isn't saved to the state file) */
2765 #define VMOBJ_TOC_TRANSIENT 0x0001
2766
2767
2768 /*
2769 * Save state to a file
2770 */
2771 void CVmObjTable::save(VMG_ CVmFile *fp)
2772 {
2773 CVmObjPageEntry **pg;
2774 CVmObjPageEntry *entry;
2775 size_t i;
2776 size_t j;
2777 vm_obj_id_t id;
2778 size_t toc_cnt;
2779 size_t save_cnt;
2780 long toc_cnt_pos;
2781 long end_pos;
2782
2783 /*
2784 * Before we save, perform a full GC pass. This will ensure that we
2785 * have removed all objects that are referenced only weakly, and
2786 * cleaned up the weak references to them; this is important because
2787 * we don't trace weak references for the purposes of calculating the
2788 * set of objects that must be saved, and hence won't save any objects
2789 * that are only weakly referenced, which would leave dangling
2790 * references in the saved state if those weak references weren't
2791 * cleaned up before the objects containing them are saved.
2792 */
2793 gc_full(vmg0_);
2794
2795 /*
2796 * Make sure that all of the metaclasses that we are actually using
2797 * are in the metaclass dependency table. We store the table in the
2798 * file, because the table provides the mapping from file-local
2799 * metaclass ID's to actual metaclasses; we must make sure that the
2800 * table is complete (i.e., contains an entry for each metaclass of
2801 * which there is an instance) before storing the table.
2802 */
2803 add_metadeps_for_instances(vmg0_);
2804
2805 /* save the metaclass table */
2806 G_meta_table->write_to_file(fp);
2807
2808 /*
2809 * Figure out what objects we need to save. We only need to save
2810 * objects that are directly reachable from the root object set, from
2811 * the imports, or from the globals.
2812 *
2813 * We don't need to save objects that are only accessible from the
2814 * undo, because we don't save any undo information in the file. We
2815 * also don't need to save any objects that are reachable only from
2816 * the stack, since the stack is inherently transient.
2817 *
2818 * Note that we don't need to trace from transient objects, since we
2819 * won't be saving the transient objects and thus won't need to save
2820 * anything referenced only from transient objects.
2821 *
2822 * So, we merely trace objects reachable from the imports, globals,
2823 * and work queue. At any time between GC passes, the work queue
2824 * contains the complete list of root-set objects, hence we can simply
2825 * trace from the current work queue.
2826 */
2827 gc_trace_imports(vmg0_);
2828 gc_trace_globals(vmg0_);
2829 gc_trace_work_queue(vmg_ FALSE);
2830
2831 /*
2832 * Before we save the objects themselves, save a table of contents of
2833 * the dynamically-allocated objects to be saved. This table of
2834 * contents will allow us to fix up references to objects on reloading
2835 * the file with the new object numbers we assign them at that time.
2836 * First, write a placeholder for the table of contents entry count.
2837 *
2838 * Note that we must store the table of contents in ascending order of
2839 * object ID. This happens naturally, since we scan the table in
2840 * order of object ID.
2841 */
2842 toc_cnt = 0;
2843 save_cnt = 0;
2844 toc_cnt_pos = fp->get_pos();
2845 fp->write_uint4(0);
2846
2847 /* now scan the object pages and save the table of contents */
2848 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2849 {
2850 /* scan all objects on this page */
2851 for (j = VM_OBJ_PAGE_CNT, entry = *pg ; j > 0 ; -- j, ++entry, ++id)
2852 {
2853 /*
2854 * If the entry is currently reachable, and it was dynamically
2855 * allocated (which means it's not in the root set), then add
2856 * it to the table of contents. Note that we won't
2857 * necessarily be saving the object, because the object could
2858 * be transient - but if so, then we still want the record of
2859 * the transient object, so we'll know on reloading that the
2860 * object is no longer available.
2861 */
2862 if (!entry->free_
2863 && entry->reachable_ == VMOBJ_REACHABLE
2864 && !entry->in_root_set_)
2865 {
2866 ulong flags;
2867
2868 /* set up the flags */
2869 flags = 0;
2870 if (entry->transient_)
2871 flags |= VMOBJ_TOC_TRANSIENT;
2872
2873 /* write the object ID and flags */
2874 fp->write_uint4(id);
2875 fp->write_uint4(flags);
2876
2877 /* count it */
2878 ++toc_cnt;
2879 }
2880
2881 /* if it's saveable, count it among the saveable objects */
2882 if (entry->is_saveable())
2883 ++save_cnt;
2884 }
2885 }
2886
2887 /* go back and fix up the size prefix for the table of contents */
2888 end_pos = fp->get_pos();
2889 fp->set_pos(toc_cnt_pos);
2890 fp->write_uint4(toc_cnt);
2891 fp->set_pos(end_pos);
2892
2893 /* write the saveable object count, which we calculated above */
2894 fp->write_uint4(save_cnt);
2895
2896 /* scan all object pages, and save each reachable object */
2897 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
2898 {
2899 /* scan all objects on this page */
2900 for (j = VM_OBJ_PAGE_CNT, entry = *pg ; j > 0 ; -- j, ++entry, ++id)
2901 {
2902 /* if this object is saveable, save it */
2903 if (entry->is_saveable())
2904 {
2905 uint idx;
2906 char buf[2];
2907
2908 /* write the object ID */
2909 fp->write_uint4(id);
2910
2911 /* store the root-set flag */
2912 buf[0] = (entry->in_root_set_ != 0);
2913
2914 /* store the dependency table index */
2915 idx = entry->get_vm_obj()->
2916 get_metaclass_reg()->get_reg_idx();
2917 buf[1] = (char)G_meta_table->get_dependency_index(idx);
2918
2919 /* write the data */
2920 fp->write_bytes(buf, 2);
2921
2922 /* save the metaclass-specific state */
2923 entry->get_vm_obj()->save_to_file(vmg_ fp);
2924 }
2925
2926 /*
2927 * restore this object to the appropriate conditions in
2928 * preparation for the next GC pass, so that we leave things
2929 * as we found them -- saving the VM's state thus has no
2930 * effect on the VM's state
2931 */
2932 gc_set_init_conditions(id, entry);
2933 }
2934 }
2935 }
2936
2937 /*
2938 * Restore state from a file
2939 */
2940 int CVmObjTable::restore(VMG_ CVmFile *fp, CVmObjFixup **fixups)
2941 {
2942 int err;
2943 ulong cnt;
2944
2945 /* presume we won't create a fixup table */
2946 *fixups = 0;
2947
2948 /* load the metaclass table */
2949 if ((err = G_meta_table->read_from_file(fp)) != 0)
2950 return err;
2951
2952 /*
2953 * Reset all objects to the initial image file load state. Note that
2954 * we wait until after we've read the metaclass table to reset the
2955 * objects, because any intrinsic class objects in the root set will
2956 * need to re-initialize their presence in the metaclass table, which
2957 * they can't do until after the metaclass table has itself been
2958 * reloaded.
2959 */
2960 G_obj_table->reset_to_image(vmg0_);
2961
2962 /* read the size of the table of contents */
2963 cnt = fp->read_uint4();
2964
2965 /* allocate the fixup table */
2966 *fixups = new CVmObjFixup(cnt);
2967
2968 /* read the fixup table */
2969 for ( ; cnt != 0 ; --cnt)
2970 {
2971 vm_obj_id_t old_id;
2972 vm_obj_id_t new_id;
2973 ulong flags;
2974
2975 /* read the next entry */
2976 old_id = (vm_obj_id_t)fp->read_uint4();
2977 flags = fp->read_uint4();
2978
2979 /*
2980 * Allocate a new object ID for this entry. If the object was
2981 * transient, then it won't actually have been saved, so we must
2982 * fix up references to the object to nil.
2983 */
2984 if (!(flags & VMOBJ_TOC_TRANSIENT))
2985 new_id = vm_new_id(vmg_ FALSE);
2986 else
2987 new_id = VM_INVALID_OBJ;
2988
2989 /*
2990 * Add the entry. Note that the table of contents is stored in
2991 * ascending order of old ID (i.e., the ID's in the saved state
2992 * file's numbering system); this is the same ordering required by
2993 * the fixup table, so we can simply read entries from the file
2994 * and add them directly to the fixup table.
2995 */
2996 (*fixups)->add_fixup(old_id, new_id);
2997 }
2998
2999 /* read the number of saved objects */
3000 cnt = fp->read_uint4();
3001
3002 /* read the objects */
3003 for ( ; cnt != 0 ; --cnt)
3004 {
3005 char buf[2];
3006 vm_obj_id_t id;
3007 int in_root_set;
3008 uint meta_idx;
3009 CVmObject *obj;
3010
3011 /* read the original object ID */
3012 id = (vm_obj_id_t)fp->read_uint4();
3013
3014 /* read the root-set flag and dependency table index */
3015 fp->read_bytes(buf, 2);
3016 in_root_set = buf[0];
3017 meta_idx = (uchar)buf[1];
3018
3019 /*
3020 * if it's not in the root set, we need to create a new object;
3021 * otherwise, the object must already exist, since it came from
3022 * the object file
3023 */
3024 if (in_root_set)
3025 {
3026 /*
3027 * make sure the object is valid - since it's supposedly in
3028 * the root set, it must already exist
3029 */
3030 if (!is_obj_id_valid(id) || get_entry(id)->free_)
3031 return VMERR_SAVED_OBJ_ID_INVALID;
3032 }
3033 else
3034 {
3035 /*
3036 * the object was dynamically allocated, so it will have a new
3037 * object number - fix up the object ID to the new numbering
3038 * system
3039 */
3040 id = (*fixups)->get_new_id(vmg_ id);
3041
3042 /* create the object */
3043 G_meta_table->create_for_restore(vmg_ meta_idx, id);
3044 }
3045
3046 /* read the object's data */
3047 obj = get_obj(id);
3048 obj->restore_from_file(vmg_ id, fp, *fixups);
3049 }
3050
3051 /* success */
3052 return 0;
3053 }
3054
3055 /*
3056 * Save an image data pointer
3057 */
3058 void CVmObjTable::save_image_pointer(vm_obj_id_t obj_id, const char *ptr,
3059 size_t siz)
3060 {
3061 vm_image_ptr *slot;
3062
3063 /* allocate a new page if we're out of slots on the current page */
3064 if (image_ptr_head_ == 0)
3065 {
3066 /* no pages yet - allocate the first page */
3067 image_ptr_head_ = (vm_image_ptr_page *)
3068 t3malloc(sizeof(vm_image_ptr_page));
3069 if (image_ptr_head_ == 0)
3070 err_throw(VMERR_OUT_OF_MEMORY);
3071
3072 /* it's also the last page */
3073 image_ptr_tail_ = image_ptr_head_;
3074 image_ptr_tail_->next_ = 0;
3075
3076 /* no slots used on this page yet */
3077 image_ptr_last_cnt_ = 0;
3078 }
3079 else if (image_ptr_last_cnt_ == VM_IMAGE_PTRS_PER_PAGE)
3080 {
3081 /* the last page is full - allocate another one */
3082 image_ptr_tail_->next_ = (vm_image_ptr_page *)
3083 t3malloc(sizeof(vm_image_ptr_page));
3084 if (image_ptr_tail_->next_ == 0)
3085 err_throw(VMERR_OUT_OF_MEMORY);
3086
3087 /* it's the new last page */
3088 image_ptr_tail_ = image_ptr_tail_->next_;
3089 image_ptr_tail_->next_ = 0;
3090
3091 /* no slots used on this page yet */
3092 image_ptr_last_cnt_ = 0;
3093 }
3094
3095 /* get the next available slot */
3096 slot = &image_ptr_tail_->ptrs_[image_ptr_last_cnt_];
3097
3098 /* save the data */
3099 slot->obj_id_ = obj_id;
3100 slot->image_data_ptr_ = ptr;
3101 slot->image_data_len_ = siz;
3102
3103 /* count the new record */
3104 ++image_ptr_last_cnt_;
3105 }
3106
3107 /*
3108 * Reset to initial image file state
3109 */
3110 void CVmObjTable::reset_to_image(VMG0_)
3111 {
3112 CVmObjPageEntry **pg;
3113 CVmObjPageEntry *entry;
3114 size_t i;
3115 size_t j;
3116 vm_obj_id_t id;
3117 vm_image_ptr_page *ip_page;
3118
3119 /*
3120 * Drop all undo information. Since we're resetting to the initial
3121 * state, the undo for our outgoing state will no longer be
3122 * relevant.
3123 */
3124 G_undo->drop_undo(vmg0_);
3125
3126 /* delete all of the globals */
3127 if (globals_ != 0)
3128 {
3129 delete globals_;
3130 globals_ = 0;
3131 }
3132
3133 /*
3134 * Go through the object table and reset each non-transient object in
3135 * the root set to its initial conditions.
3136 */
3137 for (id = 0, i = pages_used_, pg = pages_ ; i > 0 ; ++pg, --i)
3138 {
3139 /* scan all objects on this page */
3140 for (j = VM_OBJ_PAGE_CNT, entry = *pg ; j > 0 ; --j, ++entry, ++id)
3141 {
3142 /*
3143 * if it's not free, and it's in the root set, and it's not
3144 * transient, reset it
3145 */
3146 if (!entry->free_ && entry->in_root_set_ && !entry->transient_)
3147 {
3148 /*
3149 * This object is part of the root set, so it's part of
3150 * the state immediately after loading the image. Reset
3151 * the object to its load file conditions.
3152 */
3153 entry->get_vm_obj()->reset_to_image(vmg_ id);
3154 }
3155 }
3156 }
3157
3158 /*
3159 * Go through all of the objects for which we've explicitly saved the
3160 * original image file location, and ask them to reset using the image
3161 * data.
3162 */
3163 for (ip_page = image_ptr_head_ ; ip_page != 0 ; ip_page = ip_page->next_)
3164 {
3165 size_t cnt;
3166 vm_image_ptr *slot;
3167
3168 /*
3169 * get the count for this page - if this is the last page, it's
3170 * the last page counter; otherwise, it's a full page, since we
3171 * fill up each page before creating a new one
3172 */
3173 if (ip_page->next_ == 0)
3174 cnt = image_ptr_last_cnt_;
3175 else
3176 cnt = VM_IMAGE_PTRS_PER_PAGE;
3177
3178 /* go through the records on the page */
3179 for (slot = ip_page->ptrs_ ; cnt != 0 ; --cnt, ++slot)
3180 {
3181 /* it this object is non-transient, reload it */
3182 if (!get_entry(slot->obj_id_)->transient_)
3183 {
3184 /* reload it using the saved image data */
3185 vm_objp(vmg_ slot->obj_id_)
3186 ->reload_from_image(vmg_ slot->obj_id_,
3187 slot->image_data_ptr_,
3188 slot->image_data_len_);
3189 }
3190 }
3191 }
3192 }
3193
3194 /*
3195 * Create a global variable
3196 */
3197 vm_globalvar_t *CVmObjTable::create_global_var()
3198 {
3199 vm_globalvar_t *var;
3200
3201 /* create the new variable */
3202 var = new vm_globalvar_t();
3203
3204 /* initialize the variable's value to nil */
3205 var->val.set_nil();
3206
3207 /* link it into our list of globals */
3208 var->nxt = global_var_head_;
3209 var->prv = 0;
3210 if (global_var_head_ != 0)
3211 global_var_head_->prv = var;
3212 global_var_head_ = var;
3213
3214 /* return the variable */
3215 return var;
3216 }
3217
3218 /*
3219 * Delete a global variable
3220 */
3221 void CVmObjTable::delete_global_var(vm_globalvar_t *var)
3222 {
3223 /* unlink it from the list of globals */
3224 if (var->nxt != 0)
3225 var->nxt->prv = var->prv;
3226
3227 if (var->prv != 0)
3228 var->prv->nxt = var->nxt;
3229 else
3230 global_var_head_ = var->nxt;
3231
3232 /* delete the memory */
3233 delete var;
3234 }
3235
3236
3237 /* ------------------------------------------------------------------------ */
3238 /*
3239 * post-load initialization status
3240 */
3241 enum pli_stat_t
3242 {
3243 PLI_UNINITED, /* not yet initialized */
3244 PLI_IN_PROGRESS, /* initialization in progress */
3245 PLI_INITED /* initialization completed */
3246 };
3247
3248 /*
3249 * Post-load initialization hash table entry. We use the object ID,
3250 * treating the binary representation as a string of bytes, as the hash
3251 * key.
3252 */
3253 class CVmHashEntryPLI: public CVmHashEntryCS
3254 {
3255 public:
3256 CVmHashEntryPLI(vm_obj_id_t id)
3257 : CVmHashEntryCS((char *)&id, sizeof(id), TRUE)
3258 {
3259 /*
3260 * remember our object ID for easy access (technically, it's stored
3261 * as our key value as well, so this is redundant; but it's
3262 * transformed into a block of bytes for the key, so it's easier to
3263 * keep a separate copy of the true type)
3264 */
3265 id_ = id;
3266
3267 /* initialize our status */
3268 status = PLI_UNINITED;
3269 }
3270
3271 /* our object ID */
3272 vm_obj_id_t id_;
3273
3274 /* status for current operation */
3275 pli_stat_t status;
3276 };
3277
3278 /*
3279 * Request post-load initialization.
3280 */
3281 void CVmObjTable::request_post_load_init(vm_obj_id_t obj)
3282 {
3283 CVmHashEntryPLI *entry;
3284
3285 /* check for an existing entry - if there's not one already, add one */
3286 entry = (CVmHashEntryPLI *)
3287 post_load_init_table_->find((char *)&obj, sizeof(obj));
3288 if (entry == 0)
3289 {
3290 /* it's not there yet - add a new entry */
3291 post_load_init_table_->add(new CVmHashEntryPLI(obj));
3292
3293 /* mark the object as having requested post-load initialization */
3294 get_entry(obj)->requested_post_load_init_ = TRUE;
3295 }
3296 }
3297
3298 /*
3299 * Explicitly invoke post-load initialization on a given object
3300 */
3301 void CVmObjTable::ensure_post_load_init(VMG_ vm_obj_id_t obj)
3302 {
3303 CVmHashEntryPLI *entry;
3304
3305 /* find the entry */
3306 entry = (CVmHashEntryPLI *)
3307 post_load_init_table_->find((char *)&obj, sizeof(obj));
3308
3309 /* if we found it, invoke its initialization method */
3310 if (entry != 0)
3311 call_post_load_init(vmg_ entry);
3312 }
3313
3314 /*
3315 * Invoke post-load initialization on the given object, if appropriate
3316 */
3317 void CVmObjTable::call_post_load_init(VMG_ CVmHashEntryPLI *entry)
3318 {
3319 /* check the status */
3320 switch (entry->status)
3321 {
3322 case PLI_UNINITED:
3323 /*
3324 * It's not yet initialized, so we need to initialize it now. Mark
3325 * it as having its initialization in progress.
3326 */
3327 entry->status = PLI_IN_PROGRESS;
3328
3329 /*
3330 * push the entry on the stack to protect it from gc while we're
3331 * initializing it
3332 */
3333 G_stk->push()->set_obj(entry->id_);
3334
3335 /* invoke its initialization */
3336 vm_objp(vmg_ entry->id_)->post_load_init(vmg_ entry->id_);
3337
3338 /* mark the object as having completed initialization */
3339 entry->status = PLI_INITED;
3340
3341 /* discard our GC protection */
3342 G_stk->discard();
3343
3344 /* done */
3345 break;
3346
3347 case PLI_IN_PROGRESS:
3348 /*
3349 * The object is in the process of being initialized. This must
3350 * mean that the object's initializer is calling us indirectly,
3351 * probably through another object's initializer that it invoked
3352 * explicitly as a dependency, which in turn means that we have a
3353 * circular dependency. This is illegal, so abort with an error.
3354 */
3355 err_throw(VMERR_CIRCULAR_INIT);
3356 break;
3357
3358 case PLI_INITED:
3359 /* it's already been initialized, so there's nothing to do */
3360 break;
3361 }
3362 }
3363
3364 /*
3365 * Remove a post-load initialization record
3366 */
3367 void CVmObjTable::remove_post_load_init(vm_obj_id_t obj)
3368 {
3369 CVmHashEntryPLI *entry;
3370
3371 /* find the entry */
3372 entry = (CVmHashEntryPLI *)
3373 post_load_init_table_->find((char *)&obj, sizeof(obj));
3374
3375 /* if we found the entry, remove it from the table and delete it */
3376 if (entry != 0)
3377 {
3378 /* remove it */
3379 post_load_init_table_->remove(entry);
3380
3381 /* delete it */
3382 delete entry;
3383
3384 /* mark the entry as no longer being registered for post-load init */
3385 get_entry(obj)->requested_post_load_init_ = FALSE;
3386 }
3387 }
3388
3389 /*
3390 * post-load initialization enumeration context
3391 */
3392 struct pli_enum_ctx
3393 {
3394 vm_globals *globals;
3395 };
3396
3397 /*
3398 * Invoke post-load initialization on all objects that have requested it.
3399 * This must be called after initial program load, restarts, and restore
3400 * operations.
3401 */
3402 void CVmObjTable::do_all_post_load_init(VMG0_)
3403 {
3404 pli_enum_ctx ctx;
3405
3406 /* set up our context */
3407 ctx.globals = VMGLOB_ADDR;
3408
3409 /* first, mark all entries as having status 'uninitialized' */
3410 post_load_init_table_->enum_entries(&pli_status_cb, &ctx);
3411
3412 /* next, invoke the initializer method for each entry */
3413 post_load_init_table_->enum_entries(&pli_invoke_cb, &ctx);
3414 }
3415
3416 /*
3417 * post-load initialization enumeration callback: mark entries as having
3418 * status 'uninitialized'
3419 */
3420 void CVmObjTable::pli_status_cb(void *ctx0, CVmHashEntry *entry0)
3421 {
3422 CVmHashEntryPLI *entry = (CVmHashEntryPLI *)entry0;
3423
3424 /* mark the entry as having status 'uninitialized' */
3425 entry->status = PLI_UNINITED;
3426 }
3427
3428 /*
3429 * post-load initialization enumeration callback: mark entries as having
3430 * status 'uninitialized'
3431 */
3432 void CVmObjTable::pli_invoke_cb(void *ctx0, CVmHashEntry *entry0)
3433 {
3434 CVmHashEntryPLI *entry = (CVmHashEntryPLI *)entry0;
3435 VMGLOB_PTR(((pli_enum_ctx *)ctx0)->globals);
3436
3437 /* invoke post-load initialization on the object */
3438 call_post_load_init(vmg_ entry);
3439 }
3440
3441
3442 /* ------------------------------------------------------------------------ */
3443 /*
3444 * Memory manager implementation
3445 */
3446
3447 CVmMemory::CVmMemory(VMG_ CVmVarHeap *varheap)
3448 {
3449 /* remember our variable-size heap */
3450 varheap_ = varheap;
3451
3452 /* initialize the variable-size heap */
3453 varheap_->init(vmg0_);
3454 }
3455
3456 /* ------------------------------------------------------------------------ */
3457 /*
3458 * Hybrid cell/malloc memory manager - cell sub-block manager
3459 */
3460
3461 /*
3462 * Allocate an object. Since we always allocate blocks of a fixed size,
3463 * we can ignore the size parameter; the heap manager will only route us
3464 * requests that fit in our blocks.
3465 */
3466 CVmVarHeapHybrid_hdr *CVmVarHeapHybrid_head::alloc(size_t)
3467 {
3468 /* if there isn't an entry, allocate another array */
3469 if (first_free_ == 0)
3470 {
3471 CVmVarHeapHybrid_array *arr;
3472 size_t real_cell_size;
3473 char *p;
3474 size_t cnt;
3475
3476 /*
3477 * Allocate another page. We need space for the array header
3478 * itself, plus space for all of the cells. We want page_count_
3479 * cells, each of size cell_size_ plus the size of the per-cell
3480 * header, rounded to the worst-case alignment size for the
3481 * platform.
3482 */
3483 real_cell_size = osrndsz(cell_size_
3484 + osrndsz(sizeof(CVmVarHeapHybrid_hdr)));
3485 arr = (CVmVarHeapHybrid_array *)
3486 t3malloc(sizeof(CVmVarHeapHybrid_array)
3487 + (page_count_ * real_cell_size));
3488
3489 /* if that failed, throw an error */
3490 if (arr == 0)
3491 err_throw(VMERR_OUT_OF_MEMORY);
3492
3493 /* link the array into the master list */
3494 arr->next_array = mem_mgr_->first_array_;
3495 mem_mgr_->first_array_ = arr;
3496
3497 /*
3498 * Build the free list. Each cell goes into the free list; the
3499 * 'next' pointer is stored in the data area of the cell.
3500 */
3501 for (p = arr->mem, cnt = page_count_ ; cnt > 0 ;
3502 p += real_cell_size, --cnt)
3503 {
3504 /* link this one into the free list */
3505 *(void **)p = first_free_;
3506 first_free_ = (void *)p;
3507 }
3508 }
3509
3510 /* remember the return value */
3511 CVmVarHeapHybrid_hdr *ret = (CVmVarHeapHybrid_hdr *)first_free_;
3512
3513 /*
3514 * when we initialized or last freed this entry, we stored a pointer
3515 * to the next item in the free list in the object's data - retrieve
3516 * this pointer now, and update our free list head to point to the
3517 * next item
3518 */
3519 first_free_ = *(void **)first_free_;
3520
3521 /* fill in the block's pointer to the allocating heap (i.e., this) */
3522 ret->block = this;
3523
3524 /* return the item */
3525 return ret;
3526 }
3527
3528 /*
3529 * Reallocate
3530 */
3531 void *CVmVarHeapHybrid_head::realloc(CVmVarHeapHybrid_hdr *mem, size_t siz,
3532 CVmObject *obj)
3533 {
3534 /*
3535 * if the new block fits in our cell size, return the original
3536 * memory unchanged; note that we must adjust the pointer so that we
3537 * return the client-visible portion
3538 */
3539 if (siz <= cell_size_)
3540 return (void *)(mem + 1);
3541
3542 /*
3543 * The memory won't fit in our cell size, so not only can't we
3544 * re-use the existing cell, but we can't allocate the memory from
3545 * our own sub-block at all. Allocate an entirely new block from
3546 * the heap manager.
3547 */
3548 void *new_mem = mem_mgr_->alloc_mem(siz, obj);
3549
3550 /*
3551 * Copy the old cell's contents to the new memory. Note that the
3552 * user-visible portion of the old cell starts immediately after the
3553 * header; don't copy the old header, since it's not applicable to
3554 * the new object. Note also that we got a pointer directly to the
3555 * user-visible portion of the new object, so we don't need to make
3556 * any adjustments to the new pointer.
3557 */
3558 memcpy(new_mem, (void *)(mem + 1), cell_size_);
3559
3560 /* free the old memory */
3561 free(mem);
3562
3563 /* return the new memory */
3564 return new_mem;
3565 }
3566
3567 /*
3568 * Release memory
3569 */
3570 void CVmVarHeapHybrid_head::free(CVmVarHeapHybrid_hdr *mem)
3571 {
3572 /* link the block into our free list */
3573 *(void **)mem = first_free_;
3574 first_free_ = (void *)mem;
3575 }
3576
3577 /* ------------------------------------------------------------------------ */
3578 /*
3579 * Hybrid cell/malloc heap manager
3580 */
3581
3582 /*
3583 * construct
3584 */
3585 CVmVarHeapHybrid::CVmVarHeapHybrid(CVmObjTable *objtab)
3586 {
3587 /* remember my object table */
3588 objtab_ = objtab;
3589
3590 /* set the cell heap count */
3591 cell_heap_cnt_ = 5;
3592
3593 /* allocate our cell heap pointer array */
3594 cell_heaps_ = (CVmVarHeapHybrid_head **)
3595 t3malloc(cell_heap_cnt_ * sizeof(CVmVarHeapHybrid_head *));
3596
3597 /* if that failed, throw an error */
3598 if (cell_heaps_ == 0)
3599 err_throw(VMERR_OUT_OF_MEMORY);
3600
3601 /*
3602 * Allocate our cell heaps. Set up the heaps so that the pages run
3603 * about 32k each.
3604 */
3605 cell_heaps_[0] = new CVmVarHeapHybrid_head(this, 32, 850);
3606 cell_heaps_[1] = new CVmVarHeapHybrid_head(this, 64, 400);
3607 cell_heaps_[2] = new CVmVarHeapHybrid_head(this, 128, 200);
3608 cell_heaps_[3] = new CVmVarHeapHybrid_head(this, 256, 100);
3609 cell_heaps_[4] = new CVmVarHeapHybrid_head(this, 512, 50);
3610
3611 /* allocate our malloc heap manager */
3612 malloc_heap_ = new CVmVarHeapHybrid_malloc();
3613
3614 /* we haven't allocated any cell array pages yet */
3615 first_array_ = 0;
3616 }
3617
3618 /*
3619 * delete
3620 */
3621 CVmVarHeapHybrid::~CVmVarHeapHybrid()
3622 {
3623 size_t i;
3624
3625 /* delete our cell heaps */
3626 for (i = 0 ; i < cell_heap_cnt_ ; ++i)
3627 delete cell_heaps_[i];
3628
3629 /* delete the cell heap pointer array */
3630 t3free(cell_heaps_);
3631
3632 /* delete all of the arrays */
3633 while (first_array_ != 0)
3634 {
3635 CVmVarHeapHybrid_array *nxt;
3636
3637 /* remember the next one */
3638 nxt = first_array_->next_array;
3639
3640 /* delete this one */
3641 t3free(first_array_);
3642
3643 /* move on to the next one */
3644 first_array_ = nxt;
3645 }
3646
3647 /* delete the malloc-based subheap manager */
3648 delete malloc_heap_;
3649 }
3650
3651 /*
3652 * allocate memory
3653 */
3654 void *CVmVarHeapHybrid::alloc_mem(size_t siz, CVmObject *)
3655 {
3656 CVmVarHeapHybrid_head **subheap;
3657 size_t i;
3658
3659 /* count the gc statistics if desired */
3660 IF_GC_STATS(gc_stats.count_alloc_bytes(siz));
3661
3662 /* count the allocation */
3663 objtab_->count_alloc(siz);
3664
3665 /* scan for a cell-based subheap that can handle the request */
3666 for (i = 0, subheap = cell_heaps_ ; i < cell_heap_cnt_ ; ++i, ++subheap)
3667 {
3668 /*
3669 * If it will fit in this one's cell size, allocate it from this
3670 * subheap. Note that we must adjust the return pointer so that
3671 * it points to the caller-visible portion of the block returned
3672 * from the subheap, which immediately follows the internal
3673 * header.
3674 */
3675 if (siz <= (*subheap)->get_cell_size())
3676 {
3677 CVmVarHeapHybrid_hdr *hdr = (*subheap)->alloc(siz);
3678 IF_GC_STATS(hdr->siz = siz);
3679 return (void *)(hdr + 1);
3680 }
3681 }
3682
3683 /*
3684 * We couldn't find a cell-based manager that can handle a block
3685 * this large. Allocate the block from the default malloc heap.
3686 * Note that the caller-visible block is the part that immediately
3687 * follows our internal header, so we must adjust the return pointer
3688 * accordingly.
3689 */
3690 CVmVarHeapHybrid_hdr *hdr = malloc_heap_->alloc(siz);
3691 IF_GC_STATS(hdr->siz = siz);
3692 return (void *)(hdr + 1);
3693 }
3694
3695 /*
3696 * reallocate memory
3697 */
3698 void *CVmVarHeapHybrid::realloc_mem(size_t siz, void *mem,
3699 CVmObject *obj)
3700 {
3701 CVmVarHeapHybrid_hdr *hdr;
3702
3703 /*
3704 * Count the allocation. This isn't really a new allocation of 'siz'
3705 * bytes, since we're only expanding an object that already has a
3706 * non-zero size. But in many cases this will simply allocate new
3707 * memory anyway, copying the old object into the new memory, so it
3708 * could actually count against our OS-level working set. That makes
3709 * it worthwhile to count it against the GC quota.
3710 */
3711 objtab_->count_alloc(siz);
3712
3713 /*
3714 * get the block header, which immediately precedes the
3715 * caller-visible block
3716 */
3717 hdr = ((CVmVarHeapHybrid_hdr *)mem) - 1;
3718
3719 /* count the gc statistics if desired */
3720 IF_GC_STATS((gc_stats.count_realloc_bytes(hdr->siz, siz), hdr->siz = siz));
3721
3722 /*
3723 * read the header to get the block manager that originally
3724 * allocated the memory, and ask it to reallocate the memory
3725 */
3726 return hdr->block->realloc(hdr, siz, obj);
3727 }
3728
3729 /*
3730 * free memory
3731 */
3732 void CVmVarHeapHybrid::free_mem(void *mem)
3733 {
3734 CVmVarHeapHybrid_hdr *hdr;
3735
3736 /*
3737 * get the block header, which immediately precedes the
3738 * caller-visible block
3739 */
3740 hdr = ((CVmVarHeapHybrid_hdr *)mem) - 1;
3741
3742 /* count the gc statistics if desired */
3743 IF_GC_STATS(gc_stats.count_free_bytes(hdr->siz));
3744
3745 /*
3746 * read the header to get the block manager that originally
3747 * allocated the memory, and ask it to free the memory
3748 */
3749 hdr->block->free(hdr);
3750 }
3751