fix variable name.
[ruby-svn.git] / gc.c
blob0e2da328bec2683357496a4152df61574d3546bc
1 /**********************************************************************
3 gc.c -
5 $Author$
6 created at: Tue Oct 5 09:44:46 JST 1993
8 Copyright (C) 1993-2007 Yukihiro Matsumoto
9 Copyright (C) 2000 Network Applied Communication Laboratory, Inc.
10 Copyright (C) 2000 Information-technology Promotion Agency, Japan
12 **********************************************************************/
14 #include "ruby/ruby.h"
15 #include "ruby/signal.h"
16 #include "ruby/st.h"
17 #include "ruby/node.h"
18 #include "ruby/re.h"
19 #include "ruby/io.h"
20 #include "ruby/util.h"
21 #include "eval_intern.h"
22 #include "vm_core.h"
23 #include "gc.h"
24 #include <stdio.h>
25 #include <setjmp.h>
26 #include <sys/types.h>
28 #ifdef HAVE_SYS_TIME_H
29 #include <sys/time.h>
30 #endif
32 #ifdef HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
34 #endif
36 #if defined _WIN32 || defined __CYGWIN__
37 #include <windows.h>
38 #endif
40 #ifdef HAVE_VALGRIND_MEMCHECK_H
41 # include <valgrind/memcheck.h>
42 # ifndef VALGRIND_MAKE_MEM_DEFINED
43 # define VALGRIND_MAKE_MEM_DEFINED(p, n) VALGRIND_MAKE_READABLE(p, n)
44 # endif
45 # ifndef VALGRIND_MAKE_MEM_UNDEFINED
46 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE(p, n)
47 # endif
48 #else
49 # define VALGRIND_MAKE_MEM_DEFINED(p, n) /* empty */
50 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) /* empty */
51 #endif
53 int rb_io_fptr_finalize(struct rb_io_t*);
55 #define rb_setjmp(env) RUBY_SETJMP(env)
56 #define rb_jmp_buf rb_jmpbuf_t
58 /* Make alloca work the best possible way. */
59 #ifdef __GNUC__
60 # ifndef atarist
61 # ifndef alloca
62 # define alloca __builtin_alloca
63 # endif
64 # endif /* atarist */
65 #else
66 # ifdef HAVE_ALLOCA_H
67 # include <alloca.h>
68 # else
69 # ifdef _AIX
70 #pragma alloca
71 # else
72 # ifndef alloca /* predefined by HP cc +Olibcalls */
73 void *alloca ();
74 # endif
75 # endif /* AIX */
76 # endif /* HAVE_ALLOCA_H */
77 #endif /* __GNUC__ */
79 #ifndef GC_MALLOC_LIMIT
80 #if defined(MSDOS) || defined(__human68k__)
81 #define GC_MALLOC_LIMIT 200000
82 #else
83 #define GC_MALLOC_LIMIT 8000000
84 #endif
85 #endif
87 #define nomem_error GET_VM()->special_exceptions[ruby_error_nomemory]
89 #define MARK_STACK_MAX 1024
91 int ruby_gc_debug_indent = 0;
93 #undef GC_DEBUG
95 /* for GC profile */
96 #define GC_PROFILE_MORE_DETAIL 0
97 typedef struct gc_profile_record {
98 double gc_time;
99 double gc_mark_time;
100 double gc_sweep_time;
101 double gc_invoke_time;
102 size_t heap_use_slots;
103 size_t heap_live_objects;
104 size_t heap_free_objects;
105 size_t heap_total_objects;
106 size_t heap_use_size;
107 size_t heap_total_size;
108 int have_finalize;
109 size_t allocate_increase;
110 size_t allocate_limit;
111 } gc_profile_record;
113 static double
114 getrusage_time(void)
116 #ifdef RUSAGE_SELF
117 struct rusage usage;
118 struct timeval time;
119 getrusage(RUSAGE_SELF, &usage);
120 time = usage.ru_utime;
121 return time.tv_sec + time.tv_usec * 1e-6;
122 #elif defined _WIN32
123 FILETIME creation_time, exit_time, kernel_time, user_time;
124 ULARGE_INTEGER ui;
125 LONG_LONG q;
126 double t;
128 if (GetProcessTimes(GetCurrentProcess(),
129 &creation_time, &exit_time, &kernel_time, &user_time) == 0)
131 return 0.0;
133 memcpy(&ui, &user_time, sizeof(FILETIME));
134 q = ui.QuadPart / 10L;
135 t = (DWORD)(q % 1000000L) * 1e-6;
136 q /= 1000000L;
137 #ifdef __GNUC__
138 t += q;
139 #else
140 t += (double)(DWORD)(q >> 16) * (1 << 16);
141 t += (DWORD)q & ~(~0 << 16);
142 #endif
143 #else
144 return 0.0;
145 #endif
148 #define GC_PROF_TIMER_START do {\
149 if (objspace->profile.run) {\
150 if (!objspace->profile.record) {\
151 objspace->profile.size = 1000;\
152 objspace->profile.record = malloc(sizeof(gc_profile_record) * objspace->profile.size);\
154 if (count >= objspace->profile.size) {\
155 objspace->profile.size += 1000;\
156 objspace->profile.record = realloc(objspace->profile.record, sizeof(gc_profile_record) * objspace->profile.size);\
158 if (!objspace->profile.record) {\
159 rb_bug("gc_profile malloc or realloc miss");\
161 MEMZERO(&objspace->profile.record[count], gc_profile_record, 1);\
162 gc_time = getrusage_time();\
163 objspace->profile.record[count].gc_invoke_time = gc_time - objspace->profile.invoke_time;\
165 } while(0)
167 #define GC_PROF_TIMER_STOP do {\
168 if (objspace->profile.run) {\
169 gc_time = getrusage_time() - gc_time;\
170 if (gc_time < 0) gc_time = 0;\
171 objspace->profile.record[count].gc_time = gc_time;\
172 objspace->profile.count++;\
174 } while(0)
176 #if GC_PROFILE_MORE_DETAIL
177 #define INIT_GC_PROF_PARAMS double gc_time = 0, mark_time = 0, sweep_time = 0;\
178 size_t count = objspace->profile.count
180 #define GC_PROF_MARK_TIMER_START do {\
181 if (objspace->profile.run) {\
182 mark_time = getrusage_time();\
184 } while(0)
186 #define GC_PROF_MARK_TIMER_STOP do {\
187 if (objspace->profile.run) {\
188 mark_time = getrusage_time() - mark_time;\
189 if (mark_time < 0) mark_time = 0;\
190 objspace->profile.record[count].gc_mark_time = mark_time;\
192 } while(0)
194 #define GC_PROF_SWEEP_TIMER_START do {\
195 if (objspace->profile.run) {\
196 sweep_time = getrusage_time();\
198 } while(0)
200 #define GC_PROF_SWEEP_TIMER_STOP do {\
201 if (objspace->profile.run) {\
202 sweep_time = getrusage_time() - sweep_time;\
203 if (sweep_time < 0) sweep_time = 0;\
204 objspace->profile.record[count].gc_sweep_time = sweep_time;\
206 } while(0)
207 #define GC_PROF_SET_MALLOC_INFO do {\
208 if (objspace->profile.run) {\
209 size_t count = objspace->profile.count;\
210 objspace->profile.record[count].allocate_increase = malloc_increase;\
211 objspace->profile.record[count].allocate_limit = malloc_limit; \
213 } while(0)
214 #define GC_PROF_SET_HEAP_INFO do {\
215 if (objspace->profile.run) {\
216 size_t count = objspace->profile.count;\
217 objspace->profile.record[count].heap_use_slots = heaps_used;\
218 objspace->profile.record[count].heap_live_objects = live;\
219 objspace->profile.record[count].heap_free_objects = freed;\
220 objspace->profile.record[count].heap_total_objects = heaps_used * HEAP_OBJ_LIMIT;\
221 objspace->profile.record[count].have_finalize = final_list ? Qtrue : Qfalse;\
222 objspace->profile.record[count].heap_use_size = live * sizeof(RVALUE);\
223 objspace->profile.record[count].heap_total_size = heaps_used * (HEAP_OBJ_LIMIT * sizeof(RVALUE));\
225 } while(0)
227 #else
228 #define INIT_GC_PROF_PARAMS double gc_time = 0;\
229 size_t count = objspace->profile.count
230 #define GC_PROF_MARK_TIMER_START
231 #define GC_PROF_MARK_TIMER_STOP
232 #define GC_PROF_SWEEP_TIMER_START
233 #define GC_PROF_SWEEP_TIMER_STOP
234 #define GC_PROF_SET_MALLOC_INFO
235 #define GC_PROF_SET_HEAP_INFO do {\
236 if (objspace->profile.run) {\
237 size_t count = objspace->profile.count;\
238 objspace->profile.record[count].heap_total_objects = heaps_used * HEAP_OBJ_LIMIT;\
239 objspace->profile.record[count].heap_use_size = live * sizeof(RVALUE);\
240 objspace->profile.record[count].heap_total_size = heaps_used * HEAP_SIZE;\
242 } while(0)
243 #endif
246 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
247 #pragma pack(push, 1) /* magic for reducing sizeof(RVALUE): 24 -> 20 */
248 #endif
250 typedef struct RVALUE {
251 union {
252 struct {
253 VALUE flags; /* always 0 for freed obj */
254 struct RVALUE *next;
255 } free;
256 struct RBasic basic;
257 struct RObject object;
258 struct RClass klass;
259 struct RFloat flonum;
260 struct RString string;
261 struct RArray array;
262 struct RRegexp regexp;
263 struct RHash hash;
264 struct RData data;
265 struct RStruct rstruct;
266 struct RBignum bignum;
267 struct RFile file;
268 struct RNode node;
269 struct RMatch match;
270 struct RRational rational;
271 struct RComplex complex;
272 } as;
273 #ifdef GC_DEBUG
274 char *file;
275 int line;
276 #endif
277 } RVALUE;
279 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
280 #pragma pack(pop)
281 #endif
283 struct heaps_slot {
284 void *membase;
285 RVALUE *slot;
286 int limit;
289 #define HEAP_MIN_SLOTS 10000
290 #define FREE_MIN 4096
292 struct gc_list {
293 VALUE *varptr;
294 struct gc_list *next;
297 #define CALC_EXACT_MALLOC_SIZE 0
299 typedef struct rb_objspace {
300 struct {
301 size_t limit;
302 size_t increase;
303 #if CALC_EXACT_MALLOC_SIZE
304 size_t allocated_size;
305 size_t allocations;
306 #endif
307 } malloc_params;
308 struct {
309 size_t increment;
310 struct heaps_slot *ptr;
311 size_t length;
312 size_t used;
313 RVALUE *freelist;
314 RVALUE *range[2];
315 RVALUE *freed;
316 } heap;
317 struct {
318 int dont_gc;
319 int during_gc;
320 } flags;
321 struct {
322 st_table *table;
323 RVALUE *deferred;
324 } final;
325 struct {
326 VALUE buffer[MARK_STACK_MAX];
327 VALUE *ptr;
328 int overflow;
329 } markstack;
330 struct {
331 int run;
332 gc_profile_record *record;
333 size_t count;
334 size_t size;
335 double invoke_time;
336 } profile;
337 struct gc_list *global_list;
338 unsigned int count;
339 int gc_stress;
340 } rb_objspace_t;
342 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
343 #define rb_objspace (*GET_VM()->objspace)
344 static int ruby_initial_gc_stress = 0;
345 int *ruby_initial_gc_stress_ptr = &ruby_initial_gc_stress;
346 #else
347 static rb_objspace_t rb_objspace = {{GC_MALLOC_LIMIT}, {HEAP_MIN_SLOTS}};
348 int *ruby_initial_gc_stress_ptr = &rb_objspace.gc_stress;
349 #endif
350 #define malloc_limit objspace->malloc_params.limit
351 #define malloc_increase objspace->malloc_params.increase
352 #define heap_slots objspace->heap.slots
353 #define heaps objspace->heap.ptr
354 #define heaps_length objspace->heap.length
355 #define heaps_used objspace->heap.used
356 #define freelist objspace->heap.freelist
357 #define lomem objspace->heap.range[0]
358 #define himem objspace->heap.range[1]
359 #define heaps_inc objspace->heap.increment
360 #define heaps_freed objspace->heap.freed
361 #define dont_gc objspace->flags.dont_gc
362 #define during_gc objspace->flags.during_gc
363 #define finalizer_table objspace->final.table
364 #define deferred_final_list objspace->final.deferred
365 #define mark_stack objspace->markstack.buffer
366 #define mark_stack_ptr objspace->markstack.ptr
367 #define mark_stack_overflow objspace->markstack.overflow
368 #define global_List objspace->global_list
369 #define ruby_gc_stress objspace->gc_stress
371 #define need_call_final (finalizer_table && finalizer_table->num_entries)
373 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
374 rb_objspace_t *
375 rb_objspace_alloc(void)
377 rb_objspace_t *objspace = malloc(sizeof(rb_objspace_t));
378 memset(objspace, 0, sizeof(*objspace));
379 malloc_limit = GC_MALLOC_LIMIT;
380 ruby_gc_stress = ruby_initial_gc_stress;
382 return objspace;
384 #endif
386 /* tiny heap size */
387 /* 32KB */
388 /*#define HEAP_SIZE 0x8000 */
389 /* 128KB */
390 /*#define HEAP_SIZE 0x20000 */
391 /* 64KB */
392 /*#define HEAP_SIZE 0x10000 */
393 /* 16KB */
394 #define HEAP_SIZE 0x4000
395 /* 8KB */
396 /*#define HEAP_SIZE 0x2000 */
397 /* 4KB */
398 /*#define HEAP_SIZE 0x1000 */
399 /* 2KB */
400 /*#define HEAP_SIZE 0x800 */
402 #define HEAP_OBJ_LIMIT (HEAP_SIZE / sizeof(struct RVALUE))
404 extern st_table *rb_class_tbl;
406 int ruby_disable_gc_stress = 0;
408 static void run_final(rb_objspace_t *objspace, VALUE obj);
409 static int garbage_collect(rb_objspace_t *objspace);
411 void
412 rb_global_variable(VALUE *var)
414 rb_gc_register_address(var);
417 void
418 rb_memerror(void)
420 rb_thread_t *th = GET_THREAD();
421 if (!nomem_error ||
422 (rb_thread_raised_p(th, RAISED_NOMEMORY) && rb_safe_level() < 4)) {
423 fprintf(stderr, "[FATAL] failed to allocate memory\n");
424 exit(EXIT_FAILURE);
426 if (rb_thread_raised_p(th, RAISED_NOMEMORY)) {
427 rb_thread_raised_clear(th);
428 GET_THREAD()->errinfo = nomem_error;
429 JUMP_TAG(TAG_RAISE);
431 rb_thread_raised_set(th, RAISED_NOMEMORY);
432 rb_exc_raise(nomem_error);
436 * call-seq:
437 * GC.stress => true or false
439 * returns current status of GC stress mode.
442 static VALUE
443 gc_stress_get(VALUE self)
445 rb_objspace_t *objspace = &rb_objspace;
446 return ruby_gc_stress ? Qtrue : Qfalse;
450 * call-seq:
451 * GC.stress = bool => bool
453 * updates GC stress mode.
455 * When GC.stress = true, GC is invoked for all GC opportunity:
456 * all memory and object allocation.
458 * Since it makes Ruby very slow, it is only for debugging.
461 static VALUE
462 gc_stress_set(VALUE self, VALUE bool)
464 rb_objspace_t *objspace = &rb_objspace;
465 rb_secure(2);
466 ruby_gc_stress = RTEST(bool);
467 return bool;
471 * call-seq:
472 * GC::Profiler.enable? => true or false
474 * returns current status of GC profile mode.
477 static VALUE
478 gc_profile_enable_get(VALUE self)
480 rb_objspace_t *objspace = &rb_objspace;
481 return objspace->profile.run;
485 * call-seq:
486 * GC::Profiler.enable => nil
488 * updates GC profile mode.
489 * start profiler for GC.
493 static VALUE
494 gc_profile_enable(void)
496 rb_objspace_t *objspace = &rb_objspace;
498 objspace->profile.run = Qtrue;
499 return Qnil;
503 * call-seq:
504 * GC::Profiler.disable => nil
506 * updates GC profile mode.
507 * stop profiler for GC.
511 static VALUE
512 gc_profile_disable(void)
514 rb_objspace_t *objspace = &rb_objspace;
516 objspace->profile.run = Qfalse;
517 return Qnil;
521 * call-seq:
522 * GC::Profiler.clear => nil
524 * clear before profile data.
528 static VALUE
529 gc_profile_clear(void)
531 rb_objspace_t *objspace = &rb_objspace;
532 MEMZERO(objspace->profile.record, gc_profile_record, objspace->profile.size);
533 objspace->profile.count = 0;
534 return Qnil;
537 static void *
538 vm_xmalloc(rb_objspace_t *objspace, size_t size)
540 void *mem;
542 if (size < 0) {
543 rb_raise(rb_eNoMemError, "negative allocation size (or too big)");
545 if (size == 0) size = 1;
547 #if CALC_EXACT_MALLOC_SIZE
548 size += sizeof(size_t);
549 #endif
551 if ((ruby_gc_stress && !ruby_disable_gc_stress) ||
552 (malloc_increase+size) > malloc_limit) {
553 garbage_collect(objspace);
555 RUBY_CRITICAL(mem = malloc(size));
556 if (!mem) {
557 if (garbage_collect(objspace)) {
558 RUBY_CRITICAL(mem = malloc(size));
560 if (!mem) {
561 rb_memerror();
564 malloc_increase += size;
566 #if CALC_EXACT_MALLOC_SIZE
567 objspace->malloc_params.allocated_size += size;
568 objspace->malloc_params.allocations++;
569 ((size_t *)mem)[0] = size;
570 mem = (size_t *)mem + 1;
571 #endif
573 return mem;
576 static void *
577 vm_xrealloc(rb_objspace_t *objspace, void *ptr, size_t size)
579 void *mem;
581 if (size < 0) {
582 rb_raise(rb_eArgError, "negative re-allocation size");
584 if (!ptr) return ruby_xmalloc(size);
585 if (size == 0) size = 1;
586 if (ruby_gc_stress && !ruby_disable_gc_stress) garbage_collect(objspace);
588 #if CALC_EXACT_MALLOC_SIZE
589 size += sizeof(size_t);
590 objspace->malloc_params.allocated_size -= size;
591 ptr = (size_t *)ptr - 1;
592 #endif
594 RUBY_CRITICAL(mem = realloc(ptr, size));
595 if (!mem) {
596 if (garbage_collect(objspace)) {
597 RUBY_CRITICAL(mem = realloc(ptr, size));
599 if (!mem) {
600 rb_memerror();
603 malloc_increase += size;
605 #if CALC_EXACT_MALLOC_SIZE
606 objspace->malloc_params.allocated_size += size;
607 ((size_t *)mem)[0] = size;
608 mem = (size_t *)mem + 1;
609 #endif
611 return mem;
614 static void
615 vm_xfree(rb_objspace_t *objspace, void *ptr)
617 #if CALC_EXACT_MALLOC_SIZE
618 size_t size;
619 ptr = ((size_t *)ptr) - 1;
620 size = ((size_t*)ptr)[0];
621 objspace->malloc_params.allocated_size -= size;
622 objspace->malloc_params.allocations--;
623 #endif
625 RUBY_CRITICAL(free(ptr));
628 void *
629 ruby_xmalloc(size_t size)
631 return vm_xmalloc(&rb_objspace, size);
634 void *
635 ruby_xmalloc2(size_t n, size_t size)
637 size_t len = size * n;
638 if (n != 0 && size != len / n) {
639 rb_raise(rb_eArgError, "malloc: possible integer overflow");
641 return vm_xmalloc(&rb_objspace, len);
644 void *
645 ruby_xcalloc(size_t n, size_t size)
647 void *mem = ruby_xmalloc2(n, size);
648 memset(mem, 0, n * size);
650 return mem;
653 void *
654 ruby_xrealloc(void *ptr, size_t size)
656 return vm_xrealloc(&rb_objspace, ptr, size);
659 void *
660 ruby_xrealloc2(void *ptr, size_t n, size_t size)
662 size_t len = size * n;
663 if (n != 0 && size != len / n) {
664 rb_raise(rb_eArgError, "realloc: possible integer overflow");
666 return ruby_xrealloc(ptr, len);
669 void
670 ruby_xfree(void *x)
672 if (x)
673 vm_xfree(&rb_objspace, x);
678 * call-seq:
679 * GC.enable => true or false
681 * Enables garbage collection, returning <code>true</code> if garbage
682 * collection was previously disabled.
684 * GC.disable #=> false
685 * GC.enable #=> true
686 * GC.enable #=> false
690 VALUE
691 rb_gc_enable(void)
693 rb_objspace_t *objspace = &rb_objspace;
694 int old = dont_gc;
696 dont_gc = Qfalse;
697 return old;
701 * call-seq:
702 * GC.disable => true or false
704 * Disables garbage collection, returning <code>true</code> if garbage
705 * collection was already disabled.
707 * GC.disable #=> false
708 * GC.disable #=> true
712 VALUE
713 rb_gc_disable(void)
715 rb_objspace_t *objspace = &rb_objspace;
716 int old = dont_gc;
718 dont_gc = Qtrue;
719 return old;
722 VALUE rb_mGC;
724 void
725 rb_register_mark_object(VALUE obj)
727 VALUE ary = GET_THREAD()->vm->mark_object_ary;
728 rb_ary_push(ary, obj);
731 void
732 rb_gc_register_address(VALUE *addr)
734 rb_objspace_t *objspace = &rb_objspace;
735 struct gc_list *tmp;
737 tmp = ALLOC(struct gc_list);
738 tmp->next = global_List;
739 tmp->varptr = addr;
740 global_List = tmp;
743 void
744 rb_gc_unregister_address(VALUE *addr)
746 rb_objspace_t *objspace = &rb_objspace;
747 struct gc_list *tmp = global_List;
749 if (tmp->varptr == addr) {
750 global_List = tmp->next;
751 xfree(tmp);
752 return;
754 while (tmp->next) {
755 if (tmp->next->varptr == addr) {
756 struct gc_list *t = tmp->next;
758 tmp->next = tmp->next->next;
759 xfree(t);
760 break;
762 tmp = tmp->next;
767 static void
768 allocate_heaps(rb_objspace_t *objspace, size_t next_heaps_length)
770 struct heaps_slot *p;
771 size_t size;
773 size = next_heaps_length*sizeof(struct heaps_slot);
774 RUBY_CRITICAL(
775 if (heaps_used > 0) {
776 p = (struct heaps_slot *)realloc(heaps, size);
777 if (p) heaps = p;
779 else {
780 p = heaps = (struct heaps_slot *)malloc(size);
783 if (p == 0) {
784 during_gc = 0;
785 rb_memerror();
787 heaps_length = next_heaps_length;
790 static void
791 assign_heap_slot(rb_objspace_t *objspace)
793 RVALUE *p, *pend, *membase;
794 size_t hi, lo, mid;
795 int objs;
797 objs = HEAP_OBJ_LIMIT;
798 RUBY_CRITICAL(p = (RVALUE*)malloc(HEAP_SIZE));
799 if (p == 0) {
800 during_gc = 0;
801 rb_memerror();
804 membase = p;
805 if ((VALUE)p % sizeof(RVALUE) != 0) {
806 p = (RVALUE*)((VALUE)p + sizeof(RVALUE) - ((VALUE)p % sizeof(RVALUE)));
807 if ((HEAP_SIZE - HEAP_OBJ_LIMIT * sizeof(RVALUE)) < ((char*)p - (char*)membase)) {
808 objs--;
812 lo = 0;
813 hi = heaps_used;
814 while (lo < hi) {
815 register RVALUE *mid_membase;
816 mid = (lo + hi) / 2;
817 mid_membase = heaps[mid].membase;
818 if (mid_membase < membase) {
819 lo = mid + 1;
821 else if (mid_membase > membase) {
822 hi = mid;
824 else {
825 rb_bug("same heap slot is allocated: %p at %"PRIuVALUE, membase, (VALUE)mid);
828 if (hi < heaps_used) {
829 MEMMOVE(&heaps[hi+1], &heaps[hi], struct heaps_slot, heaps_used - hi);
831 heaps[hi].membase = membase;
832 heaps[hi].slot = p;
833 heaps[hi].limit = objs;
834 pend = p + objs;
835 if (lomem == 0 || lomem > p) lomem = p;
836 if (himem < pend) himem = pend;
837 heaps_used++;
839 while (p < pend) {
840 p->as.free.flags = 0;
841 p->as.free.next = freelist;
842 freelist = p;
843 p++;
847 static void
848 init_heap(rb_objspace_t *objspace)
850 size_t add, i;
852 add = HEAP_MIN_SLOTS / HEAP_OBJ_LIMIT;
854 if ((heaps_used + add) > heaps_length) {
855 allocate_heaps(objspace, heaps_used + add);
858 for (i = 0; i < add; i++) {
859 assign_heap_slot(objspace);
861 heaps_inc = 0;
862 objspace->profile.invoke_time = getrusage_time();
866 static void
867 set_heaps_increment(rb_objspace_t *objspace)
869 size_t next_heaps_length = heaps_used * 1.8;
870 heaps_inc = next_heaps_length - heaps_used;
872 if (next_heaps_length > heaps_length) {
873 allocate_heaps(objspace, next_heaps_length);
877 static int
878 heaps_increment(rb_objspace_t *objspace)
880 if (heaps_inc > 0) {
881 assign_heap_slot(objspace);
882 heaps_inc--;
883 return Qtrue;
885 return Qfalse;
888 #define RANY(o) ((RVALUE*)(o))
890 static VALUE
891 rb_newobj_from_heap(rb_objspace_t *objspace)
893 VALUE obj;
895 if ((ruby_gc_stress && !ruby_disable_gc_stress) || !freelist) {
896 if (!heaps_increment(objspace) && !garbage_collect(objspace)) {
897 during_gc = 0;
898 rb_memerror();
902 obj = (VALUE)freelist;
903 freelist = freelist->as.free.next;
905 MEMZERO((void*)obj, RVALUE, 1);
906 #ifdef GC_DEBUG
907 RANY(obj)->file = rb_sourcefile();
908 RANY(obj)->line = rb_sourceline();
909 #endif
911 return obj;
914 #if USE_VALUE_CACHE
915 static VALUE
916 rb_fill_value_cache(rb_thread_t *th)
918 rb_objspace_t *objspace = &rb_objspace;
919 int i;
920 VALUE rv;
922 /* LOCK */
923 for (i=0; i<RUBY_VM_VALUE_CACHE_SIZE; i++) {
924 VALUE v = rb_newobj_from_heap(objspace);
926 th->value_cache[i] = v;
927 RBASIC(v)->flags = FL_MARK;
929 th->value_cache_ptr = &th->value_cache[0];
930 rv = rb_newobj_from_heap(objspace);
931 /* UNLOCK */
932 return rv;
934 #endif
937 rb_during_gc(void)
939 rb_objspace_t *objspace = &rb_objspace;
940 return during_gc;
943 VALUE
944 rb_newobj(void)
946 #if USE_VALUE_CACHE || (defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE)
947 rb_thread_t *th = GET_THREAD();
948 #endif
949 #if USE_VALUE_CACHE
950 VALUE v = *th->value_cache_ptr;
951 #endif
952 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
953 rb_objspace_t *objspace = th->vm->objspace;
954 #else
955 rb_objspace_t *objspace = &rb_objspace;
956 #endif
958 if (during_gc) {
959 dont_gc = 1;
960 during_gc = 0;
961 rb_bug("object allocation during garbage collection phase");
964 #if USE_VALUE_CACHE
965 if (v) {
966 RBASIC(v)->flags = 0;
967 th->value_cache_ptr++;
969 else {
970 v = rb_fill_value_cache(th);
973 #if defined(GC_DEBUG)
974 printf("cache index: %d, v: %p, th: %p\n",
975 th->value_cache_ptr - th->value_cache, v, th);
976 #endif
977 return v;
978 #else
979 return rb_newobj_from_heap(objspace);
980 #endif
983 NODE*
984 rb_node_newnode(enum node_type type, VALUE a0, VALUE a1, VALUE a2)
986 NODE *n = (NODE*)rb_newobj();
988 n->flags |= T_NODE;
989 nd_set_type(n, type);
991 n->u1.value = a0;
992 n->u2.value = a1;
993 n->u3.value = a2;
995 return n;
998 VALUE
999 rb_data_object_alloc(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
1001 NEWOBJ(data, struct RData);
1002 if (klass) Check_Type(klass, T_CLASS);
1003 OBJSETUP(data, klass, T_DATA);
1004 data->data = datap;
1005 data->dfree = dfree;
1006 data->dmark = dmark;
1008 return (VALUE)data;
1011 #ifdef __ia64
1012 #define SET_STACK_END (SET_MACHINE_STACK_END(&th->machine_stack_end), th->machine_register_stack_end = rb_ia64_bsp())
1013 #else
1014 #define SET_STACK_END SET_MACHINE_STACK_END(&th->machine_stack_end)
1015 #endif
1017 #define STACK_START (th->machine_stack_start)
1018 #define STACK_END (th->machine_stack_end)
1019 #define STACK_LEVEL_MAX (th->machine_stack_maxsize/sizeof(VALUE))
1021 #if STACK_GROW_DIRECTION < 0
1022 # define STACK_LENGTH (STACK_START - STACK_END)
1023 #elif STACK_GROW_DIRECTION > 0
1024 # define STACK_LENGTH (STACK_END - STACK_START + 1)
1025 #else
1026 # define STACK_LENGTH ((STACK_END < STACK_START) ? STACK_START - STACK_END\
1027 : STACK_END - STACK_START + 1)
1028 #endif
1029 #if !STACK_GROW_DIRECTION
1030 int ruby_stack_grow_direction;
1032 ruby_get_stack_grow_direction(VALUE *addr)
1034 rb_thread_t *th = GET_THREAD();
1035 SET_STACK_END;
1037 if (STACK_END > addr) return ruby_stack_grow_direction = 1;
1038 return ruby_stack_grow_direction = -1;
1040 #endif
1042 #define GC_WATER_MARK 512
1044 size_t
1045 ruby_stack_length(VALUE **p)
1047 rb_thread_t *th = GET_THREAD();
1048 SET_STACK_END;
1049 if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END);
1050 return STACK_LENGTH;
1054 ruby_stack_check(void)
1056 int ret;
1057 rb_thread_t *th = GET_THREAD();
1058 SET_STACK_END;
1059 ret = STACK_LENGTH > STACK_LEVEL_MAX - GC_WATER_MARK;
1060 #ifdef __ia64
1061 if (!ret) {
1062 ret = (VALUE*)rb_ia64_bsp() - th->machine_register_stack_start >
1063 th->machine_register_stack_maxsize/sizeof(VALUE) - GC_WATER_MARK;
1065 #endif
1066 return ret;
1069 static void
1070 init_mark_stack(rb_objspace_t *objspace)
1072 mark_stack_overflow = 0;
1073 mark_stack_ptr = mark_stack;
1076 #define MARK_STACK_EMPTY (mark_stack_ptr == mark_stack)
1078 static void gc_mark(rb_objspace_t *objspace, VALUE ptr, int lev);
1079 static void gc_mark_children(rb_objspace_t *objspace, VALUE ptr, int lev);
1081 static void
1082 gc_mark_all(rb_objspace_t *objspace)
1084 RVALUE *p, *pend;
1085 size_t i;
1087 init_mark_stack(objspace);
1088 for (i = 0; i < heaps_used; i++) {
1089 p = heaps[i].slot; pend = p + heaps[i].limit;
1090 while (p < pend) {
1091 if ((p->as.basic.flags & FL_MARK) &&
1092 (p->as.basic.flags != FL_MARK)) {
1093 gc_mark_children(objspace, (VALUE)p, 0);
1095 p++;
1100 static void
1101 gc_mark_rest(rb_objspace_t *objspace)
1103 VALUE tmp_arry[MARK_STACK_MAX];
1104 VALUE *p;
1106 p = (mark_stack_ptr - mark_stack) + tmp_arry;
1107 MEMCPY(tmp_arry, mark_stack, VALUE, p - tmp_arry);
1109 init_mark_stack(objspace);
1110 while (p != tmp_arry) {
1111 p--;
1112 gc_mark_children(objspace, *p, 0);
1116 static inline int
1117 is_pointer_to_heap(rb_objspace_t *objspace, void *ptr)
1119 register RVALUE *p = RANY(ptr);
1120 register struct heaps_slot *heap;
1121 register size_t hi, lo, mid;
1123 if (p < lomem || p > himem) return Qfalse;
1124 if ((VALUE)p % sizeof(RVALUE) != 0) return Qfalse;
1126 /* check if p looks like a pointer using bsearch*/
1127 lo = 0;
1128 hi = heaps_used;
1129 while (lo < hi) {
1130 mid = (lo + hi) / 2;
1131 heap = &heaps[mid];
1132 if (heap->slot <= p) {
1133 if (p < heap->slot + heap->limit)
1134 return Qtrue;
1135 lo = mid + 1;
1137 else {
1138 hi = mid;
1141 return Qfalse;
1144 static void
1145 mark_locations_array(rb_objspace_t *objspace, register VALUE *x, register long n)
1147 VALUE v;
1148 while (n--) {
1149 v = *x;
1150 VALGRIND_MAKE_MEM_DEFINED(&v, sizeof(v));
1151 if (is_pointer_to_heap(objspace, (void *)v)) {
1152 gc_mark(objspace, v, 0);
1154 x++;
1158 static void
1159 gc_mark_locations(rb_objspace_t *objspace, VALUE *start, VALUE *end)
1161 long n;
1163 if (end <= start) return;
1164 n = end - start;
1165 mark_locations_array(objspace, start, n);
1168 void
1169 rb_gc_mark_locations(VALUE *start, VALUE *end)
1171 gc_mark_locations(&rb_objspace, start, end);
1174 #define rb_gc_mark_locations(start, end) gc_mark_locations(objspace, start, end)
1176 struct mark_tbl_arg {
1177 rb_objspace_t *objspace;
1178 int lev;
1181 static int
1182 mark_entry(ID key, VALUE value, st_data_t data)
1184 struct mark_tbl_arg *arg = (void*)data;
1185 gc_mark(arg->objspace, value, arg->lev);
1186 return ST_CONTINUE;
1189 static void
1190 mark_tbl(rb_objspace_t *objspace, st_table *tbl, int lev)
1192 struct mark_tbl_arg arg;
1193 if (!tbl) return;
1194 arg.objspace = objspace;
1195 arg.lev = lev;
1196 st_foreach(tbl, mark_entry, (st_data_t)&arg);
1199 void
1200 rb_mark_tbl(st_table *tbl)
1202 mark_tbl(&rb_objspace, tbl, 0);
1205 static int
1206 mark_key(VALUE key, VALUE value, st_data_t data)
1208 struct mark_tbl_arg *arg = (void*)data;
1209 gc_mark(arg->objspace, key, arg->lev);
1210 return ST_CONTINUE;
1213 static void
1214 mark_set(rb_objspace_t *objspace, st_table *tbl, int lev)
1216 struct mark_tbl_arg arg;
1217 if (!tbl) return;
1218 arg.objspace = objspace;
1219 arg.lev = lev;
1220 st_foreach(tbl, mark_key, (st_data_t)&arg);
1223 void
1224 rb_mark_set(st_table *tbl)
1226 mark_set(&rb_objspace, tbl, 0);
1229 static int
1230 mark_keyvalue(VALUE key, VALUE value, st_data_t data)
1232 struct mark_tbl_arg *arg = (void*)data;
1233 gc_mark(arg->objspace, key, arg->lev);
1234 gc_mark(arg->objspace, value, arg->lev);
1235 return ST_CONTINUE;
1238 static void
1239 mark_hash(rb_objspace_t *objspace, st_table *tbl, int lev)
1241 struct mark_tbl_arg arg;
1242 if (!tbl) return;
1243 arg.objspace = objspace;
1244 arg.lev = lev;
1245 st_foreach(tbl, mark_keyvalue, (st_data_t)&arg);
1248 void
1249 rb_mark_hash(st_table *tbl)
1251 mark_hash(&rb_objspace, tbl, 0);
1254 void
1255 rb_gc_mark_maybe(VALUE obj)
1257 if (is_pointer_to_heap(&rb_objspace, (void *)obj)) {
1258 gc_mark(&rb_objspace, obj, 0);
1262 #define GC_LEVEL_MAX 250
1264 static void
1265 gc_mark(rb_objspace_t *objspace, VALUE ptr, int lev)
1267 register RVALUE *obj;
1269 obj = RANY(ptr);
1270 if (rb_special_const_p(ptr)) return; /* special const not marked */
1271 if (obj->as.basic.flags == 0) return; /* free cell */
1272 if (obj->as.basic.flags & FL_MARK) return; /* already marked */
1273 obj->as.basic.flags |= FL_MARK;
1275 if (lev > GC_LEVEL_MAX || (lev == 0 && ruby_stack_check())) {
1276 if (!mark_stack_overflow) {
1277 if (mark_stack_ptr - mark_stack < MARK_STACK_MAX) {
1278 *mark_stack_ptr = ptr;
1279 mark_stack_ptr++;
1281 else {
1282 mark_stack_overflow = 1;
1285 return;
1287 gc_mark_children(objspace, ptr, lev+1);
1290 void
1291 rb_gc_mark(VALUE ptr)
1293 gc_mark(&rb_objspace, ptr, 0);
1296 static void
1297 gc_mark_children(rb_objspace_t *objspace, VALUE ptr, int lev)
1299 register RVALUE *obj = RANY(ptr);
1301 goto marking; /* skip */
1303 again:
1304 obj = RANY(ptr);
1305 if (rb_special_const_p(ptr)) return; /* special const not marked */
1306 if (obj->as.basic.flags == 0) return; /* free cell */
1307 if (obj->as.basic.flags & FL_MARK) return; /* already marked */
1308 obj->as.basic.flags |= FL_MARK;
1310 marking:
1311 if (FL_TEST(obj, FL_EXIVAR)) {
1312 rb_mark_generic_ivar(ptr);
1315 switch (BUILTIN_TYPE(obj)) {
1316 case T_NIL:
1317 case T_FIXNUM:
1318 rb_bug("rb_gc_mark() called for broken object");
1319 break;
1321 case T_NODE:
1322 switch (nd_type(obj)) {
1323 case NODE_IF: /* 1,2,3 */
1324 case NODE_FOR:
1325 case NODE_ITER:
1326 case NODE_WHEN:
1327 case NODE_MASGN:
1328 case NODE_RESCUE:
1329 case NODE_RESBODY:
1330 case NODE_CLASS:
1331 case NODE_BLOCK_PASS:
1332 gc_mark(objspace, (VALUE)obj->as.node.u2.node, lev);
1333 /* fall through */
1334 case NODE_BLOCK: /* 1,3 */
1335 case NODE_OPTBLOCK:
1336 case NODE_ARRAY:
1337 case NODE_DSTR:
1338 case NODE_DXSTR:
1339 case NODE_DREGX:
1340 case NODE_DREGX_ONCE:
1341 case NODE_ENSURE:
1342 case NODE_CALL:
1343 case NODE_DEFS:
1344 case NODE_OP_ASGN1:
1345 case NODE_ARGS:
1346 gc_mark(objspace, (VALUE)obj->as.node.u1.node, lev);
1347 /* fall through */
1348 case NODE_SUPER: /* 3 */
1349 case NODE_FCALL:
1350 case NODE_DEFN:
1351 case NODE_ARGS_AUX:
1352 ptr = (VALUE)obj->as.node.u3.node;
1353 goto again;
1355 case NODE_METHOD: /* 1,2 */
1356 case NODE_WHILE:
1357 case NODE_UNTIL:
1358 case NODE_AND:
1359 case NODE_OR:
1360 case NODE_CASE:
1361 case NODE_SCLASS:
1362 case NODE_DOT2:
1363 case NODE_DOT3:
1364 case NODE_FLIP2:
1365 case NODE_FLIP3:
1366 case NODE_MATCH2:
1367 case NODE_MATCH3:
1368 case NODE_OP_ASGN_OR:
1369 case NODE_OP_ASGN_AND:
1370 case NODE_MODULE:
1371 case NODE_ALIAS:
1372 case NODE_VALIAS:
1373 case NODE_ARGSCAT:
1374 gc_mark(objspace, (VALUE)obj->as.node.u1.node, lev);
1375 /* fall through */
1376 case NODE_FBODY: /* 2 */
1377 case NODE_GASGN:
1378 case NODE_LASGN:
1379 case NODE_DASGN:
1380 case NODE_DASGN_CURR:
1381 case NODE_IASGN:
1382 case NODE_IASGN2:
1383 case NODE_CVASGN:
1384 case NODE_COLON3:
1385 case NODE_OPT_N:
1386 case NODE_EVSTR:
1387 case NODE_UNDEF:
1388 case NODE_POSTEXE:
1389 ptr = (VALUE)obj->as.node.u2.node;
1390 goto again;
1392 case NODE_HASH: /* 1 */
1393 case NODE_LIT:
1394 case NODE_STR:
1395 case NODE_XSTR:
1396 case NODE_DEFINED:
1397 case NODE_MATCH:
1398 case NODE_RETURN:
1399 case NODE_BREAK:
1400 case NODE_NEXT:
1401 case NODE_YIELD:
1402 case NODE_COLON2:
1403 case NODE_SPLAT:
1404 case NODE_TO_ARY:
1405 ptr = (VALUE)obj->as.node.u1.node;
1406 goto again;
1408 case NODE_SCOPE: /* 2,3 */
1409 case NODE_CDECL:
1410 case NODE_OPT_ARG:
1411 gc_mark(objspace, (VALUE)obj->as.node.u3.node, lev);
1412 ptr = (VALUE)obj->as.node.u2.node;
1413 goto again;
1415 case NODE_ZARRAY: /* - */
1416 case NODE_ZSUPER:
1417 case NODE_CFUNC:
1418 case NODE_VCALL:
1419 case NODE_GVAR:
1420 case NODE_LVAR:
1421 case NODE_DVAR:
1422 case NODE_IVAR:
1423 case NODE_CVAR:
1424 case NODE_NTH_REF:
1425 case NODE_BACK_REF:
1426 case NODE_REDO:
1427 case NODE_RETRY:
1428 case NODE_SELF:
1429 case NODE_NIL:
1430 case NODE_TRUE:
1431 case NODE_FALSE:
1432 case NODE_ERRINFO:
1433 case NODE_ATTRSET:
1434 case NODE_BLOCK_ARG:
1435 break;
1436 case NODE_ALLOCA:
1437 mark_locations_array(objspace,
1438 (VALUE*)obj->as.node.u1.value,
1439 obj->as.node.u3.cnt);
1440 ptr = (VALUE)obj->as.node.u2.node;
1441 goto again;
1443 default: /* unlisted NODE */
1444 if (is_pointer_to_heap(objspace, obj->as.node.u1.node)) {
1445 gc_mark(objspace, (VALUE)obj->as.node.u1.node, lev);
1447 if (is_pointer_to_heap(objspace, obj->as.node.u2.node)) {
1448 gc_mark(objspace, (VALUE)obj->as.node.u2.node, lev);
1450 if (is_pointer_to_heap(objspace, obj->as.node.u3.node)) {
1451 gc_mark(objspace, (VALUE)obj->as.node.u3.node, lev);
1454 return; /* no need to mark class. */
1457 gc_mark(objspace, obj->as.basic.klass, lev);
1458 switch (BUILTIN_TYPE(obj)) {
1459 case T_ICLASS:
1460 case T_CLASS:
1461 case T_MODULE:
1462 mark_tbl(objspace, RCLASS_M_TBL(obj), lev);
1463 mark_tbl(objspace, RCLASS_IV_TBL(obj), lev);
1464 ptr = RCLASS_SUPER(obj);
1465 goto again;
1467 case T_ARRAY:
1468 if (FL_TEST(obj, ELTS_SHARED)) {
1469 ptr = obj->as.array.aux.shared;
1470 goto again;
1472 else {
1473 long i, len = RARRAY_LEN(obj);
1474 VALUE *ptr = RARRAY_PTR(obj);
1475 for (i=0; i < len; i++) {
1476 gc_mark(objspace, *ptr++, lev);
1479 break;
1481 case T_HASH:
1482 mark_hash(objspace, obj->as.hash.ntbl, lev);
1483 ptr = obj->as.hash.ifnone;
1484 goto again;
1486 case T_STRING:
1487 #define STR_ASSOC FL_USER3 /* copied from string.c */
1488 if (FL_TEST(obj, RSTRING_NOEMBED) && FL_ANY(obj, ELTS_SHARED|STR_ASSOC)) {
1489 ptr = obj->as.string.as.heap.aux.shared;
1490 goto again;
1492 break;
1494 case T_DATA:
1495 if (obj->as.data.dmark) (*obj->as.data.dmark)(DATA_PTR(obj));
1496 break;
1498 case T_OBJECT:
1500 long i, len = ROBJECT_NUMIV(obj);
1501 VALUE *ptr = ROBJECT_IVPTR(obj);
1502 for (i = 0; i < len; i++) {
1503 gc_mark(objspace, *ptr++, lev);
1506 break;
1508 case T_FILE:
1509 if (obj->as.file.fptr)
1510 gc_mark(objspace, obj->as.file.fptr->tied_io_for_writing, lev);
1511 break;
1513 case T_REGEXP:
1514 gc_mark(objspace, obj->as.regexp.src, lev);
1515 break;
1517 case T_FLOAT:
1518 case T_BIGNUM:
1519 break;
1521 case T_MATCH:
1522 gc_mark(objspace, obj->as.match.regexp, lev);
1523 if (obj->as.match.str) {
1524 ptr = obj->as.match.str;
1525 goto again;
1527 break;
1529 case T_RATIONAL:
1530 gc_mark(objspace, obj->as.rational.num, lev);
1531 gc_mark(objspace, obj->as.rational.den, lev);
1532 break;
1534 case T_COMPLEX:
1535 gc_mark(objspace, obj->as.complex.real, lev);
1536 gc_mark(objspace, obj->as.complex.image, lev);
1537 break;
1539 case T_STRUCT:
1541 long len = RSTRUCT_LEN(obj);
1542 VALUE *ptr = RSTRUCT_PTR(obj);
1544 while (len--) {
1545 gc_mark(objspace, *ptr++, lev);
1548 break;
1550 default:
1551 rb_bug("rb_gc_mark(): unknown data type 0x%lx(%p) %s",
1552 BUILTIN_TYPE(obj), obj,
1553 is_pointer_to_heap(objspace, obj) ? "corrupted object" : "non object");
1557 static int obj_free(rb_objspace_t *, VALUE);
1559 static inline void
1560 add_freelist(rb_objspace_t *objspace, RVALUE *p)
1562 VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
1563 p->as.free.flags = 0;
1564 p->as.free.next = freelist;
1565 freelist = p;
1568 static void
1569 finalize_list(rb_objspace_t *objspace, RVALUE *p)
1571 while (p) {
1572 RVALUE *tmp = p->as.free.next;
1573 run_final(objspace, (VALUE)p);
1574 if (!FL_TEST(p, FL_SINGLETON)) { /* not freeing page */
1575 add_freelist(objspace, p);
1577 else {
1578 struct heaps_slot *slot = (struct heaps_slot *)RDATA(p)->dmark;
1579 slot->limit--;
1581 p = tmp;
1585 static void
1586 free_unused_heaps(rb_objspace_t *objspace)
1588 size_t i, j;
1589 RVALUE *last = 0;
1591 for (i = j = 1; j < heaps_used; i++) {
1592 if (heaps[i].limit == 0) {
1593 if (!last) {
1594 last = heaps[i].membase;
1596 else {
1597 free(heaps[i].membase);
1599 heaps_used--;
1601 else {
1602 if (i != j) {
1603 heaps[j] = heaps[i];
1605 j++;
1608 if (last) {
1609 if (last < heaps_freed) {
1610 free(heaps_freed);
1611 heaps_freed = last;
1613 else {
1614 free(last);
1619 static void
1620 gc_sweep(rb_objspace_t *objspace)
1622 RVALUE *p, *pend, *final_list;
1623 size_t freed = 0;
1624 size_t i;
1625 size_t live = 0, free_min = 0, do_heap_free = 0;
1627 do_heap_free = (heaps_used * HEAP_OBJ_LIMIT) * 0.65;
1628 free_min = (heaps_used * HEAP_OBJ_LIMIT) * 0.2;
1630 if (free_min < FREE_MIN) {
1631 do_heap_free = heaps_used * HEAP_OBJ_LIMIT;
1632 free_min = FREE_MIN;
1635 freelist = 0;
1636 final_list = deferred_final_list;
1637 deferred_final_list = 0;
1638 for (i = 0; i < heaps_used; i++) {
1639 int n = 0;
1640 RVALUE *free = freelist;
1641 RVALUE *final = final_list;
1642 int deferred;
1644 p = heaps[i].slot; pend = p + heaps[i].limit;
1645 while (p < pend) {
1646 if (!(p->as.basic.flags & FL_MARK)) {
1647 if (p->as.basic.flags &&
1648 ((deferred = obj_free(objspace, (VALUE)p)) ||
1649 ((FL_TEST(p, FL_FINALIZE)) && need_call_final))) {
1650 if (!deferred) {
1651 p->as.free.flags = T_DEFERRED;
1652 RDATA(p)->dfree = 0;
1654 p->as.free.flags |= FL_MARK;
1655 p->as.free.next = final_list;
1656 final_list = p;
1658 else {
1659 add_freelist(objspace, p);
1661 n++;
1663 else if (BUILTIN_TYPE(p) == T_DEFERRED) {
1664 /* objects to be finalized */
1665 /* do nothing remain marked */
1667 else {
1668 RBASIC(p)->flags &= ~FL_MARK;
1669 live++;
1671 p++;
1673 if (n == heaps[i].limit && freed > do_heap_free) {
1674 RVALUE *pp;
1675 int f_count = 0;
1677 for (pp = final_list; pp != final; pp = pp->as.free.next) {
1678 f_count++;
1679 RDATA(pp)->dmark = (void *)&heaps[i];
1680 pp->as.free.flags |= FL_SINGLETON; /* freeing page mark */
1682 heaps[i].limit = f_count;
1684 freelist = free; /* cancel this page from freelist */
1686 else {
1687 freed += n;
1690 GC_PROF_SET_MALLOC_INFO;
1691 if (malloc_increase > malloc_limit) {
1692 malloc_limit += (malloc_increase - malloc_limit) * (double)live / (live + freed);
1693 if (malloc_limit < GC_MALLOC_LIMIT) malloc_limit = GC_MALLOC_LIMIT;
1695 malloc_increase = 0;
1696 if (freed < free_min) {
1697 set_heaps_increment(objspace);
1698 heaps_increment(objspace);
1700 during_gc = 0;
1702 /* clear finalization list */
1703 if (final_list) {
1704 GC_PROF_SET_HEAP_INFO;
1705 deferred_final_list = final_list;
1706 RUBY_VM_SET_FINALIZER_INTERRUPT(GET_THREAD());
1708 else{
1709 free_unused_heaps(objspace);
1710 GC_PROF_SET_HEAP_INFO;
1714 void
1715 rb_gc_force_recycle(VALUE p)
1717 rb_objspace_t *objspace = &rb_objspace;
1718 add_freelist(objspace, (RVALUE *)p);
1721 static inline void
1722 make_deferred(RVALUE *p)
1724 p->as.basic.flags = (p->as.basic.flags & ~T_MASK) | T_DEFERRED;
1727 static int
1728 obj_free(rb_objspace_t *objspace, VALUE obj)
1730 switch (BUILTIN_TYPE(obj)) {
1731 case T_NIL:
1732 case T_FIXNUM:
1733 case T_TRUE:
1734 case T_FALSE:
1735 rb_bug("obj_free() called for broken object");
1736 break;
1739 if (FL_TEST(obj, FL_EXIVAR)) {
1740 rb_free_generic_ivar((VALUE)obj);
1741 FL_UNSET(obj, FL_EXIVAR);
1744 switch (BUILTIN_TYPE(obj)) {
1745 case T_OBJECT:
1746 if (!(RANY(obj)->as.basic.flags & ROBJECT_EMBED) &&
1747 RANY(obj)->as.object.as.heap.ivptr) {
1748 xfree(RANY(obj)->as.object.as.heap.ivptr);
1750 break;
1751 case T_MODULE:
1752 case T_CLASS:
1753 rb_clear_cache_by_class((VALUE)obj);
1754 st_free_table(RCLASS_M_TBL(obj));
1755 if (RCLASS_IV_TBL(obj)) {
1756 st_free_table(RCLASS_IV_TBL(obj));
1758 if (RCLASS_IV_INDEX_TBL(obj)) {
1759 st_free_table(RCLASS_IV_INDEX_TBL(obj));
1761 xfree(RANY(obj)->as.klass.ptr);
1762 break;
1763 case T_STRING:
1764 rb_str_free(obj);
1765 break;
1766 case T_ARRAY:
1767 rb_ary_free(obj);
1768 break;
1769 case T_HASH:
1770 if (RANY(obj)->as.hash.ntbl) {
1771 st_free_table(RANY(obj)->as.hash.ntbl);
1773 break;
1774 case T_REGEXP:
1775 if (RANY(obj)->as.regexp.ptr) {
1776 onig_free(RANY(obj)->as.regexp.ptr);
1778 break;
1779 case T_DATA:
1780 if (DATA_PTR(obj)) {
1781 if ((long)RANY(obj)->as.data.dfree == -1) {
1782 xfree(DATA_PTR(obj));
1784 else if (RANY(obj)->as.data.dfree) {
1785 make_deferred(RANY(obj));
1786 return 1;
1789 break;
1790 case T_MATCH:
1791 if (RANY(obj)->as.match.rmatch) {
1792 struct rmatch *rm = RANY(obj)->as.match.rmatch;
1793 onig_region_free(&rm->regs, 0);
1794 if (rm->char_offset)
1795 xfree(rm->char_offset);
1796 xfree(rm);
1798 break;
1799 case T_FILE:
1800 if (RANY(obj)->as.file.fptr) {
1801 rb_io_t *fptr = RANY(obj)->as.file.fptr;
1802 make_deferred(RANY(obj));
1803 RDATA(obj)->dfree = (void (*)(void*))rb_io_fptr_finalize;
1804 RDATA(obj)->data = fptr;
1805 return 1;
1807 break;
1808 case T_RATIONAL:
1809 case T_COMPLEX:
1810 break;
1811 case T_ICLASS:
1812 /* iClass shares table with the module */
1813 break;
1815 case T_FLOAT:
1816 break;
1818 case T_BIGNUM:
1819 if (!(RBASIC(obj)->flags & RBIGNUM_EMBED_FLAG) && RBIGNUM_DIGITS(obj)) {
1820 xfree(RBIGNUM_DIGITS(obj));
1822 break;
1823 case T_NODE:
1824 switch (nd_type(obj)) {
1825 case NODE_SCOPE:
1826 if (RANY(obj)->as.node.u1.tbl) {
1827 xfree(RANY(obj)->as.node.u1.tbl);
1829 break;
1830 case NODE_ALLOCA:
1831 xfree(RANY(obj)->as.node.u1.node);
1832 break;
1834 break; /* no need to free iv_tbl */
1836 case T_STRUCT:
1837 if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 &&
1838 RANY(obj)->as.rstruct.as.heap.ptr) {
1839 xfree(RANY(obj)->as.rstruct.as.heap.ptr);
1841 break;
1843 default:
1844 rb_bug("gc_sweep(): unknown data type 0x%lx(%p)",
1845 BUILTIN_TYPE(obj), (void*)obj);
1848 return 0;
1851 #ifdef __GNUC__
1852 #if defined(__human68k__) || defined(DJGPP)
1853 #undef rb_setjmp
1854 #undef rb_jmp_buf
1855 #if defined(__human68k__)
1856 typedef unsigned long rb_jmp_buf[8];
1857 __asm__ (".even\n\
1858 _rb_setjmp:\n\
1859 move.l 4(sp),a0\n\
1860 movem.l d3-d7/a3-a5,(a0)\n\
1861 moveq.l #0,d0\n\
1862 rts");
1863 #else
1864 #if defined(DJGPP)
1865 typedef unsigned long rb_jmp_buf[6];
1866 __asm__ (".align 4\n\
1867 _rb_setjmp:\n\
1868 pushl %ebp\n\
1869 movl %esp,%ebp\n\
1870 movl 8(%ebp),%ebp\n\
1871 movl %eax,(%ebp)\n\
1872 movl %ebx,4(%ebp)\n\
1873 movl %ecx,8(%ebp)\n\
1874 movl %edx,12(%ebp)\n\
1875 movl %esi,16(%ebp)\n\
1876 movl %edi,20(%ebp)\n\
1877 popl %ebp\n\
1878 xorl %eax,%eax\n\
1879 ret");
1880 #endif
1881 #endif
1882 int rb_setjmp (rb_jmp_buf);
1883 #endif /* __human68k__ or DJGPP */
1884 #endif /* __GNUC__ */
1886 #define GC_NOTIFY 0
1888 void rb_vm_mark(void *ptr);
1890 static void
1891 mark_current_machine_context(rb_objspace_t *objspace, rb_thread_t *th)
1893 rb_jmp_buf save_regs_gc_mark;
1894 VALUE *stack_start, *stack_end;
1896 SET_STACK_END;
1897 #if STACK_GROW_DIRECTION < 0
1898 stack_start = th->machine_stack_end;
1899 stack_end = th->machine_stack_start;
1900 #elif STACK_GROW_DIRECTION > 0
1901 stack_start = th->machine_stack_start;
1902 stack_end = th->machine_stack_end + 1;
1903 #else
1904 if (th->machine_stack_end < th->machine_stack_start) {
1905 stack_start = th->machine_stack_end;
1906 stack_end = th->machine_stack_start;
1908 else {
1909 stack_start = th->machine_stack_start;
1910 stack_end = th->machine_stack_end + 1;
1912 #endif
1914 FLUSH_REGISTER_WINDOWS;
1915 /* This assumes that all registers are saved into the jmp_buf (and stack) */
1916 rb_setjmp(save_regs_gc_mark);
1917 mark_locations_array(objspace,
1918 (VALUE*)save_regs_gc_mark,
1919 sizeof(save_regs_gc_mark) / sizeof(VALUE));
1921 rb_gc_mark_locations(stack_start, stack_end);
1922 #ifdef __ia64
1923 rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end);
1924 #endif
1925 #if defined(__human68k__) || defined(__mc68000__)
1926 mark_locations_array((VALUE*)((char*)STACK_END + 2),
1927 (STACK_START - STACK_END));
1928 #endif
1931 void rb_gc_mark_encodings(void);
1933 static int
1934 garbage_collect(rb_objspace_t *objspace)
1936 struct gc_list *list;
1937 rb_thread_t *th = GET_THREAD();
1938 INIT_GC_PROF_PARAMS;
1940 if (GC_NOTIFY) printf("start garbage_collect()\n");
1942 if (!heaps) {
1943 return Qfalse;
1946 if (dont_gc || during_gc) {
1947 if (!freelist) {
1948 if (!heaps_increment(objspace)) {
1949 set_heaps_increment(objspace);
1950 heaps_increment(objspace);
1953 return Qtrue;
1955 during_gc++;
1956 objspace->count++;
1958 GC_PROF_TIMER_START;
1959 GC_PROF_MARK_TIMER_START;
1960 SET_STACK_END;
1962 init_mark_stack(objspace);
1964 th->vm->self ? rb_gc_mark(th->vm->self) : rb_vm_mark(th->vm);
1966 if (finalizer_table) {
1967 mark_tbl(objspace, finalizer_table, 0);
1970 mark_current_machine_context(objspace, th);
1972 rb_gc_mark_threads();
1973 rb_gc_mark_symbols();
1974 rb_gc_mark_encodings();
1976 /* mark protected global variables */
1977 for (list = global_List; list; list = list->next) {
1978 rb_gc_mark_maybe(*list->varptr);
1980 rb_mark_end_proc();
1981 rb_gc_mark_global_tbl();
1983 mark_tbl(objspace, rb_class_tbl, 0);
1984 rb_gc_mark_trap_list();
1986 /* mark generic instance variables for special constants */
1987 rb_mark_generic_ivar_tbl();
1989 rb_gc_mark_parser();
1991 /* gc_mark objects whose marking are not completed*/
1992 while (!MARK_STACK_EMPTY) {
1993 if (mark_stack_overflow) {
1994 gc_mark_all(objspace);
1996 else {
1997 gc_mark_rest(objspace);
2000 GC_PROF_MARK_TIMER_STOP;
2002 GC_PROF_SWEEP_TIMER_START;
2003 gc_sweep(objspace);
2004 GC_PROF_SWEEP_TIMER_STOP;
2006 GC_PROF_TIMER_STOP;
2007 if (GC_NOTIFY) printf("end garbage_collect()\n");
2008 return Qtrue;
2012 rb_garbage_collect(void)
2014 return garbage_collect(&rb_objspace);
2017 void
2018 rb_gc_mark_machine_stack(rb_thread_t *th)
2020 rb_objspace_t *objspace = &rb_objspace;
2021 #if STACK_GROW_DIRECTION < 0
2022 rb_gc_mark_locations(th->machine_stack_end, th->machine_stack_start);
2023 #elif STACK_GROW_DIRECTION > 0
2024 rb_gc_mark_locations(th->machine_stack_start, th->machine_stack_end);
2025 #else
2026 if (th->machine_stack_start < th->machine_stack_end) {
2027 rb_gc_mark_locations(th->machine_stack_start, th->machine_stack_end);
2029 else {
2030 rb_gc_mark_locations(th->machine_stack_end, th->machine_stack_start);
2032 #endif
2033 #ifdef __ia64
2034 rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end);
2035 #endif
2040 * call-seq:
2041 * GC.start => nil
2042 * gc.garbage_collect => nil
2043 * ObjectSpace.garbage_collect => nil
2045 * Initiates garbage collection, unless manually disabled.
2049 VALUE
2050 rb_gc_start(void)
2052 rb_gc();
2053 return Qnil;
2056 #undef Init_stack
2058 void
2059 Init_stack(VALUE *addr)
2061 ruby_init_stack(addr);
2065 * Document-class: ObjectSpace
2067 * The <code>ObjectSpace</code> module contains a number of routines
2068 * that interact with the garbage collection facility and allow you to
2069 * traverse all living objects with an iterator.
2071 * <code>ObjectSpace</code> also provides support for object
2072 * finalizers, procs that will be called when a specific object is
2073 * about to be destroyed by garbage collection.
2075 * include ObjectSpace
2078 * a = "A"
2079 * b = "B"
2080 * c = "C"
2083 * define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
2084 * define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
2085 * define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
2087 * <em>produces:</em>
2089 * Finalizer three on 537763470
2090 * Finalizer one on 537763480
2091 * Finalizer two on 537763480
2095 void
2096 Init_heap(void)
2098 init_heap(&rb_objspace);
2101 static VALUE
2102 os_obj_of(rb_objspace_t *objspace, VALUE of)
2104 size_t i;
2105 size_t n = 0;
2106 RVALUE *membase = 0;
2107 RVALUE *p, *pend;
2108 volatile VALUE v;
2110 i = 0;
2111 while (i < heaps_used) {
2112 while (0 < i && (uintptr_t)membase < (uintptr_t)heaps[i-1].membase)
2113 i--;
2114 while (i < heaps_used && (uintptr_t)heaps[i].membase <= (uintptr_t)membase )
2115 i++;
2116 if (heaps_used <= i)
2117 break;
2118 membase = heaps[i].membase;
2120 p = heaps[i].slot; pend = p + heaps[i].limit;
2121 for (;p < pend; p++) {
2122 if (p->as.basic.flags) {
2123 switch (BUILTIN_TYPE(p)) {
2124 case T_NONE:
2125 case T_ICLASS:
2126 case T_NODE:
2127 case T_DEFERRED:
2128 continue;
2129 case T_CLASS:
2130 if (FL_TEST(p, FL_SINGLETON)) continue;
2131 default:
2132 if (!p->as.basic.klass) continue;
2133 v = (VALUE)p;
2134 if (!of || rb_obj_is_kind_of(v, of)) {
2135 rb_yield(v);
2136 n++;
2143 return SIZET2NUM(n);
2147 * call-seq:
2148 * ObjectSpace.each_object([module]) {|obj| ... } => fixnum
2150 * Calls the block once for each living, nonimmediate object in this
2151 * Ruby process. If <i>module</i> is specified, calls the block
2152 * for only those classes or modules that match (or are a subclass of)
2153 * <i>module</i>. Returns the number of objects found. Immediate
2154 * objects (<code>Fixnum</code>s, <code>Symbol</code>s
2155 * <code>true</code>, <code>false</code>, and <code>nil</code>) are
2156 * never returned. In the example below, <code>each_object</code>
2157 * returns both the numbers we defined and several constants defined in
2158 * the <code>Math</code> module.
2160 * a = 102.7
2161 * b = 95 # Won't be returned
2162 * c = 12345678987654321
2163 * count = ObjectSpace.each_object(Numeric) {|x| p x }
2164 * puts "Total count: #{count}"
2166 * <em>produces:</em>
2168 * 12345678987654321
2169 * 102.7
2170 * 2.71828182845905
2171 * 3.14159265358979
2172 * 2.22044604925031e-16
2173 * 1.7976931348623157e+308
2174 * 2.2250738585072e-308
2175 * Total count: 7
2179 static VALUE
2180 os_each_obj(int argc, VALUE *argv, VALUE os)
2182 VALUE of;
2184 rb_secure(4);
2185 if (argc == 0) {
2186 of = 0;
2188 else {
2189 rb_scan_args(argc, argv, "01", &of);
2191 RETURN_ENUMERATOR(os, 1, &of);
2192 return os_obj_of(&rb_objspace, of);
2196 * call-seq:
2197 * ObjectSpace.undefine_finalizer(obj)
2199 * Removes all finalizers for <i>obj</i>.
2203 static VALUE
2204 undefine_final(VALUE os, VALUE obj)
2206 rb_objspace_t *objspace = &rb_objspace;
2207 if (finalizer_table) {
2208 st_delete(finalizer_table, (st_data_t*)&obj, 0);
2210 return obj;
2214 * call-seq:
2215 * ObjectSpace.define_finalizer(obj, aProc=proc())
2217 * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
2218 * was destroyed.
2222 static VALUE
2223 define_final(int argc, VALUE *argv, VALUE os)
2225 rb_objspace_t *objspace = &rb_objspace;
2226 VALUE obj, block, table;
2228 rb_scan_args(argc, argv, "11", &obj, &block);
2229 if (argc == 1) {
2230 block = rb_block_proc();
2232 else if (!rb_respond_to(block, rb_intern("call"))) {
2233 rb_raise(rb_eArgError, "wrong type argument %s (should be callable)",
2234 rb_obj_classname(block));
2236 FL_SET(obj, FL_FINALIZE);
2238 block = rb_ary_new3(2, INT2FIX(rb_safe_level()), block);
2240 if (!finalizer_table) {
2241 finalizer_table = st_init_numtable();
2243 if (st_lookup(finalizer_table, obj, &table)) {
2244 rb_ary_push(table, block);
2246 else {
2247 st_add_direct(finalizer_table, obj, rb_ary_new3(1, block));
2249 return block;
2252 void
2253 rb_gc_copy_finalizer(VALUE dest, VALUE obj)
2255 rb_objspace_t *objspace = &rb_objspace;
2256 VALUE table;
2258 if (!finalizer_table) return;
2259 if (!FL_TEST(obj, FL_FINALIZE)) return;
2260 if (st_lookup(finalizer_table, obj, &table)) {
2261 st_insert(finalizer_table, dest, table);
2263 FL_SET(dest, FL_FINALIZE);
2266 static VALUE
2267 run_single_final(VALUE arg)
2269 VALUE *args = (VALUE *)arg;
2270 rb_eval_cmd(args[0], args[1], (int)args[2]);
2271 return Qnil;
2274 static void
2275 run_final(rb_objspace_t *objspace, VALUE obj)
2277 long i;
2278 int status;
2279 VALUE args[3], table, objid;
2281 objid = rb_obj_id(obj); /* make obj into id */
2282 RBASIC(obj)->klass = 0;
2284 if (RDATA(obj)->dfree) {
2285 (*RDATA(obj)->dfree)(DATA_PTR(obj));
2288 if (finalizer_table &&
2289 st_delete(finalizer_table, (st_data_t*)&obj, &table)) {
2290 args[1] = 0;
2291 args[2] = (VALUE)rb_safe_level();
2292 if (!args[1] && RARRAY_LEN(table) > 0) {
2293 args[1] = rb_obj_freeze(rb_ary_new3(1, objid));
2295 for (i=0; i<RARRAY_LEN(table); i++) {
2296 VALUE final = RARRAY_PTR(table)[i];
2297 args[0] = RARRAY_PTR(final)[1];
2298 args[2] = FIX2INT(RARRAY_PTR(final)[0]);
2299 rb_protect(run_single_final, (VALUE)args, &status);
2304 static void
2305 gc_finalize_deferred(rb_objspace_t *objspace)
2307 RVALUE *p = deferred_final_list;
2308 deferred_final_list = 0;
2310 if (p) {
2311 finalize_list(objspace, p);
2313 free_unused_heaps(objspace);
2316 void
2317 rb_gc_finalize_deferred(void)
2319 gc_finalize_deferred(&rb_objspace);
2322 static int
2323 chain_finalized_object(st_data_t key, st_data_t val, st_data_t arg)
2325 RVALUE *p = (RVALUE *)key, **final_list = (RVALUE **)arg;
2326 if (p->as.basic.flags & FL_FINALIZE) {
2327 if (BUILTIN_TYPE(p) != T_DEFERRED) {
2328 p->as.free.flags = FL_MARK | T_DEFERRED; /* remain marked */
2329 RDATA(p)->dfree = 0;
2331 p->as.free.next = *final_list;
2332 *final_list = p;
2333 return ST_CONTINUE;
2335 else {
2336 return ST_DELETE;
2340 void
2341 rb_gc_call_finalizer_at_exit(void)
2343 rb_objspace_t *objspace = &rb_objspace;
2344 RVALUE *p, *pend;
2345 size_t i;
2347 /* run finalizers */
2348 if (finalizer_table) {
2349 p = deferred_final_list;
2350 deferred_final_list = 0;
2351 finalize_list(objspace, p);
2352 while (finalizer_table->num_entries > 0) {
2353 RVALUE *final_list = 0;
2354 st_foreach(finalizer_table, chain_finalized_object,
2355 (st_data_t)&final_list);
2356 if (!(p = final_list)) break;
2357 do {
2358 final_list = p->as.free.next;
2359 run_final(objspace, (VALUE)p);
2360 } while ((p = final_list) != 0);
2362 st_free_table(finalizer_table);
2363 finalizer_table = 0;
2365 /* finalizers are part of garbage collection */
2366 during_gc++;
2367 /* run data object's finalizers */
2368 for (i = 0; i < heaps_used; i++) {
2369 p = heaps[i].slot; pend = p + heaps[i].limit;
2370 while (p < pend) {
2371 if (BUILTIN_TYPE(p) == T_DATA &&
2372 DATA_PTR(p) && RANY(p)->as.data.dfree &&
2373 RANY(p)->as.basic.klass != rb_cThread) {
2374 p->as.free.flags = 0;
2375 if ((long)RANY(p)->as.data.dfree == -1) {
2376 xfree(DATA_PTR(p));
2378 else if (RANY(p)->as.data.dfree) {
2379 (*RANY(p)->as.data.dfree)(DATA_PTR(p));
2381 VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
2383 else if (BUILTIN_TYPE(p) == T_FILE) {
2384 if (rb_io_fptr_finalize(RANY(p)->as.file.fptr)) {
2385 p->as.free.flags = 0;
2386 VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
2389 p++;
2392 during_gc = 0;
2395 void
2396 rb_gc(void)
2398 rb_objspace_t *objspace = &rb_objspace;
2399 garbage_collect(objspace);
2400 gc_finalize_deferred(objspace);
2404 * call-seq:
2405 * ObjectSpace._id2ref(object_id) -> an_object
2407 * Converts an object id to a reference to the object. May not be
2408 * called on an object id passed as a parameter to a finalizer.
2410 * s = "I am a string" #=> "I am a string"
2411 * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
2412 * r == s #=> true
2416 static VALUE
2417 id2ref(VALUE obj, VALUE objid)
2419 #if SIZEOF_LONG == SIZEOF_VOIDP
2420 #define NUM2PTR(x) NUM2ULONG(x)
2421 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
2422 #define NUM2PTR(x) NUM2ULL(x)
2423 #endif
2424 rb_objspace_t *objspace = &rb_objspace;
2425 VALUE ptr;
2426 void *p0;
2428 rb_secure(4);
2429 ptr = NUM2PTR(objid);
2430 p0 = (void *)ptr;
2432 if (ptr == Qtrue) return Qtrue;
2433 if (ptr == Qfalse) return Qfalse;
2434 if (ptr == Qnil) return Qnil;
2435 if (FIXNUM_P(ptr)) return (VALUE)ptr;
2436 ptr = objid ^ FIXNUM_FLAG; /* unset FIXNUM_FLAG */
2438 if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
2439 ID symid = ptr / sizeof(RVALUE);
2440 if (rb_id2name(symid) == 0)
2441 rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
2442 return ID2SYM(symid);
2445 if (!is_pointer_to_heap(objspace, (void *)ptr) ||
2446 BUILTIN_TYPE(ptr) > T_FIXNUM || BUILTIN_TYPE(ptr) == T_ICLASS) {
2447 rb_raise(rb_eRangeError, "%p is not id value", p0);
2449 if (BUILTIN_TYPE(ptr) == 0 || RBASIC(ptr)->klass == 0) {
2450 rb_raise(rb_eRangeError, "%p is recycled object", p0);
2452 return (VALUE)ptr;
2456 * Document-method: __id__
2457 * Document-method: object_id
2459 * call-seq:
2460 * obj.__id__ => fixnum
2461 * obj.object_id => fixnum
2463 * Returns an integer identifier for <i>obj</i>. The same number will
2464 * be returned on all calls to <code>id</code> for a given object, and
2465 * no two active objects will share an id.
2466 * <code>Object#object_id</code> is a different concept from the
2467 * <code>:name</code> notation, which returns the symbol id of
2468 * <code>name</code>. Replaces the deprecated <code>Object#id</code>.
2472 * call-seq:
2473 * obj.hash => fixnum
2475 * Generates a <code>Fixnum</code> hash value for this object. This
2476 * function must have the property that <code>a.eql?(b)</code> implies
2477 * <code>a.hash == b.hash</code>. The hash value is used by class
2478 * <code>Hash</code>. Any hash value that exceeds the capacity of a
2479 * <code>Fixnum</code> will be truncated before being used.
2482 VALUE
2483 rb_obj_id(VALUE obj)
2486 * 32-bit VALUE space
2487 * MSB ------------------------ LSB
2488 * false 00000000000000000000000000000000
2489 * true 00000000000000000000000000000010
2490 * nil 00000000000000000000000000000100
2491 * undef 00000000000000000000000000000110
2492 * symbol ssssssssssssssssssssssss00001110
2493 * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
2494 * fixnum fffffffffffffffffffffffffffffff1
2496 * object_id space
2497 * LSB
2498 * false 00000000000000000000000000000000
2499 * true 00000000000000000000000000000010
2500 * nil 00000000000000000000000000000100
2501 * undef 00000000000000000000000000000110
2502 * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
2503 * object oooooooooooooooooooooooooooooo0 o...o % A = 0
2504 * fixnum fffffffffffffffffffffffffffffff1 bignum if required
2506 * where A = sizeof(RVALUE)/4
2508 * sizeof(RVALUE) is
2509 * 20 if 32-bit, double is 4-byte aligned
2510 * 24 if 32-bit, double is 8-byte aligned
2511 * 40 if 64-bit
2513 if (TYPE(obj) == T_SYMBOL) {
2514 return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
2516 if (SPECIAL_CONST_P(obj)) {
2517 return LONG2NUM((SIGNED_VALUE)obj);
2519 return (VALUE)((SIGNED_VALUE)obj|FIXNUM_FLAG);
2522 static int
2523 set_zero(st_data_t key, st_data_t val, st_data_t arg)
2525 VALUE k = (VALUE)key;
2526 VALUE hash = (VALUE)arg;
2527 rb_hash_aset(hash, k, INT2FIX(0));
2528 return ST_CONTINUE;
2532 * call-seq:
2533 * ObjectSpace.count_objects([result_hash]) -> hash
2535 * Counts objects for each type.
2537 * It returns a hash as:
2538 * {:TOTAL=>10000, :FREE=>3011, :T_OBJECT=>6, :T_CLASS=>404, ...}
2540 * If the optional argument, result_hash, is given,
2541 * it is overwritten and returned.
2542 * This is intended to avoid probe effect.
2544 * The contents of the returned hash is implementation defined.
2545 * It may be changed in future.
2547 * This method is not expected to work except C Ruby.
2551 static VALUE
2552 count_objects(int argc, VALUE *argv, VALUE os)
2554 rb_objspace_t *objspace = &rb_objspace;
2555 size_t counts[T_MASK+1];
2556 size_t freed = 0;
2557 size_t total = 0;
2558 size_t i;
2559 VALUE hash;
2561 if (rb_scan_args(argc, argv, "01", &hash) == 1) {
2562 if (TYPE(hash) != T_HASH)
2563 rb_raise(rb_eTypeError, "non-hash given");
2566 for (i = 0; i <= T_MASK; i++) {
2567 counts[i] = 0;
2570 for (i = 0; i < heaps_used; i++) {
2571 RVALUE *p, *pend;
2573 p = heaps[i].slot; pend = p + heaps[i].limit;
2574 for (;p < pend; p++) {
2575 if (p->as.basic.flags) {
2576 counts[BUILTIN_TYPE(p)]++;
2578 else {
2579 freed++;
2582 total += heaps[i].limit;
2585 if (hash == Qnil) {
2586 hash = rb_hash_new();
2588 else if (!RHASH_EMPTY_P(hash)) {
2589 st_foreach(RHASH_TBL(hash), set_zero, hash);
2591 rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
2592 rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed));
2594 for (i = 0; i <= T_MASK; i++) {
2595 VALUE type;
2596 switch (i) {
2597 #define COUNT_TYPE(t) case t: type = ID2SYM(rb_intern(#t)); break;
2598 COUNT_TYPE(T_NONE);
2599 COUNT_TYPE(T_OBJECT);
2600 COUNT_TYPE(T_CLASS);
2601 COUNT_TYPE(T_MODULE);
2602 COUNT_TYPE(T_FLOAT);
2603 COUNT_TYPE(T_STRING);
2604 COUNT_TYPE(T_REGEXP);
2605 COUNT_TYPE(T_ARRAY);
2606 COUNT_TYPE(T_HASH);
2607 COUNT_TYPE(T_STRUCT);
2608 COUNT_TYPE(T_BIGNUM);
2609 COUNT_TYPE(T_FILE);
2610 COUNT_TYPE(T_DATA);
2611 COUNT_TYPE(T_MATCH);
2612 COUNT_TYPE(T_COMPLEX);
2613 COUNT_TYPE(T_RATIONAL);
2614 COUNT_TYPE(T_NIL);
2615 COUNT_TYPE(T_TRUE);
2616 COUNT_TYPE(T_FALSE);
2617 COUNT_TYPE(T_SYMBOL);
2618 COUNT_TYPE(T_FIXNUM);
2619 COUNT_TYPE(T_UNDEF);
2620 COUNT_TYPE(T_NODE);
2621 COUNT_TYPE(T_ICLASS);
2622 COUNT_TYPE(T_DEFERRED);
2623 #undef COUNT_TYPE
2624 default: type = INT2NUM(i); break;
2626 if (counts[i])
2627 rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
2630 return hash;
2634 * call-seq:
2635 * GC.count -> Integer
2637 * The number of times GC occured.
2639 * It returns the number of times GC occured since the process started.
2643 static VALUE
2644 gc_count(VALUE self)
2646 return UINT2NUM((&rb_objspace)->count);
2649 #if CALC_EXACT_MALLOC_SIZE
2651 * call-seq:
2652 * GC.malloc_allocated_size -> Integer
2654 * The allocated size by malloc().
2656 * It returns the allocated size by malloc().
2659 static VALUE
2660 gc_malloc_allocated_size(VALUE self)
2662 return UINT2NUM((&rb_objspace)->malloc_params.allocated_size);
2666 * call-seq:
2667 * GC.malloc_allocations -> Integer
2669 * The number of allocated memory object by malloc().
2671 * It returns the number of allocated memory object by malloc().
2674 static VALUE
2675 gc_malloc_allocations(VALUE self)
2677 return UINT2NUM((&rb_objspace)->malloc_params.allocations);
2679 #endif
2681 VALUE
2682 gc_profile_record_get(void)
2684 VALUE prof;
2685 VALUE gc_profile = rb_ary_new();
2686 size_t i;
2687 rb_objspace_t *objspace = (&rb_objspace);
2689 if (!objspace->profile.run) {
2690 return Qnil;
2693 for (i =0; i < objspace->profile.count; i++) {
2694 prof = rb_hash_new();
2695 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_time));
2696 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_invoke_time));
2697 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), rb_uint2inum(objspace->profile.record[i].heap_use_size));
2698 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), rb_uint2inum(objspace->profile.record[i].heap_total_size));
2699 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), rb_uint2inum(objspace->profile.record[i].heap_total_objects));
2700 #if GC_PROFILE_MORE_DETAIL
2701 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_mark_time));
2702 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_sweep_time));
2703 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), rb_uint2inum(objspace->profile.record[i].allocate_increase));
2704 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), rb_uint2inum(objspace->profile.record[i].allocate_limit));
2705 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SLOTS")), rb_uint2inum(objspace->profile.record[i].heap_use_slots));
2706 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), rb_uint2inum(objspace->profile.record[i].heap_live_objects));
2707 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), rb_uint2inum(objspace->profile.record[i].heap_free_objects));
2708 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), objspace->profile.record[i].have_finalize);
2709 #endif
2710 rb_ary_push(gc_profile, prof);
2713 return gc_profile;
2717 * call-seq:
2718 * GC::Profiler.result -> string
2720 * Report profile data to string.
2722 * It returns a string as:
2723 * GC 1 invokes.
2724 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
2725 * 1 0.012 159240 212940 10647 0.00000000000001530000
2728 VALUE
2729 gc_profile_result(void)
2731 rb_objspace_t *objspace = &rb_objspace;
2732 VALUE record = gc_profile_record_get();
2733 VALUE result;
2734 int i;
2736 if (objspace->profile.run && objspace->profile.count) {
2737 result = rb_sprintf("GC %d invokes.\n", NUM2INT(gc_count(0)));
2738 rb_str_cat2(result, "Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n");
2739 for (i = 0; i < (int)RARRAY_LEN(record); i++) {
2740 VALUE r = RARRAY_PTR(record)[i];
2741 rb_str_catf(result, "%5d %19.3f %20d %20d %20d %30.20f\n",
2742 i+1, NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_INVOKE_TIME")))),
2743 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_USE_SIZE")))),
2744 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")))),
2745 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")))),
2746 NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_TIME"))))*100);
2748 #if GC_PROFILE_MORE_DETAIL
2749 rb_str_cat2(result, "\n\n");
2750 rb_str_cat2(result, "More detail.\n");
2751 rb_str_cat2(result, "Index Allocate Increase Allocate Limit Use Slot Have Finalize Mark Time(ms) Sweep Time(ms)\n");
2752 for (i = 0; i < (int)RARRAY_LEN(record); i++) {
2753 VALUE r = RARRAY_PTR(record)[i];
2754 rb_str_catf(result, "%5d %17d %17d %9d %14s %25.20f %25.20f\n",
2755 i+1, NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("ALLOCATE_INCREASE")))),
2756 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("ALLOCATE_LIMIT")))),
2757 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_USE_SLOTS")))),
2758 rb_hash_aref(r, ID2SYM(rb_intern("HAVE_FINALIZE")))? "true" : "false",
2759 NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_MARK_TIME"))))*100,
2760 NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_SWEEP_TIME"))))*100);
2762 #endif
2764 else {
2765 result = rb_str_new2("");
2767 return result;
2772 * call-seq:
2773 * GC::Profiler.report
2775 * GC::Profiler.result display
2779 VALUE
2780 gc_profile_report(int argc, VALUE *argv, VALUE self)
2782 VALUE out;
2784 if (argc == 0) {
2785 out = rb_stdout;
2787 else {
2788 rb_scan_args(argc, argv, "01", &out);
2790 rb_io_write(out, gc_profile_result());
2792 return Qnil;
2797 * The <code>GC</code> module provides an interface to Ruby's mark and
2798 * sweep garbage collection mechanism. Some of the underlying methods
2799 * are also available via the <code>ObjectSpace</code> module.
2802 void
2803 Init_GC(void)
2805 VALUE rb_mObSpace;
2806 VALUE rb_mProfiler;
2808 rb_mGC = rb_define_module("GC");
2809 rb_define_singleton_method(rb_mGC, "start", rb_gc_start, 0);
2810 rb_define_singleton_method(rb_mGC, "enable", rb_gc_enable, 0);
2811 rb_define_singleton_method(rb_mGC, "disable", rb_gc_disable, 0);
2812 rb_define_singleton_method(rb_mGC, "stress", gc_stress_get, 0);
2813 rb_define_singleton_method(rb_mGC, "stress=", gc_stress_set, 1);
2814 rb_define_singleton_method(rb_mGC, "count", gc_count, 0);
2815 rb_define_method(rb_mGC, "garbage_collect", rb_gc_start, 0);
2817 rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
2818 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
2819 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
2820 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
2821 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
2822 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
2823 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
2825 rb_mObSpace = rb_define_module("ObjectSpace");
2826 rb_define_module_function(rb_mObSpace, "each_object", os_each_obj, -1);
2827 rb_define_module_function(rb_mObSpace, "garbage_collect", rb_gc_start, 0);
2829 rb_define_module_function(rb_mObSpace, "define_finalizer", define_final, -1);
2830 rb_define_module_function(rb_mObSpace, "undefine_finalizer", undefine_final, 1);
2832 rb_define_module_function(rb_mObSpace, "_id2ref", id2ref, 1);
2834 nomem_error = rb_exc_new3(rb_eNoMemError,
2835 rb_obj_freeze(rb_str_new2("failed to allocate memory")));
2836 OBJ_TAINT(nomem_error);
2837 OBJ_FREEZE(nomem_error);
2839 rb_define_method(rb_mKernel, "hash", rb_obj_id, 0);
2840 rb_define_method(rb_mKernel, "__id__", rb_obj_id, 0);
2841 rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
2843 rb_define_module_function(rb_mObSpace, "count_objects", count_objects, -1);
2845 #if CALC_EXACT_MALLOC_SIZE
2846 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
2847 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
2848 #endif