1 /**********************************************************************
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"
17 #include "ruby/node.h"
20 #include "ruby/util.h"
21 #include "eval_intern.h"
26 #include <sys/types.h>
28 #ifdef HAVE_SYS_TIME_H
32 #ifdef HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
36 #if defined _WIN32 || defined __CYGWIN__
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)
45 # ifndef VALGRIND_MAKE_MEM_UNDEFINED
46 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE(p, n)
49 # define VALGRIND_MAKE_MEM_DEFINED(p, n) /* empty */
50 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) /* empty */
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. */
62 # define alloca __builtin_alloca
72 # ifndef alloca /* predefined by HP cc +Olibcalls */
76 # endif /* HAVE_ALLOCA_H */
79 #ifndef GC_MALLOC_LIMIT
80 #if defined(MSDOS) || defined(__human68k__)
81 #define GC_MALLOC_LIMIT 200000
83 #define GC_MALLOC_LIMIT 8000000
87 #define nomem_error GET_VM()->special_exceptions[ruby_error_nomemory]
89 #define MARK_STACK_MAX 1024
91 int ruby_gc_debug_indent
= 0;
95 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
96 #pragma pack(push, 1) /* magic for reducing sizeof(RVALUE): 24 -> 20 */
99 typedef struct RVALUE
{
102 VALUE flags
; /* always 0 for freed obj */
106 struct RObject object
;
108 struct RFloat flonum
;
109 struct RString string
;
111 struct RRegexp regexp
;
114 struct RStruct rstruct
;
115 struct RBignum bignum
;
119 struct RRational rational
;
120 struct RComplex
complex;
128 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
138 #define HEAP_MIN_SLOTS 10000
139 #define FREE_MIN 4096
143 struct gc_list
*next
;
146 #define CALC_EXACT_MALLOC_SIZE 0
148 typedef struct rb_objspace
{
152 #if CALC_EXACT_MALLOC_SIZE
153 size_t allocated_size
;
159 struct heaps_slot
*ptr
;
175 VALUE buffer
[MARK_STACK_MAX
];
179 struct gc_list
*global_list
;
184 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
185 #define rb_objspace (*GET_VM()->objspace)
186 static int ruby_initial_gc_stress
= 0;
187 int *ruby_initial_gc_stress_ptr
= &ruby_initial_gc_stress
;
189 static rb_objspace_t rb_objspace
= {{GC_MALLOC_LIMIT
}, {HEAP_MIN_SLOTS
}};
190 int *ruby_initial_gc_stress_ptr
= &rb_objspace
.gc_stress
;
192 #define malloc_limit objspace->malloc_params.limit
193 #define malloc_increase objspace->malloc_params.increase
194 #define heap_slots objspace->heap.slots
195 #define heaps objspace->heap.ptr
196 #define heaps_length objspace->heap.length
197 #define heaps_used objspace->heap.used
198 #define freelist objspace->heap.freelist
199 #define lomem objspace->heap.range[0]
200 #define himem objspace->heap.range[1]
201 #define heaps_inc objspace->heap.increment
202 #define heaps_freed objspace->heap.freed
203 #define dont_gc objspace->flags.dont_gc
204 #define during_gc objspace->flags.during_gc
205 #define finalizer_table objspace->final.table
206 #define deferred_final_list objspace->final.deferred
207 #define mark_stack objspace->markstack.buffer
208 #define mark_stack_ptr objspace->markstack.ptr
209 #define mark_stack_overflow objspace->markstack.overflow
210 #define global_List objspace->global_list
211 #define ruby_gc_stress objspace->gc_stress
213 #define need_call_final (finalizer_table && finalizer_table->num_entries)
215 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
217 rb_objspace_alloc(void)
219 rb_objspace_t
*objspace
= malloc(sizeof(rb_objspace_t
));
220 memset(objspace
, 0, sizeof(*objspace
));
221 malloc_limit
= GC_MALLOC_LIMIT
;
222 ruby_gc_stress
= ruby_initial_gc_stress
;
230 /*#define HEAP_SIZE 0x8000 */
232 /*#define HEAP_SIZE 0x20000 */
234 /*#define HEAP_SIZE 0x10000 */
236 #define HEAP_SIZE 0x4000
238 /*#define HEAP_SIZE 0x2000 */
240 /*#define HEAP_SIZE 0x1000 */
242 /*#define HEAP_SIZE 0x800 */
244 #define HEAP_OBJ_LIMIT (HEAP_SIZE / sizeof(struct RVALUE))
246 extern st_table
*rb_class_tbl
;
248 int ruby_disable_gc_stress
= 0;
250 static void run_final(rb_objspace_t
*objspace
, VALUE obj
);
251 static int garbage_collect(rb_objspace_t
*objspace
);
254 rb_global_variable(VALUE
*var
)
256 rb_gc_register_address(var
);
262 rb_thread_t
*th
= GET_THREAD();
264 (rb_thread_raised_p(th
, RAISED_NOMEMORY
) && rb_safe_level() < 4)) {
265 fprintf(stderr
, "[FATAL] failed to allocate memory\n");
268 if (rb_thread_raised_p(th
, RAISED_NOMEMORY
)) {
269 rb_thread_raised_clear(th
);
270 GET_THREAD()->errinfo
= nomem_error
;
273 rb_thread_raised_set(th
, RAISED_NOMEMORY
);
274 rb_exc_raise(nomem_error
);
279 * GC.stress => true or false
281 * returns current status of GC stress mode.
285 gc_stress_get(VALUE self
)
287 rb_objspace_t
*objspace
= &rb_objspace
;
288 return ruby_gc_stress
? Qtrue
: Qfalse
;
293 * GC.stress = bool => bool
295 * updates GC stress mode.
297 * When GC.stress = true, GC is invoked for all GC opportunity:
298 * all memory and object allocation.
300 * Since it makes Ruby very slow, it is only for debugging.
304 gc_stress_set(VALUE self
, VALUE
bool)
306 rb_objspace_t
*objspace
= &rb_objspace
;
308 ruby_gc_stress
= RTEST(bool);
313 vm_xmalloc(rb_objspace_t
*objspace
, size_t size
)
318 rb_raise(rb_eNoMemError
, "negative allocation size (or too big)");
320 if (size
== 0) size
= 1;
322 #if CALC_EXACT_MALLOC_SIZE
323 size
+= sizeof(size_t);
326 if ((ruby_gc_stress
&& !ruby_disable_gc_stress
) ||
327 (malloc_increase
+size
) > malloc_limit
) {
328 garbage_collect(objspace
);
330 RUBY_CRITICAL(mem
= malloc(size
));
332 if (garbage_collect(objspace
)) {
333 RUBY_CRITICAL(mem
= malloc(size
));
339 malloc_increase
+= size
;
341 #if CALC_EXACT_MALLOC_SIZE
342 objspace
->malloc_params
.allocated_size
+= size
;
343 objspace
->malloc_params
.allocations
++;
344 ((size_t *)mem
)[0] = size
;
345 mem
= (size_t *)mem
+ 1;
352 vm_xrealloc(rb_objspace_t
*objspace
, void *ptr
, size_t size
)
357 rb_raise(rb_eArgError
, "negative re-allocation size");
359 if (!ptr
) return ruby_xmalloc(size
);
360 if (size
== 0) size
= 1;
361 if (ruby_gc_stress
&& !ruby_disable_gc_stress
) garbage_collect(objspace
);
363 #if CALC_EXACT_MALLOC_SIZE
364 size
+= sizeof(size_t);
365 objspace
->malloc_params
.allocated_size
-= size
;
366 ptr
= (size_t *)ptr
- 1;
369 RUBY_CRITICAL(mem
= realloc(ptr
, size
));
371 if (garbage_collect(objspace
)) {
372 RUBY_CRITICAL(mem
= realloc(ptr
, size
));
378 malloc_increase
+= size
;
380 #if CALC_EXACT_MALLOC_SIZE
381 objspace
->malloc_params
.allocated_size
+= size
;
382 ((size_t *)mem
)[0] = size
;
383 mem
= (size_t *)mem
+ 1;
390 vm_xfree(rb_objspace_t
*objspace
, void *ptr
)
392 #if CALC_EXACT_MALLOC_SIZE
394 ptr
= ((size_t *)ptr
) - 1;
395 size
= ((size_t*)ptr
)[0];
396 objspace
->malloc_params
.allocated_size
-= size
;
397 objspace
->malloc_params
.allocations
--;
400 RUBY_CRITICAL(free(ptr
));
404 ruby_xmalloc(size_t size
)
406 return vm_xmalloc(&rb_objspace
, size
);
410 ruby_xmalloc2(size_t n
, size_t size
)
412 size_t len
= size
* n
;
413 if (n
!= 0 && size
!= len
/ n
) {
414 rb_raise(rb_eArgError
, "malloc: possible integer overflow");
416 return vm_xmalloc(&rb_objspace
, len
);
420 ruby_xcalloc(size_t n
, size_t size
)
422 void *mem
= ruby_xmalloc2(n
, size
);
423 memset(mem
, 0, n
* size
);
429 ruby_xrealloc(void *ptr
, size_t size
)
431 return vm_xrealloc(&rb_objspace
, ptr
, size
);
435 ruby_xrealloc2(void *ptr
, size_t n
, size_t size
)
437 size_t len
= size
* n
;
438 if (n
!= 0 && size
!= len
/ n
) {
439 rb_raise(rb_eArgError
, "realloc: possible integer overflow");
441 return ruby_xrealloc(ptr
, len
);
448 vm_xfree(&rb_objspace
, x
);
454 * GC.enable => true or false
456 * Enables garbage collection, returning <code>true</code> if garbage
457 * collection was previously disabled.
459 * GC.disable #=> false
461 * GC.enable #=> false
468 rb_objspace_t
*objspace
= &rb_objspace
;
477 * GC.disable => true or false
479 * Disables garbage collection, returning <code>true</code> if garbage
480 * collection was already disabled.
482 * GC.disable #=> false
483 * GC.disable #=> true
490 rb_objspace_t
*objspace
= &rb_objspace
;
500 rb_register_mark_object(VALUE obj
)
502 VALUE ary
= GET_THREAD()->vm
->mark_object_ary
;
503 rb_ary_push(ary
, obj
);
507 rb_gc_register_address(VALUE
*addr
)
509 rb_objspace_t
*objspace
= &rb_objspace
;
512 tmp
= ALLOC(struct gc_list
);
513 tmp
->next
= global_List
;
519 rb_gc_unregister_address(VALUE
*addr
)
521 rb_objspace_t
*objspace
= &rb_objspace
;
522 struct gc_list
*tmp
= global_List
;
524 if (tmp
->varptr
== addr
) {
525 global_List
= tmp
->next
;
530 if (tmp
->next
->varptr
== addr
) {
531 struct gc_list
*t
= tmp
->next
;
533 tmp
->next
= tmp
->next
->next
;
543 allocate_heaps(rb_objspace_t
*objspace
, size_t next_heaps_length
)
545 struct heaps_slot
*p
;
548 size
= next_heaps_length
*sizeof(struct heaps_slot
);
550 if (heaps_used
> 0) {
551 p
= (struct heaps_slot
*)realloc(heaps
, size
);
555 p
= heaps
= (struct heaps_slot
*)malloc(size
);
558 if (p
== 0) rb_memerror();
559 heaps_length
= next_heaps_length
;
563 assign_heap_slot(rb_objspace_t
*objspace
)
565 RVALUE
*p
, *pend
, *membase
;
569 objs
= HEAP_OBJ_LIMIT
;
570 RUBY_CRITICAL(p
= (RVALUE
*)malloc(HEAP_SIZE
));
575 if ((VALUE
)p
% sizeof(RVALUE
) != 0) {
576 p
= (RVALUE
*)((VALUE
)p
+ sizeof(RVALUE
) - ((VALUE
)p
% sizeof(RVALUE
)));
577 if ((HEAP_SIZE
- HEAP_OBJ_LIMIT
* sizeof(RVALUE
)) < ((char*)p
- (char*)membase
)) {
585 register RVALUE
*mid_membase
;
587 mid_membase
= heaps
[mid
].membase
;
588 if (mid_membase
< membase
) {
591 else if (mid_membase
> membase
) {
595 rb_bug("same heap slot is allocated: %p at %"PRIuVALUE
, membase
, (VALUE
)mid
);
598 if (hi
< heaps_used
) {
599 MEMMOVE(&heaps
[hi
+1], &heaps
[hi
], struct heaps_slot
, heaps_used
- hi
);
601 heaps
[hi
].membase
= membase
;
603 heaps
[hi
].limit
= objs
;
605 if (lomem
== 0 || lomem
> p
) lomem
= p
;
606 if (himem
< pend
) himem
= pend
;
610 p
->as
.free
.flags
= 0;
611 p
->as
.free
.next
= freelist
;
618 init_heap(rb_objspace_t
*objspace
)
622 add
= HEAP_MIN_SLOTS
/ HEAP_OBJ_LIMIT
;
624 if ((heaps_used
+ add
) > heaps_length
) {
625 allocate_heaps(objspace
, heaps_used
+ add
);
628 for (i
= 0; i
< add
; i
++) {
629 assign_heap_slot(objspace
);
636 set_heaps_increment(rb_objspace_t
*objspace
)
638 size_t next_heaps_length
= heaps_used
* 1.8;
639 heaps_inc
= next_heaps_length
- heaps_used
;
641 if (next_heaps_length
> heaps_length
) {
642 allocate_heaps(objspace
, next_heaps_length
);
647 heaps_increment(rb_objspace_t
*objspace
)
650 assign_heap_slot(objspace
);
657 #define RANY(o) ((RVALUE*)(o))
660 rb_newobj_from_heap(rb_objspace_t
*objspace
)
664 if ((ruby_gc_stress
&& !ruby_disable_gc_stress
) || !freelist
) {
665 if (!heaps_increment(objspace
) && !garbage_collect(objspace
)) {
670 obj
= (VALUE
)freelist
;
671 freelist
= freelist
->as
.free
.next
;
673 MEMZERO((void*)obj
, RVALUE
, 1);
675 RANY(obj
)->file
= rb_sourcefile();
676 RANY(obj
)->line
= rb_sourceline();
684 rb_fill_value_cache(rb_thread_t
*th
)
686 rb_objspace_t
*objspace
= &rb_objspace
;
691 for (i
=0; i
<RUBY_VM_VALUE_CACHE_SIZE
; i
++) {
692 VALUE v
= rb_newobj_from_heap(objspace
);
694 th
->value_cache
[i
] = v
;
695 RBASIC(v
)->flags
= FL_MARK
;
697 th
->value_cache_ptr
= &th
->value_cache
[0];
698 rv
= rb_newobj_from_heap(objspace
);
707 rb_objspace_t
*objspace
= &rb_objspace
;
714 #if USE_VALUE_CACHE || (defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE)
715 rb_thread_t
*th
= GET_THREAD();
718 VALUE v
= *th
->value_cache_ptr
;
720 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
721 rb_objspace_t
*objspace
= th
->vm
->objspace
;
723 rb_objspace_t
*objspace
= &rb_objspace
;
729 rb_bug("object allocation during garbage collection phase");
734 RBASIC(v
)->flags
= 0;
735 th
->value_cache_ptr
++;
738 v
= rb_fill_value_cache(th
);
741 #if defined(GC_DEBUG)
742 printf("cache index: %d, v: %p, th: %p\n",
743 th
->value_cache_ptr
- th
->value_cache
, v
, th
);
747 return rb_newobj_from_heap(objspace
);
752 rb_node_newnode(enum node_type type
, VALUE a0
, VALUE a1
, VALUE a2
)
754 NODE
*n
= (NODE
*)rb_newobj();
757 nd_set_type(n
, type
);
767 rb_data_object_alloc(VALUE klass
, void *datap
, RUBY_DATA_FUNC dmark
, RUBY_DATA_FUNC dfree
)
769 NEWOBJ(data
, struct RData
);
770 if (klass
) Check_Type(klass
, T_CLASS
);
771 OBJSETUP(data
, klass
, T_DATA
);
780 #define SET_STACK_END (SET_MACHINE_STACK_END(&th->machine_stack_end), th->machine_register_stack_end = rb_ia64_bsp())
782 #define SET_STACK_END SET_MACHINE_STACK_END(&th->machine_stack_end)
785 #define STACK_START (th->machine_stack_start)
786 #define STACK_END (th->machine_stack_end)
787 #define STACK_LEVEL_MAX (th->machine_stack_maxsize/sizeof(VALUE))
789 #if STACK_GROW_DIRECTION < 0
790 # define STACK_LENGTH (STACK_START - STACK_END)
791 #elif STACK_GROW_DIRECTION > 0
792 # define STACK_LENGTH (STACK_END - STACK_START + 1)
794 # define STACK_LENGTH ((STACK_END < STACK_START) ? STACK_START - STACK_END\
795 : STACK_END - STACK_START + 1)
797 #if !STACK_GROW_DIRECTION
798 int ruby_stack_grow_direction
;
800 ruby_get_stack_grow_direction(VALUE
*addr
)
802 rb_thread_t
*th
= GET_THREAD();
805 if (STACK_END
> addr
) return ruby_stack_grow_direction
= 1;
806 return ruby_stack_grow_direction
= -1;
810 #define GC_WATER_MARK 512
813 ruby_stack_length(VALUE
**p
)
815 rb_thread_t
*th
= GET_THREAD();
817 if (p
) *p
= STACK_UPPER(STACK_END
, STACK_START
, STACK_END
);
822 ruby_stack_check(void)
825 rb_thread_t
*th
= GET_THREAD();
827 ret
= STACK_LENGTH
> STACK_LEVEL_MAX
- GC_WATER_MARK
;
830 ret
= (VALUE
*)rb_ia64_bsp() - th
->machine_register_stack_start
>
831 th
->machine_register_stack_maxsize
/sizeof(VALUE
) - GC_WATER_MARK
;
838 init_mark_stack(rb_objspace_t
*objspace
)
840 mark_stack_overflow
= 0;
841 mark_stack_ptr
= mark_stack
;
844 #define MARK_STACK_EMPTY (mark_stack_ptr == mark_stack)
846 static void gc_mark(rb_objspace_t
*objspace
, VALUE ptr
, int lev
);
847 static void gc_mark_children(rb_objspace_t
*objspace
, VALUE ptr
, int lev
);
850 gc_mark_all(rb_objspace_t
*objspace
)
855 init_mark_stack(objspace
);
856 for (i
= 0; i
< heaps_used
; i
++) {
857 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
859 if ((p
->as
.basic
.flags
& FL_MARK
) &&
860 (p
->as
.basic
.flags
!= FL_MARK
)) {
861 gc_mark_children(objspace
, (VALUE
)p
, 0);
869 gc_mark_rest(rb_objspace_t
*objspace
)
871 VALUE tmp_arry
[MARK_STACK_MAX
];
874 p
= (mark_stack_ptr
- mark_stack
) + tmp_arry
;
875 MEMCPY(tmp_arry
, mark_stack
, VALUE
, p
- tmp_arry
);
877 init_mark_stack(objspace
);
878 while (p
!= tmp_arry
) {
880 gc_mark_children(objspace
, *p
, 0);
885 is_pointer_to_heap(rb_objspace_t
*objspace
, void *ptr
)
887 register RVALUE
*p
= RANY(ptr
);
888 register struct heaps_slot
*heap
;
889 register size_t hi
, lo
, mid
;
891 if (p
< lomem
|| p
> himem
) return Qfalse
;
892 if ((VALUE
)p
% sizeof(RVALUE
) != 0) return Qfalse
;
894 /* check if p looks like a pointer using bsearch*/
900 if (heap
->slot
<= p
) {
901 if (p
< heap
->slot
+ heap
->limit
)
913 mark_locations_array(rb_objspace_t
*objspace
, register VALUE
*x
, register long n
)
918 VALGRIND_MAKE_MEM_DEFINED(&v
, sizeof(v
));
919 if (is_pointer_to_heap(objspace
, (void *)v
)) {
920 gc_mark(objspace
, v
, 0);
927 gc_mark_locations(rb_objspace_t
*objspace
, VALUE
*start
, VALUE
*end
)
931 if (end
<= start
) return;
933 mark_locations_array(objspace
, start
, n
);
937 rb_gc_mark_locations(VALUE
*start
, VALUE
*end
)
939 gc_mark_locations(&rb_objspace
, start
, end
);
942 #define rb_gc_mark_locations(start, end) gc_mark_locations(objspace, start, end)
944 struct mark_tbl_arg
{
945 rb_objspace_t
*objspace
;
950 mark_entry(ID key
, VALUE value
, st_data_t data
)
952 struct mark_tbl_arg
*arg
= (void*)data
;
953 gc_mark(arg
->objspace
, value
, arg
->lev
);
958 mark_tbl(rb_objspace_t
*objspace
, st_table
*tbl
, int lev
)
960 struct mark_tbl_arg arg
;
962 arg
.objspace
= objspace
;
964 st_foreach(tbl
, mark_entry
, (st_data_t
)&arg
);
968 rb_mark_tbl(st_table
*tbl
)
970 mark_tbl(&rb_objspace
, tbl
, 0);
974 mark_key(VALUE key
, VALUE value
, st_data_t data
)
976 struct mark_tbl_arg
*arg
= (void*)data
;
977 gc_mark(arg
->objspace
, key
, arg
->lev
);
982 mark_set(rb_objspace_t
*objspace
, st_table
*tbl
, int lev
)
984 struct mark_tbl_arg arg
;
986 arg
.objspace
= objspace
;
988 st_foreach(tbl
, mark_key
, (st_data_t
)&arg
);
992 rb_mark_set(st_table
*tbl
)
994 mark_set(&rb_objspace
, tbl
, 0);
998 mark_keyvalue(VALUE key
, VALUE value
, st_data_t data
)
1000 struct mark_tbl_arg
*arg
= (void*)data
;
1001 gc_mark(arg
->objspace
, key
, arg
->lev
);
1002 gc_mark(arg
->objspace
, value
, arg
->lev
);
1007 mark_hash(rb_objspace_t
*objspace
, st_table
*tbl
, int lev
)
1009 struct mark_tbl_arg arg
;
1011 arg
.objspace
= objspace
;
1013 st_foreach(tbl
, mark_keyvalue
, (st_data_t
)&arg
);
1017 rb_mark_hash(st_table
*tbl
)
1019 mark_hash(&rb_objspace
, tbl
, 0);
1023 rb_gc_mark_maybe(VALUE obj
)
1025 if (is_pointer_to_heap(&rb_objspace
, (void *)obj
)) {
1026 gc_mark(&rb_objspace
, obj
, 0);
1030 #define GC_LEVEL_MAX 250
1033 gc_mark(rb_objspace_t
*objspace
, VALUE ptr
, int lev
)
1035 register RVALUE
*obj
;
1038 if (rb_special_const_p(ptr
)) return; /* special const not marked */
1039 if (obj
->as
.basic
.flags
== 0) return; /* free cell */
1040 if (obj
->as
.basic
.flags
& FL_MARK
) return; /* already marked */
1041 obj
->as
.basic
.flags
|= FL_MARK
;
1043 if (lev
> GC_LEVEL_MAX
|| (lev
== 0 && ruby_stack_check())) {
1044 if (!mark_stack_overflow
) {
1045 if (mark_stack_ptr
- mark_stack
< MARK_STACK_MAX
) {
1046 *mark_stack_ptr
= ptr
;
1050 mark_stack_overflow
= 1;
1055 gc_mark_children(objspace
, ptr
, lev
+1);
1059 rb_gc_mark(VALUE ptr
)
1061 gc_mark(&rb_objspace
, ptr
, 0);
1065 gc_mark_children(rb_objspace_t
*objspace
, VALUE ptr
, int lev
)
1067 register RVALUE
*obj
= RANY(ptr
);
1069 goto marking
; /* skip */
1073 if (rb_special_const_p(ptr
)) return; /* special const not marked */
1074 if (obj
->as
.basic
.flags
== 0) return; /* free cell */
1075 if (obj
->as
.basic
.flags
& FL_MARK
) return; /* already marked */
1076 obj
->as
.basic
.flags
|= FL_MARK
;
1079 if (FL_TEST(obj
, FL_EXIVAR
)) {
1080 rb_mark_generic_ivar(ptr
);
1083 switch (BUILTIN_TYPE(obj
)) {
1086 rb_bug("rb_gc_mark() called for broken object");
1090 switch (nd_type(obj
)) {
1091 case NODE_IF
: /* 1,2,3 */
1099 case NODE_BLOCK_PASS
:
1100 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u2
.node
, lev
);
1102 case NODE_BLOCK
: /* 1,3 */
1108 case NODE_DREGX_ONCE
:
1114 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u1
.node
, lev
);
1116 case NODE_SUPER
: /* 3 */
1120 ptr
= (VALUE
)obj
->as
.node
.u3
.node
;
1123 case NODE_METHOD
: /* 1,2 */
1136 case NODE_OP_ASGN_OR
:
1137 case NODE_OP_ASGN_AND
:
1142 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u1
.node
, lev
);
1144 case NODE_FBODY
: /* 2 */
1148 case NODE_DASGN_CURR
:
1157 ptr
= (VALUE
)obj
->as
.node
.u2
.node
;
1160 case NODE_HASH
: /* 1 */
1173 ptr
= (VALUE
)obj
->as
.node
.u1
.node
;
1176 case NODE_SCOPE
: /* 2,3 */
1179 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u3
.node
, lev
);
1180 ptr
= (VALUE
)obj
->as
.node
.u2
.node
;
1183 case NODE_ZARRAY
: /* - */
1202 case NODE_BLOCK_ARG
:
1205 mark_locations_array(objspace
,
1206 (VALUE
*)obj
->as
.node
.u1
.value
,
1207 obj
->as
.node
.u3
.cnt
);
1208 ptr
= (VALUE
)obj
->as
.node
.u2
.node
;
1211 default: /* unlisted NODE */
1212 if (is_pointer_to_heap(objspace
, obj
->as
.node
.u1
.node
)) {
1213 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u1
.node
, lev
);
1215 if (is_pointer_to_heap(objspace
, obj
->as
.node
.u2
.node
)) {
1216 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u2
.node
, lev
);
1218 if (is_pointer_to_heap(objspace
, obj
->as
.node
.u3
.node
)) {
1219 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u3
.node
, lev
);
1222 return; /* no need to mark class. */
1225 gc_mark(objspace
, obj
->as
.basic
.klass
, lev
);
1226 switch (BUILTIN_TYPE(obj
)) {
1230 mark_tbl(objspace
, RCLASS_M_TBL(obj
), lev
);
1231 mark_tbl(objspace
, RCLASS_IV_TBL(obj
), lev
);
1232 ptr
= RCLASS_SUPER(obj
);
1236 if (FL_TEST(obj
, ELTS_SHARED
)) {
1237 ptr
= obj
->as
.array
.aux
.shared
;
1241 long i
, len
= RARRAY_LEN(obj
);
1242 VALUE
*ptr
= RARRAY_PTR(obj
);
1243 for (i
=0; i
< len
; i
++) {
1244 gc_mark(objspace
, *ptr
++, lev
);
1250 mark_hash(objspace
, obj
->as
.hash
.ntbl
, lev
);
1251 ptr
= obj
->as
.hash
.ifnone
;
1255 #define STR_ASSOC FL_USER3 /* copied from string.c */
1256 if (FL_TEST(obj
, RSTRING_NOEMBED
) && FL_ANY(obj
, ELTS_SHARED
|STR_ASSOC
)) {
1257 ptr
= obj
->as
.string
.as
.heap
.aux
.shared
;
1263 if (obj
->as
.data
.dmark
) (*obj
->as
.data
.dmark
)(DATA_PTR(obj
));
1268 long i
, len
= ROBJECT_NUMIV(obj
);
1269 VALUE
*ptr
= ROBJECT_IVPTR(obj
);
1270 for (i
= 0; i
< len
; i
++) {
1271 gc_mark(objspace
, *ptr
++, lev
);
1277 if (obj
->as
.file
.fptr
)
1278 gc_mark(objspace
, obj
->as
.file
.fptr
->tied_io_for_writing
, lev
);
1282 gc_mark(objspace
, obj
->as
.regexp
.src
, lev
);
1290 gc_mark(objspace
, obj
->as
.match
.regexp
, lev
);
1291 if (obj
->as
.match
.str
) {
1292 ptr
= obj
->as
.match
.str
;
1298 gc_mark(objspace
, obj
->as
.rational
.num
, lev
);
1299 gc_mark(objspace
, obj
->as
.rational
.den
, lev
);
1303 gc_mark(objspace
, obj
->as
.complex.real
, lev
);
1304 gc_mark(objspace
, obj
->as
.complex.image
, lev
);
1309 long len
= RSTRUCT_LEN(obj
);
1310 VALUE
*ptr
= RSTRUCT_PTR(obj
);
1313 gc_mark(objspace
, *ptr
++, lev
);
1319 rb_bug("rb_gc_mark(): unknown data type 0x%lx(%p) %s",
1320 BUILTIN_TYPE(obj
), obj
,
1321 is_pointer_to_heap(objspace
, obj
) ? "corrupted object" : "non object");
1325 static int obj_free(rb_objspace_t
*, VALUE
);
1328 add_freelist(rb_objspace_t
*objspace
, RVALUE
*p
)
1330 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
1331 p
->as
.free
.flags
= 0;
1332 p
->as
.free
.next
= freelist
;
1337 finalize_list(rb_objspace_t
*objspace
, RVALUE
*p
)
1340 RVALUE
*tmp
= p
->as
.free
.next
;
1341 run_final(objspace
, (VALUE
)p
);
1342 if (!FL_TEST(p
, FL_SINGLETON
)) { /* not freeing page */
1343 add_freelist(objspace
, p
);
1346 struct heaps_slot
*slot
= (struct heaps_slot
*)RDATA(p
)->dmark
;
1354 free_unused_heaps(rb_objspace_t
*objspace
)
1359 for (i
= j
= 1; j
< heaps_used
; i
++) {
1360 if (heaps
[i
].limit
== 0) {
1362 last
= heaps
[i
].membase
;
1365 free(heaps
[i
].membase
);
1371 heaps
[j
] = heaps
[i
];
1377 if (last
< heaps_freed
) {
1388 gc_sweep(rb_objspace_t
*objspace
)
1390 RVALUE
*p
, *pend
, *final_list
;
1393 size_t live
= 0, free_min
= 0, do_heap_free
= 0;
1395 do_heap_free
= (heaps_used
* HEAP_OBJ_LIMIT
) * 0.65;
1396 free_min
= (heaps_used
* HEAP_OBJ_LIMIT
) * 0.2;
1398 if (free_min
< FREE_MIN
) {
1399 do_heap_free
= heaps_used
* HEAP_OBJ_LIMIT
;
1400 free_min
= FREE_MIN
;
1404 final_list
= deferred_final_list
;
1405 deferred_final_list
= 0;
1406 for (i
= 0; i
< heaps_used
; i
++) {
1408 RVALUE
*free
= freelist
;
1409 RVALUE
*final
= final_list
;
1412 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
1414 if (!(p
->as
.basic
.flags
& FL_MARK
)) {
1415 if (p
->as
.basic
.flags
&&
1416 ((deferred
= obj_free(objspace
, (VALUE
)p
)) ||
1417 ((FL_TEST(p
, FL_FINALIZE
)) && need_call_final
))) {
1419 p
->as
.free
.flags
= T_DEFERRED
;
1420 RDATA(p
)->dfree
= 0;
1422 p
->as
.free
.flags
|= FL_MARK
;
1423 p
->as
.free
.next
= final_list
;
1427 add_freelist(objspace
, p
);
1431 else if (BUILTIN_TYPE(p
) == T_DEFERRED
) {
1432 /* objects to be finalized */
1433 /* do nothing remain marked */
1436 RBASIC(p
)->flags
&= ~FL_MARK
;
1441 if (n
== heaps
[i
].limit
&& freed
> do_heap_free
) {
1445 for (pp
= final_list
; pp
!= final
; pp
= pp
->as
.free
.next
) {
1447 RDATA(pp
)->dmark
= (void *)&heaps
[i
];
1448 pp
->as
.free
.flags
|= FL_SINGLETON
; /* freeing page mark */
1450 heaps
[i
].limit
= f_count
;
1452 freelist
= free
; /* cancel this page from freelist */
1458 if (malloc_increase
> malloc_limit
) {
1459 malloc_limit
+= (malloc_increase
- malloc_limit
) * (double)live
/ (live
+ freed
);
1460 if (malloc_limit
< GC_MALLOC_LIMIT
) malloc_limit
= GC_MALLOC_LIMIT
;
1462 malloc_increase
= 0;
1463 if (freed
< free_min
) {
1464 set_heaps_increment(objspace
);
1465 heaps_increment(objspace
);
1469 /* clear finalization list */
1471 deferred_final_list
= final_list
;
1472 RUBY_VM_SET_FINALIZER_INTERRUPT(GET_THREAD());
1475 free_unused_heaps(objspace
);
1480 rb_gc_force_recycle(VALUE p
)
1482 rb_objspace_t
*objspace
= &rb_objspace
;
1483 add_freelist(objspace
, (RVALUE
*)p
);
1487 obj_free(rb_objspace_t
*objspace
, VALUE obj
)
1489 switch (BUILTIN_TYPE(obj
)) {
1494 rb_bug("obj_free() called for broken object");
1498 if (FL_TEST(obj
, FL_EXIVAR
)) {
1499 rb_free_generic_ivar((VALUE
)obj
);
1502 switch (BUILTIN_TYPE(obj
)) {
1504 if (!(RANY(obj
)->as
.basic
.flags
& ROBJECT_EMBED
) &&
1505 RANY(obj
)->as
.object
.as
.heap
.ivptr
) {
1506 xfree(RANY(obj
)->as
.object
.as
.heap
.ivptr
);
1511 rb_clear_cache_by_class((VALUE
)obj
);
1512 st_free_table(RCLASS_M_TBL(obj
));
1513 if (RCLASS_IV_TBL(obj
)) {
1514 st_free_table(RCLASS_IV_TBL(obj
));
1516 if (RCLASS_IV_INDEX_TBL(obj
)) {
1517 st_free_table(RCLASS_IV_INDEX_TBL(obj
));
1519 xfree(RANY(obj
)->as
.klass
.ptr
);
1528 if (RANY(obj
)->as
.hash
.ntbl
) {
1529 st_free_table(RANY(obj
)->as
.hash
.ntbl
);
1533 if (RANY(obj
)->as
.regexp
.ptr
) {
1534 onig_free(RANY(obj
)->as
.regexp
.ptr
);
1538 if (DATA_PTR(obj
)) {
1539 if ((long)RANY(obj
)->as
.data
.dfree
== -1) {
1540 xfree(DATA_PTR(obj
));
1542 else if (RANY(obj
)->as
.data
.dfree
) {
1544 RANY(obj
)->as
.basic
.flags
&= ~T_MASK
;
1545 RANY(obj
)->as
.basic
.flags
|= T_DEFERRED
;
1549 (*RANY(obj
)->as
.data
.dfree
)(DATA_PTR(obj
));
1555 if (RANY(obj
)->as
.match
.rmatch
) {
1556 struct rmatch
*rm
= RANY(obj
)->as
.match
.rmatch
;
1557 onig_region_free(&rm
->regs
, 0);
1558 if (rm
->char_offset
)
1559 xfree(rm
->char_offset
);
1564 if (RANY(obj
)->as
.file
.fptr
) {
1565 rb_io_t
*fptr
= RANY(obj
)->as
.file
.fptr
;
1567 RANY(obj
)->as
.basic
.flags
&= ~T_MASK
;
1568 RANY(obj
)->as
.basic
.flags
|= T_DEFERRED
;
1569 RDATA(obj
)->dfree
= (void (*)(void*))rb_io_fptr_finalize
;
1570 RDATA(obj
)->data
= fptr
;
1574 rb_io_fptr_finalize(fptr
);
1582 /* iClass shares table with the module */
1589 if (!(RBASIC(obj
)->flags
& RBIGNUM_EMBED_FLAG
) && RBIGNUM_DIGITS(obj
)) {
1590 xfree(RBIGNUM_DIGITS(obj
));
1594 switch (nd_type(obj
)) {
1596 if (RANY(obj
)->as
.node
.u1
.tbl
) {
1597 xfree(RANY(obj
)->as
.node
.u1
.tbl
);
1601 xfree(RANY(obj
)->as
.node
.u1
.node
);
1604 break; /* no need to free iv_tbl */
1607 if ((RBASIC(obj
)->flags
& RSTRUCT_EMBED_LEN_MASK
) == 0 &&
1608 RANY(obj
)->as
.rstruct
.as
.heap
.ptr
) {
1609 xfree(RANY(obj
)->as
.rstruct
.as
.heap
.ptr
);
1614 rb_bug("gc_sweep(): unknown data type 0x%lx(%p)",
1615 BUILTIN_TYPE(obj
), (void*)obj
);
1622 #if defined(__human68k__) || defined(DJGPP)
1625 #if defined(__human68k__)
1626 typedef unsigned long rb_jmp_buf
[8];
1630 movem.l d3-d7/a3-a5,(a0)\n\
1635 typedef unsigned long rb_jmp_buf
[6];
1636 __asm__ (".align 4\n\
1640 movl 8(%ebp),%ebp\n\
1642 movl %ebx,4(%ebp)\n\
1643 movl %ecx,8(%ebp)\n\
1644 movl %edx,12(%ebp)\n\
1645 movl %esi,16(%ebp)\n\
1646 movl %edi,20(%ebp)\n\
1652 int rb_setjmp (rb_jmp_buf
);
1653 #endif /* __human68k__ or DJGPP */
1654 #endif /* __GNUC__ */
1658 void rb_vm_mark(void *ptr
);
1661 mark_current_machine_context(rb_objspace_t
*objspace
, rb_thread_t
*th
)
1663 rb_jmp_buf save_regs_gc_mark
;
1664 VALUE
*stack_start
, *stack_end
;
1667 #if STACK_GROW_DIRECTION < 0
1668 stack_start
= th
->machine_stack_end
;
1669 stack_end
= th
->machine_stack_start
;
1670 #elif STACK_GROW_DIRECTION > 0
1671 stack_start
= th
->machine_stack_start
;
1672 stack_end
= th
->machine_stack_end
+ 1;
1674 if (th
->machine_stack_end
< th
->machine_stack_start
) {
1675 stack_start
= th
->machine_stack_end
;
1676 stack_end
= th
->machine_stack_start
;
1679 stack_start
= th
->machine_stack_start
;
1680 stack_end
= th
->machine_stack_end
+ 1;
1684 FLUSH_REGISTER_WINDOWS
;
1685 /* This assumes that all registers are saved into the jmp_buf (and stack) */
1686 rb_setjmp(save_regs_gc_mark
);
1687 mark_locations_array(objspace
,
1688 (VALUE
*)save_regs_gc_mark
,
1689 sizeof(save_regs_gc_mark
) / sizeof(VALUE
));
1691 rb_gc_mark_locations(stack_start
, stack_end
);
1693 rb_gc_mark_locations(th
->machine_register_stack_start
, th
->machine_register_stack_end
);
1695 #if defined(__human68k__) || defined(__mc68000__)
1696 mark_locations_array((VALUE
*)((char*)STACK_END
+ 2),
1697 (STACK_START
- STACK_END
));
1701 void rb_gc_mark_encodings(void);
1704 garbage_collect(rb_objspace_t
*objspace
)
1706 struct gc_list
*list
;
1707 rb_thread_t
*th
= GET_THREAD();
1709 if (GC_NOTIFY
) printf("start garbage_collect()\n");
1715 if (dont_gc
|| during_gc
) {
1717 if (!heaps_increment(objspace
)) {
1718 set_heaps_increment(objspace
);
1719 heaps_increment(objspace
);
1729 init_mark_stack(objspace
);
1731 th
->vm
->self
? rb_gc_mark(th
->vm
->self
) : rb_vm_mark(th
->vm
);
1733 if (finalizer_table
) {
1734 mark_tbl(objspace
, finalizer_table
, 0);
1737 mark_current_machine_context(objspace
, th
);
1739 rb_gc_mark_threads();
1740 rb_gc_mark_symbols();
1741 rb_gc_mark_encodings();
1743 /* mark protected global variables */
1744 for (list
= global_List
; list
; list
= list
->next
) {
1745 rb_gc_mark_maybe(*list
->varptr
);
1748 rb_gc_mark_global_tbl();
1750 mark_tbl(objspace
, rb_class_tbl
, 0);
1751 rb_gc_mark_trap_list();
1753 /* mark generic instance variables for special constants */
1754 rb_mark_generic_ivar_tbl();
1756 rb_gc_mark_parser();
1758 /* gc_mark objects whose marking are not completed*/
1759 while (!MARK_STACK_EMPTY
) {
1760 if (mark_stack_overflow
) {
1761 gc_mark_all(objspace
);
1764 gc_mark_rest(objspace
);
1770 if (GC_NOTIFY
) printf("end garbage_collect()\n");
1775 rb_garbage_collect(void)
1777 return garbage_collect(&rb_objspace
);
1781 rb_gc_mark_machine_stack(rb_thread_t
*th
)
1783 rb_objspace_t
*objspace
= &rb_objspace
;
1784 #if STACK_GROW_DIRECTION < 0
1785 rb_gc_mark_locations(th
->machine_stack_end
, th
->machine_stack_start
);
1786 #elif STACK_GROW_DIRECTION > 0
1787 rb_gc_mark_locations(th
->machine_stack_start
, th
->machine_stack_end
);
1789 if (th
->machine_stack_start
< th
->machine_stack_end
) {
1790 rb_gc_mark_locations(th
->machine_stack_start
, th
->machine_stack_end
);
1793 rb_gc_mark_locations(th
->machine_stack_end
, th
->machine_stack_start
);
1797 rb_gc_mark_locations(th
->machine_register_stack_start
, th
->machine_register_stack_end
);
1805 * gc.garbage_collect => nil
1806 * ObjectSpace.garbage_collect => nil
1808 * Initiates garbage collection, unless manually disabled.
1822 Init_stack(VALUE
*addr
)
1824 ruby_init_stack(addr
);
1828 * Document-class: ObjectSpace
1830 * The <code>ObjectSpace</code> module contains a number of routines
1831 * that interact with the garbage collection facility and allow you to
1832 * traverse all living objects with an iterator.
1834 * <code>ObjectSpace</code> also provides support for object
1835 * finalizers, procs that will be called when a specific object is
1836 * about to be destroyed by garbage collection.
1838 * include ObjectSpace
1846 * define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
1847 * define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
1848 * define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
1850 * <em>produces:</em>
1852 * Finalizer three on 537763470
1853 * Finalizer one on 537763480
1854 * Finalizer two on 537763480
1861 init_heap(&rb_objspace
);
1865 os_obj_of(rb_objspace_t
*objspace
, VALUE of
)
1869 RVALUE
*membase
= 0;
1874 while (i
< heaps_used
) {
1875 while (0 < i
&& (uintptr_t)membase
< (uintptr_t)heaps
[i
-1].membase
)
1877 while (i
< heaps_used
&& (uintptr_t)heaps
[i
].membase
<= (uintptr_t)membase
)
1879 if (heaps_used
<= i
)
1881 membase
= heaps
[i
].membase
;
1883 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
1884 for (;p
< pend
; p
++) {
1885 if (p
->as
.basic
.flags
) {
1886 switch (BUILTIN_TYPE(p
)) {
1893 if (FL_TEST(p
, FL_SINGLETON
)) continue;
1895 if (!p
->as
.basic
.klass
) continue;
1897 if (!of
|| rb_obj_is_kind_of(v
, of
)) {
1906 return SIZET2NUM(n
);
1911 * ObjectSpace.each_object([module]) {|obj| ... } => fixnum
1913 * Calls the block once for each living, nonimmediate object in this
1914 * Ruby process. If <i>module</i> is specified, calls the block
1915 * for only those classes or modules that match (or are a subclass of)
1916 * <i>module</i>. Returns the number of objects found. Immediate
1917 * objects (<code>Fixnum</code>s, <code>Symbol</code>s
1918 * <code>true</code>, <code>false</code>, and <code>nil</code>) are
1919 * never returned. In the example below, <code>each_object</code>
1920 * returns both the numbers we defined and several constants defined in
1921 * the <code>Math</code> module.
1924 * b = 95 # Won't be returned
1925 * c = 12345678987654321
1926 * count = ObjectSpace.each_object(Numeric) {|x| p x }
1927 * puts "Total count: #{count}"
1929 * <em>produces:</em>
1935 * 2.22044604925031e-16
1936 * 1.7976931348623157e+308
1937 * 2.2250738585072e-308
1943 os_each_obj(int argc
, VALUE
*argv
, VALUE os
)
1952 rb_scan_args(argc
, argv
, "01", &of
);
1954 RETURN_ENUMERATOR(os
, 1, &of
);
1955 return os_obj_of(&rb_objspace
, of
);
1960 * ObjectSpace.undefine_finalizer(obj)
1962 * Removes all finalizers for <i>obj</i>.
1967 undefine_final(VALUE os
, VALUE obj
)
1969 rb_objspace_t
*objspace
= &rb_objspace
;
1970 if (finalizer_table
) {
1971 st_delete(finalizer_table
, (st_data_t
*)&obj
, 0);
1978 * ObjectSpace.define_finalizer(obj, aProc=proc())
1980 * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
1986 define_final(int argc
, VALUE
*argv
, VALUE os
)
1988 rb_objspace_t
*objspace
= &rb_objspace
;
1989 VALUE obj
, block
, table
;
1991 rb_scan_args(argc
, argv
, "11", &obj
, &block
);
1993 block
= rb_block_proc();
1995 else if (!rb_respond_to(block
, rb_intern("call"))) {
1996 rb_raise(rb_eArgError
, "wrong type argument %s (should be callable)",
1997 rb_obj_classname(block
));
1999 FL_SET(obj
, FL_FINALIZE
);
2001 block
= rb_ary_new3(2, INT2FIX(rb_safe_level()), block
);
2003 if (!finalizer_table
) {
2004 finalizer_table
= st_init_numtable();
2006 if (st_lookup(finalizer_table
, obj
, &table
)) {
2007 rb_ary_push(table
, block
);
2010 st_add_direct(finalizer_table
, obj
, rb_ary_new3(1, block
));
2016 rb_gc_copy_finalizer(VALUE dest
, VALUE obj
)
2018 rb_objspace_t
*objspace
= &rb_objspace
;
2021 if (!finalizer_table
) return;
2022 if (!FL_TEST(obj
, FL_FINALIZE
)) return;
2023 if (st_lookup(finalizer_table
, obj
, &table
)) {
2024 st_insert(finalizer_table
, dest
, table
);
2026 FL_SET(dest
, FL_FINALIZE
);
2030 run_single_final(VALUE arg
)
2032 VALUE
*args
= (VALUE
*)arg
;
2033 rb_eval_cmd(args
[0], args
[1], (int)args
[2]);
2038 run_final(rb_objspace_t
*objspace
, VALUE obj
)
2042 VALUE args
[3], table
, objid
;
2044 objid
= rb_obj_id(obj
); /* make obj into id */
2046 if (RDATA(obj
)->dfree
) {
2047 (*RDATA(obj
)->dfree
)(DATA_PTR(obj
));
2050 if (finalizer_table
&&
2051 st_delete(finalizer_table
, (st_data_t
*)&obj
, &table
)) {
2053 args
[2] = (VALUE
)rb_safe_level();
2054 if (!args
[1] && RARRAY_LEN(table
) > 0) {
2055 args
[1] = rb_obj_freeze(rb_ary_new3(1, objid
));
2057 for (i
=0; i
<RARRAY_LEN(table
); i
++) {
2058 VALUE final
= RARRAY_PTR(table
)[i
];
2059 args
[0] = RARRAY_PTR(final
)[1];
2060 args
[2] = FIX2INT(RARRAY_PTR(final
)[0]);
2061 rb_protect(run_single_final
, (VALUE
)args
, &status
);
2067 gc_finalize_deferred(rb_objspace_t
*objspace
)
2069 RVALUE
*p
= deferred_final_list
;
2070 deferred_final_list
= 0;
2073 finalize_list(objspace
, p
);
2075 free_unused_heaps(objspace
);
2079 rb_gc_finalize_deferred(void)
2081 gc_finalize_deferred(&rb_objspace
);
2085 chain_finalized_object(st_data_t key
, st_data_t val
, st_data_t arg
)
2087 RVALUE
*p
= (RVALUE
*)key
, **final_list
= (RVALUE
**)arg
;
2088 if (p
->as
.basic
.flags
& FL_FINALIZE
) {
2089 if (BUILTIN_TYPE(p
) != T_DEFERRED
) {
2090 p
->as
.free
.flags
= FL_MARK
| T_DEFERRED
; /* remain marked */
2091 RDATA(p
)->dfree
= 0;
2093 p
->as
.free
.next
= *final_list
;
2100 rb_gc_call_finalizer_at_exit(void)
2102 rb_objspace_t
*objspace
= &rb_objspace
;
2106 /* run finalizers */
2107 if (need_call_final
) {
2109 p
= deferred_final_list
;
2110 deferred_final_list
= 0;
2111 finalize_list(objspace
, p
);
2112 st_foreach(finalizer_table
, chain_finalized_object
,
2113 (st_data_t
)&deferred_final_list
);
2114 } while (deferred_final_list
);
2116 /* finalizers are part of garbage collection */
2118 /* run data object's finalizers */
2119 for (i
= 0; i
< heaps_used
; i
++) {
2120 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
2122 if (BUILTIN_TYPE(p
) == T_DATA
&&
2123 DATA_PTR(p
) && RANY(p
)->as
.data
.dfree
&&
2124 RANY(p
)->as
.basic
.klass
!= rb_cThread
) {
2125 p
->as
.free
.flags
= 0;
2126 if ((long)RANY(p
)->as
.data
.dfree
== -1) {
2129 else if (RANY(p
)->as
.data
.dfree
) {
2130 (*RANY(p
)->as
.data
.dfree
)(DATA_PTR(p
));
2132 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
2134 else if (BUILTIN_TYPE(p
) == T_FILE
) {
2135 if (rb_io_fptr_finalize(RANY(p
)->as
.file
.fptr
)) {
2136 p
->as
.free
.flags
= 0;
2137 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
2149 rb_objspace_t
*objspace
= &rb_objspace
;
2150 garbage_collect(objspace
);
2151 gc_finalize_deferred(objspace
);
2156 * ObjectSpace._id2ref(object_id) -> an_object
2158 * Converts an object id to a reference to the object. May not be
2159 * called on an object id passed as a parameter to a finalizer.
2161 * s = "I am a string" #=> "I am a string"
2162 * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
2168 id2ref(VALUE obj
, VALUE objid
)
2170 #if SIZEOF_LONG == SIZEOF_VOIDP
2171 #define NUM2PTR(x) NUM2ULONG(x)
2172 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
2173 #define NUM2PTR(x) NUM2ULL(x)
2175 rb_objspace_t
*objspace
= &rb_objspace
;
2180 ptr
= NUM2PTR(objid
);
2183 if (ptr
== Qtrue
) return Qtrue
;
2184 if (ptr
== Qfalse
) return Qfalse
;
2185 if (ptr
== Qnil
) return Qnil
;
2186 if (FIXNUM_P(ptr
)) return (VALUE
)ptr
;
2187 ptr
= objid
^ FIXNUM_FLAG
; /* unset FIXNUM_FLAG */
2189 if ((ptr
% sizeof(RVALUE
)) == (4 << 2)) {
2190 ID symid
= ptr
/ sizeof(RVALUE
);
2191 if (rb_id2name(symid
) == 0)
2192 rb_raise(rb_eRangeError
, "%p is not symbol id value", p0
);
2193 return ID2SYM(symid
);
2196 if (!is_pointer_to_heap(objspace
, (void *)ptr
) ||
2197 BUILTIN_TYPE(ptr
) > T_FIXNUM
|| BUILTIN_TYPE(ptr
) == T_ICLASS
) {
2198 rb_raise(rb_eRangeError
, "%p is not id value", p0
);
2200 if (BUILTIN_TYPE(ptr
) == 0 || RBASIC(ptr
)->klass
== 0) {
2201 rb_raise(rb_eRangeError
, "%p is recycled object", p0
);
2207 * Document-method: __id__
2208 * Document-method: object_id
2211 * obj.__id__ => fixnum
2212 * obj.object_id => fixnum
2214 * Returns an integer identifier for <i>obj</i>. The same number will
2215 * be returned on all calls to <code>id</code> for a given object, and
2216 * no two active objects will share an id.
2217 * <code>Object#object_id</code> is a different concept from the
2218 * <code>:name</code> notation, which returns the symbol id of
2219 * <code>name</code>. Replaces the deprecated <code>Object#id</code>.
2224 * obj.hash => fixnum
2226 * Generates a <code>Fixnum</code> hash value for this object. This
2227 * function must have the property that <code>a.eql?(b)</code> implies
2228 * <code>a.hash == b.hash</code>. The hash value is used by class
2229 * <code>Hash</code>. Any hash value that exceeds the capacity of a
2230 * <code>Fixnum</code> will be truncated before being used.
2234 rb_obj_id(VALUE obj
)
2237 * 32-bit VALUE space
2238 * MSB ------------------------ LSB
2239 * false 00000000000000000000000000000000
2240 * true 00000000000000000000000000000010
2241 * nil 00000000000000000000000000000100
2242 * undef 00000000000000000000000000000110
2243 * symbol ssssssssssssssssssssssss00001110
2244 * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
2245 * fixnum fffffffffffffffffffffffffffffff1
2249 * false 00000000000000000000000000000000
2250 * true 00000000000000000000000000000010
2251 * nil 00000000000000000000000000000100
2252 * undef 00000000000000000000000000000110
2253 * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
2254 * object oooooooooooooooooooooooooooooo0 o...o % A = 0
2255 * fixnum fffffffffffffffffffffffffffffff1 bignum if required
2257 * where A = sizeof(RVALUE)/4
2260 * 20 if 32-bit, double is 4-byte aligned
2261 * 24 if 32-bit, double is 8-byte aligned
2264 if (TYPE(obj
) == T_SYMBOL
) {
2265 return (SYM2ID(obj
) * sizeof(RVALUE
) + (4 << 2)) | FIXNUM_FLAG
;
2267 if (SPECIAL_CONST_P(obj
)) {
2268 return LONG2NUM((SIGNED_VALUE
)obj
);
2270 return (VALUE
)((SIGNED_VALUE
)obj
|FIXNUM_FLAG
);
2274 set_zero(st_data_t key
, st_data_t val
, st_data_t arg
)
2276 VALUE k
= (VALUE
)key
;
2277 VALUE hash
= (VALUE
)arg
;
2278 rb_hash_aset(hash
, k
, INT2FIX(0));
2284 * ObjectSpace.count_objects([result_hash]) -> hash
2286 * Counts objects for each type.
2288 * It returns a hash as:
2289 * {:TOTAL=>10000, :FREE=>3011, :T_OBJECT=>6, :T_CLASS=>404, ...}
2291 * If the optional argument, result_hash, is given,
2292 * it is overwritten and returned.
2293 * This is intended to avoid probe effect.
2295 * The contents of the returned hash is implementation defined.
2296 * It may be changed in future.
2298 * This method is not expected to work except C Ruby.
2303 count_objects(int argc
, VALUE
*argv
, VALUE os
)
2305 rb_objspace_t
*objspace
= &rb_objspace
;
2306 size_t counts
[T_MASK
+1];
2312 if (rb_scan_args(argc
, argv
, "01", &hash
) == 1) {
2313 if (TYPE(hash
) != T_HASH
)
2314 rb_raise(rb_eTypeError
, "non-hash given");
2317 for (i
= 0; i
<= T_MASK
; i
++) {
2321 for (i
= 0; i
< heaps_used
; i
++) {
2324 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
2325 for (;p
< pend
; p
++) {
2326 if (p
->as
.basic
.flags
) {
2327 counts
[BUILTIN_TYPE(p
)]++;
2333 total
+= heaps
[i
].limit
;
2337 hash
= rb_hash_new();
2339 else if (!RHASH_EMPTY_P(hash
)) {
2340 st_foreach(RHASH_TBL(hash
), set_zero
, hash
);
2342 rb_hash_aset(hash
, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total
));
2343 rb_hash_aset(hash
, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed
));
2344 for (i
= 0; i
<= T_MASK
; i
++) {
2347 #define COUNT_TYPE(t) case t: type = ID2SYM(rb_intern(#t)); break;
2349 COUNT_TYPE(T_OBJECT
);
2350 COUNT_TYPE(T_CLASS
);
2351 COUNT_TYPE(T_MODULE
);
2352 COUNT_TYPE(T_FLOAT
);
2353 COUNT_TYPE(T_STRING
);
2354 COUNT_TYPE(T_REGEXP
);
2355 COUNT_TYPE(T_ARRAY
);
2357 COUNT_TYPE(T_STRUCT
);
2358 COUNT_TYPE(T_BIGNUM
);
2361 COUNT_TYPE(T_MATCH
);
2362 COUNT_TYPE(T_COMPLEX
);
2363 COUNT_TYPE(T_RATIONAL
);
2366 COUNT_TYPE(T_FALSE
);
2367 COUNT_TYPE(T_SYMBOL
);
2368 COUNT_TYPE(T_FIXNUM
);
2369 COUNT_TYPE(T_UNDEF
);
2371 COUNT_TYPE(T_ICLASS
);
2372 COUNT_TYPE(T_DEFERRED
);
2374 default: type
= INT2NUM(i
); break;
2377 rb_hash_aset(hash
, type
, SIZET2NUM(counts
[i
]));
2385 * GC.count -> Integer
2387 * The number of times GC occured.
2389 * It returns the number of times GC occured since the process started.
2394 gc_count(VALUE self
)
2396 return UINT2NUM((&rb_objspace
)->count
);
2399 #if CALC_EXACT_MALLOC_SIZE
2402 * GC.malloc_allocated_size -> Integer
2404 * The allocated size by malloc().
2406 * It returns the allocated size by malloc().
2410 gc_malloc_allocated_size(VALUE self
)
2412 return UINT2NUM((&rb_objspace
)->malloc_params
.allocated_size
);
2417 * GC.malloc_allocations -> Integer
2419 * The number of allocated memory object by malloc().
2421 * It returns the number of allocated memory object by malloc().
2425 gc_malloc_allocations(VALUE self
)
2427 return UINT2NUM((&rb_objspace
)->malloc_params
.allocations
);
2432 * The <code>GC</code> module provides an interface to Ruby's mark and
2433 * sweep garbage collection mechanism. Some of the underlying methods
2434 * are also available via the <code>ObjectSpace</code> module.
2442 rb_mGC
= rb_define_module("GC");
2443 rb_define_singleton_method(rb_mGC
, "start", rb_gc_start
, 0);
2444 rb_define_singleton_method(rb_mGC
, "enable", rb_gc_enable
, 0);
2445 rb_define_singleton_method(rb_mGC
, "disable", rb_gc_disable
, 0);
2446 rb_define_singleton_method(rb_mGC
, "stress", gc_stress_get
, 0);
2447 rb_define_singleton_method(rb_mGC
, "stress=", gc_stress_set
, 1);
2448 rb_define_singleton_method(rb_mGC
, "count", gc_count
, 0);
2449 rb_define_method(rb_mGC
, "garbage_collect", rb_gc_start
, 0);
2451 rb_mObSpace
= rb_define_module("ObjectSpace");
2452 rb_define_module_function(rb_mObSpace
, "each_object", os_each_obj
, -1);
2453 rb_define_module_function(rb_mObSpace
, "garbage_collect", rb_gc_start
, 0);
2455 rb_define_module_function(rb_mObSpace
, "define_finalizer", define_final
, -1);
2456 rb_define_module_function(rb_mObSpace
, "undefine_finalizer", undefine_final
, 1);
2458 rb_define_module_function(rb_mObSpace
, "_id2ref", id2ref
, 1);
2460 nomem_error
= rb_exc_new3(rb_eNoMemError
,
2461 rb_obj_freeze(rb_str_new2("failed to allocate memory")));
2462 OBJ_TAINT(nomem_error
);
2463 OBJ_FREEZE(nomem_error
);
2465 rb_define_method(rb_mKernel
, "hash", rb_obj_id
, 0);
2466 rb_define_method(rb_mKernel
, "__id__", rb_obj_id
, 0);
2467 rb_define_method(rb_mKernel
, "object_id", rb_obj_id
, 0);
2469 rb_define_module_function(rb_mObSpace
, "count_objects", count_objects
, -1);
2471 #if CALC_EXACT_MALLOC_SIZE
2472 rb_define_singleton_method(rb_mGC
, "malloc_allocated_size", gc_malloc_allocated_size
, 0);
2473 rb_define_singleton_method(rb_mGC
, "malloc_allocations", gc_malloc_allocations
, 0);