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
)) {
586 register RVALUE
*mid_membase
;
588 mid_membase
= heaps
[mid
].membase
;
589 if (mid_membase
< membase
) {
592 else if (mid_membase
> membase
) {
596 rb_bug("same heap slot is allocated: %p at %"PRIuVALUE
, membase
, (VALUE
)mid
);
599 if (hi
< heaps_used
) {
600 MEMMOVE(&heaps
[hi
+1], &heaps
[hi
], struct heaps_slot
, heaps_used
- hi
);
602 heaps
[hi
].membase
= membase
;
604 heaps
[hi
].limit
= objs
;
606 if (lomem
== 0 || lomem
> p
) lomem
= p
;
607 if (himem
< pend
) himem
= pend
;
611 p
->as
.free
.flags
= 0;
612 p
->as
.free
.next
= freelist
;
619 init_heap(rb_objspace_t
*objspace
)
623 add
= HEAP_MIN_SLOTS
/ HEAP_OBJ_LIMIT
;
625 if ((heaps_used
+ add
) > heaps_length
) {
626 allocate_heaps(objspace
, heaps_used
+ add
);
629 for (i
= 0; i
< add
; i
++) {
630 assign_heap_slot(objspace
);
637 set_heaps_increment(rb_objspace_t
*objspace
)
639 size_t next_heaps_length
= heaps_used
* 1.8;
640 heaps_inc
= next_heaps_length
- heaps_used
;
642 if (next_heaps_length
> heaps_length
) {
643 allocate_heaps(objspace
, next_heaps_length
);
648 heaps_increment(rb_objspace_t
*objspace
)
651 assign_heap_slot(objspace
);
658 #define RANY(o) ((RVALUE*)(o))
661 rb_newobj_from_heap(rb_objspace_t
*objspace
)
665 if ((ruby_gc_stress
&& !ruby_disable_gc_stress
) || !freelist
) {
666 if (!heaps_increment(objspace
) && !garbage_collect(objspace
)) {
671 obj
= (VALUE
)freelist
;
672 freelist
= freelist
->as
.free
.next
;
674 MEMZERO((void*)obj
, RVALUE
, 1);
676 RANY(obj
)->file
= rb_sourcefile();
677 RANY(obj
)->line
= rb_sourceline();
685 rb_fill_value_cache(rb_thread_t
*th
)
687 rb_objspace_t
*objspace
= &rb_objspace
;
692 for (i
=0; i
<RUBY_VM_VALUE_CACHE_SIZE
; i
++) {
693 VALUE v
= rb_newobj_from_heap(objspace
);
695 th
->value_cache
[i
] = v
;
696 RBASIC(v
)->flags
= FL_MARK
;
698 th
->value_cache_ptr
= &th
->value_cache
[0];
699 rv
= rb_newobj_from_heap(objspace
);
708 rb_objspace_t
*objspace
= &rb_objspace
;
715 #if USE_VALUE_CACHE || (defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE)
716 rb_thread_t
*th
= GET_THREAD();
719 VALUE v
= *th
->value_cache_ptr
;
721 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
722 rb_objspace_t
*objspace
= th
->vm
->objspace
;
724 rb_objspace_t
*objspace
= &rb_objspace
;
730 rb_bug("object allocation during garbage collection phase");
735 RBASIC(v
)->flags
= 0;
736 th
->value_cache_ptr
++;
739 v
= rb_fill_value_cache(th
);
742 #if defined(GC_DEBUG)
743 printf("cache index: %d, v: %p, th: %p\n",
744 th
->value_cache_ptr
- th
->value_cache
, v
, th
);
748 return rb_newobj_from_heap(objspace
);
753 rb_node_newnode(enum node_type type
, VALUE a0
, VALUE a1
, VALUE a2
)
755 NODE
*n
= (NODE
*)rb_newobj();
758 nd_set_type(n
, type
);
768 rb_data_object_alloc(VALUE klass
, void *datap
, RUBY_DATA_FUNC dmark
, RUBY_DATA_FUNC dfree
)
770 NEWOBJ(data
, struct RData
);
771 if (klass
) Check_Type(klass
, T_CLASS
);
772 OBJSETUP(data
, klass
, T_DATA
);
781 #define SET_STACK_END (SET_MACHINE_STACK_END(&th->machine_stack_end), th->machine_register_stack_end = rb_ia64_bsp())
783 #define SET_STACK_END SET_MACHINE_STACK_END(&th->machine_stack_end)
786 #define STACK_START (th->machine_stack_start)
787 #define STACK_END (th->machine_stack_end)
788 #define STACK_LEVEL_MAX (th->machine_stack_maxsize/sizeof(VALUE))
790 #if STACK_GROW_DIRECTION < 0
791 # define STACK_LENGTH (STACK_START - STACK_END)
792 #elif STACK_GROW_DIRECTION > 0
793 # define STACK_LENGTH (STACK_END - STACK_START + 1)
795 # define STACK_LENGTH ((STACK_END < STACK_START) ? STACK_START - STACK_END\
796 : STACK_END - STACK_START + 1)
798 #if !STACK_GROW_DIRECTION
799 int ruby_stack_grow_direction
;
801 ruby_get_stack_grow_direction(VALUE
*addr
)
803 rb_thread_t
*th
= GET_THREAD();
806 if (STACK_END
> addr
) return ruby_stack_grow_direction
= 1;
807 return ruby_stack_grow_direction
= -1;
811 #define GC_WATER_MARK 512
814 ruby_stack_length(VALUE
**p
)
816 rb_thread_t
*th
= GET_THREAD();
818 if (p
) *p
= STACK_UPPER(STACK_END
, STACK_START
, STACK_END
);
823 ruby_stack_check(void)
826 rb_thread_t
*th
= GET_THREAD();
828 ret
= STACK_LENGTH
> STACK_LEVEL_MAX
- GC_WATER_MARK
;
831 ret
= (VALUE
*)rb_ia64_bsp() - th
->machine_register_stack_start
>
832 th
->machine_register_stack_maxsize
/sizeof(VALUE
) - GC_WATER_MARK
;
839 init_mark_stack(rb_objspace_t
*objspace
)
841 mark_stack_overflow
= 0;
842 mark_stack_ptr
= mark_stack
;
845 #define MARK_STACK_EMPTY (mark_stack_ptr == mark_stack)
847 static void gc_mark(rb_objspace_t
*objspace
, VALUE ptr
, int lev
);
848 static void gc_mark_children(rb_objspace_t
*objspace
, VALUE ptr
, int lev
);
851 gc_mark_all(rb_objspace_t
*objspace
)
856 init_mark_stack(objspace
);
857 for (i
= 0; i
< heaps_used
; i
++) {
858 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
860 if ((p
->as
.basic
.flags
& FL_MARK
) &&
861 (p
->as
.basic
.flags
!= FL_MARK
)) {
862 gc_mark_children(objspace
, (VALUE
)p
, 0);
870 gc_mark_rest(rb_objspace_t
*objspace
)
872 VALUE tmp_arry
[MARK_STACK_MAX
];
875 p
= (mark_stack_ptr
- mark_stack
) + tmp_arry
;
876 MEMCPY(tmp_arry
, mark_stack
, VALUE
, p
- tmp_arry
);
878 init_mark_stack(objspace
);
879 while (p
!= tmp_arry
) {
881 gc_mark_children(objspace
, *p
, 0);
886 is_pointer_to_heap(rb_objspace_t
*objspace
, void *ptr
)
888 register RVALUE
*p
= RANY(ptr
);
889 register struct heaps_slot
*heap
;
890 register size_t hi
, lo
, mid
;
892 if (p
< lomem
|| p
> himem
) return Qfalse
;
893 if ((VALUE
)p
% sizeof(RVALUE
) != 0) return Qfalse
;
895 /* check if p looks like a pointer using bsearch*/
901 if (heap
->slot
<= p
) {
902 if (p
< heap
->slot
+ heap
->limit
)
914 mark_locations_array(rb_objspace_t
*objspace
, register VALUE
*x
, register long n
)
919 VALGRIND_MAKE_MEM_DEFINED(&v
, sizeof(v
));
920 if (is_pointer_to_heap(objspace
, (void *)v
)) {
921 gc_mark(objspace
, v
, 0);
928 gc_mark_locations(rb_objspace_t
*objspace
, VALUE
*start
, VALUE
*end
)
932 if (end
<= start
) return;
934 mark_locations_array(objspace
, start
, n
);
938 rb_gc_mark_locations(VALUE
*start
, VALUE
*end
)
940 gc_mark_locations(&rb_objspace
, start
, end
);
943 #define rb_gc_mark_locations(start, end) gc_mark_locations(objspace, start, end)
945 struct mark_tbl_arg
{
946 rb_objspace_t
*objspace
;
951 mark_entry(ID key
, VALUE value
, st_data_t data
)
953 struct mark_tbl_arg
*arg
= (void*)data
;
954 gc_mark(arg
->objspace
, value
, arg
->lev
);
959 mark_tbl(rb_objspace_t
*objspace
, st_table
*tbl
, int lev
)
961 struct mark_tbl_arg arg
;
963 arg
.objspace
= objspace
;
965 st_foreach(tbl
, mark_entry
, (st_data_t
)&arg
);
969 rb_mark_tbl(st_table
*tbl
)
971 mark_tbl(&rb_objspace
, tbl
, 0);
975 mark_key(VALUE key
, VALUE value
, st_data_t data
)
977 struct mark_tbl_arg
*arg
= (void*)data
;
978 gc_mark(arg
->objspace
, key
, arg
->lev
);
983 mark_set(rb_objspace_t
*objspace
, st_table
*tbl
, int lev
)
985 struct mark_tbl_arg arg
;
987 arg
.objspace
= objspace
;
989 st_foreach(tbl
, mark_key
, (st_data_t
)&arg
);
993 rb_mark_set(st_table
*tbl
)
995 mark_set(&rb_objspace
, tbl
, 0);
999 mark_keyvalue(VALUE key
, VALUE value
, st_data_t data
)
1001 struct mark_tbl_arg
*arg
= (void*)data
;
1002 gc_mark(arg
->objspace
, key
, arg
->lev
);
1003 gc_mark(arg
->objspace
, value
, arg
->lev
);
1008 mark_hash(rb_objspace_t
*objspace
, st_table
*tbl
, int lev
)
1010 struct mark_tbl_arg arg
;
1012 arg
.objspace
= objspace
;
1014 st_foreach(tbl
, mark_keyvalue
, (st_data_t
)&arg
);
1018 rb_mark_hash(st_table
*tbl
)
1020 mark_hash(&rb_objspace
, tbl
, 0);
1024 rb_gc_mark_maybe(VALUE obj
)
1026 if (is_pointer_to_heap(&rb_objspace
, (void *)obj
)) {
1027 gc_mark(&rb_objspace
, obj
, 0);
1031 #define GC_LEVEL_MAX 250
1034 gc_mark(rb_objspace_t
*objspace
, VALUE ptr
, int lev
)
1036 register RVALUE
*obj
;
1039 if (rb_special_const_p(ptr
)) return; /* special const not marked */
1040 if (obj
->as
.basic
.flags
== 0) return; /* free cell */
1041 if (obj
->as
.basic
.flags
& FL_MARK
) return; /* already marked */
1042 obj
->as
.basic
.flags
|= FL_MARK
;
1044 if (lev
> GC_LEVEL_MAX
|| (lev
== 0 && ruby_stack_check())) {
1045 if (!mark_stack_overflow
) {
1046 if (mark_stack_ptr
- mark_stack
< MARK_STACK_MAX
) {
1047 *mark_stack_ptr
= ptr
;
1051 mark_stack_overflow
= 1;
1056 gc_mark_children(objspace
, ptr
, lev
+1);
1060 rb_gc_mark(VALUE ptr
)
1062 gc_mark(&rb_objspace
, ptr
, 0);
1066 gc_mark_children(rb_objspace_t
*objspace
, VALUE ptr
, int lev
)
1068 register RVALUE
*obj
= RANY(ptr
);
1070 goto marking
; /* skip */
1074 if (rb_special_const_p(ptr
)) return; /* special const not marked */
1075 if (obj
->as
.basic
.flags
== 0) return; /* free cell */
1076 if (obj
->as
.basic
.flags
& FL_MARK
) return; /* already marked */
1077 obj
->as
.basic
.flags
|= FL_MARK
;
1080 if (FL_TEST(obj
, FL_EXIVAR
)) {
1081 rb_mark_generic_ivar(ptr
);
1084 switch (obj
->as
.basic
.flags
& T_MASK
) {
1087 rb_bug("rb_gc_mark() called for broken object");
1091 switch (nd_type(obj
)) {
1092 case NODE_IF
: /* 1,2,3 */
1100 case NODE_BLOCK_PASS
:
1101 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u2
.node
, lev
);
1103 case NODE_BLOCK
: /* 1,3 */
1109 case NODE_DREGX_ONCE
:
1115 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u1
.node
, lev
);
1117 case NODE_SUPER
: /* 3 */
1121 ptr
= (VALUE
)obj
->as
.node
.u3
.node
;
1124 case NODE_METHOD
: /* 1,2 */
1137 case NODE_OP_ASGN_OR
:
1138 case NODE_OP_ASGN_AND
:
1143 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u1
.node
, lev
);
1145 case NODE_FBODY
: /* 2 */
1149 case NODE_DASGN_CURR
:
1158 ptr
= (VALUE
)obj
->as
.node
.u2
.node
;
1161 case NODE_HASH
: /* 1 */
1174 ptr
= (VALUE
)obj
->as
.node
.u1
.node
;
1177 case NODE_SCOPE
: /* 2,3 */
1180 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u3
.node
, lev
);
1181 ptr
= (VALUE
)obj
->as
.node
.u2
.node
;
1184 case NODE_ZARRAY
: /* - */
1203 case NODE_BLOCK_ARG
:
1206 mark_locations_array(objspace
,
1207 (VALUE
*)obj
->as
.node
.u1
.value
,
1208 obj
->as
.node
.u3
.cnt
);
1209 ptr
= (VALUE
)obj
->as
.node
.u2
.node
;
1212 default: /* unlisted NODE */
1213 if (is_pointer_to_heap(objspace
, obj
->as
.node
.u1
.node
)) {
1214 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u1
.node
, lev
);
1216 if (is_pointer_to_heap(objspace
, obj
->as
.node
.u2
.node
)) {
1217 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u2
.node
, lev
);
1219 if (is_pointer_to_heap(objspace
, obj
->as
.node
.u3
.node
)) {
1220 gc_mark(objspace
, (VALUE
)obj
->as
.node
.u3
.node
, lev
);
1223 return; /* no need to mark class. */
1226 gc_mark(objspace
, obj
->as
.basic
.klass
, lev
);
1227 switch (obj
->as
.basic
.flags
& T_MASK
) {
1231 mark_tbl(objspace
, RCLASS_M_TBL(obj
), lev
);
1232 mark_tbl(objspace
, RCLASS_IV_TBL(obj
), lev
);
1233 ptr
= RCLASS_SUPER(obj
);
1237 if (FL_TEST(obj
, ELTS_SHARED
)) {
1238 ptr
= obj
->as
.array
.aux
.shared
;
1242 long i
, len
= RARRAY_LEN(obj
);
1243 VALUE
*ptr
= RARRAY_PTR(obj
);
1244 for (i
=0; i
< len
; i
++) {
1245 gc_mark(objspace
, *ptr
++, lev
);
1251 mark_hash(objspace
, obj
->as
.hash
.ntbl
, lev
);
1252 ptr
= obj
->as
.hash
.ifnone
;
1256 #define STR_ASSOC FL_USER3 /* copied from string.c */
1257 if (FL_TEST(obj
, RSTRING_NOEMBED
) && FL_ANY(obj
, ELTS_SHARED
|STR_ASSOC
)) {
1258 ptr
= obj
->as
.string
.as
.heap
.aux
.shared
;
1264 if (obj
->as
.data
.dmark
) (*obj
->as
.data
.dmark
)(DATA_PTR(obj
));
1269 long i
, len
= ROBJECT_NUMIV(obj
);
1270 VALUE
*ptr
= ROBJECT_IVPTR(obj
);
1271 for (i
= 0; i
< len
; i
++) {
1272 gc_mark(objspace
, *ptr
++, lev
);
1278 if (obj
->as
.file
.fptr
)
1279 gc_mark(objspace
, obj
->as
.file
.fptr
->tied_io_for_writing
, lev
);
1283 gc_mark(objspace
, obj
->as
.regexp
.src
, lev
);
1291 gc_mark(objspace
, obj
->as
.match
.regexp
, lev
);
1292 if (obj
->as
.match
.str
) {
1293 ptr
= obj
->as
.match
.str
;
1299 gc_mark(objspace
, obj
->as
.rational
.num
, lev
);
1300 gc_mark(objspace
, obj
->as
.rational
.den
, lev
);
1304 gc_mark(objspace
, obj
->as
.complex.real
, lev
);
1305 gc_mark(objspace
, obj
->as
.complex.image
, lev
);
1310 long len
= RSTRUCT_LEN(obj
);
1311 VALUE
*ptr
= RSTRUCT_PTR(obj
);
1314 gc_mark(objspace
, *ptr
++, lev
);
1320 rb_bug("rb_gc_mark(): unknown data type 0x%lx(%p) %s",
1321 obj
->as
.basic
.flags
& T_MASK
, obj
,
1322 is_pointer_to_heap(objspace
, obj
) ? "corrupted object" : "non object");
1326 static void obj_free(rb_objspace_t
*, VALUE
);
1329 finalize_list(rb_objspace_t
*objspace
, RVALUE
*p
)
1332 RVALUE
*tmp
= p
->as
.free
.next
;
1333 run_final(objspace
, (VALUE
)p
);
1334 if (!FL_TEST(p
, FL_SINGLETON
)) { /* not freeing page */
1335 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
1336 p
->as
.free
.flags
= 0;
1337 p
->as
.free
.next
= freelist
;
1345 free_unused_heaps(rb_objspace_t
*objspace
)
1350 for (i
= j
= 1; j
< heaps_used
; i
++) {
1351 if (heaps
[i
].limit
== 0) {
1353 last
= heaps
[i
].membase
;
1356 free(heaps
[i
].membase
);
1362 heaps
[j
] = heaps
[i
];
1368 if (last
< heaps_freed
) {
1379 gc_sweep(rb_objspace_t
*objspace
)
1381 RVALUE
*p
, *pend
, *final_list
;
1384 size_t live
= 0, free_min
= 0, do_heap_free
= 0;
1386 do_heap_free
= (heaps_used
* HEAP_OBJ_LIMIT
) * 0.65;
1387 free_min
= (heaps_used
* HEAP_OBJ_LIMIT
) * 0.2;
1388 if (free_min
< FREE_MIN
) {
1389 do_heap_free
= heaps_used
* HEAP_OBJ_LIMIT
;
1390 free_min
= FREE_MIN
;
1394 final_list
= deferred_final_list
;
1395 deferred_final_list
= 0;
1396 for (i
= 0; i
< heaps_used
; i
++) {
1398 RVALUE
*free
= freelist
;
1399 RVALUE
*final
= final_list
;
1401 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
1403 if (!(p
->as
.basic
.flags
& FL_MARK
)) {
1404 if (p
->as
.basic
.flags
) {
1405 obj_free(objspace
, (VALUE
)p
);
1407 if (need_call_final
&& FL_TEST(p
, FL_FINALIZE
)) {
1408 p
->as
.free
.flags
= FL_MARK
; /* remain marked */
1409 p
->as
.free
.next
= final_list
;
1413 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
1414 p
->as
.free
.flags
= 0;
1415 p
->as
.free
.next
= freelist
;
1420 else if (RBASIC(p
)->flags
== FL_MARK
) {
1421 /* objects to be finalized */
1422 /* do nothing remain marked */
1425 RBASIC(p
)->flags
&= ~FL_MARK
;
1430 if (n
== heaps
[i
].limit
&& freed
> do_heap_free
) {
1434 for (pp
= final_list
; pp
!= final
; pp
= pp
->as
.free
.next
) {
1435 p
->as
.free
.flags
|= FL_SINGLETON
; /* freeing page mark */
1437 freelist
= free
; /* cancel this page from freelist */
1443 if (malloc_increase
> malloc_limit
) {
1444 malloc_limit
+= (malloc_increase
- malloc_limit
) * (double)live
/ (live
+ freed
);
1445 if (malloc_limit
< GC_MALLOC_LIMIT
) malloc_limit
= GC_MALLOC_LIMIT
;
1447 malloc_increase
= 0;
1448 if (freed
< free_min
) {
1449 set_heaps_increment(objspace
);
1450 heaps_increment(objspace
);
1454 /* clear finalization list */
1456 deferred_final_list
= final_list
;
1459 free_unused_heaps(objspace
);
1463 rb_gc_force_recycle(VALUE p
)
1465 rb_objspace_t
*objspace
= &rb_objspace
;
1466 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
1467 RANY(p
)->as
.free
.flags
= 0;
1468 RANY(p
)->as
.free
.next
= freelist
;
1473 obj_free(rb_objspace_t
*objspace
, VALUE obj
)
1475 switch (RANY(obj
)->as
.basic
.flags
& T_MASK
) {
1480 rb_bug("obj_free() called for broken object");
1484 if (FL_TEST(obj
, FL_EXIVAR
)) {
1485 rb_free_generic_ivar((VALUE
)obj
);
1488 switch (RANY(obj
)->as
.basic
.flags
& T_MASK
) {
1490 if (!(RANY(obj
)->as
.basic
.flags
& ROBJECT_EMBED
) &&
1491 RANY(obj
)->as
.object
.as
.heap
.ivptr
) {
1492 xfree(RANY(obj
)->as
.object
.as
.heap
.ivptr
);
1497 rb_clear_cache_by_class((VALUE
)obj
);
1498 st_free_table(RCLASS_M_TBL(obj
));
1499 if (RCLASS_IV_TBL(obj
)) {
1500 st_free_table(RCLASS_IV_TBL(obj
));
1502 if (RCLASS_IV_INDEX_TBL(obj
)) {
1503 st_free_table(RCLASS_IV_INDEX_TBL(obj
));
1505 xfree(RANY(obj
)->as
.klass
.ptr
);
1514 if (RANY(obj
)->as
.hash
.ntbl
) {
1515 st_free_table(RANY(obj
)->as
.hash
.ntbl
);
1519 if (RANY(obj
)->as
.regexp
.ptr
) {
1520 onig_free(RANY(obj
)->as
.regexp
.ptr
);
1524 if (DATA_PTR(obj
)) {
1525 if ((long)RANY(obj
)->as
.data
.dfree
== -1) {
1526 xfree(DATA_PTR(obj
));
1528 else if (RANY(obj
)->as
.data
.dfree
) {
1529 (*RANY(obj
)->as
.data
.dfree
)(DATA_PTR(obj
));
1534 if (RANY(obj
)->as
.match
.rmatch
) {
1535 struct rmatch
*rm
= RANY(obj
)->as
.match
.rmatch
;
1536 onig_region_free(&rm
->regs
, 0);
1537 if (rm
->char_offset
)
1538 xfree(rm
->char_offset
);
1543 if (RANY(obj
)->as
.file
.fptr
) {
1544 rb_io_fptr_finalize(RANY(obj
)->as
.file
.fptr
);
1551 /* iClass shares table with the module */
1558 if (!(RBASIC(obj
)->flags
& RBIGNUM_EMBED_FLAG
) && RBIGNUM_DIGITS(obj
)) {
1559 xfree(RBIGNUM_DIGITS(obj
));
1563 switch (nd_type(obj
)) {
1565 if (RANY(obj
)->as
.node
.u1
.tbl
) {
1566 xfree(RANY(obj
)->as
.node
.u1
.tbl
);
1570 xfree(RANY(obj
)->as
.node
.u1
.node
);
1573 return; /* no need to free iv_tbl */
1576 if ((RBASIC(obj
)->flags
& RSTRUCT_EMBED_LEN_MASK
) == 0 &&
1577 RANY(obj
)->as
.rstruct
.as
.heap
.ptr
) {
1578 xfree(RANY(obj
)->as
.rstruct
.as
.heap
.ptr
);
1583 rb_bug("gc_sweep(): unknown data type 0x%lx(%p)",
1584 RANY(obj
)->as
.basic
.flags
& T_MASK
, (void*)obj
);
1589 #if defined(__human68k__) || defined(DJGPP)
1592 #if defined(__human68k__)
1593 typedef unsigned long rb_jmp_buf
[8];
1597 movem.l d3-d7/a3-a5,(a0)\n\
1602 typedef unsigned long rb_jmp_buf
[6];
1603 __asm__ (".align 4\n\
1607 movl 8(%ebp),%ebp\n\
1609 movl %ebx,4(%ebp)\n\
1610 movl %ecx,8(%ebp)\n\
1611 movl %edx,12(%ebp)\n\
1612 movl %esi,16(%ebp)\n\
1613 movl %edi,20(%ebp)\n\
1619 int rb_setjmp (rb_jmp_buf
);
1620 #endif /* __human68k__ or DJGPP */
1621 #endif /* __GNUC__ */
1625 void rb_vm_mark(void *ptr
);
1628 mark_current_machine_context(rb_objspace_t
*objspace
, rb_thread_t
*th
)
1630 rb_jmp_buf save_regs_gc_mark
;
1631 VALUE
*stack_start
, *stack_end
;
1634 #if STACK_GROW_DIRECTION < 0
1635 stack_start
= th
->machine_stack_end
;
1636 stack_end
= th
->machine_stack_start
;
1637 #elif STACK_GROW_DIRECTION > 0
1638 stack_start
= th
->machine_stack_start
;
1639 stack_end
= th
->machine_stack_end
+ 1;
1641 if (th
->machine_stack_end
< th
->machine_stack_start
) {
1642 stack_start
= th
->machine_stack_end
;
1643 stack_end
= th
->machine_stack_start
;
1646 stack_start
= th
->machine_stack_start
;
1647 stack_end
= th
->machine_stack_end
+ 1;
1651 FLUSH_REGISTER_WINDOWS
;
1652 /* This assumes that all registers are saved into the jmp_buf (and stack) */
1653 rb_setjmp(save_regs_gc_mark
);
1654 mark_locations_array(objspace
,
1655 (VALUE
*)save_regs_gc_mark
,
1656 sizeof(save_regs_gc_mark
) / sizeof(VALUE
));
1658 rb_gc_mark_locations(stack_start
, stack_end
);
1660 rb_gc_mark_locations(th
->machine_register_stack_start
, th
->machine_register_stack_end
);
1662 #if defined(__human68k__) || defined(__mc68000__)
1663 mark_locations_array((VALUE
*)((char*)STACK_END
+ 2),
1664 (STACK_START
- STACK_END
));
1668 void rb_gc_mark_encodings(void);
1671 garbage_collect(rb_objspace_t
*objspace
)
1673 struct gc_list
*list
;
1674 rb_thread_t
*th
= GET_THREAD();
1676 if (GC_NOTIFY
) printf("start garbage_collect()\n");
1682 if (dont_gc
|| during_gc
) {
1684 if (!heaps_increment(objspace
)) {
1685 set_heaps_increment(objspace
);
1686 heaps_increment(objspace
);
1696 init_mark_stack(objspace
);
1698 th
->vm
->self
? rb_gc_mark(th
->vm
->self
) : rb_vm_mark(th
->vm
);
1700 if (finalizer_table
) {
1701 mark_tbl(objspace
, finalizer_table
, 0);
1704 mark_current_machine_context(objspace
, th
);
1706 rb_gc_mark_threads();
1707 rb_gc_mark_symbols();
1708 rb_gc_mark_encodings();
1710 /* mark protected global variables */
1711 for (list
= global_List
; list
; list
= list
->next
) {
1712 rb_gc_mark_maybe(*list
->varptr
);
1715 rb_gc_mark_global_tbl();
1717 mark_tbl(objspace
, rb_class_tbl
, 0);
1718 rb_gc_mark_trap_list();
1720 /* mark generic instance variables for special constants */
1721 rb_mark_generic_ivar_tbl();
1723 rb_gc_mark_parser();
1725 /* gc_mark objects whose marking are not completed*/
1726 while (!MARK_STACK_EMPTY
) {
1727 if (mark_stack_overflow
) {
1728 gc_mark_all(objspace
);
1731 gc_mark_rest(objspace
);
1737 if (GC_NOTIFY
) printf("end garbage_collect()\n");
1742 rb_garbage_collect(void)
1744 return garbage_collect(&rb_objspace
);
1748 rb_gc_mark_machine_stack(rb_thread_t
*th
)
1750 rb_objspace_t
*objspace
= &rb_objspace
;
1751 #if STACK_GROW_DIRECTION < 0
1752 rb_gc_mark_locations(th
->machine_stack_end
, th
->machine_stack_start
);
1753 #elif STACK_GROW_DIRECTION > 0
1754 rb_gc_mark_locations(th
->machine_stack_start
, th
->machine_stack_end
);
1756 if (th
->machine_stack_start
< th
->machine_stack_end
) {
1757 rb_gc_mark_locations(th
->machine_stack_start
, th
->machine_stack_end
);
1760 rb_gc_mark_locations(th
->machine_stack_end
, th
->machine_stack_start
);
1764 rb_gc_mark_locations(th
->machine_register_stack_start
, th
->machine_register_stack_end
);
1772 * gc.garbage_collect => nil
1773 * ObjectSpace.garbage_collect => nil
1775 * Initiates garbage collection, unless manually disabled.
1789 Init_stack(VALUE
*addr
)
1791 ruby_init_stack(addr
);
1795 * Document-class: ObjectSpace
1797 * The <code>ObjectSpace</code> module contains a number of routines
1798 * that interact with the garbage collection facility and allow you to
1799 * traverse all living objects with an iterator.
1801 * <code>ObjectSpace</code> also provides support for object
1802 * finalizers, procs that will be called when a specific object is
1803 * about to be destroyed by garbage collection.
1805 * include ObjectSpace
1813 * define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
1814 * define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
1815 * define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
1817 * <em>produces:</em>
1819 * Finalizer three on 537763470
1820 * Finalizer one on 537763480
1821 * Finalizer two on 537763480
1828 init_heap(&rb_objspace
);
1832 os_obj_of(rb_objspace_t
*objspace
, VALUE of
)
1836 RVALUE
*membase
= 0;
1841 while (i
< heaps_used
) {
1842 while (0 < i
&& (uintptr_t)membase
< (uintptr_t)heaps
[i
-1].membase
)
1844 while (i
< heaps_used
&& (uintptr_t)heaps
[i
].membase
<= (uintptr_t)membase
)
1846 if (heaps_used
<= i
)
1848 membase
= heaps
[i
].membase
;
1850 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
1851 for (;p
< pend
; p
++) {
1852 if (p
->as
.basic
.flags
) {
1853 switch (BUILTIN_TYPE(p
)) {
1859 if (FL_TEST(p
, FL_SINGLETON
)) continue;
1861 if (!p
->as
.basic
.klass
) continue;
1863 if (!of
|| rb_obj_is_kind_of(v
, of
)) {
1872 return SIZET2NUM(n
);
1877 * ObjectSpace.each_object([module]) {|obj| ... } => fixnum
1879 * Calls the block once for each living, nonimmediate object in this
1880 * Ruby process. If <i>module</i> is specified, calls the block
1881 * for only those classes or modules that match (or are a subclass of)
1882 * <i>module</i>. Returns the number of objects found. Immediate
1883 * objects (<code>Fixnum</code>s, <code>Symbol</code>s
1884 * <code>true</code>, <code>false</code>, and <code>nil</code>) are
1885 * never returned. In the example below, <code>each_object</code>
1886 * returns both the numbers we defined and several constants defined in
1887 * the <code>Math</code> module.
1890 * b = 95 # Won't be returned
1891 * c = 12345678987654321
1892 * count = ObjectSpace.each_object(Numeric) {|x| p x }
1893 * puts "Total count: #{count}"
1895 * <em>produces:</em>
1901 * 2.22044604925031e-16
1902 * 1.7976931348623157e+308
1903 * 2.2250738585072e-308
1909 os_each_obj(int argc
, VALUE
*argv
, VALUE os
)
1918 rb_scan_args(argc
, argv
, "01", &of
);
1920 RETURN_ENUMERATOR(os
, 1, &of
);
1921 return os_obj_of(&rb_objspace
, of
);
1926 * ObjectSpace.undefine_finalizer(obj)
1928 * Removes all finalizers for <i>obj</i>.
1933 undefine_final(VALUE os
, VALUE obj
)
1935 rb_objspace_t
*objspace
= &rb_objspace
;
1936 if (finalizer_table
) {
1937 st_delete(finalizer_table
, (st_data_t
*)&obj
, 0);
1944 * ObjectSpace.define_finalizer(obj, aProc=proc())
1946 * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
1952 define_final(int argc
, VALUE
*argv
, VALUE os
)
1954 rb_objspace_t
*objspace
= &rb_objspace
;
1955 VALUE obj
, block
, table
;
1957 rb_scan_args(argc
, argv
, "11", &obj
, &block
);
1959 block
= rb_block_proc();
1961 else if (!rb_respond_to(block
, rb_intern("call"))) {
1962 rb_raise(rb_eArgError
, "wrong type argument %s (should be callable)",
1963 rb_obj_classname(block
));
1965 FL_SET(obj
, FL_FINALIZE
);
1967 block
= rb_ary_new3(2, INT2FIX(rb_safe_level()), block
);
1969 if (!finalizer_table
) {
1970 finalizer_table
= st_init_numtable();
1972 if (st_lookup(finalizer_table
, obj
, &table
)) {
1973 rb_ary_push(table
, block
);
1976 st_add_direct(finalizer_table
, obj
, rb_ary_new3(1, block
));
1982 rb_gc_copy_finalizer(VALUE dest
, VALUE obj
)
1984 rb_objspace_t
*objspace
= &rb_objspace
;
1987 if (!finalizer_table
) return;
1988 if (!FL_TEST(obj
, FL_FINALIZE
)) return;
1989 if (st_lookup(finalizer_table
, obj
, &table
)) {
1990 st_insert(finalizer_table
, dest
, table
);
1992 FL_SET(dest
, FL_FINALIZE
);
1996 run_single_final(VALUE arg
)
1998 VALUE
*args
= (VALUE
*)arg
;
1999 rb_eval_cmd(args
[0], args
[1], (int)args
[2]);
2004 run_final(rb_objspace_t
*objspace
, VALUE obj
)
2007 int status
, critical_save
= rb_thread_critical
;
2008 VALUE args
[3], table
, objid
;
2010 objid
= rb_obj_id(obj
); /* make obj into id */
2011 rb_thread_critical
= Qtrue
;
2013 args
[2] = (VALUE
)rb_safe_level();
2014 if (finalizer_table
&& st_delete(finalizer_table
, (st_data_t
*)&obj
, &table
)) {
2015 if (!args
[1] && RARRAY_LEN(table
) > 0) {
2016 args
[1] = rb_obj_freeze(rb_ary_new3(1, objid
));
2018 for (i
=0; i
<RARRAY_LEN(table
); i
++) {
2019 VALUE final
= RARRAY_PTR(table
)[i
];
2020 args
[0] = RARRAY_PTR(final
)[1];
2021 args
[2] = FIX2INT(RARRAY_PTR(final
)[0]);
2022 rb_protect(run_single_final
, (VALUE
)args
, &status
);
2025 rb_thread_critical
= critical_save
;
2029 gc_finalize_deferred(rb_objspace_t
*objspace
)
2031 RVALUE
*p
= deferred_final_list
;
2033 deferred_final_list
= 0;
2035 finalize_list(objspace
, p
);
2037 free_unused_heaps(objspace
);
2041 rb_gc_finalize_deferred(void)
2043 gc_finalize_deferred(&rb_objspace
);
2047 chain_finalized_object(st_data_t key
, st_data_t val
, st_data_t arg
)
2049 RVALUE
*p
= (RVALUE
*)key
, **final_list
= (RVALUE
**)arg
;
2050 if (p
->as
.basic
.flags
& FL_FINALIZE
) {
2051 p
->as
.free
.flags
= FL_MARK
; /* remain marked */
2052 p
->as
.free
.next
= *final_list
;
2059 rb_gc_call_finalizer_at_exit(void)
2061 rb_objspace_t
*objspace
= &rb_objspace
;
2065 /* run finalizers */
2066 if (need_call_final
) {
2068 p
= deferred_final_list
;
2069 deferred_final_list
= 0;
2070 finalize_list(objspace
, p
);
2071 st_foreach(finalizer_table
, chain_finalized_object
,
2072 (st_data_t
)&deferred_final_list
);
2073 } while (deferred_final_list
);
2075 /* finalizers are part of garbage collection */
2077 /* run data object's finalizers */
2078 for (i
= 0; i
< heaps_used
; i
++) {
2079 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
2081 if (BUILTIN_TYPE(p
) == T_DATA
&&
2082 DATA_PTR(p
) && RANY(p
)->as
.data
.dfree
&&
2083 RANY(p
)->as
.basic
.klass
!= rb_cThread
) {
2084 p
->as
.free
.flags
= 0;
2085 if ((long)RANY(p
)->as
.data
.dfree
== -1) {
2088 else if (RANY(p
)->as
.data
.dfree
) {
2089 (*RANY(p
)->as
.data
.dfree
)(DATA_PTR(p
));
2091 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
2093 else if (BUILTIN_TYPE(p
) == T_FILE
) {
2094 if (rb_io_fptr_finalize(RANY(p
)->as
.file
.fptr
)) {
2095 p
->as
.free
.flags
= 0;
2096 VALGRIND_MAKE_MEM_UNDEFINED((void*)p
, sizeof(RVALUE
));
2108 rb_objspace_t
*objspace
= &rb_objspace
;
2109 garbage_collect(objspace
);
2110 gc_finalize_deferred(objspace
);
2115 * ObjectSpace._id2ref(object_id) -> an_object
2117 * Converts an object id to a reference to the object. May not be
2118 * called on an object id passed as a parameter to a finalizer.
2120 * s = "I am a string" #=> "I am a string"
2121 * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
2127 id2ref(VALUE obj
, VALUE objid
)
2129 #if SIZEOF_LONG == SIZEOF_VOIDP
2130 #define NUM2PTR(x) NUM2ULONG(x)
2131 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
2132 #define NUM2PTR(x) NUM2ULL(x)
2134 rb_objspace_t
*objspace
= &rb_objspace
;
2139 ptr
= NUM2PTR(objid
);
2142 if (ptr
== Qtrue
) return Qtrue
;
2143 if (ptr
== Qfalse
) return Qfalse
;
2144 if (ptr
== Qnil
) return Qnil
;
2145 if (FIXNUM_P(ptr
)) return (VALUE
)ptr
;
2146 ptr
= objid
^ FIXNUM_FLAG
; /* unset FIXNUM_FLAG */
2148 if ((ptr
% sizeof(RVALUE
)) == (4 << 2)) {
2149 ID symid
= ptr
/ sizeof(RVALUE
);
2150 if (rb_id2name(symid
) == 0)
2151 rb_raise(rb_eRangeError
, "%p is not symbol id value", p0
);
2152 return ID2SYM(symid
);
2155 if (!is_pointer_to_heap(objspace
, (void *)ptr
) ||
2156 BUILTIN_TYPE(ptr
) > T_FIXNUM
|| BUILTIN_TYPE(ptr
) == T_ICLASS
) {
2157 rb_raise(rb_eRangeError
, "%p is not id value", p0
);
2159 if (BUILTIN_TYPE(ptr
) == 0 || RBASIC(ptr
)->klass
== 0) {
2160 rb_raise(rb_eRangeError
, "%p is recycled object", p0
);
2166 * Document-method: __id__
2167 * Document-method: object_id
2170 * obj.__id__ => fixnum
2171 * obj.object_id => fixnum
2173 * Returns an integer identifier for <i>obj</i>. The same number will
2174 * be returned on all calls to <code>id</code> for a given object, and
2175 * no two active objects will share an id.
2176 * <code>Object#object_id</code> is a different concept from the
2177 * <code>:name</code> notation, which returns the symbol id of
2178 * <code>name</code>. Replaces the deprecated <code>Object#id</code>.
2183 * obj.hash => fixnum
2185 * Generates a <code>Fixnum</code> hash value for this object. This
2186 * function must have the property that <code>a.eql?(b)</code> implies
2187 * <code>a.hash == b.hash</code>. The hash value is used by class
2188 * <code>Hash</code>. Any hash value that exceeds the capacity of a
2189 * <code>Fixnum</code> will be truncated before being used.
2193 rb_obj_id(VALUE obj
)
2196 * 32-bit VALUE space
2197 * MSB ------------------------ LSB
2198 * false 00000000000000000000000000000000
2199 * true 00000000000000000000000000000010
2200 * nil 00000000000000000000000000000100
2201 * undef 00000000000000000000000000000110
2202 * symbol ssssssssssssssssssssssss00001110
2203 * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
2204 * fixnum fffffffffffffffffffffffffffffff1
2208 * false 00000000000000000000000000000000
2209 * true 00000000000000000000000000000010
2210 * nil 00000000000000000000000000000100
2211 * undef 00000000000000000000000000000110
2212 * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
2213 * object oooooooooooooooooooooooooooooo0 o...o % A = 0
2214 * fixnum fffffffffffffffffffffffffffffff1 bignum if required
2216 * where A = sizeof(RVALUE)/4
2219 * 20 if 32-bit, double is 4-byte aligned
2220 * 24 if 32-bit, double is 8-byte aligned
2223 if (TYPE(obj
) == T_SYMBOL
) {
2224 return (SYM2ID(obj
) * sizeof(RVALUE
) + (4 << 2)) | FIXNUM_FLAG
;
2226 if (SPECIAL_CONST_P(obj
)) {
2227 return LONG2NUM((SIGNED_VALUE
)obj
);
2229 return (VALUE
)((SIGNED_VALUE
)obj
|FIXNUM_FLAG
);
2233 set_zero(st_data_t key
, st_data_t val
, st_data_t arg
)
2235 VALUE k
= (VALUE
)key
;
2236 VALUE hash
= (VALUE
)arg
;
2237 rb_hash_aset(hash
, k
, INT2FIX(0));
2243 * ObjectSpace.count_objects([result_hash]) -> hash
2245 * Counts objects for each type.
2247 * It returns a hash as:
2248 * {:TOTAL=>10000, :FREE=>3011, :T_OBJECT=>6, :T_CLASS=>404, ...}
2250 * If the optional argument, result_hash, is given,
2251 * it is overwritten and returned.
2252 * This is intended to avoid probe effect.
2254 * The contents of the returned hash is implementation defined.
2255 * It may be changed in future.
2257 * This method is not expected to work except C Ruby.
2262 count_objects(int argc
, VALUE
*argv
, VALUE os
)
2264 rb_objspace_t
*objspace
= &rb_objspace
;
2265 size_t counts
[T_MASK
+1];
2271 if (rb_scan_args(argc
, argv
, "01", &hash
) == 1) {
2272 if (TYPE(hash
) != T_HASH
)
2273 rb_raise(rb_eTypeError
, "non-hash given");
2276 for (i
= 0; i
<= T_MASK
; i
++) {
2280 for (i
= 0; i
< heaps_used
; i
++) {
2283 p
= heaps
[i
].slot
; pend
= p
+ heaps
[i
].limit
;
2284 for (;p
< pend
; p
++) {
2285 if (p
->as
.basic
.flags
) {
2286 counts
[BUILTIN_TYPE(p
)]++;
2292 total
+= heaps
[i
].limit
;
2296 hash
= rb_hash_new();
2298 else if (!RHASH_EMPTY_P(hash
)) {
2299 st_foreach(RHASH_TBL(hash
), set_zero
, hash
);
2301 rb_hash_aset(hash
, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total
));
2302 rb_hash_aset(hash
, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed
));
2303 for (i
= 0; i
<= T_MASK
; i
++) {
2306 #define COUNT_TYPE(t) case t: type = ID2SYM(rb_intern(#t)); break;
2308 COUNT_TYPE(T_OBJECT
);
2309 COUNT_TYPE(T_CLASS
);
2310 COUNT_TYPE(T_MODULE
);
2311 COUNT_TYPE(T_FLOAT
);
2312 COUNT_TYPE(T_STRING
);
2313 COUNT_TYPE(T_REGEXP
);
2314 COUNT_TYPE(T_ARRAY
);
2316 COUNT_TYPE(T_STRUCT
);
2317 COUNT_TYPE(T_BIGNUM
);
2320 COUNT_TYPE(T_MATCH
);
2321 COUNT_TYPE(T_COMPLEX
);
2322 COUNT_TYPE(T_RATIONAL
);
2325 COUNT_TYPE(T_FALSE
);
2326 COUNT_TYPE(T_SYMBOL
);
2327 COUNT_TYPE(T_FIXNUM
);
2328 COUNT_TYPE(T_UNDEF
);
2330 COUNT_TYPE(T_ICLASS
);
2332 default: type
= INT2NUM(i
); break;
2335 rb_hash_aset(hash
, type
, SIZET2NUM(counts
[i
]));
2343 * GC.count -> Integer
2345 * The number of times GC occured.
2347 * It returns the number of times GC occured since the process started.
2352 gc_count(VALUE self
)
2354 return UINT2NUM((&rb_objspace
)->count
);
2357 #if CALC_EXACT_MALLOC_SIZE
2360 * GC.malloc_allocated_size -> Integer
2362 * The allocated size by malloc().
2364 * It returns the allocated size by malloc().
2368 gc_malloc_allocated_size(VALUE self
)
2370 return UINT2NUM((&rb_objspace
)->malloc_params
.allocated_size
);
2375 * GC.malloc_allocations -> Integer
2377 * The number of allocated memory object by malloc().
2379 * It returns the number of allocated memory object by malloc().
2383 gc_malloc_allocations(VALUE self
)
2385 return UINT2NUM((&rb_objspace
)->malloc_params
.allocations
);
2390 * The <code>GC</code> module provides an interface to Ruby's mark and
2391 * sweep garbage collection mechanism. Some of the underlying methods
2392 * are also available via the <code>ObjectSpace</code> module.
2400 rb_mGC
= rb_define_module("GC");
2401 rb_define_singleton_method(rb_mGC
, "start", rb_gc_start
, 0);
2402 rb_define_singleton_method(rb_mGC
, "enable", rb_gc_enable
, 0);
2403 rb_define_singleton_method(rb_mGC
, "disable", rb_gc_disable
, 0);
2404 rb_define_singleton_method(rb_mGC
, "stress", gc_stress_get
, 0);
2405 rb_define_singleton_method(rb_mGC
, "stress=", gc_stress_set
, 1);
2406 rb_define_singleton_method(rb_mGC
, "count", gc_count
, 0);
2407 rb_define_method(rb_mGC
, "garbage_collect", rb_gc_start
, 0);
2409 rb_mObSpace
= rb_define_module("ObjectSpace");
2410 rb_define_module_function(rb_mObSpace
, "each_object", os_each_obj
, -1);
2411 rb_define_module_function(rb_mObSpace
, "garbage_collect", rb_gc_start
, 0);
2413 rb_define_module_function(rb_mObSpace
, "define_finalizer", define_final
, -1);
2414 rb_define_module_function(rb_mObSpace
, "undefine_finalizer", undefine_final
, 1);
2416 rb_define_module_function(rb_mObSpace
, "_id2ref", id2ref
, 1);
2418 nomem_error
= rb_exc_new3(rb_eNoMemError
,
2419 rb_obj_freeze(rb_str_new2("failed to allocate memory")));
2420 OBJ_TAINT(nomem_error
);
2421 OBJ_FREEZE(nomem_error
);
2423 rb_define_method(rb_mKernel
, "hash", rb_obj_id
, 0);
2424 rb_define_method(rb_mKernel
, "__id__", rb_obj_id
, 0);
2425 rb_define_method(rb_mKernel
, "object_id", rb_obj_id
, 0);
2427 rb_define_module_function(rb_mObSpace
, "count_objects", count_objects
, -1);
2429 #if CALC_EXACT_MALLOC_SIZE
2430 rb_define_singleton_method(rb_mGC
, "malloc_allocated_size", gc_malloc_allocated_size
, 0);
2431 rb_define_singleton_method(rb_mGC
, "malloc_allocations", gc_malloc_allocations
, 0);