* io.c (rb_open_file): encoding in mode string was ignored if perm is
[ruby-svn.git] / gc.c
blob551437ac442b18b8f734a7db5e764400cdf14b21
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 return t;
144 #else
145 return 0.0;
146 #endif
149 #define GC_PROF_TIMER_START do {\
150 if (objspace->profile.run) {\
151 if (!objspace->profile.record) {\
152 objspace->profile.size = 1000;\
153 objspace->profile.record = malloc(sizeof(gc_profile_record) * objspace->profile.size);\
155 if (count >= objspace->profile.size) {\
156 objspace->profile.size += 1000;\
157 objspace->profile.record = realloc(objspace->profile.record, sizeof(gc_profile_record) * objspace->profile.size);\
159 if (!objspace->profile.record) {\
160 rb_bug("gc_profile malloc or realloc miss");\
162 MEMZERO(&objspace->profile.record[count], gc_profile_record, 1);\
163 gc_time = getrusage_time();\
164 objspace->profile.record[count].gc_invoke_time = gc_time - objspace->profile.invoke_time;\
166 } while(0)
168 #define GC_PROF_TIMER_STOP do {\
169 if (objspace->profile.run) {\
170 gc_time = getrusage_time() - gc_time;\
171 if (gc_time < 0) gc_time = 0;\
172 objspace->profile.record[count].gc_time = gc_time;\
173 objspace->profile.count++;\
175 } while(0)
177 #if GC_PROFILE_MORE_DETAIL
178 #define INIT_GC_PROF_PARAMS double gc_time = 0, mark_time = 0, sweep_time = 0;\
179 size_t count = objspace->profile.count
181 #define GC_PROF_MARK_TIMER_START do {\
182 if (objspace->profile.run) {\
183 mark_time = getrusage_time();\
185 } while(0)
187 #define GC_PROF_MARK_TIMER_STOP do {\
188 if (objspace->profile.run) {\
189 mark_time = getrusage_time() - mark_time;\
190 if (mark_time < 0) mark_time = 0;\
191 objspace->profile.record[count].gc_mark_time = mark_time;\
193 } while(0)
195 #define GC_PROF_SWEEP_TIMER_START do {\
196 if (objspace->profile.run) {\
197 sweep_time = getrusage_time();\
199 } while(0)
201 #define GC_PROF_SWEEP_TIMER_STOP do {\
202 if (objspace->profile.run) {\
203 sweep_time = getrusage_time() - sweep_time;\
204 if (sweep_time < 0) sweep_time = 0;\
205 objspace->profile.record[count].gc_sweep_time = sweep_time;\
207 } while(0)
208 #define GC_PROF_SET_MALLOC_INFO do {\
209 if (objspace->profile.run) {\
210 size_t count = objspace->profile.count;\
211 objspace->profile.record[count].allocate_increase = malloc_increase;\
212 objspace->profile.record[count].allocate_limit = malloc_limit; \
214 } while(0)
215 #define GC_PROF_SET_HEAP_INFO do {\
216 if (objspace->profile.run) {\
217 size_t count = objspace->profile.count;\
218 objspace->profile.record[count].heap_use_slots = heaps_used;\
219 objspace->profile.record[count].heap_live_objects = live;\
220 objspace->profile.record[count].heap_free_objects = freed;\
221 objspace->profile.record[count].heap_total_objects = heaps_used * HEAP_OBJ_LIMIT;\
222 objspace->profile.record[count].have_finalize = final_list ? Qtrue : Qfalse;\
223 objspace->profile.record[count].heap_use_size = live * sizeof(RVALUE);\
224 objspace->profile.record[count].heap_total_size = heaps_used * (HEAP_OBJ_LIMIT * sizeof(RVALUE));\
226 } while(0)
228 #else
229 #define INIT_GC_PROF_PARAMS double gc_time = 0;\
230 size_t count = objspace->profile.count
231 #define GC_PROF_MARK_TIMER_START
232 #define GC_PROF_MARK_TIMER_STOP
233 #define GC_PROF_SWEEP_TIMER_START
234 #define GC_PROF_SWEEP_TIMER_STOP
235 #define GC_PROF_SET_MALLOC_INFO
236 #define GC_PROF_SET_HEAP_INFO do {\
237 if (objspace->profile.run) {\
238 size_t count = objspace->profile.count;\
239 objspace->profile.record[count].heap_total_objects = heaps_used * HEAP_OBJ_LIMIT;\
240 objspace->profile.record[count].heap_use_size = live * sizeof(RVALUE);\
241 objspace->profile.record[count].heap_total_size = heaps_used * HEAP_SIZE;\
243 } while(0)
244 #endif
247 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
248 #pragma pack(push, 1) /* magic for reducing sizeof(RVALUE): 24 -> 20 */
249 #endif
251 typedef struct RVALUE {
252 union {
253 struct {
254 VALUE flags; /* always 0 for freed obj */
255 struct RVALUE *next;
256 } free;
257 struct RBasic basic;
258 struct RObject object;
259 struct RClass klass;
260 struct RFloat flonum;
261 struct RString string;
262 struct RArray array;
263 struct RRegexp regexp;
264 struct RHash hash;
265 struct RData data;
266 struct RStruct rstruct;
267 struct RBignum bignum;
268 struct RFile file;
269 struct RNode node;
270 struct RMatch match;
271 struct RRational rational;
272 struct RComplex complex;
273 } as;
274 #ifdef GC_DEBUG
275 char *file;
276 int line;
277 #endif
278 } RVALUE;
280 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
281 #pragma pack(pop)
282 #endif
284 struct heaps_slot {
285 void *membase;
286 RVALUE *slot;
287 int limit;
290 #define HEAP_MIN_SLOTS 10000
291 #define FREE_MIN 4096
293 struct gc_list {
294 VALUE *varptr;
295 struct gc_list *next;
298 #define CALC_EXACT_MALLOC_SIZE 0
300 typedef struct rb_objspace {
301 struct {
302 size_t limit;
303 size_t increase;
304 #if CALC_EXACT_MALLOC_SIZE
305 size_t allocated_size;
306 size_t allocations;
307 #endif
308 } malloc_params;
309 struct {
310 size_t increment;
311 struct heaps_slot *ptr;
312 size_t length;
313 size_t used;
314 RVALUE *freelist;
315 RVALUE *range[2];
316 RVALUE *freed;
317 } heap;
318 struct {
319 int dont_gc;
320 int during_gc;
321 } flags;
322 struct {
323 st_table *table;
324 RVALUE *deferred;
325 } final;
326 struct {
327 VALUE buffer[MARK_STACK_MAX];
328 VALUE *ptr;
329 int overflow;
330 } markstack;
331 struct {
332 int run;
333 gc_profile_record *record;
334 size_t count;
335 size_t size;
336 double invoke_time;
337 } profile;
338 struct gc_list *global_list;
339 unsigned int count;
340 int gc_stress;
341 } rb_objspace_t;
343 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
344 #define rb_objspace (*GET_VM()->objspace)
345 static int ruby_initial_gc_stress = 0;
346 int *ruby_initial_gc_stress_ptr = &ruby_initial_gc_stress;
347 #else
348 static rb_objspace_t rb_objspace = {{GC_MALLOC_LIMIT}, {HEAP_MIN_SLOTS}};
349 int *ruby_initial_gc_stress_ptr = &rb_objspace.gc_stress;
350 #endif
351 #define malloc_limit objspace->malloc_params.limit
352 #define malloc_increase objspace->malloc_params.increase
353 #define heap_slots objspace->heap.slots
354 #define heaps objspace->heap.ptr
355 #define heaps_length objspace->heap.length
356 #define heaps_used objspace->heap.used
357 #define freelist objspace->heap.freelist
358 #define lomem objspace->heap.range[0]
359 #define himem objspace->heap.range[1]
360 #define heaps_inc objspace->heap.increment
361 #define heaps_freed objspace->heap.freed
362 #define dont_gc objspace->flags.dont_gc
363 #define during_gc objspace->flags.during_gc
364 #define finalizer_table objspace->final.table
365 #define deferred_final_list objspace->final.deferred
366 #define mark_stack objspace->markstack.buffer
367 #define mark_stack_ptr objspace->markstack.ptr
368 #define mark_stack_overflow objspace->markstack.overflow
369 #define global_List objspace->global_list
370 #define ruby_gc_stress objspace->gc_stress
372 #define need_call_final (finalizer_table && finalizer_table->num_entries)
374 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
375 rb_objspace_t *
376 rb_objspace_alloc(void)
378 rb_objspace_t *objspace = malloc(sizeof(rb_objspace_t));
379 memset(objspace, 0, sizeof(*objspace));
380 malloc_limit = GC_MALLOC_LIMIT;
381 ruby_gc_stress = ruby_initial_gc_stress;
383 return objspace;
385 #endif
387 /* tiny heap size */
388 /* 32KB */
389 /*#define HEAP_SIZE 0x8000 */
390 /* 128KB */
391 /*#define HEAP_SIZE 0x20000 */
392 /* 64KB */
393 /*#define HEAP_SIZE 0x10000 */
394 /* 16KB */
395 #define HEAP_SIZE 0x4000
396 /* 8KB */
397 /*#define HEAP_SIZE 0x2000 */
398 /* 4KB */
399 /*#define HEAP_SIZE 0x1000 */
400 /* 2KB */
401 /*#define HEAP_SIZE 0x800 */
403 #define HEAP_OBJ_LIMIT (HEAP_SIZE / sizeof(struct RVALUE))
405 extern st_table *rb_class_tbl;
407 int ruby_disable_gc_stress = 0;
409 static void run_final(rb_objspace_t *objspace, VALUE obj);
410 static int garbage_collect(rb_objspace_t *objspace);
412 void
413 rb_global_variable(VALUE *var)
415 rb_gc_register_address(var);
418 void
419 rb_memerror(void)
421 rb_thread_t *th = GET_THREAD();
422 if (!nomem_error ||
423 (rb_thread_raised_p(th, RAISED_NOMEMORY) && rb_safe_level() < 4)) {
424 fprintf(stderr, "[FATAL] failed to allocate memory\n");
425 exit(EXIT_FAILURE);
427 if (rb_thread_raised_p(th, RAISED_NOMEMORY)) {
428 rb_thread_raised_clear(th);
429 GET_THREAD()->errinfo = nomem_error;
430 JUMP_TAG(TAG_RAISE);
432 rb_thread_raised_set(th, RAISED_NOMEMORY);
433 rb_exc_raise(nomem_error);
437 * call-seq:
438 * GC.stress => true or false
440 * returns current status of GC stress mode.
443 static VALUE
444 gc_stress_get(VALUE self)
446 rb_objspace_t *objspace = &rb_objspace;
447 return ruby_gc_stress ? Qtrue : Qfalse;
451 * call-seq:
452 * GC.stress = bool => bool
454 * updates GC stress mode.
456 * When GC.stress = true, GC is invoked for all GC opportunity:
457 * all memory and object allocation.
459 * Since it makes Ruby very slow, it is only for debugging.
462 static VALUE
463 gc_stress_set(VALUE self, VALUE bool)
465 rb_objspace_t *objspace = &rb_objspace;
466 rb_secure(2);
467 ruby_gc_stress = RTEST(bool);
468 return bool;
472 * call-seq:
473 * GC::Profiler.enable? => true or false
475 * returns current status of GC profile mode.
478 static VALUE
479 gc_profile_enable_get(VALUE self)
481 rb_objspace_t *objspace = &rb_objspace;
482 return objspace->profile.run;
486 * call-seq:
487 * GC::Profiler.enable => nil
489 * updates GC profile mode.
490 * start profiler for GC.
494 static VALUE
495 gc_profile_enable(void)
497 rb_objspace_t *objspace = &rb_objspace;
499 objspace->profile.run = Qtrue;
500 return Qnil;
504 * call-seq:
505 * GC::Profiler.disable => nil
507 * updates GC profile mode.
508 * stop profiler for GC.
512 static VALUE
513 gc_profile_disable(void)
515 rb_objspace_t *objspace = &rb_objspace;
517 objspace->profile.run = Qfalse;
518 return Qnil;
522 * call-seq:
523 * GC::Profiler.clear => nil
525 * clear before profile data.
529 static VALUE
530 gc_profile_clear(void)
532 rb_objspace_t *objspace = &rb_objspace;
533 MEMZERO(objspace->profile.record, gc_profile_record, objspace->profile.size);
534 objspace->profile.count = 0;
535 return Qnil;
538 static void *
539 vm_xmalloc(rb_objspace_t *objspace, size_t size)
541 void *mem;
543 if (size < 0) {
544 rb_raise(rb_eNoMemError, "negative allocation size (or too big)");
546 if (size == 0) size = 1;
548 #if CALC_EXACT_MALLOC_SIZE
549 size += sizeof(size_t);
550 #endif
552 if ((ruby_gc_stress && !ruby_disable_gc_stress) ||
553 (malloc_increase+size) > malloc_limit) {
554 garbage_collect(objspace);
556 RUBY_CRITICAL(mem = malloc(size));
557 if (!mem) {
558 if (garbage_collect(objspace)) {
559 RUBY_CRITICAL(mem = malloc(size));
561 if (!mem) {
562 rb_memerror();
565 malloc_increase += size;
567 #if CALC_EXACT_MALLOC_SIZE
568 objspace->malloc_params.allocated_size += size;
569 objspace->malloc_params.allocations++;
570 ((size_t *)mem)[0] = size;
571 mem = (size_t *)mem + 1;
572 #endif
574 return mem;
577 static void *
578 vm_xrealloc(rb_objspace_t *objspace, void *ptr, size_t size)
580 void *mem;
582 if (size < 0) {
583 rb_raise(rb_eArgError, "negative re-allocation size");
585 if (!ptr) return ruby_xmalloc(size);
586 if (size == 0) size = 1;
587 if (ruby_gc_stress && !ruby_disable_gc_stress) garbage_collect(objspace);
589 #if CALC_EXACT_MALLOC_SIZE
590 size += sizeof(size_t);
591 objspace->malloc_params.allocated_size -= size;
592 ptr = (size_t *)ptr - 1;
593 #endif
595 RUBY_CRITICAL(mem = realloc(ptr, size));
596 if (!mem) {
597 if (garbage_collect(objspace)) {
598 RUBY_CRITICAL(mem = realloc(ptr, size));
600 if (!mem) {
601 rb_memerror();
604 malloc_increase += size;
606 #if CALC_EXACT_MALLOC_SIZE
607 objspace->malloc_params.allocated_size += size;
608 ((size_t *)mem)[0] = size;
609 mem = (size_t *)mem + 1;
610 #endif
612 return mem;
615 static void
616 vm_xfree(rb_objspace_t *objspace, void *ptr)
618 #if CALC_EXACT_MALLOC_SIZE
619 size_t size;
620 ptr = ((size_t *)ptr) - 1;
621 size = ((size_t*)ptr)[0];
622 objspace->malloc_params.allocated_size -= size;
623 objspace->malloc_params.allocations--;
624 #endif
626 RUBY_CRITICAL(free(ptr));
629 void *
630 ruby_xmalloc(size_t size)
632 return vm_xmalloc(&rb_objspace, size);
635 void *
636 ruby_xmalloc2(size_t n, size_t size)
638 size_t len = size * n;
639 if (n != 0 && size != len / n) {
640 rb_raise(rb_eArgError, "malloc: possible integer overflow");
642 return vm_xmalloc(&rb_objspace, len);
645 void *
646 ruby_xcalloc(size_t n, size_t size)
648 void *mem = ruby_xmalloc2(n, size);
649 memset(mem, 0, n * size);
651 return mem;
654 void *
655 ruby_xrealloc(void *ptr, size_t size)
657 return vm_xrealloc(&rb_objspace, ptr, size);
660 void *
661 ruby_xrealloc2(void *ptr, size_t n, size_t size)
663 size_t len = size * n;
664 if (n != 0 && size != len / n) {
665 rb_raise(rb_eArgError, "realloc: possible integer overflow");
667 return ruby_xrealloc(ptr, len);
670 void
671 ruby_xfree(void *x)
673 if (x)
674 vm_xfree(&rb_objspace, x);
679 * call-seq:
680 * GC.enable => true or false
682 * Enables garbage collection, returning <code>true</code> if garbage
683 * collection was previously disabled.
685 * GC.disable #=> false
686 * GC.enable #=> true
687 * GC.enable #=> false
691 VALUE
692 rb_gc_enable(void)
694 rb_objspace_t *objspace = &rb_objspace;
695 int old = dont_gc;
697 dont_gc = Qfalse;
698 return old;
702 * call-seq:
703 * GC.disable => true or false
705 * Disables garbage collection, returning <code>true</code> if garbage
706 * collection was already disabled.
708 * GC.disable #=> false
709 * GC.disable #=> true
713 VALUE
714 rb_gc_disable(void)
716 rb_objspace_t *objspace = &rb_objspace;
717 int old = dont_gc;
719 dont_gc = Qtrue;
720 return old;
723 VALUE rb_mGC;
725 void
726 rb_register_mark_object(VALUE obj)
728 VALUE ary = GET_THREAD()->vm->mark_object_ary;
729 rb_ary_push(ary, obj);
732 void
733 rb_gc_register_address(VALUE *addr)
735 rb_objspace_t *objspace = &rb_objspace;
736 struct gc_list *tmp;
738 tmp = ALLOC(struct gc_list);
739 tmp->next = global_List;
740 tmp->varptr = addr;
741 global_List = tmp;
744 void
745 rb_gc_unregister_address(VALUE *addr)
747 rb_objspace_t *objspace = &rb_objspace;
748 struct gc_list *tmp = global_List;
750 if (tmp->varptr == addr) {
751 global_List = tmp->next;
752 xfree(tmp);
753 return;
755 while (tmp->next) {
756 if (tmp->next->varptr == addr) {
757 struct gc_list *t = tmp->next;
759 tmp->next = tmp->next->next;
760 xfree(t);
761 break;
763 tmp = tmp->next;
768 static void
769 allocate_heaps(rb_objspace_t *objspace, size_t next_heaps_length)
771 struct heaps_slot *p;
772 size_t size;
774 size = next_heaps_length*sizeof(struct heaps_slot);
775 RUBY_CRITICAL(
776 if (heaps_used > 0) {
777 p = (struct heaps_slot *)realloc(heaps, size);
778 if (p) heaps = p;
780 else {
781 p = heaps = (struct heaps_slot *)malloc(size);
784 if (p == 0) {
785 during_gc = 0;
786 rb_memerror();
788 heaps_length = next_heaps_length;
791 static void
792 assign_heap_slot(rb_objspace_t *objspace)
794 RVALUE *p, *pend, *membase;
795 size_t hi, lo, mid;
796 int objs;
798 objs = HEAP_OBJ_LIMIT;
799 RUBY_CRITICAL(p = (RVALUE*)malloc(HEAP_SIZE));
800 if (p == 0) {
801 during_gc = 0;
802 rb_memerror();
805 membase = p;
806 if ((VALUE)p % sizeof(RVALUE) != 0) {
807 p = (RVALUE*)((VALUE)p + sizeof(RVALUE) - ((VALUE)p % sizeof(RVALUE)));
808 if ((HEAP_SIZE - HEAP_OBJ_LIMIT * sizeof(RVALUE)) < ((char*)p - (char*)membase)) {
809 objs--;
813 lo = 0;
814 hi = heaps_used;
815 while (lo < hi) {
816 register RVALUE *mid_membase;
817 mid = (lo + hi) / 2;
818 mid_membase = heaps[mid].membase;
819 if (mid_membase < membase) {
820 lo = mid + 1;
822 else if (mid_membase > membase) {
823 hi = mid;
825 else {
826 rb_bug("same heap slot is allocated: %p at %"PRIuVALUE, membase, (VALUE)mid);
829 if (hi < heaps_used) {
830 MEMMOVE(&heaps[hi+1], &heaps[hi], struct heaps_slot, heaps_used - hi);
832 heaps[hi].membase = membase;
833 heaps[hi].slot = p;
834 heaps[hi].limit = objs;
835 pend = p + objs;
836 if (lomem == 0 || lomem > p) lomem = p;
837 if (himem < pend) himem = pend;
838 heaps_used++;
840 while (p < pend) {
841 p->as.free.flags = 0;
842 p->as.free.next = freelist;
843 freelist = p;
844 p++;
848 static void
849 init_heap(rb_objspace_t *objspace)
851 size_t add, i;
853 add = HEAP_MIN_SLOTS / HEAP_OBJ_LIMIT;
855 if ((heaps_used + add) > heaps_length) {
856 allocate_heaps(objspace, heaps_used + add);
859 for (i = 0; i < add; i++) {
860 assign_heap_slot(objspace);
862 heaps_inc = 0;
863 objspace->profile.invoke_time = getrusage_time();
867 static void
868 set_heaps_increment(rb_objspace_t *objspace)
870 size_t next_heaps_length = heaps_used * 1.8;
871 heaps_inc = next_heaps_length - heaps_used;
873 if (next_heaps_length > heaps_length) {
874 allocate_heaps(objspace, next_heaps_length);
878 static int
879 heaps_increment(rb_objspace_t *objspace)
881 if (heaps_inc > 0) {
882 assign_heap_slot(objspace);
883 heaps_inc--;
884 return Qtrue;
886 return Qfalse;
889 #define RANY(o) ((RVALUE*)(o))
891 static VALUE
892 rb_newobj_from_heap(rb_objspace_t *objspace)
894 VALUE obj;
896 if ((ruby_gc_stress && !ruby_disable_gc_stress) || !freelist) {
897 if (!heaps_increment(objspace) && !garbage_collect(objspace)) {
898 during_gc = 0;
899 rb_memerror();
903 obj = (VALUE)freelist;
904 freelist = freelist->as.free.next;
906 MEMZERO((void*)obj, RVALUE, 1);
907 #ifdef GC_DEBUG
908 RANY(obj)->file = rb_sourcefile();
909 RANY(obj)->line = rb_sourceline();
910 #endif
912 return obj;
915 #if USE_VALUE_CACHE
916 static VALUE
917 rb_fill_value_cache(rb_thread_t *th)
919 rb_objspace_t *objspace = &rb_objspace;
920 int i;
921 VALUE rv;
923 /* LOCK */
924 for (i=0; i<RUBY_VM_VALUE_CACHE_SIZE; i++) {
925 VALUE v = rb_newobj_from_heap(objspace);
927 th->value_cache[i] = v;
928 RBASIC(v)->flags = FL_MARK;
930 th->value_cache_ptr = &th->value_cache[0];
931 rv = rb_newobj_from_heap(objspace);
932 /* UNLOCK */
933 return rv;
935 #endif
938 rb_during_gc(void)
940 rb_objspace_t *objspace = &rb_objspace;
941 return during_gc;
944 VALUE
945 rb_newobj(void)
947 #if USE_VALUE_CACHE || (defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE)
948 rb_thread_t *th = GET_THREAD();
949 #endif
950 #if USE_VALUE_CACHE
951 VALUE v = *th->value_cache_ptr;
952 #endif
953 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
954 rb_objspace_t *objspace = th->vm->objspace;
955 #else
956 rb_objspace_t *objspace = &rb_objspace;
957 #endif
959 if (during_gc) {
960 dont_gc = 1;
961 during_gc = 0;
962 rb_bug("object allocation during garbage collection phase");
965 #if USE_VALUE_CACHE
966 if (v) {
967 RBASIC(v)->flags = 0;
968 th->value_cache_ptr++;
970 else {
971 v = rb_fill_value_cache(th);
974 #if defined(GC_DEBUG)
975 printf("cache index: %d, v: %p, th: %p\n",
976 th->value_cache_ptr - th->value_cache, v, th);
977 #endif
978 return v;
979 #else
980 return rb_newobj_from_heap(objspace);
981 #endif
984 NODE*
985 rb_node_newnode(enum node_type type, VALUE a0, VALUE a1, VALUE a2)
987 NODE *n = (NODE*)rb_newobj();
989 n->flags |= T_NODE;
990 nd_set_type(n, type);
992 n->u1.value = a0;
993 n->u2.value = a1;
994 n->u3.value = a2;
996 return n;
999 VALUE
1000 rb_data_object_alloc(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
1002 NEWOBJ(data, struct RData);
1003 if (klass) Check_Type(klass, T_CLASS);
1004 OBJSETUP(data, klass, T_DATA);
1005 data->data = datap;
1006 data->dfree = dfree;
1007 data->dmark = dmark;
1009 return (VALUE)data;
1012 #ifdef __ia64
1013 #define SET_STACK_END (SET_MACHINE_STACK_END(&th->machine_stack_end), th->machine_register_stack_end = rb_ia64_bsp())
1014 #else
1015 #define SET_STACK_END SET_MACHINE_STACK_END(&th->machine_stack_end)
1016 #endif
1018 #define STACK_START (th->machine_stack_start)
1019 #define STACK_END (th->machine_stack_end)
1020 #define STACK_LEVEL_MAX (th->machine_stack_maxsize/sizeof(VALUE))
1022 #if STACK_GROW_DIRECTION < 0
1023 # define STACK_LENGTH (STACK_START - STACK_END)
1024 #elif STACK_GROW_DIRECTION > 0
1025 # define STACK_LENGTH (STACK_END - STACK_START + 1)
1026 #else
1027 # define STACK_LENGTH ((STACK_END < STACK_START) ? STACK_START - STACK_END\
1028 : STACK_END - STACK_START + 1)
1029 #endif
1030 #if !STACK_GROW_DIRECTION
1031 int ruby_stack_grow_direction;
1033 ruby_get_stack_grow_direction(VALUE *addr)
1035 rb_thread_t *th = GET_THREAD();
1036 SET_STACK_END;
1038 if (STACK_END > addr) return ruby_stack_grow_direction = 1;
1039 return ruby_stack_grow_direction = -1;
1041 #endif
1043 #define GC_WATER_MARK 512
1045 size_t
1046 ruby_stack_length(VALUE **p)
1048 rb_thread_t *th = GET_THREAD();
1049 SET_STACK_END;
1050 if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END);
1051 return STACK_LENGTH;
1055 ruby_stack_check(void)
1057 int ret;
1058 rb_thread_t *th = GET_THREAD();
1059 SET_STACK_END;
1060 ret = STACK_LENGTH > STACK_LEVEL_MAX - GC_WATER_MARK;
1061 #ifdef __ia64
1062 if (!ret) {
1063 ret = (VALUE*)rb_ia64_bsp() - th->machine_register_stack_start >
1064 th->machine_register_stack_maxsize/sizeof(VALUE) - GC_WATER_MARK;
1066 #endif
1067 return ret;
1070 static void
1071 init_mark_stack(rb_objspace_t *objspace)
1073 mark_stack_overflow = 0;
1074 mark_stack_ptr = mark_stack;
1077 #define MARK_STACK_EMPTY (mark_stack_ptr == mark_stack)
1079 static void gc_mark(rb_objspace_t *objspace, VALUE ptr, int lev);
1080 static void gc_mark_children(rb_objspace_t *objspace, VALUE ptr, int lev);
1082 static void
1083 gc_mark_all(rb_objspace_t *objspace)
1085 RVALUE *p, *pend;
1086 size_t i;
1088 init_mark_stack(objspace);
1089 for (i = 0; i < heaps_used; i++) {
1090 p = heaps[i].slot; pend = p + heaps[i].limit;
1091 while (p < pend) {
1092 if ((p->as.basic.flags & FL_MARK) &&
1093 (p->as.basic.flags != FL_MARK)) {
1094 gc_mark_children(objspace, (VALUE)p, 0);
1096 p++;
1101 static void
1102 gc_mark_rest(rb_objspace_t *objspace)
1104 VALUE tmp_arry[MARK_STACK_MAX];
1105 VALUE *p;
1107 p = (mark_stack_ptr - mark_stack) + tmp_arry;
1108 MEMCPY(tmp_arry, mark_stack, VALUE, p - tmp_arry);
1110 init_mark_stack(objspace);
1111 while (p != tmp_arry) {
1112 p--;
1113 gc_mark_children(objspace, *p, 0);
1117 static inline int
1118 is_pointer_to_heap(rb_objspace_t *objspace, void *ptr)
1120 register RVALUE *p = RANY(ptr);
1121 register struct heaps_slot *heap;
1122 register size_t hi, lo, mid;
1124 if (p < lomem || p > himem) return Qfalse;
1125 if ((VALUE)p % sizeof(RVALUE) != 0) return Qfalse;
1127 /* check if p looks like a pointer using bsearch*/
1128 lo = 0;
1129 hi = heaps_used;
1130 while (lo < hi) {
1131 mid = (lo + hi) / 2;
1132 heap = &heaps[mid];
1133 if (heap->slot <= p) {
1134 if (p < heap->slot + heap->limit)
1135 return Qtrue;
1136 lo = mid + 1;
1138 else {
1139 hi = mid;
1142 return Qfalse;
1145 static void
1146 mark_locations_array(rb_objspace_t *objspace, register VALUE *x, register long n)
1148 VALUE v;
1149 while (n--) {
1150 v = *x;
1151 VALGRIND_MAKE_MEM_DEFINED(&v, sizeof(v));
1152 if (is_pointer_to_heap(objspace, (void *)v)) {
1153 gc_mark(objspace, v, 0);
1155 x++;
1159 static void
1160 gc_mark_locations(rb_objspace_t *objspace, VALUE *start, VALUE *end)
1162 long n;
1164 if (end <= start) return;
1165 n = end - start;
1166 mark_locations_array(objspace, start, n);
1169 void
1170 rb_gc_mark_locations(VALUE *start, VALUE *end)
1172 gc_mark_locations(&rb_objspace, start, end);
1175 #define rb_gc_mark_locations(start, end) gc_mark_locations(objspace, start, end)
1177 struct mark_tbl_arg {
1178 rb_objspace_t *objspace;
1179 int lev;
1182 static int
1183 mark_entry(ID key, VALUE value, st_data_t data)
1185 struct mark_tbl_arg *arg = (void*)data;
1186 gc_mark(arg->objspace, value, arg->lev);
1187 return ST_CONTINUE;
1190 static void
1191 mark_tbl(rb_objspace_t *objspace, st_table *tbl, int lev)
1193 struct mark_tbl_arg arg;
1194 if (!tbl) return;
1195 arg.objspace = objspace;
1196 arg.lev = lev;
1197 st_foreach(tbl, mark_entry, (st_data_t)&arg);
1200 void
1201 rb_mark_tbl(st_table *tbl)
1203 mark_tbl(&rb_objspace, tbl, 0);
1206 static int
1207 mark_key(VALUE key, VALUE value, st_data_t data)
1209 struct mark_tbl_arg *arg = (void*)data;
1210 gc_mark(arg->objspace, key, arg->lev);
1211 return ST_CONTINUE;
1214 static void
1215 mark_set(rb_objspace_t *objspace, st_table *tbl, int lev)
1217 struct mark_tbl_arg arg;
1218 if (!tbl) return;
1219 arg.objspace = objspace;
1220 arg.lev = lev;
1221 st_foreach(tbl, mark_key, (st_data_t)&arg);
1224 void
1225 rb_mark_set(st_table *tbl)
1227 mark_set(&rb_objspace, tbl, 0);
1230 static int
1231 mark_keyvalue(VALUE key, VALUE value, st_data_t data)
1233 struct mark_tbl_arg *arg = (void*)data;
1234 gc_mark(arg->objspace, key, arg->lev);
1235 gc_mark(arg->objspace, value, arg->lev);
1236 return ST_CONTINUE;
1239 static void
1240 mark_hash(rb_objspace_t *objspace, st_table *tbl, int lev)
1242 struct mark_tbl_arg arg;
1243 if (!tbl) return;
1244 arg.objspace = objspace;
1245 arg.lev = lev;
1246 st_foreach(tbl, mark_keyvalue, (st_data_t)&arg);
1249 void
1250 rb_mark_hash(st_table *tbl)
1252 mark_hash(&rb_objspace, tbl, 0);
1255 void
1256 rb_gc_mark_maybe(VALUE obj)
1258 if (is_pointer_to_heap(&rb_objspace, (void *)obj)) {
1259 gc_mark(&rb_objspace, obj, 0);
1263 #define GC_LEVEL_MAX 250
1265 static void
1266 gc_mark(rb_objspace_t *objspace, VALUE ptr, int lev)
1268 register RVALUE *obj;
1270 obj = RANY(ptr);
1271 if (rb_special_const_p(ptr)) return; /* special const not marked */
1272 if (obj->as.basic.flags == 0) return; /* free cell */
1273 if (obj->as.basic.flags & FL_MARK) return; /* already marked */
1274 obj->as.basic.flags |= FL_MARK;
1276 if (lev > GC_LEVEL_MAX || (lev == 0 && ruby_stack_check())) {
1277 if (!mark_stack_overflow) {
1278 if (mark_stack_ptr - mark_stack < MARK_STACK_MAX) {
1279 *mark_stack_ptr = ptr;
1280 mark_stack_ptr++;
1282 else {
1283 mark_stack_overflow = 1;
1286 return;
1288 gc_mark_children(objspace, ptr, lev+1);
1291 void
1292 rb_gc_mark(VALUE ptr)
1294 gc_mark(&rb_objspace, ptr, 0);
1297 static void
1298 gc_mark_children(rb_objspace_t *objspace, VALUE ptr, int lev)
1300 register RVALUE *obj = RANY(ptr);
1302 goto marking; /* skip */
1304 again:
1305 obj = RANY(ptr);
1306 if (rb_special_const_p(ptr)) return; /* special const not marked */
1307 if (obj->as.basic.flags == 0) return; /* free cell */
1308 if (obj->as.basic.flags & FL_MARK) return; /* already marked */
1309 obj->as.basic.flags |= FL_MARK;
1311 marking:
1312 if (FL_TEST(obj, FL_EXIVAR)) {
1313 rb_mark_generic_ivar(ptr);
1316 switch (BUILTIN_TYPE(obj)) {
1317 case T_NIL:
1318 case T_FIXNUM:
1319 rb_bug("rb_gc_mark() called for broken object");
1320 break;
1322 case T_NODE:
1323 switch (nd_type(obj)) {
1324 case NODE_IF: /* 1,2,3 */
1325 case NODE_FOR:
1326 case NODE_ITER:
1327 case NODE_WHEN:
1328 case NODE_MASGN:
1329 case NODE_RESCUE:
1330 case NODE_RESBODY:
1331 case NODE_CLASS:
1332 case NODE_BLOCK_PASS:
1333 gc_mark(objspace, (VALUE)obj->as.node.u2.node, lev);
1334 /* fall through */
1335 case NODE_BLOCK: /* 1,3 */
1336 case NODE_OPTBLOCK:
1337 case NODE_ARRAY:
1338 case NODE_DSTR:
1339 case NODE_DXSTR:
1340 case NODE_DREGX:
1341 case NODE_DREGX_ONCE:
1342 case NODE_ENSURE:
1343 case NODE_CALL:
1344 case NODE_DEFS:
1345 case NODE_OP_ASGN1:
1346 case NODE_ARGS:
1347 gc_mark(objspace, (VALUE)obj->as.node.u1.node, lev);
1348 /* fall through */
1349 case NODE_SUPER: /* 3 */
1350 case NODE_FCALL:
1351 case NODE_DEFN:
1352 case NODE_ARGS_AUX:
1353 ptr = (VALUE)obj->as.node.u3.node;
1354 goto again;
1356 case NODE_METHOD: /* 1,2 */
1357 case NODE_WHILE:
1358 case NODE_UNTIL:
1359 case NODE_AND:
1360 case NODE_OR:
1361 case NODE_CASE:
1362 case NODE_SCLASS:
1363 case NODE_DOT2:
1364 case NODE_DOT3:
1365 case NODE_FLIP2:
1366 case NODE_FLIP3:
1367 case NODE_MATCH2:
1368 case NODE_MATCH3:
1369 case NODE_OP_ASGN_OR:
1370 case NODE_OP_ASGN_AND:
1371 case NODE_MODULE:
1372 case NODE_ALIAS:
1373 case NODE_VALIAS:
1374 case NODE_ARGSCAT:
1375 gc_mark(objspace, (VALUE)obj->as.node.u1.node, lev);
1376 /* fall through */
1377 case NODE_FBODY: /* 2 */
1378 case NODE_GASGN:
1379 case NODE_LASGN:
1380 case NODE_DASGN:
1381 case NODE_DASGN_CURR:
1382 case NODE_IASGN:
1383 case NODE_IASGN2:
1384 case NODE_CVASGN:
1385 case NODE_COLON3:
1386 case NODE_OPT_N:
1387 case NODE_EVSTR:
1388 case NODE_UNDEF:
1389 case NODE_POSTEXE:
1390 ptr = (VALUE)obj->as.node.u2.node;
1391 goto again;
1393 case NODE_HASH: /* 1 */
1394 case NODE_LIT:
1395 case NODE_STR:
1396 case NODE_XSTR:
1397 case NODE_DEFINED:
1398 case NODE_MATCH:
1399 case NODE_RETURN:
1400 case NODE_BREAK:
1401 case NODE_NEXT:
1402 case NODE_YIELD:
1403 case NODE_COLON2:
1404 case NODE_SPLAT:
1405 case NODE_TO_ARY:
1406 ptr = (VALUE)obj->as.node.u1.node;
1407 goto again;
1409 case NODE_SCOPE: /* 2,3 */
1410 case NODE_CDECL:
1411 case NODE_OPT_ARG:
1412 gc_mark(objspace, (VALUE)obj->as.node.u3.node, lev);
1413 ptr = (VALUE)obj->as.node.u2.node;
1414 goto again;
1416 case NODE_ZARRAY: /* - */
1417 case NODE_ZSUPER:
1418 case NODE_CFUNC:
1419 case NODE_VCALL:
1420 case NODE_GVAR:
1421 case NODE_LVAR:
1422 case NODE_DVAR:
1423 case NODE_IVAR:
1424 case NODE_CVAR:
1425 case NODE_NTH_REF:
1426 case NODE_BACK_REF:
1427 case NODE_REDO:
1428 case NODE_RETRY:
1429 case NODE_SELF:
1430 case NODE_NIL:
1431 case NODE_TRUE:
1432 case NODE_FALSE:
1433 case NODE_ERRINFO:
1434 case NODE_ATTRSET:
1435 case NODE_BLOCK_ARG:
1436 break;
1437 case NODE_ALLOCA:
1438 mark_locations_array(objspace,
1439 (VALUE*)obj->as.node.u1.value,
1440 obj->as.node.u3.cnt);
1441 ptr = (VALUE)obj->as.node.u2.node;
1442 goto again;
1444 default: /* unlisted NODE */
1445 if (is_pointer_to_heap(objspace, obj->as.node.u1.node)) {
1446 gc_mark(objspace, (VALUE)obj->as.node.u1.node, lev);
1448 if (is_pointer_to_heap(objspace, obj->as.node.u2.node)) {
1449 gc_mark(objspace, (VALUE)obj->as.node.u2.node, lev);
1451 if (is_pointer_to_heap(objspace, obj->as.node.u3.node)) {
1452 gc_mark(objspace, (VALUE)obj->as.node.u3.node, lev);
1455 return; /* no need to mark class. */
1458 gc_mark(objspace, obj->as.basic.klass, lev);
1459 switch (BUILTIN_TYPE(obj)) {
1460 case T_ICLASS:
1461 case T_CLASS:
1462 case T_MODULE:
1463 mark_tbl(objspace, RCLASS_M_TBL(obj), lev);
1464 mark_tbl(objspace, RCLASS_IV_TBL(obj), lev);
1465 ptr = RCLASS_SUPER(obj);
1466 goto again;
1468 case T_ARRAY:
1469 if (FL_TEST(obj, ELTS_SHARED)) {
1470 ptr = obj->as.array.aux.shared;
1471 goto again;
1473 else {
1474 long i, len = RARRAY_LEN(obj);
1475 VALUE *ptr = RARRAY_PTR(obj);
1476 for (i=0; i < len; i++) {
1477 gc_mark(objspace, *ptr++, lev);
1480 break;
1482 case T_HASH:
1483 mark_hash(objspace, obj->as.hash.ntbl, lev);
1484 ptr = obj->as.hash.ifnone;
1485 goto again;
1487 case T_STRING:
1488 #define STR_ASSOC FL_USER3 /* copied from string.c */
1489 if (FL_TEST(obj, RSTRING_NOEMBED) && FL_ANY(obj, ELTS_SHARED|STR_ASSOC)) {
1490 ptr = obj->as.string.as.heap.aux.shared;
1491 goto again;
1493 break;
1495 case T_DATA:
1496 if (obj->as.data.dmark) (*obj->as.data.dmark)(DATA_PTR(obj));
1497 break;
1499 case T_OBJECT:
1501 long i, len = ROBJECT_NUMIV(obj);
1502 VALUE *ptr = ROBJECT_IVPTR(obj);
1503 for (i = 0; i < len; i++) {
1504 gc_mark(objspace, *ptr++, lev);
1507 break;
1509 case T_FILE:
1510 if (obj->as.file.fptr) {
1511 gc_mark(objspace, obj->as.file.fptr->tied_io_for_writing, lev);
1512 gc_mark(objspace, obj->as.file.fptr->writeconv_stateless, lev);
1514 break;
1516 case T_REGEXP:
1517 gc_mark(objspace, obj->as.regexp.src, lev);
1518 break;
1520 case T_FLOAT:
1521 case T_BIGNUM:
1522 break;
1524 case T_MATCH:
1525 gc_mark(objspace, obj->as.match.regexp, lev);
1526 if (obj->as.match.str) {
1527 ptr = obj->as.match.str;
1528 goto again;
1530 break;
1532 case T_RATIONAL:
1533 gc_mark(objspace, obj->as.rational.num, lev);
1534 gc_mark(objspace, obj->as.rational.den, lev);
1535 break;
1537 case T_COMPLEX:
1538 gc_mark(objspace, obj->as.complex.real, lev);
1539 gc_mark(objspace, obj->as.complex.image, lev);
1540 break;
1542 case T_STRUCT:
1544 long len = RSTRUCT_LEN(obj);
1545 VALUE *ptr = RSTRUCT_PTR(obj);
1547 while (len--) {
1548 gc_mark(objspace, *ptr++, lev);
1551 break;
1553 default:
1554 rb_bug("rb_gc_mark(): unknown data type 0x%lx(%p) %s",
1555 BUILTIN_TYPE(obj), obj,
1556 is_pointer_to_heap(objspace, obj) ? "corrupted object" : "non object");
1560 static int obj_free(rb_objspace_t *, VALUE);
1562 static inline void
1563 add_freelist(rb_objspace_t *objspace, RVALUE *p)
1565 VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
1566 p->as.free.flags = 0;
1567 p->as.free.next = freelist;
1568 freelist = p;
1571 static void
1572 finalize_list(rb_objspace_t *objspace, RVALUE *p)
1574 while (p) {
1575 RVALUE *tmp = p->as.free.next;
1576 run_final(objspace, (VALUE)p);
1577 if (!FL_TEST(p, FL_SINGLETON)) { /* not freeing page */
1578 add_freelist(objspace, p);
1580 else {
1581 struct heaps_slot *slot = (struct heaps_slot *)RDATA(p)->dmark;
1582 slot->limit--;
1584 p = tmp;
1588 static void
1589 free_unused_heaps(rb_objspace_t *objspace)
1591 size_t i, j;
1592 RVALUE *last = 0;
1594 for (i = j = 1; j < heaps_used; i++) {
1595 if (heaps[i].limit == 0) {
1596 if (!last) {
1597 last = heaps[i].membase;
1599 else {
1600 free(heaps[i].membase);
1602 heaps_used--;
1604 else {
1605 if (i != j) {
1606 heaps[j] = heaps[i];
1608 j++;
1611 if (last) {
1612 if (last < heaps_freed) {
1613 free(heaps_freed);
1614 heaps_freed = last;
1616 else {
1617 free(last);
1622 static void
1623 gc_sweep(rb_objspace_t *objspace)
1625 RVALUE *p, *pend, *final_list;
1626 size_t freed = 0;
1627 size_t i;
1628 size_t live = 0, free_min = 0, do_heap_free = 0;
1630 do_heap_free = (heaps_used * HEAP_OBJ_LIMIT) * 0.65;
1631 free_min = (heaps_used * HEAP_OBJ_LIMIT) * 0.2;
1633 if (free_min < FREE_MIN) {
1634 do_heap_free = heaps_used * HEAP_OBJ_LIMIT;
1635 free_min = FREE_MIN;
1638 freelist = 0;
1639 final_list = deferred_final_list;
1640 deferred_final_list = 0;
1641 for (i = 0; i < heaps_used; i++) {
1642 int free_num = 0, final_num = 0;
1643 RVALUE *free = freelist;
1644 RVALUE *final = final_list;
1645 int deferred;
1647 p = heaps[i].slot; pend = p + heaps[i].limit;
1648 while (p < pend) {
1649 if (!(p->as.basic.flags & FL_MARK)) {
1650 if (p->as.basic.flags &&
1651 ((deferred = obj_free(objspace, (VALUE)p)) ||
1652 ((FL_TEST(p, FL_FINALIZE)) && need_call_final))) {
1653 if (!deferred) {
1654 p->as.free.flags = T_DEFERRED;
1655 RDATA(p)->dfree = 0;
1657 p->as.free.flags |= FL_MARK;
1658 p->as.free.next = final_list;
1659 final_list = p;
1660 final_num++;
1662 else {
1663 add_freelist(objspace, p);
1664 free_num++;
1667 else if (BUILTIN_TYPE(p) == T_DEFERRED) {
1668 /* objects to be finalized */
1669 /* do nothing remain marked */
1671 else {
1672 RBASIC(p)->flags &= ~FL_MARK;
1673 live++;
1675 p++;
1677 if (final_num + free_num == heaps[i].limit && freed > do_heap_free) {
1678 RVALUE *pp;
1680 for (pp = final_list; pp != final; pp = pp->as.free.next) {
1681 RDATA(pp)->dmark = (void *)&heaps[i];
1682 pp->as.free.flags |= FL_SINGLETON; /* freeing page mark */
1684 heaps[i].limit = final_num;
1686 freelist = free; /* cancel this page from freelist */
1688 else {
1689 freed += free_num;
1692 GC_PROF_SET_MALLOC_INFO;
1693 if (malloc_increase > malloc_limit) {
1694 malloc_limit += (malloc_increase - malloc_limit) * (double)live / (live + freed);
1695 if (malloc_limit < GC_MALLOC_LIMIT) malloc_limit = GC_MALLOC_LIMIT;
1697 malloc_increase = 0;
1698 if (freed < free_min) {
1699 set_heaps_increment(objspace);
1700 heaps_increment(objspace);
1702 during_gc = 0;
1704 /* clear finalization list */
1705 if (final_list) {
1706 GC_PROF_SET_HEAP_INFO;
1707 deferred_final_list = final_list;
1708 RUBY_VM_SET_FINALIZER_INTERRUPT(GET_THREAD());
1710 else{
1711 free_unused_heaps(objspace);
1712 GC_PROF_SET_HEAP_INFO;
1716 void
1717 rb_gc_force_recycle(VALUE p)
1719 rb_objspace_t *objspace = &rb_objspace;
1720 add_freelist(objspace, (RVALUE *)p);
1723 static inline void
1724 make_deferred(RVALUE *p)
1726 p->as.basic.flags = (p->as.basic.flags & ~T_MASK) | T_DEFERRED;
1729 static int
1730 obj_free(rb_objspace_t *objspace, VALUE obj)
1732 switch (BUILTIN_TYPE(obj)) {
1733 case T_NIL:
1734 case T_FIXNUM:
1735 case T_TRUE:
1736 case T_FALSE:
1737 rb_bug("obj_free() called for broken object");
1738 break;
1741 if (FL_TEST(obj, FL_EXIVAR)) {
1742 rb_free_generic_ivar((VALUE)obj);
1743 FL_UNSET(obj, FL_EXIVAR);
1746 switch (BUILTIN_TYPE(obj)) {
1747 case T_OBJECT:
1748 if (!(RANY(obj)->as.basic.flags & ROBJECT_EMBED) &&
1749 RANY(obj)->as.object.as.heap.ivptr) {
1750 xfree(RANY(obj)->as.object.as.heap.ivptr);
1752 break;
1753 case T_MODULE:
1754 case T_CLASS:
1755 rb_clear_cache_by_class((VALUE)obj);
1756 st_free_table(RCLASS_M_TBL(obj));
1757 if (RCLASS_IV_TBL(obj)) {
1758 st_free_table(RCLASS_IV_TBL(obj));
1760 if (RCLASS_IV_INDEX_TBL(obj)) {
1761 st_free_table(RCLASS_IV_INDEX_TBL(obj));
1763 xfree(RANY(obj)->as.klass.ptr);
1764 break;
1765 case T_STRING:
1766 rb_str_free(obj);
1767 break;
1768 case T_ARRAY:
1769 rb_ary_free(obj);
1770 break;
1771 case T_HASH:
1772 if (RANY(obj)->as.hash.ntbl) {
1773 st_free_table(RANY(obj)->as.hash.ntbl);
1775 break;
1776 case T_REGEXP:
1777 if (RANY(obj)->as.regexp.ptr) {
1778 onig_free(RANY(obj)->as.regexp.ptr);
1780 break;
1781 case T_DATA:
1782 if (DATA_PTR(obj)) {
1783 if ((long)RANY(obj)->as.data.dfree == -1) {
1784 xfree(DATA_PTR(obj));
1786 else if (RANY(obj)->as.data.dfree) {
1787 make_deferred(RANY(obj));
1788 return 1;
1791 break;
1792 case T_MATCH:
1793 if (RANY(obj)->as.match.rmatch) {
1794 struct rmatch *rm = RANY(obj)->as.match.rmatch;
1795 onig_region_free(&rm->regs, 0);
1796 if (rm->char_offset)
1797 xfree(rm->char_offset);
1798 xfree(rm);
1800 break;
1801 case T_FILE:
1802 if (RANY(obj)->as.file.fptr) {
1803 rb_io_t *fptr = RANY(obj)->as.file.fptr;
1804 make_deferred(RANY(obj));
1805 RDATA(obj)->dfree = (void (*)(void*))rb_io_fptr_finalize;
1806 RDATA(obj)->data = fptr;
1807 return 1;
1809 break;
1810 case T_RATIONAL:
1811 case T_COMPLEX:
1812 break;
1813 case T_ICLASS:
1814 /* iClass shares table with the module */
1815 break;
1817 case T_FLOAT:
1818 break;
1820 case T_BIGNUM:
1821 if (!(RBASIC(obj)->flags & RBIGNUM_EMBED_FLAG) && RBIGNUM_DIGITS(obj)) {
1822 xfree(RBIGNUM_DIGITS(obj));
1824 break;
1825 case T_NODE:
1826 switch (nd_type(obj)) {
1827 case NODE_SCOPE:
1828 if (RANY(obj)->as.node.u1.tbl) {
1829 xfree(RANY(obj)->as.node.u1.tbl);
1831 break;
1832 case NODE_ALLOCA:
1833 xfree(RANY(obj)->as.node.u1.node);
1834 break;
1836 break; /* no need to free iv_tbl */
1838 case T_STRUCT:
1839 if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 &&
1840 RANY(obj)->as.rstruct.as.heap.ptr) {
1841 xfree(RANY(obj)->as.rstruct.as.heap.ptr);
1843 break;
1845 default:
1846 rb_bug("gc_sweep(): unknown data type 0x%lx(%p)",
1847 BUILTIN_TYPE(obj), (void*)obj);
1850 return 0;
1853 #ifdef __GNUC__
1854 #if defined(__human68k__) || defined(DJGPP)
1855 #undef rb_setjmp
1856 #undef rb_jmp_buf
1857 #if defined(__human68k__)
1858 typedef unsigned long rb_jmp_buf[8];
1859 __asm__ (".even\n\
1860 _rb_setjmp:\n\
1861 move.l 4(sp),a0\n\
1862 movem.l d3-d7/a3-a5,(a0)\n\
1863 moveq.l #0,d0\n\
1864 rts");
1865 #else
1866 #if defined(DJGPP)
1867 typedef unsigned long rb_jmp_buf[6];
1868 __asm__ (".align 4\n\
1869 _rb_setjmp:\n\
1870 pushl %ebp\n\
1871 movl %esp,%ebp\n\
1872 movl 8(%ebp),%ebp\n\
1873 movl %eax,(%ebp)\n\
1874 movl %ebx,4(%ebp)\n\
1875 movl %ecx,8(%ebp)\n\
1876 movl %edx,12(%ebp)\n\
1877 movl %esi,16(%ebp)\n\
1878 movl %edi,20(%ebp)\n\
1879 popl %ebp\n\
1880 xorl %eax,%eax\n\
1881 ret");
1882 #endif
1883 #endif
1884 int rb_setjmp (rb_jmp_buf);
1885 #endif /* __human68k__ or DJGPP */
1886 #endif /* __GNUC__ */
1888 #define GC_NOTIFY 0
1890 void rb_vm_mark(void *ptr);
1892 static void
1893 mark_current_machine_context(rb_objspace_t *objspace, rb_thread_t *th)
1895 rb_jmp_buf save_regs_gc_mark;
1896 VALUE *stack_start, *stack_end;
1898 SET_STACK_END;
1899 #if STACK_GROW_DIRECTION < 0
1900 stack_start = th->machine_stack_end;
1901 stack_end = th->machine_stack_start;
1902 #elif STACK_GROW_DIRECTION > 0
1903 stack_start = th->machine_stack_start;
1904 stack_end = th->machine_stack_end + 1;
1905 #else
1906 if (th->machine_stack_end < th->machine_stack_start) {
1907 stack_start = th->machine_stack_end;
1908 stack_end = th->machine_stack_start;
1910 else {
1911 stack_start = th->machine_stack_start;
1912 stack_end = th->machine_stack_end + 1;
1914 #endif
1916 FLUSH_REGISTER_WINDOWS;
1917 /* This assumes that all registers are saved into the jmp_buf (and stack) */
1918 rb_setjmp(save_regs_gc_mark);
1919 mark_locations_array(objspace,
1920 (VALUE*)save_regs_gc_mark,
1921 sizeof(save_regs_gc_mark) / sizeof(VALUE));
1923 rb_gc_mark_locations(stack_start, stack_end);
1924 #ifdef __ia64
1925 rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end);
1926 #endif
1927 #if defined(__human68k__) || defined(__mc68000__)
1928 mark_locations_array((VALUE*)((char*)STACK_END + 2),
1929 (STACK_START - STACK_END));
1930 #endif
1933 void rb_gc_mark_encodings(void);
1935 static int
1936 garbage_collect(rb_objspace_t *objspace)
1938 struct gc_list *list;
1939 rb_thread_t *th = GET_THREAD();
1940 INIT_GC_PROF_PARAMS;
1942 if (GC_NOTIFY) printf("start garbage_collect()\n");
1944 if (!heaps) {
1945 return Qfalse;
1948 if (dont_gc || during_gc) {
1949 if (!freelist) {
1950 if (!heaps_increment(objspace)) {
1951 set_heaps_increment(objspace);
1952 heaps_increment(objspace);
1955 return Qtrue;
1957 during_gc++;
1958 objspace->count++;
1960 GC_PROF_TIMER_START;
1961 GC_PROF_MARK_TIMER_START;
1962 SET_STACK_END;
1964 init_mark_stack(objspace);
1966 th->vm->self ? rb_gc_mark(th->vm->self) : rb_vm_mark(th->vm);
1968 if (finalizer_table) {
1969 mark_tbl(objspace, finalizer_table, 0);
1972 mark_current_machine_context(objspace, th);
1974 rb_gc_mark_threads();
1975 rb_gc_mark_symbols();
1976 rb_gc_mark_encodings();
1978 /* mark protected global variables */
1979 for (list = global_List; list; list = list->next) {
1980 rb_gc_mark_maybe(*list->varptr);
1982 rb_mark_end_proc();
1983 rb_gc_mark_global_tbl();
1985 mark_tbl(objspace, rb_class_tbl, 0);
1986 rb_gc_mark_trap_list();
1988 /* mark generic instance variables for special constants */
1989 rb_mark_generic_ivar_tbl();
1991 rb_gc_mark_parser();
1993 /* gc_mark objects whose marking are not completed*/
1994 while (!MARK_STACK_EMPTY) {
1995 if (mark_stack_overflow) {
1996 gc_mark_all(objspace);
1998 else {
1999 gc_mark_rest(objspace);
2002 GC_PROF_MARK_TIMER_STOP;
2004 GC_PROF_SWEEP_TIMER_START;
2005 gc_sweep(objspace);
2006 GC_PROF_SWEEP_TIMER_STOP;
2008 GC_PROF_TIMER_STOP;
2009 if (GC_NOTIFY) printf("end garbage_collect()\n");
2010 return Qtrue;
2014 rb_garbage_collect(void)
2016 return garbage_collect(&rb_objspace);
2019 void
2020 rb_gc_mark_machine_stack(rb_thread_t *th)
2022 rb_objspace_t *objspace = &rb_objspace;
2023 #if STACK_GROW_DIRECTION < 0
2024 rb_gc_mark_locations(th->machine_stack_end, th->machine_stack_start);
2025 #elif STACK_GROW_DIRECTION > 0
2026 rb_gc_mark_locations(th->machine_stack_start, th->machine_stack_end);
2027 #else
2028 if (th->machine_stack_start < th->machine_stack_end) {
2029 rb_gc_mark_locations(th->machine_stack_start, th->machine_stack_end);
2031 else {
2032 rb_gc_mark_locations(th->machine_stack_end, th->machine_stack_start);
2034 #endif
2035 #ifdef __ia64
2036 rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end);
2037 #endif
2042 * call-seq:
2043 * GC.start => nil
2044 * gc.garbage_collect => nil
2045 * ObjectSpace.garbage_collect => nil
2047 * Initiates garbage collection, unless manually disabled.
2051 VALUE
2052 rb_gc_start(void)
2054 rb_gc();
2055 return Qnil;
2058 #undef Init_stack
2060 void
2061 Init_stack(VALUE *addr)
2063 ruby_init_stack(addr);
2067 * Document-class: ObjectSpace
2069 * The <code>ObjectSpace</code> module contains a number of routines
2070 * that interact with the garbage collection facility and allow you to
2071 * traverse all living objects with an iterator.
2073 * <code>ObjectSpace</code> also provides support for object
2074 * finalizers, procs that will be called when a specific object is
2075 * about to be destroyed by garbage collection.
2077 * include ObjectSpace
2080 * a = "A"
2081 * b = "B"
2082 * c = "C"
2085 * define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
2086 * define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
2087 * define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
2089 * <em>produces:</em>
2091 * Finalizer three on 537763470
2092 * Finalizer one on 537763480
2093 * Finalizer two on 537763480
2097 void
2098 Init_heap(void)
2100 init_heap(&rb_objspace);
2103 static VALUE
2104 os_obj_of(rb_objspace_t *objspace, VALUE of)
2106 size_t i;
2107 size_t n = 0;
2108 RVALUE *membase = 0;
2109 RVALUE *p, *pend;
2110 volatile VALUE v;
2112 i = 0;
2113 while (i < heaps_used) {
2114 while (0 < i && (uintptr_t)membase < (uintptr_t)heaps[i-1].membase)
2115 i--;
2116 while (i < heaps_used && (uintptr_t)heaps[i].membase <= (uintptr_t)membase )
2117 i++;
2118 if (heaps_used <= i)
2119 break;
2120 membase = heaps[i].membase;
2122 p = heaps[i].slot; pend = p + heaps[i].limit;
2123 for (;p < pend; p++) {
2124 if (p->as.basic.flags) {
2125 switch (BUILTIN_TYPE(p)) {
2126 case T_NONE:
2127 case T_ICLASS:
2128 case T_NODE:
2129 case T_DEFERRED:
2130 continue;
2131 case T_CLASS:
2132 if (FL_TEST(p, FL_SINGLETON)) continue;
2133 default:
2134 if (!p->as.basic.klass) continue;
2135 v = (VALUE)p;
2136 if (!of || rb_obj_is_kind_of(v, of)) {
2137 rb_yield(v);
2138 n++;
2145 return SIZET2NUM(n);
2149 * call-seq:
2150 * ObjectSpace.each_object([module]) {|obj| ... } => fixnum
2152 * Calls the block once for each living, nonimmediate object in this
2153 * Ruby process. If <i>module</i> is specified, calls the block
2154 * for only those classes or modules that match (or are a subclass of)
2155 * <i>module</i>. Returns the number of objects found. Immediate
2156 * objects (<code>Fixnum</code>s, <code>Symbol</code>s
2157 * <code>true</code>, <code>false</code>, and <code>nil</code>) are
2158 * never returned. In the example below, <code>each_object</code>
2159 * returns both the numbers we defined and several constants defined in
2160 * the <code>Math</code> module.
2162 * a = 102.7
2163 * b = 95 # Won't be returned
2164 * c = 12345678987654321
2165 * count = ObjectSpace.each_object(Numeric) {|x| p x }
2166 * puts "Total count: #{count}"
2168 * <em>produces:</em>
2170 * 12345678987654321
2171 * 102.7
2172 * 2.71828182845905
2173 * 3.14159265358979
2174 * 2.22044604925031e-16
2175 * 1.7976931348623157e+308
2176 * 2.2250738585072e-308
2177 * Total count: 7
2181 static VALUE
2182 os_each_obj(int argc, VALUE *argv, VALUE os)
2184 VALUE of;
2186 rb_secure(4);
2187 if (argc == 0) {
2188 of = 0;
2190 else {
2191 rb_scan_args(argc, argv, "01", &of);
2193 RETURN_ENUMERATOR(os, 1, &of);
2194 return os_obj_of(&rb_objspace, of);
2198 * call-seq:
2199 * ObjectSpace.undefine_finalizer(obj)
2201 * Removes all finalizers for <i>obj</i>.
2205 static VALUE
2206 undefine_final(VALUE os, VALUE obj)
2208 rb_objspace_t *objspace = &rb_objspace;
2209 if (finalizer_table) {
2210 st_delete(finalizer_table, (st_data_t*)&obj, 0);
2212 return obj;
2216 * call-seq:
2217 * ObjectSpace.define_finalizer(obj, aProc=proc())
2219 * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
2220 * was destroyed.
2224 static VALUE
2225 define_final(int argc, VALUE *argv, VALUE os)
2227 rb_objspace_t *objspace = &rb_objspace;
2228 VALUE obj, block, table;
2230 rb_scan_args(argc, argv, "11", &obj, &block);
2231 if (argc == 1) {
2232 block = rb_block_proc();
2234 else if (!rb_respond_to(block, rb_intern("call"))) {
2235 rb_raise(rb_eArgError, "wrong type argument %s (should be callable)",
2236 rb_obj_classname(block));
2238 FL_SET(obj, FL_FINALIZE);
2240 block = rb_ary_new3(2, INT2FIX(rb_safe_level()), block);
2242 if (!finalizer_table) {
2243 finalizer_table = st_init_numtable();
2245 if (st_lookup(finalizer_table, obj, &table)) {
2246 rb_ary_push(table, block);
2248 else {
2249 st_add_direct(finalizer_table, obj, rb_ary_new3(1, block));
2251 return block;
2254 void
2255 rb_gc_copy_finalizer(VALUE dest, VALUE obj)
2257 rb_objspace_t *objspace = &rb_objspace;
2258 VALUE table;
2260 if (!finalizer_table) return;
2261 if (!FL_TEST(obj, FL_FINALIZE)) return;
2262 if (st_lookup(finalizer_table, obj, &table)) {
2263 st_insert(finalizer_table, dest, table);
2265 FL_SET(dest, FL_FINALIZE);
2268 static VALUE
2269 run_single_final(VALUE arg)
2271 VALUE *args = (VALUE *)arg;
2272 rb_eval_cmd(args[0], args[1], (int)args[2]);
2273 return Qnil;
2276 static void
2277 run_final(rb_objspace_t *objspace, VALUE obj)
2279 long i;
2280 int status;
2281 VALUE args[3], table, objid;
2283 objid = rb_obj_id(obj); /* make obj into id */
2284 RBASIC(obj)->klass = 0;
2286 if (RDATA(obj)->dfree) {
2287 (*RDATA(obj)->dfree)(DATA_PTR(obj));
2290 if (finalizer_table &&
2291 st_delete(finalizer_table, (st_data_t*)&obj, &table)) {
2292 args[1] = 0;
2293 args[2] = (VALUE)rb_safe_level();
2294 if (!args[1] && RARRAY_LEN(table) > 0) {
2295 args[1] = rb_obj_freeze(rb_ary_new3(1, objid));
2297 for (i=0; i<RARRAY_LEN(table); i++) {
2298 VALUE final = RARRAY_PTR(table)[i];
2299 args[0] = RARRAY_PTR(final)[1];
2300 args[2] = FIX2INT(RARRAY_PTR(final)[0]);
2301 rb_protect(run_single_final, (VALUE)args, &status);
2306 static void
2307 gc_finalize_deferred(rb_objspace_t *objspace)
2309 RVALUE *p = deferred_final_list;
2310 deferred_final_list = 0;
2312 if (p) {
2313 finalize_list(objspace, p);
2315 free_unused_heaps(objspace);
2318 void
2319 rb_gc_finalize_deferred(void)
2321 gc_finalize_deferred(&rb_objspace);
2324 static int
2325 chain_finalized_object(st_data_t key, st_data_t val, st_data_t arg)
2327 RVALUE *p = (RVALUE *)key, **final_list = (RVALUE **)arg;
2328 if (p->as.basic.flags & FL_FINALIZE) {
2329 if (BUILTIN_TYPE(p) != T_DEFERRED) {
2330 p->as.free.flags = FL_MARK | T_DEFERRED; /* remain marked */
2331 RDATA(p)->dfree = 0;
2333 p->as.free.next = *final_list;
2334 *final_list = p;
2335 return ST_CONTINUE;
2337 else {
2338 return ST_DELETE;
2342 void
2343 rb_gc_call_finalizer_at_exit(void)
2345 rb_objspace_t *objspace = &rb_objspace;
2346 RVALUE *p, *pend;
2347 size_t i;
2349 /* run finalizers */
2350 if (finalizer_table) {
2351 p = deferred_final_list;
2352 deferred_final_list = 0;
2353 finalize_list(objspace, p);
2354 while (finalizer_table->num_entries > 0) {
2355 RVALUE *final_list = 0;
2356 st_foreach(finalizer_table, chain_finalized_object,
2357 (st_data_t)&final_list);
2358 if (!(p = final_list)) break;
2359 do {
2360 final_list = p->as.free.next;
2361 run_final(objspace, (VALUE)p);
2362 } while ((p = final_list) != 0);
2364 st_free_table(finalizer_table);
2365 finalizer_table = 0;
2367 /* finalizers are part of garbage collection */
2368 during_gc++;
2369 /* run data object's finalizers */
2370 for (i = 0; i < heaps_used; i++) {
2371 p = heaps[i].slot; pend = p + heaps[i].limit;
2372 while (p < pend) {
2373 if (BUILTIN_TYPE(p) == T_DATA &&
2374 DATA_PTR(p) && RANY(p)->as.data.dfree &&
2375 RANY(p)->as.basic.klass != rb_cThread) {
2376 p->as.free.flags = 0;
2377 if ((long)RANY(p)->as.data.dfree == -1) {
2378 xfree(DATA_PTR(p));
2380 else if (RANY(p)->as.data.dfree) {
2381 (*RANY(p)->as.data.dfree)(DATA_PTR(p));
2383 VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
2385 else if (BUILTIN_TYPE(p) == T_FILE) {
2386 if (rb_io_fptr_finalize(RANY(p)->as.file.fptr)) {
2387 p->as.free.flags = 0;
2388 VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
2391 p++;
2394 during_gc = 0;
2397 void
2398 rb_gc(void)
2400 rb_objspace_t *objspace = &rb_objspace;
2401 garbage_collect(objspace);
2402 gc_finalize_deferred(objspace);
2406 * call-seq:
2407 * ObjectSpace._id2ref(object_id) -> an_object
2409 * Converts an object id to a reference to the object. May not be
2410 * called on an object id passed as a parameter to a finalizer.
2412 * s = "I am a string" #=> "I am a string"
2413 * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
2414 * r == s #=> true
2418 static VALUE
2419 id2ref(VALUE obj, VALUE objid)
2421 #if SIZEOF_LONG == SIZEOF_VOIDP
2422 #define NUM2PTR(x) NUM2ULONG(x)
2423 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
2424 #define NUM2PTR(x) NUM2ULL(x)
2425 #endif
2426 rb_objspace_t *objspace = &rb_objspace;
2427 VALUE ptr;
2428 void *p0;
2430 rb_secure(4);
2431 ptr = NUM2PTR(objid);
2432 p0 = (void *)ptr;
2434 if (ptr == Qtrue) return Qtrue;
2435 if (ptr == Qfalse) return Qfalse;
2436 if (ptr == Qnil) return Qnil;
2437 if (FIXNUM_P(ptr)) return (VALUE)ptr;
2438 ptr = objid ^ FIXNUM_FLAG; /* unset FIXNUM_FLAG */
2440 if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
2441 ID symid = ptr / sizeof(RVALUE);
2442 if (rb_id2name(symid) == 0)
2443 rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
2444 return ID2SYM(symid);
2447 if (!is_pointer_to_heap(objspace, (void *)ptr) ||
2448 BUILTIN_TYPE(ptr) > T_FIXNUM || BUILTIN_TYPE(ptr) == T_ICLASS) {
2449 rb_raise(rb_eRangeError, "%p is not id value", p0);
2451 if (BUILTIN_TYPE(ptr) == 0 || RBASIC(ptr)->klass == 0) {
2452 rb_raise(rb_eRangeError, "%p is recycled object", p0);
2454 return (VALUE)ptr;
2458 * Document-method: __id__
2459 * Document-method: object_id
2461 * call-seq:
2462 * obj.__id__ => fixnum
2463 * obj.object_id => fixnum
2465 * Returns an integer identifier for <i>obj</i>. The same number will
2466 * be returned on all calls to <code>id</code> for a given object, and
2467 * no two active objects will share an id.
2468 * <code>Object#object_id</code> is a different concept from the
2469 * <code>:name</code> notation, which returns the symbol id of
2470 * <code>name</code>. Replaces the deprecated <code>Object#id</code>.
2474 * call-seq:
2475 * obj.hash => fixnum
2477 * Generates a <code>Fixnum</code> hash value for this object. This
2478 * function must have the property that <code>a.eql?(b)</code> implies
2479 * <code>a.hash == b.hash</code>. The hash value is used by class
2480 * <code>Hash</code>. Any hash value that exceeds the capacity of a
2481 * <code>Fixnum</code> will be truncated before being used.
2484 VALUE
2485 rb_obj_id(VALUE obj)
2488 * 32-bit VALUE space
2489 * MSB ------------------------ LSB
2490 * false 00000000000000000000000000000000
2491 * true 00000000000000000000000000000010
2492 * nil 00000000000000000000000000000100
2493 * undef 00000000000000000000000000000110
2494 * symbol ssssssssssssssssssssssss00001110
2495 * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
2496 * fixnum fffffffffffffffffffffffffffffff1
2498 * object_id space
2499 * LSB
2500 * false 00000000000000000000000000000000
2501 * true 00000000000000000000000000000010
2502 * nil 00000000000000000000000000000100
2503 * undef 00000000000000000000000000000110
2504 * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
2505 * object oooooooooooooooooooooooooooooo0 o...o % A = 0
2506 * fixnum fffffffffffffffffffffffffffffff1 bignum if required
2508 * where A = sizeof(RVALUE)/4
2510 * sizeof(RVALUE) is
2511 * 20 if 32-bit, double is 4-byte aligned
2512 * 24 if 32-bit, double is 8-byte aligned
2513 * 40 if 64-bit
2515 if (TYPE(obj) == T_SYMBOL) {
2516 return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
2518 if (SPECIAL_CONST_P(obj)) {
2519 return LONG2NUM((SIGNED_VALUE)obj);
2521 return (VALUE)((SIGNED_VALUE)obj|FIXNUM_FLAG);
2524 static int
2525 set_zero(st_data_t key, st_data_t val, st_data_t arg)
2527 VALUE k = (VALUE)key;
2528 VALUE hash = (VALUE)arg;
2529 rb_hash_aset(hash, k, INT2FIX(0));
2530 return ST_CONTINUE;
2534 * call-seq:
2535 * ObjectSpace.count_objects([result_hash]) -> hash
2537 * Counts objects for each type.
2539 * It returns a hash as:
2540 * {:TOTAL=>10000, :FREE=>3011, :T_OBJECT=>6, :T_CLASS=>404, ...}
2542 * If the optional argument, result_hash, is given,
2543 * it is overwritten and returned.
2544 * This is intended to avoid probe effect.
2546 * The contents of the returned hash is implementation defined.
2547 * It may be changed in future.
2549 * This method is not expected to work except C Ruby.
2553 static VALUE
2554 count_objects(int argc, VALUE *argv, VALUE os)
2556 rb_objspace_t *objspace = &rb_objspace;
2557 size_t counts[T_MASK+1];
2558 size_t freed = 0;
2559 size_t total = 0;
2560 size_t i;
2561 VALUE hash;
2563 if (rb_scan_args(argc, argv, "01", &hash) == 1) {
2564 if (TYPE(hash) != T_HASH)
2565 rb_raise(rb_eTypeError, "non-hash given");
2568 for (i = 0; i <= T_MASK; i++) {
2569 counts[i] = 0;
2572 for (i = 0; i < heaps_used; i++) {
2573 RVALUE *p, *pend;
2575 p = heaps[i].slot; pend = p + heaps[i].limit;
2576 for (;p < pend; p++) {
2577 if (p->as.basic.flags) {
2578 counts[BUILTIN_TYPE(p)]++;
2580 else {
2581 freed++;
2584 total += heaps[i].limit;
2587 if (hash == Qnil) {
2588 hash = rb_hash_new();
2590 else if (!RHASH_EMPTY_P(hash)) {
2591 st_foreach(RHASH_TBL(hash), set_zero, hash);
2593 rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
2594 rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed));
2596 for (i = 0; i <= T_MASK; i++) {
2597 VALUE type;
2598 switch (i) {
2599 #define COUNT_TYPE(t) case t: type = ID2SYM(rb_intern(#t)); break;
2600 COUNT_TYPE(T_NONE);
2601 COUNT_TYPE(T_OBJECT);
2602 COUNT_TYPE(T_CLASS);
2603 COUNT_TYPE(T_MODULE);
2604 COUNT_TYPE(T_FLOAT);
2605 COUNT_TYPE(T_STRING);
2606 COUNT_TYPE(T_REGEXP);
2607 COUNT_TYPE(T_ARRAY);
2608 COUNT_TYPE(T_HASH);
2609 COUNT_TYPE(T_STRUCT);
2610 COUNT_TYPE(T_BIGNUM);
2611 COUNT_TYPE(T_FILE);
2612 COUNT_TYPE(T_DATA);
2613 COUNT_TYPE(T_MATCH);
2614 COUNT_TYPE(T_COMPLEX);
2615 COUNT_TYPE(T_RATIONAL);
2616 COUNT_TYPE(T_NIL);
2617 COUNT_TYPE(T_TRUE);
2618 COUNT_TYPE(T_FALSE);
2619 COUNT_TYPE(T_SYMBOL);
2620 COUNT_TYPE(T_FIXNUM);
2621 COUNT_TYPE(T_UNDEF);
2622 COUNT_TYPE(T_NODE);
2623 COUNT_TYPE(T_ICLASS);
2624 COUNT_TYPE(T_DEFERRED);
2625 #undef COUNT_TYPE
2626 default: type = INT2NUM(i); break;
2628 if (counts[i])
2629 rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
2632 return hash;
2636 * call-seq:
2637 * GC.count -> Integer
2639 * The number of times GC occured.
2641 * It returns the number of times GC occured since the process started.
2645 static VALUE
2646 gc_count(VALUE self)
2648 return UINT2NUM((&rb_objspace)->count);
2651 #if CALC_EXACT_MALLOC_SIZE
2653 * call-seq:
2654 * GC.malloc_allocated_size -> Integer
2656 * The allocated size by malloc().
2658 * It returns the allocated size by malloc().
2661 static VALUE
2662 gc_malloc_allocated_size(VALUE self)
2664 return UINT2NUM((&rb_objspace)->malloc_params.allocated_size);
2668 * call-seq:
2669 * GC.malloc_allocations -> Integer
2671 * The number of allocated memory object by malloc().
2673 * It returns the number of allocated memory object by malloc().
2676 static VALUE
2677 gc_malloc_allocations(VALUE self)
2679 return UINT2NUM((&rb_objspace)->malloc_params.allocations);
2681 #endif
2683 VALUE
2684 gc_profile_record_get(void)
2686 VALUE prof;
2687 VALUE gc_profile = rb_ary_new();
2688 size_t i;
2689 rb_objspace_t *objspace = (&rb_objspace);
2691 if (!objspace->profile.run) {
2692 return Qnil;
2695 for (i =0; i < objspace->profile.count; i++) {
2696 prof = rb_hash_new();
2697 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_time));
2698 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_invoke_time));
2699 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), rb_uint2inum(objspace->profile.record[i].heap_use_size));
2700 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), rb_uint2inum(objspace->profile.record[i].heap_total_size));
2701 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), rb_uint2inum(objspace->profile.record[i].heap_total_objects));
2702 #if GC_PROFILE_MORE_DETAIL
2703 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_mark_time));
2704 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DOUBLE2NUM(objspace->profile.record[i].gc_sweep_time));
2705 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), rb_uint2inum(objspace->profile.record[i].allocate_increase));
2706 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), rb_uint2inum(objspace->profile.record[i].allocate_limit));
2707 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SLOTS")), rb_uint2inum(objspace->profile.record[i].heap_use_slots));
2708 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), rb_uint2inum(objspace->profile.record[i].heap_live_objects));
2709 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), rb_uint2inum(objspace->profile.record[i].heap_free_objects));
2710 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), objspace->profile.record[i].have_finalize);
2711 #endif
2712 rb_ary_push(gc_profile, prof);
2715 return gc_profile;
2719 * call-seq:
2720 * GC::Profiler.result -> string
2722 * Report profile data to string.
2724 * It returns a string as:
2725 * GC 1 invokes.
2726 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
2727 * 1 0.012 159240 212940 10647 0.00000000000001530000
2730 VALUE
2731 gc_profile_result(void)
2733 rb_objspace_t *objspace = &rb_objspace;
2734 VALUE record = gc_profile_record_get();
2735 VALUE result;
2736 int i;
2738 if (objspace->profile.run && objspace->profile.count) {
2739 result = rb_sprintf("GC %d invokes.\n", NUM2INT(gc_count(0)));
2740 rb_str_cat2(result, "Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n");
2741 for (i = 0; i < (int)RARRAY_LEN(record); i++) {
2742 VALUE r = RARRAY_PTR(record)[i];
2743 rb_str_catf(result, "%5d %19.3f %20d %20d %20d %30.20f\n",
2744 i+1, NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_INVOKE_TIME")))),
2745 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_USE_SIZE")))),
2746 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")))),
2747 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")))),
2748 NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_TIME"))))*100);
2750 #if GC_PROFILE_MORE_DETAIL
2751 rb_str_cat2(result, "\n\n");
2752 rb_str_cat2(result, "More detail.\n");
2753 rb_str_cat2(result, "Index Allocate Increase Allocate Limit Use Slot Have Finalize Mark Time(ms) Sweep Time(ms)\n");
2754 for (i = 0; i < (int)RARRAY_LEN(record); i++) {
2755 VALUE r = RARRAY_PTR(record)[i];
2756 rb_str_catf(result, "%5d %17d %17d %9d %14s %25.20f %25.20f\n",
2757 i+1, NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("ALLOCATE_INCREASE")))),
2758 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("ALLOCATE_LIMIT")))),
2759 NUM2INT(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_USE_SLOTS")))),
2760 rb_hash_aref(r, ID2SYM(rb_intern("HAVE_FINALIZE")))? "true" : "false",
2761 NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_MARK_TIME"))))*100,
2762 NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_SWEEP_TIME"))))*100);
2764 #endif
2766 else {
2767 result = rb_str_new2("");
2769 return result;
2774 * call-seq:
2775 * GC::Profiler.report
2777 * GC::Profiler.result display
2781 VALUE
2782 gc_profile_report(int argc, VALUE *argv, VALUE self)
2784 VALUE out;
2786 if (argc == 0) {
2787 out = rb_stdout;
2789 else {
2790 rb_scan_args(argc, argv, "01", &out);
2792 rb_io_write(out, gc_profile_result());
2794 return Qnil;
2799 * The <code>GC</code> module provides an interface to Ruby's mark and
2800 * sweep garbage collection mechanism. Some of the underlying methods
2801 * are also available via the <code>ObjectSpace</code> module.
2804 void
2805 Init_GC(void)
2807 VALUE rb_mObSpace;
2808 VALUE rb_mProfiler;
2810 rb_mGC = rb_define_module("GC");
2811 rb_define_singleton_method(rb_mGC, "start", rb_gc_start, 0);
2812 rb_define_singleton_method(rb_mGC, "enable", rb_gc_enable, 0);
2813 rb_define_singleton_method(rb_mGC, "disable", rb_gc_disable, 0);
2814 rb_define_singleton_method(rb_mGC, "stress", gc_stress_get, 0);
2815 rb_define_singleton_method(rb_mGC, "stress=", gc_stress_set, 1);
2816 rb_define_singleton_method(rb_mGC, "count", gc_count, 0);
2817 rb_define_method(rb_mGC, "garbage_collect", rb_gc_start, 0);
2819 rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
2820 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
2821 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
2822 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
2823 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
2824 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
2825 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
2827 rb_mObSpace = rb_define_module("ObjectSpace");
2828 rb_define_module_function(rb_mObSpace, "each_object", os_each_obj, -1);
2829 rb_define_module_function(rb_mObSpace, "garbage_collect", rb_gc_start, 0);
2831 rb_define_module_function(rb_mObSpace, "define_finalizer", define_final, -1);
2832 rb_define_module_function(rb_mObSpace, "undefine_finalizer", undefine_final, 1);
2834 rb_define_module_function(rb_mObSpace, "_id2ref", id2ref, 1);
2836 nomem_error = rb_exc_new3(rb_eNoMemError,
2837 rb_obj_freeze(rb_str_new2("failed to allocate memory")));
2838 OBJ_TAINT(nomem_error);
2839 OBJ_FREEZE(nomem_error);
2841 rb_define_method(rb_mKernel, "hash", rb_obj_id, 0);
2842 rb_define_method(rb_mKernel, "__id__", rb_obj_id, 0);
2843 rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
2845 rb_define_module_function(rb_mObSpace, "count_objects", count_objects, -1);
2847 #if CALC_EXACT_MALLOC_SIZE
2848 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
2849 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
2850 #endif