Ruby  1.9.3p429(2013-05-15revision40747)
gc.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  gc.c -
4 
5  $Author: usa $
6  created at: Tue Oct 5 09:44:46 JST 1993
7 
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
11 
12 **********************************************************************/
13 
14 #include "ruby/ruby.h"
15 #include "ruby/st.h"
16 #include "ruby/re.h"
17 #include "ruby/io.h"
18 #include "ruby/util.h"
19 #include "eval_intern.h"
20 #include "vm_core.h"
21 #include "internal.h"
22 #include "gc.h"
23 #include "constant.h"
24 #include "ruby_atomic.h"
25 #include <stdio.h>
26 #include <setjmp.h>
27 #include <sys/types.h>
28 #include <assert.h>
29 
30 #ifdef HAVE_SYS_TIME_H
31 #include <sys/time.h>
32 #endif
33 
34 #ifdef HAVE_SYS_RESOURCE_H
35 #include <sys/resource.h>
36 #endif
37 
38 #if defined _WIN32 || defined __CYGWIN__
39 #include <windows.h>
40 #endif
41 
42 #ifdef HAVE_VALGRIND_MEMCHECK_H
43 # include <valgrind/memcheck.h>
44 # ifndef VALGRIND_MAKE_MEM_DEFINED
45 # define VALGRIND_MAKE_MEM_DEFINED(p, n) VALGRIND_MAKE_READABLE((p), (n))
46 # endif
47 # ifndef VALGRIND_MAKE_MEM_UNDEFINED
48 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE((p), (n))
49 # endif
50 #else
51 # define VALGRIND_MAKE_MEM_DEFINED(p, n) /* empty */
52 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) /* empty */
53 #endif
54 
55 #define rb_setjmp(env) RUBY_SETJMP(env)
56 #define rb_jmp_buf rb_jmpbuf_t
57 
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__ */
78 
79 #ifndef GC_MALLOC_LIMIT
80 #define GC_MALLOC_LIMIT 8000000
81 #endif
82 #define HEAP_MIN_SLOTS 10000
83 #define FREE_MIN 4096
84 
85 typedef struct {
86  unsigned int initial_malloc_limit;
87  unsigned int initial_heap_min_slots;
88  unsigned int initial_free_min;
89  int gc_stress;
91 
95  FREE_MIN,
96 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
97  FALSE,
98 #endif
99 };
100 
101 #define nomem_error GET_VM()->special_exceptions[ruby_error_nomemory]
102 
103 #if SIZEOF_LONG == SIZEOF_VOIDP
104 # define nonspecial_obj_id(obj) (VALUE)((SIGNED_VALUE)(obj)|FIXNUM_FLAG)
105 # define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG) /* unset FIXNUM_FLAG */
106 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
107 # define nonspecial_obj_id(obj) LL2NUM((SIGNED_VALUE)(obj) / 2)
108 # define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \
109  ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1))
110 #else
111 # error not supported
112 #endif
113 
115 
116 /* for GC profile */
117 #define GC_PROFILE_MORE_DETAIL 0
118 typedef struct gc_profile_record {
119  double gc_time;
120  double gc_mark_time;
123 
130 
133 
137 
138 static double
140 {
141 #ifdef RUSAGE_SELF
142  struct rusage usage;
143  struct timeval time;
144  getrusage(RUSAGE_SELF, &usage);
145  time = usage.ru_utime;
146  return time.tv_sec + time.tv_usec * 1e-6;
147 #elif defined _WIN32
148  FILETIME creation_time, exit_time, kernel_time, user_time;
149  ULARGE_INTEGER ui;
150  LONG_LONG q;
151  double t;
152 
153  if (GetProcessTimes(GetCurrentProcess(),
154  &creation_time, &exit_time, &kernel_time, &user_time) == 0)
155  {
156  return 0.0;
157  }
158  memcpy(&ui, &user_time, sizeof(FILETIME));
159  q = ui.QuadPart / 10L;
160  t = (DWORD)(q % 1000000L) * 1e-6;
161  q /= 1000000L;
162 #ifdef __GNUC__
163  t += q;
164 #else
165  t += (double)(DWORD)(q >> 16) * (1 << 16);
166  t += (DWORD)q & ~(~0 << 16);
167 #endif
168  return t;
169 #else
170  return 0.0;
171 #endif
172 }
173 
174 #define GC_PROF_TIMER_START do {\
175  if (objspace->profile.run) {\
176  if (!objspace->profile.record) {\
177  objspace->profile.size = 1000;\
178  objspace->profile.record = malloc(sizeof(gc_profile_record) * objspace->profile.size);\
179  }\
180  if (count >= objspace->profile.size) {\
181  objspace->profile.size += 1000;\
182  objspace->profile.record = realloc(objspace->profile.record, sizeof(gc_profile_record) * objspace->profile.size);\
183  }\
184  if (!objspace->profile.record) {\
185  rb_bug("gc_profile malloc or realloc miss");\
186  }\
187  MEMZERO(&objspace->profile.record[count], gc_profile_record, 1);\
188  gc_time = getrusage_time();\
189  objspace->profile.record[count].gc_invoke_time = gc_time - objspace->profile.invoke_time;\
190  }\
191  } while(0)
192 
193 #define GC_PROF_TIMER_STOP(marked) do {\
194  if (objspace->profile.run) {\
195  gc_time = getrusage_time() - gc_time;\
196  if (gc_time < 0) gc_time = 0;\
197  objspace->profile.record[count].gc_time = gc_time;\
198  objspace->profile.record[count].is_marked = !!(marked);\
199  GC_PROF_SET_HEAP_INFO(objspace->profile.record[count]);\
200  objspace->profile.count++;\
201  }\
202  } while(0)
203 
204 #if GC_PROFILE_MORE_DETAIL
205 #define INIT_GC_PROF_PARAMS double gc_time = 0, sweep_time = 0;\
206  size_t count = objspace->profile.count, total = 0, live = 0
207 
208 #define GC_PROF_MARK_TIMER_START double mark_time = 0;\
209  do {\
210  if (objspace->profile.run) {\
211  mark_time = getrusage_time();\
212  }\
213  } while(0)
214 
215 #define GC_PROF_MARK_TIMER_STOP do {\
216  if (objspace->profile.run) {\
217  mark_time = getrusage_time() - mark_time;\
218  if (mark_time < 0) mark_time = 0;\
219  objspace->profile.record[objspace->profile.count].gc_mark_time = mark_time;\
220  }\
221  } while(0)
222 
223 #define GC_PROF_SWEEP_TIMER_START do {\
224  if (objspace->profile.run) {\
225  sweep_time = getrusage_time();\
226  }\
227  } while(0)
228 
229 #define GC_PROF_SWEEP_TIMER_STOP do {\
230  if (objspace->profile.run) {\
231  sweep_time = getrusage_time() - sweep_time;\
232  if (sweep_time < 0) sweep_time = 0;\
233  objspace->profile.record[count].gc_sweep_time = sweep_time;\
234  }\
235  } while(0)
236 #define GC_PROF_SET_MALLOC_INFO do {\
237  if (objspace->profile.run) {\
238  gc_profile_record *record = &objspace->profile.record[objspace->profile.count];\
239  record->allocate_increase = malloc_increase;\
240  record->allocate_limit = malloc_limit; \
241  }\
242  } while(0)
243 #define GC_PROF_SET_HEAP_INFO(record) do {\
244  live = objspace->heap.live_num;\
245  total = heaps_used * HEAP_OBJ_LIMIT;\
246  (record).heap_use_slots = heaps_used;\
247  (record).heap_live_objects = live;\
248  (record).heap_free_objects = total - live;\
249  (record).heap_total_objects = total;\
250  (record).have_finalize = deferred_final_list ? Qtrue : Qfalse;\
251  (record).heap_use_size = live * sizeof(RVALUE);\
252  (record).heap_total_size = total * sizeof(RVALUE);\
253  } while(0)
254 #define GC_PROF_INC_LIVE_NUM objspace->heap.live_num++
255 #define GC_PROF_DEC_LIVE_NUM objspace->heap.live_num--
256 #else
257 #define INIT_GC_PROF_PARAMS double gc_time = 0;\
258  size_t count = objspace->profile.count, total = 0, live = 0
259 #define GC_PROF_MARK_TIMER_START
260 #define GC_PROF_MARK_TIMER_STOP
261 #define GC_PROF_SWEEP_TIMER_START
262 #define GC_PROF_SWEEP_TIMER_STOP
263 #define GC_PROF_SET_MALLOC_INFO
264 #define GC_PROF_SET_HEAP_INFO(record) do {\
265  live = objspace->heap.live_num;\
266  total = heaps_used * HEAP_OBJ_LIMIT;\
267  (record).heap_total_objects = total;\
268  (record).heap_use_size = live * sizeof(RVALUE);\
269  (record).heap_total_size = total * sizeof(RVALUE);\
270  } while(0)
271 #define GC_PROF_INC_LIVE_NUM
272 #define GC_PROF_DEC_LIVE_NUM
273 #endif
274 
275 
276 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
277 #pragma pack(push, 1) /* magic for reducing sizeof(RVALUE): 24 -> 20 */
278 #endif
279 
280 typedef struct RVALUE {
281  union {
282  struct {
283  VALUE flags; /* always 0 for freed obj */
284  struct RVALUE *next;
285  } free;
286  struct RBasic basic;
287  struct RObject object;
288  struct RClass klass;
289  struct RFloat flonum;
290  struct RString string;
291  struct RArray array;
292  struct RRegexp regexp;
293  struct RHash hash;
294  struct RData data;
296  struct RStruct rstruct;
297  struct RBignum bignum;
298  struct RFile file;
299  struct RNode node;
300  struct RMatch match;
303  } as;
304 #ifdef GC_DEBUG
305  const char *file;
306  int line;
307 #endif
308 } RVALUE;
309 
310 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__)
311 #pragma pack(pop)
312 #endif
313 
314 struct heaps_slot {
315  void *membase;
317  size_t limit;
318  struct heaps_slot *next;
319  struct heaps_slot *prev;
320 };
321 
325  struct heaps_slot *slot;
326 };
327 
328 struct gc_list {
330  struct gc_list *next;
331 };
332 
333 #define STACK_CHUNK_SIZE 500
334 
335 typedef struct stack_chunk {
337  struct stack_chunk *next;
338 } stack_chunk_t;
339 
340 typedef struct mark_stack {
343  size_t index;
344  size_t limit;
345  size_t cache_size;
347 } mark_stack_t;
348 
349 #define CALC_EXACT_MALLOC_SIZE 0
350 
351 typedef struct rb_objspace {
352  struct {
353  size_t limit;
354  size_t increase;
355 #if CALC_EXACT_MALLOC_SIZE
356  size_t allocated_size;
357  size_t allocations;
358 #endif
359  } malloc_params;
360  struct {
361  size_t increment;
362  struct heaps_slot *ptr;
365  size_t length;
366  size_t used;
370  size_t live_num;
371  size_t free_num;
372  size_t free_min;
373  size_t final_num;
374  size_t do_heap_free;
375  } heap;
376  struct {
377  int dont_gc;
380  } flags;
381  struct {
384  } final;
386  struct {
387  int run;
389  size_t count;
390  size_t size;
391  double invoke_time;
392  } profile;
394  size_t count;
396 } rb_objspace_t;
397 
398 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
399 #define rb_objspace (*GET_VM()->objspace)
400 #define ruby_initial_gc_stress initial_params.gc_stress
402 #else
404 int *ruby_initial_gc_stress_ptr = &rb_objspace.gc_stress;
405 #endif
406 #define malloc_limit objspace->malloc_params.limit
407 #define malloc_increase objspace->malloc_params.increase
408 #define heaps objspace->heap.ptr
409 #define heaps_length objspace->heap.length
410 #define heaps_used objspace->heap.used
411 #define freelist objspace->heap.freelist
412 #define lomem objspace->heap.range[0]
413 #define himem objspace->heap.range[1]
414 #define heaps_inc objspace->heap.increment
415 #define heaps_freed objspace->heap.freed
416 #define dont_gc objspace->flags.dont_gc
417 #define during_gc objspace->flags.during_gc
418 #define finalizer_table objspace->final.table
419 #define deferred_final_list objspace->final.deferred
420 #define global_List objspace->global_list
421 #define ruby_gc_stress objspace->gc_stress
422 #define initial_malloc_limit initial_params.initial_malloc_limit
423 #define initial_heap_min_slots initial_params.initial_heap_min_slots
424 #define initial_free_min initial_params.initial_free_min
425 
426 static void rb_objspace_call_finalizer(rb_objspace_t *objspace);
427 
428 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
431 {
432  rb_objspace_t *objspace = malloc(sizeof(rb_objspace_t));
433  memset(objspace, 0, sizeof(*objspace));
436 
437  return objspace;
438 }
439 #endif
440 
441 static void initial_expand_heap(rb_objspace_t *objspace);
442 static void init_mark_stack(mark_stack_t *stack);
443 
444 void
446 {
447  char *malloc_limit_ptr, *heap_min_slots_ptr, *free_min_ptr;
448 
449  if (rb_safe_level() > 0) return;
450 
451  malloc_limit_ptr = getenv("RUBY_GC_MALLOC_LIMIT");
452  if (malloc_limit_ptr != NULL) {
453  int malloc_limit_i = atoi(malloc_limit_ptr);
454  if (RTEST(ruby_verbose))
455  fprintf(stderr, "malloc_limit=%d (%d)\n",
456  malloc_limit_i, initial_malloc_limit);
457  if (malloc_limit_i > 0) {
458  initial_malloc_limit = malloc_limit_i;
459  }
460  }
461 
462  heap_min_slots_ptr = getenv("RUBY_HEAP_MIN_SLOTS");
463  if (heap_min_slots_ptr != NULL) {
464  int heap_min_slots_i = atoi(heap_min_slots_ptr);
465  if (RTEST(ruby_verbose))
466  fprintf(stderr, "heap_min_slots=%d (%d)\n",
467  heap_min_slots_i, initial_heap_min_slots);
468  if (heap_min_slots_i > 0) {
469  initial_heap_min_slots = heap_min_slots_i;
470  initial_expand_heap(&rb_objspace);
471  }
472  }
473 
474  free_min_ptr = getenv("RUBY_FREE_MIN");
475  if (free_min_ptr != NULL) {
476  int free_min_i = atoi(free_min_ptr);
477  if (RTEST(ruby_verbose))
478  fprintf(stderr, "free_min=%d (%d)\n", free_min_i, initial_free_min);
479  if (free_min_i > 0) {
480  initial_free_min = free_min_i;
481  }
482  }
483 }
484 
485 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
486 static void gc_sweep(rb_objspace_t *);
487 static void slot_sweep(rb_objspace_t *, struct heaps_slot *);
488 static void rest_sweep(rb_objspace_t *);
489 static void free_stack_chunks(mark_stack_t *);
490 
491 void
493 {
494  rest_sweep(objspace);
495  if (objspace->profile.record) {
496  free(objspace->profile.record);
497  objspace->profile.record = 0;
498  }
499  if (global_List) {
500  struct gc_list *list, *next;
501  for (list = global_List; list; list = next) {
502  next = list->next;
503  free(list);
504  }
505  }
506  if (objspace->heap.sorted) {
507  size_t i;
508  for (i = 0; i < heaps_used; ++i) {
509  free(objspace->heap.sorted[i].slot->membase);
510  free(objspace->heap.sorted[i].slot);
511  }
512  free(objspace->heap.sorted);
513  heaps_used = 0;
514  heaps = 0;
515  }
516  free_stack_chunks(&objspace->mark_stack);
517  free(objspace);
518 }
519 #endif
520 
521 /* tiny heap size */
522 /* 32KB */
523 /*#define HEAP_SIZE 0x8000 */
524 /* 128KB */
525 /*#define HEAP_SIZE 0x20000 */
526 /* 64KB */
527 /*#define HEAP_SIZE 0x10000 */
528 /* 16KB */
529 #define HEAP_SIZE 0x4000
530 /* 8KB */
531 /*#define HEAP_SIZE 0x2000 */
532 /* 4KB */
533 /*#define HEAP_SIZE 0x1000 */
534 /* 2KB */
535 /*#define HEAP_SIZE 0x800 */
536 
537 #define HEAP_OBJ_LIMIT (unsigned int)(HEAP_SIZE / sizeof(struct RVALUE))
538 
539 extern st_table *rb_class_tbl;
540 
542 
543 static void run_final(rb_objspace_t *objspace, VALUE obj);
544 static int garbage_collect(rb_objspace_t *objspace);
545 static int gc_lazy_sweep(rb_objspace_t *objspace);
546 
547 void
549 {
551 }
552 
553 static void *
554 ruby_memerror_body(void *dummy)
555 {
556  rb_memerror();
557  return 0;
558 }
559 
560 static void
562 {
563  if (ruby_thread_has_gvl_p()) {
564  rb_memerror();
565  }
566  else {
567  if (ruby_native_thread_p()) {
569  }
570  else {
571  /* no ruby thread */
572  fprintf(stderr, "[FATAL] failed to allocate memory\n");
573  exit(EXIT_FAILURE);
574  }
575  }
576 }
577 
578 void
580 {
581  rb_thread_t *th = GET_THREAD();
582  if (!nomem_error ||
584  fprintf(stderr, "[FATAL] failed to allocate memory\n");
585  exit(EXIT_FAILURE);
586  }
589  GET_THREAD()->errinfo = nomem_error;
591  }
594 }
595 
596 /*
597  * call-seq:
598  * GC.stress -> true or false
599  *
600  * returns current status of GC stress mode.
601  */
602 
603 static VALUE
605 {
606  rb_objspace_t *objspace = &rb_objspace;
607  return ruby_gc_stress ? Qtrue : Qfalse;
608 }
609 
610 /*
611  * call-seq:
612  * GC.stress = bool -> bool
613  *
614  * Updates the GC stress mode.
615  *
616  * When stress mode is enabled the GC is invoked at every GC opportunity:
617  * all memory and object allocations.
618  *
619  * Enabling stress mode makes Ruby very slow, it is only for debugging.
620  */
621 
622 static VALUE
624 {
625  rb_objspace_t *objspace = &rb_objspace;
626  rb_secure(2);
627  ruby_gc_stress = RTEST(flag);
628  return flag;
629 }
630 
631 /*
632  * call-seq:
633  * GC::Profiler.enable? -> true or false
634  *
635  * The current status of GC profile mode.
636  */
637 
638 static VALUE
640 {
641  rb_objspace_t *objspace = &rb_objspace;
642  return objspace->profile.run ? Qtrue : Qfalse;
643 }
644 
645 /*
646  * call-seq:
647  * GC::Profiler.enable -> nil
648  *
649  * Starts the GC profiler.
650  *
651  */
652 
653 static VALUE
655 {
656  rb_objspace_t *objspace = &rb_objspace;
657 
658  objspace->profile.run = TRUE;
659  return Qnil;
660 }
661 
662 /*
663  * call-seq:
664  * GC::Profiler.disable -> nil
665  *
666  * Stops the GC profiler.
667  *
668  */
669 
670 static VALUE
672 {
673  rb_objspace_t *objspace = &rb_objspace;
674 
675  objspace->profile.run = FALSE;
676  return Qnil;
677 }
678 
679 /*
680  * call-seq:
681  * GC::Profiler.clear -> nil
682  *
683  * Clears the GC profiler data.
684  *
685  */
686 
687 static VALUE
689 {
690  rb_objspace_t *objspace = &rb_objspace;
691  MEMZERO(objspace->profile.record, gc_profile_record, objspace->profile.size);
692  objspace->profile.count = 0;
693  return Qnil;
694 }
695 
696 static void *
698 {
699  rb_raise(rb_eNoMemError, "%s", (const char *)ptr);
700  return 0; /* should not be reached */
701 }
702 
703 static void
705 {
706  if (ruby_thread_has_gvl_p()) {
707  rb_raise(rb_eNoMemError, "%s", msg);
708  }
709  else {
710  if (ruby_native_thread_p()) {
712  }
713  else {
714  fprintf(stderr, "[FATAL] %s\n", msg);
715  exit(EXIT_FAILURE);
716  }
717  }
718 }
719 
720 static void *
721 gc_with_gvl(void *ptr)
722 {
723  return (void *)(VALUE)garbage_collect((rb_objspace_t *)ptr);
724 }
725 
726 static int
728 {
729  if (dont_gc) return TRUE;
730  if (ruby_thread_has_gvl_p()) {
731  return garbage_collect(objspace);
732  }
733  else {
734  if (ruby_native_thread_p()) {
735  return (int)(VALUE)rb_thread_call_with_gvl(gc_with_gvl, (void *)objspace);
736  }
737  else {
738  /* no ruby thread */
739  fprintf(stderr, "[FATAL] failed to allocate memory\n");
740  exit(EXIT_FAILURE);
741  }
742  }
743 }
744 
745 static void vm_xfree(rb_objspace_t *objspace, void *ptr);
746 
747 static inline size_t
749 {
750  if ((ssize_t)size < 0) {
751  negative_size_allocation_error("negative allocation size (or too big)");
752  }
753  if (size == 0) size = 1;
754 
755 #if CALC_EXACT_MALLOC_SIZE
756  size += sizeof(size_t);
757 #endif
758 
761  garbage_collect_with_gvl(objspace);
762  }
763 
764  return size;
765 }
766 
767 static inline void *
768 vm_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size)
769 {
771 
772 #if CALC_EXACT_MALLOC_SIZE
773  objspace->malloc_params.allocated_size += size;
774  objspace->malloc_params.allocations++;
775  ((size_t *)mem)[0] = size;
776  mem = (size_t *)mem + 1;
777 #endif
778 
779  return mem;
780 }
781 
782 #define TRY_WITH_GC(alloc) do { \
783  if (!(alloc) && \
784  (!garbage_collect_with_gvl(objspace) || \
785  !(alloc))) { \
786  ruby_memerror(); \
787  } \
788  } while (0)
789 
790 static void *
791 vm_xmalloc(rb_objspace_t *objspace, size_t size)
792 {
793  void *mem;
794 
795  size = vm_malloc_prepare(objspace, size);
796  TRY_WITH_GC(mem = malloc(size));
797  return vm_malloc_fixup(objspace, mem, size);
798 }
799 
800 static void *
801 vm_xrealloc(rb_objspace_t *objspace, void *ptr, size_t size)
802 {
803  void *mem;
804 
805  if ((ssize_t)size < 0) {
806  negative_size_allocation_error("negative re-allocation size");
807  }
808  if (!ptr) return vm_xmalloc(objspace, size);
809  if (size == 0) {
810  vm_xfree(objspace, ptr);
811  return 0;
812  }
814  garbage_collect_with_gvl(objspace);
815 
816 #if CALC_EXACT_MALLOC_SIZE
817  size += sizeof(size_t);
818  objspace->malloc_params.allocated_size -= size;
819  ptr = (size_t *)ptr - 1;
820 #endif
821 
822  mem = realloc(ptr, size);
823  if (!mem) {
824  if (garbage_collect_with_gvl(objspace)) {
825  mem = realloc(ptr, size);
826  }
827  if (!mem) {
828  ruby_memerror();
829  }
830  }
832 
833 #if CALC_EXACT_MALLOC_SIZE
834  objspace->malloc_params.allocated_size += size;
835  ((size_t *)mem)[0] = size;
836  mem = (size_t *)mem + 1;
837 #endif
838 
839  return mem;
840 }
841 
842 static void
843 vm_xfree(rb_objspace_t *objspace, void *ptr)
844 {
845 #if CALC_EXACT_MALLOC_SIZE
846  size_t size;
847  ptr = ((size_t *)ptr) - 1;
848  size = ((size_t*)ptr)[0];
849  objspace->malloc_params.allocated_size -= size;
850  objspace->malloc_params.allocations--;
851 #endif
852 
853  free(ptr);
854 }
855 
856 void *
858 {
859  return vm_xmalloc(&rb_objspace, size);
860 }
861 
862 static inline size_t
863 xmalloc2_size(size_t n, size_t size)
864 {
865  size_t len = size * n;
866  if (n != 0 && size != len / n) {
867  rb_raise(rb_eArgError, "malloc: possible integer overflow");
868  }
869  return len;
870 }
871 
872 void *
873 ruby_xmalloc2(size_t n, size_t size)
874 {
875  return vm_xmalloc(&rb_objspace, xmalloc2_size(n, size));
876 }
877 
878 static void *
879 vm_xcalloc(rb_objspace_t *objspace, size_t count, size_t elsize)
880 {
881  void *mem;
882  size_t size;
883 
884  size = xmalloc2_size(count, elsize);
885  size = vm_malloc_prepare(objspace, size);
886 
887  TRY_WITH_GC(mem = calloc(1, size));
888  return vm_malloc_fixup(objspace, mem, size);
889 }
890 
891 void *
892 ruby_xcalloc(size_t n, size_t size)
893 {
894  return vm_xcalloc(&rb_objspace, n, size);
895 }
896 
897 void *
898 ruby_xrealloc(void *ptr, size_t size)
899 {
900  return vm_xrealloc(&rb_objspace, ptr, size);
901 }
902 
903 void *
904 ruby_xrealloc2(void *ptr, size_t n, size_t size)
905 {
906  size_t len = size * n;
907  if (n != 0 && size != len / n) {
908  rb_raise(rb_eArgError, "realloc: possible integer overflow");
909  }
910  return ruby_xrealloc(ptr, len);
911 }
912 
913 void
914 ruby_xfree(void *x)
915 {
916  if (x)
917  vm_xfree(&rb_objspace, x);
918 }
919 
920 
921 /*
922  * call-seq:
923  * GC.enable -> true or false
924  *
925  * Enables garbage collection, returning <code>true</code> if garbage
926  * collection was previously disabled.
927  *
928  * GC.disable #=> false
929  * GC.enable #=> true
930  * GC.enable #=> false
931  *
932  */
933 
934 VALUE
936 {
937  rb_objspace_t *objspace = &rb_objspace;
938  int old = dont_gc;
939 
940  dont_gc = FALSE;
941  return old ? Qtrue : Qfalse;
942 }
943 
944 /*
945  * call-seq:
946  * GC.disable -> true or false
947  *
948  * Disables garbage collection, returning <code>true</code> if garbage
949  * collection was already disabled.
950  *
951  * GC.disable #=> false
952  * GC.disable #=> true
953  *
954  */
955 
956 VALUE
958 {
959  rb_objspace_t *objspace = &rb_objspace;
960  int old = dont_gc;
961 
962  dont_gc = TRUE;
963  return old ? Qtrue : Qfalse;
964 }
965 
967 
968 void
970 {
971  VALUE ary = GET_THREAD()->vm->mark_object_ary;
972  rb_ary_push(ary, obj);
973 }
974 
975 void
977 {
978  rb_objspace_t *objspace = &rb_objspace;
979  struct gc_list *tmp;
980 
981  tmp = ALLOC(struct gc_list);
982  tmp->next = global_List;
983  tmp->varptr = addr;
984  global_List = tmp;
985 }
986 
987 void
989 {
990  rb_objspace_t *objspace = &rb_objspace;
991  struct gc_list *tmp = global_List;
992 
993  if (tmp->varptr == addr) {
994  global_List = tmp->next;
995  xfree(tmp);
996  return;
997  }
998  while (tmp->next) {
999  if (tmp->next->varptr == addr) {
1000  struct gc_list *t = tmp->next;
1001 
1002  tmp->next = tmp->next->next;
1003  xfree(t);
1004  break;
1005  }
1006  tmp = tmp->next;
1007  }
1008 }
1009 
1010 
1011 static void
1012 allocate_sorted_heaps(rb_objspace_t *objspace, size_t next_heaps_length)
1013 {
1014  struct sorted_heaps_slot *p;
1015  size_t size;
1016 
1017  size = next_heaps_length*sizeof(struct sorted_heaps_slot);
1018 
1019  if (heaps_used > 0) {
1020  p = (struct sorted_heaps_slot *)realloc(objspace->heap.sorted, size);
1021  if (p) objspace->heap.sorted = p;
1022  }
1023  else {
1024  p = objspace->heap.sorted = (struct sorted_heaps_slot *)malloc(size);
1025  }
1026 
1027  if (p == 0) {
1028  during_gc = 0;
1029  rb_memerror();
1030  }
1031  heaps_length = next_heaps_length;
1032 }
1033 
1034 static void
1036 {
1037  RVALUE *p, *pend, *membase;
1038  struct heaps_slot *slot;
1039  size_t hi, lo, mid;
1040  size_t objs;
1041 
1042  objs = HEAP_OBJ_LIMIT;
1043  p = (RVALUE*)malloc(HEAP_SIZE);
1044  if (p == 0) {
1045  during_gc = 0;
1046  rb_memerror();
1047  }
1048  slot = (struct heaps_slot *)malloc(sizeof(struct heaps_slot));
1049  if (slot == 0) {
1050  xfree(p);
1051  during_gc = 0;
1052  rb_memerror();
1053  }
1054  MEMZERO((void*)slot, struct heaps_slot, 1);
1055 
1056  slot->next = heaps;
1057  if (heaps) heaps->prev = slot;
1058  heaps = slot;
1059 
1060  membase = p;
1061  if ((VALUE)p % sizeof(RVALUE) != 0) {
1062  p = (RVALUE*)((VALUE)p + sizeof(RVALUE) - ((VALUE)p % sizeof(RVALUE)));
1063  if ((HEAP_SIZE - HEAP_OBJ_LIMIT * sizeof(RVALUE)) < (size_t)((char*)p - (char*)membase)) {
1064  objs--;
1065  }
1066  }
1067 
1068  lo = 0;
1069  hi = heaps_used;
1070  while (lo < hi) {
1071  register RVALUE *mid_membase;
1072  mid = (lo + hi) / 2;
1073  mid_membase = objspace->heap.sorted[mid].slot->membase;
1074  if (mid_membase < membase) {
1075  lo = mid + 1;
1076  }
1077  else if (mid_membase > membase) {
1078  hi = mid;
1079  }
1080  else {
1081  rb_bug("same heap slot is allocated: %p at %"PRIuVALUE, (void *)membase, (VALUE)mid);
1082  }
1083  }
1084  if (hi < heaps_used) {
1085  MEMMOVE(&objspace->heap.sorted[hi+1], &objspace->heap.sorted[hi], struct sorted_heaps_slot, heaps_used - hi);
1086  }
1087  objspace->heap.sorted[hi].slot = slot;
1088  objspace->heap.sorted[hi].start = p;
1089  objspace->heap.sorted[hi].end = (p + objs);
1090  heaps->membase = membase;
1091  heaps->slot = p;
1092  heaps->limit = objs;
1093  objspace->heap.free_num += objs;
1094  pend = p + objs;
1095  if (lomem == 0 || lomem > p) lomem = p;
1096  if (himem < pend) himem = pend;
1097  heaps_used++;
1098 
1099  while (p < pend) {
1100  p->as.free.flags = 0;
1101  p->as.free.next = freelist;
1102  freelist = p;
1103  p++;
1104  }
1105 }
1106 
1107 static void
1109 {
1110  size_t i;
1111 
1112  if ((heaps_used + add) > heaps_length) {
1113  allocate_sorted_heaps(objspace, heaps_used + add);
1114  }
1115 
1116  for (i = 0; i < add; i++) {
1117  assign_heap_slot(objspace);
1118  }
1119  heaps_inc = 0;
1120 }
1121 
1122 static void
1124 {
1126  init_mark_stack(&objspace->mark_stack);
1127 #ifdef USE_SIGALTSTACK
1128  {
1129  /* altstack of another threads are allocated in another place */
1130  rb_thread_t *th = GET_THREAD();
1131  void *tmp = th->altstack;
1132  th->altstack = malloc(ALT_STACK_SIZE);
1133  free(tmp); /* free previously allocated area */
1134  }
1135 #endif
1136 
1137  objspace->profile.invoke_time = getrusage_time();
1139 }
1140 
1141 static void
1143 {
1144  size_t min_size = initial_heap_min_slots / HEAP_OBJ_LIMIT;
1145 
1146  if (min_size > heaps_used) {
1147  add_heap_slots(objspace, min_size - heaps_used);
1148  }
1149 }
1150 
1151 static void
1153 {
1154  size_t next_heaps_length = (size_t)(heaps_used * 1.8);
1155 
1156  if (next_heaps_length == heaps_used) {
1157  next_heaps_length++;
1158  }
1159 
1160  heaps_inc = next_heaps_length - heaps_used;
1161 
1162  if (next_heaps_length > heaps_length) {
1163  allocate_sorted_heaps(objspace, next_heaps_length);
1164  }
1165 }
1166 
1167 static int
1169 {
1170  if (heaps_inc > 0) {
1171  assign_heap_slot(objspace);
1172  heaps_inc--;
1173  return TRUE;
1174  }
1175  return FALSE;
1176 }
1177 
1178 int
1180 {
1181  rb_objspace_t *objspace = &rb_objspace;
1182  return during_gc;
1183 }
1184 
1185 #define RANY(o) ((RVALUE*)(o))
1186 
1187 VALUE
1189 {
1190  rb_objspace_t *objspace = &rb_objspace;
1191  VALUE obj;
1192 
1193  if (UNLIKELY(during_gc)) {
1194  dont_gc = 1;
1195  during_gc = 0;
1196  rb_bug("object allocation during garbage collection phase");
1197  }
1198 
1200  if (!garbage_collect(objspace)) {
1201  during_gc = 0;
1202  rb_memerror();
1203  }
1204  }
1205 
1206  if (UNLIKELY(!freelist)) {
1207  if (!gc_lazy_sweep(objspace)) {
1208  during_gc = 0;
1209  rb_memerror();
1210  }
1211  }
1212 
1213  obj = (VALUE)freelist;
1214  freelist = freelist->as.free.next;
1215 
1216  MEMZERO((void*)obj, RVALUE, 1);
1217 #ifdef GC_DEBUG
1218  RANY(obj)->file = rb_sourcefile();
1219  RANY(obj)->line = rb_sourceline();
1220 #endif
1222 
1223  return obj;
1224 }
1225 
1226 NODE*
1228 {
1229  NODE *n = (NODE*)rb_newobj();
1230 
1231  n->flags |= T_NODE;
1232  nd_set_type(n, type);
1233 
1234  n->u1.value = a0;
1235  n->u2.value = a1;
1236  n->u3.value = a2;
1237 
1238  return n;
1239 }
1240 
1241 VALUE
1242 rb_data_object_alloc(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
1243 {
1244  NEWOBJ(data, struct RData);
1245  if (klass) Check_Type(klass, T_CLASS);
1246  OBJSETUP(data, klass, T_DATA);
1247  data->data = datap;
1248  data->dfree = dfree;
1249  data->dmark = dmark;
1250 
1251  return (VALUE)data;
1252 }
1253 
1254 VALUE
1256 {
1257  NEWOBJ(data, struct RTypedData);
1258 
1259  if (klass) Check_Type(klass, T_CLASS);
1260 
1261  OBJSETUP(data, klass, T_DATA);
1262 
1263  data->data = datap;
1264  data->typed_flag = 1;
1265  data->type = type;
1266 
1267  return (VALUE)data;
1268 }
1269 
1270 size_t
1272 {
1273  if (RTYPEDDATA_P(obj) && RTYPEDDATA_TYPE(obj)->function.dsize) {
1274  return RTYPEDDATA_TYPE(obj)->function.dsize(RTYPEDDATA_DATA(obj));
1275  }
1276  else {
1277  return 0;
1278  }
1279 }
1280 
1281 const char *
1283 {
1284  if (RTYPEDDATA_P(obj)) {
1285  return RTYPEDDATA_TYPE(obj)->wrap_struct_name;
1286  }
1287  else {
1288  return 0;
1289  }
1290 }
1291 
1292 #ifdef __ia64
1293 #define SET_STACK_END (SET_MACHINE_STACK_END(&th->machine_stack_end), th->machine_register_stack_end = rb_ia64_bsp())
1294 #else
1295 #define SET_STACK_END SET_MACHINE_STACK_END(&th->machine_stack_end)
1296 #endif
1297 
1298 #define STACK_START (th->machine_stack_start)
1299 #define STACK_END (th->machine_stack_end)
1300 #define STACK_LEVEL_MAX (th->machine_stack_maxsize/sizeof(VALUE))
1301 
1302 #if STACK_GROW_DIRECTION < 0
1303 # define STACK_LENGTH (size_t)(STACK_START - STACK_END)
1304 #elif STACK_GROW_DIRECTION > 0
1305 # define STACK_LENGTH (size_t)(STACK_END - STACK_START + 1)
1306 #else
1307 # define STACK_LENGTH ((STACK_END < STACK_START) ? (size_t)(STACK_START - STACK_END) \
1308  : (size_t)(STACK_END - STACK_START + 1))
1309 #endif
1310 #if !STACK_GROW_DIRECTION
1312 int
1314 {
1315  VALUE *end;
1316  SET_MACHINE_STACK_END(&end);
1317 
1318  if (end > addr) return ruby_stack_grow_direction = 1;
1319  return ruby_stack_grow_direction = -1;
1320 }
1321 #endif
1322 
1323 /* Marking stack */
1324 
1325 static void push_mark_stack(mark_stack_t *, VALUE);
1326 static int pop_mark_stack(mark_stack_t *, VALUE *);
1327 static void shrink_stack_chunk_cache(mark_stack_t *stack);
1328 
1329 static stack_chunk_t *
1331 {
1332  stack_chunk_t *res;
1333 
1334  res = malloc(sizeof(stack_chunk_t));
1335  if (!res)
1336  rb_memerror();
1337 
1338  return res;
1339 }
1340 
1341 static inline int
1343 {
1344  return stack->chunk == NULL;
1345 }
1346 
1347 static void
1349 {
1350  chunk->next = stack->cache;
1351  stack->cache = chunk;
1352  stack->cache_size++;
1353 }
1354 
1355 static void
1357 {
1358  stack_chunk_t *chunk;
1359 
1360  if (stack->unused_cache_size > (stack->cache_size/2)) {
1361  chunk = stack->cache;
1362  stack->cache = stack->cache->next;
1363  stack->cache_size--;
1364  free(chunk);
1365  }
1366  stack->unused_cache_size = stack->cache_size;
1367 }
1368 
1369 static void
1371 {
1373 
1374  if (stack->cache_size > 0) {
1375  next = stack->cache;
1376  stack->cache = stack->cache->next;
1377  stack->cache_size--;
1378  if (stack->unused_cache_size > stack->cache_size)
1379  stack->unused_cache_size = stack->cache_size;
1380  }
1381  else {
1382  next = stack_chunk_alloc();
1383  }
1384  next->next = stack->chunk;
1385  stack->chunk = next;
1386  stack->index = 0;
1387 }
1388 
1389 static void
1391 {
1393 
1394  prev = stack->chunk->next;
1395  add_stack_chunk_cache(stack, stack->chunk);
1396  stack->chunk = prev;
1397  stack->index = stack->limit;
1398 }
1399 
1400 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
1401 static void
1403 {
1404  stack_chunk_t *chunk = stack->chunk;
1405  stack_chunk_t *next = NULL;
1406 
1407  while (chunk != NULL) {
1408  next = chunk->next;
1409  free(chunk);
1410  chunk = next;
1411  }
1412 }
1413 #endif
1414 
1415 static void
1417 {
1418  if (stack->index == stack->limit) {
1419  push_mark_stack_chunk(stack);
1420  }
1421  stack->chunk->data[stack->index++] = data;
1422 }
1423 
1424 static int
1426 {
1427  if (is_mark_stask_empty(stack)) {
1428  return FALSE;
1429  }
1430  if (stack->index == 1) {
1431  *data = stack->chunk->data[--stack->index];
1432  pop_mark_stack_chunk(stack);
1433  return TRUE;
1434  }
1435  *data = stack->chunk->data[--stack->index];
1436  return TRUE;
1437 }
1438 
1439 static void
1441 {
1442  int i;
1443 
1444  push_mark_stack_chunk(stack);
1445  stack->limit = STACK_CHUNK_SIZE;
1446 
1447  for(i=0; i < 4; i++) {
1449  }
1450  stack->unused_cache_size = stack->cache_size;
1451 }
1452 
1453 
1454 size_t
1456 {
1457  rb_thread_t *th = GET_THREAD();
1458  SET_STACK_END;
1459  if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END);
1460  return STACK_LENGTH;
1461 }
1462 
1463 #if !(defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK))
1464 static int
1465 stack_check(int water_mark)
1466 {
1467  int ret;
1468  rb_thread_t *th = GET_THREAD();
1469  SET_STACK_END;
1470  ret = STACK_LENGTH > STACK_LEVEL_MAX - water_mark;
1471 #ifdef __ia64
1472  if (!ret) {
1473  ret = (VALUE*)rb_ia64_bsp() - th->machine_register_stack_start >
1474  th->machine_register_stack_maxsize/sizeof(VALUE) - water_mark;
1475  }
1476 #endif
1477  return ret;
1478 }
1479 #endif
1480 
1481 #define STACKFRAME_FOR_CALL_CFUNC 512
1482 
1483 int
1485 {
1486 #if defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK)
1487  return 0;
1488 #else
1490 #endif
1491 }
1492 
1493 #define MARK_STACK_EMPTY (mark_stack_ptr == mark_stack)
1494 
1495 static void gc_mark(rb_objspace_t *objspace, VALUE ptr);
1496 static void gc_mark_children(rb_objspace_t *objspace, VALUE ptr);
1497 
1498 static void
1500 {
1501  mark_stack_t *mstack = &objspace->mark_stack;
1502  VALUE obj = 0;
1503 
1504  if (!mstack->index) return;
1505  while (pop_mark_stack(mstack, &obj)) {
1506  gc_mark_children(objspace, obj);
1507  }
1508  shrink_stack_chunk_cache(mstack);
1509 }
1510 
1511 static inline int
1512 is_pointer_to_heap(rb_objspace_t *objspace, void *ptr)
1513 {
1514  register RVALUE *p = RANY(ptr);
1515  register struct sorted_heaps_slot *heap;
1516  register size_t hi, lo, mid;
1517 
1518  if (p < lomem || p > himem) return FALSE;
1519  if ((VALUE)p % sizeof(RVALUE) != 0) return FALSE;
1520 
1521  /* check if p looks like a pointer using bsearch*/
1522  lo = 0;
1523  hi = heaps_used;
1524  while (lo < hi) {
1525  mid = (lo + hi) / 2;
1526  heap = &objspace->heap.sorted[mid];
1527  if (heap->start <= p) {
1528  if (p < heap->end)
1529  return TRUE;
1530  lo = mid + 1;
1531  }
1532  else {
1533  hi = mid;
1534  }
1535  }
1536  return FALSE;
1537 }
1538 
1539 static void
1540 mark_locations_array(rb_objspace_t *objspace, register VALUE *x, register long n)
1541 {
1542  VALUE v;
1543  while (n--) {
1544  v = *x;
1545  VALGRIND_MAKE_MEM_DEFINED(&v, sizeof(v));
1546  if (is_pointer_to_heap(objspace, (void *)v)) {
1547  gc_mark(objspace, v);
1548  }
1549  x++;
1550  }
1551 }
1552 
1553 static void
1555 {
1556  long n;
1557 
1558  if (end <= start) return;
1559  n = end - start;
1560  mark_locations_array(objspace, start, n);
1561 }
1562 
1563 void
1565 {
1566  gc_mark_locations(&rb_objspace, start, end);
1567 }
1568 
1569 #define rb_gc_mark_locations(start, end) gc_mark_locations(objspace, (start), (end))
1570 
1573 };
1574 
1575 static int
1577 {
1578  struct mark_tbl_arg *arg = (void*)data;
1579  gc_mark(arg->objspace, value);
1580  return ST_CONTINUE;
1581 }
1582 
1583 static void
1585 {
1586  struct mark_tbl_arg arg;
1587  if (!tbl || tbl->num_entries == 0) return;
1588  arg.objspace = objspace;
1589  st_foreach(tbl, mark_entry, (st_data_t)&arg);
1590 }
1591 
1592 static int
1594 {
1595  struct mark_tbl_arg *arg = (void*)data;
1596  gc_mark(arg->objspace, key);
1597  return ST_CONTINUE;
1598 }
1599 
1600 static void
1602 {
1603  struct mark_tbl_arg arg;
1604  if (!tbl) return;
1605  arg.objspace = objspace;
1606  st_foreach(tbl, mark_key, (st_data_t)&arg);
1607 }
1608 
1609 void
1611 {
1612  mark_set(&rb_objspace, tbl);
1613 }
1614 
1615 static int
1617 {
1618  struct mark_tbl_arg *arg = (void*)data;
1619  gc_mark(arg->objspace, key);
1620  gc_mark(arg->objspace, value);
1621  return ST_CONTINUE;
1622 }
1623 
1624 static void
1626 {
1627  struct mark_tbl_arg arg;
1628  if (!tbl) return;
1629  arg.objspace = objspace;
1630  st_foreach(tbl, mark_keyvalue, (st_data_t)&arg);
1631 }
1632 
1633 void
1635 {
1636  mark_hash(&rb_objspace, tbl);
1637 }
1638 
1639 static void
1641 {
1642  const rb_method_definition_t *def = me->def;
1643 
1644  gc_mark(objspace, me->klass);
1645  if (!def) return;
1646  switch (def->type) {
1647  case VM_METHOD_TYPE_ISEQ:
1648  gc_mark(objspace, def->body.iseq->self);
1649  break;
1651  gc_mark(objspace, def->body.proc);
1652  break;
1654  case VM_METHOD_TYPE_IVAR:
1655  gc_mark(objspace, def->body.attr.location);
1656  break;
1657  default:
1658  break; /* ignore */
1659  }
1660 }
1661 
1662 void
1664 {
1665  mark_method_entry(&rb_objspace, me);
1666 }
1667 
1668 static int
1670 {
1671  struct mark_tbl_arg *arg = (void*)data;
1672  mark_method_entry(arg->objspace, me);
1673  return ST_CONTINUE;
1674 }
1675 
1676 static void
1678 {
1679  struct mark_tbl_arg arg;
1680  if (!tbl) return;
1681  arg.objspace = objspace;
1683 }
1684 
1685 static int
1687 {
1688  if (!me->mark) {
1690  }
1691  return ST_CONTINUE;
1692 }
1693 
1694 void
1696 {
1698  st_free_table(tbl);
1699 }
1700 
1701 static int
1703 {
1704  struct mark_tbl_arg *arg = (void*)data;
1705  gc_mark(arg->objspace, ce->value);
1706  return ST_CONTINUE;
1707 }
1708 
1709 static void
1711 {
1712  struct mark_tbl_arg arg;
1713  if (!tbl) return;
1714  arg.objspace = objspace;
1716 }
1717 
1718 static int
1720 {
1721  xfree(ce);
1722  return ST_CONTINUE;
1723 }
1724 
1725 void
1727 {
1728  st_foreach(tbl, free_const_entry_i, 0);
1729  st_free_table(tbl);
1730 }
1731 
1732 void
1734 {
1735  mark_tbl(&rb_objspace, tbl);
1736 }
1737 
1738 void
1740 {
1741  if (is_pointer_to_heap(&rb_objspace, (void *)obj)) {
1742  gc_mark(&rb_objspace, obj);
1743  }
1744 }
1745 
1746 static void
1748 {
1749  register RVALUE *obj;
1750 
1751  obj = RANY(ptr);
1752  if (rb_special_const_p(ptr)) return; /* special const not marked */
1753  if (obj->as.basic.flags == 0) return; /* free cell */
1754  if (obj->as.basic.flags & FL_MARK) return; /* already marked */
1755  obj->as.basic.flags |= FL_MARK;
1756  objspace->heap.live_num++;
1757 
1758  push_mark_stack(&objspace->mark_stack, ptr);
1759 }
1760 
1761 void
1763 {
1764  gc_mark(&rb_objspace, ptr);
1765 }
1766 
1767 static void
1769 {
1770  register RVALUE *obj = RANY(ptr);
1771 
1772  goto marking; /* skip */
1773 
1774  again:
1775  obj = RANY(ptr);
1776  if (rb_special_const_p(ptr)) return; /* special const not marked */
1777  if (obj->as.basic.flags == 0) return; /* free cell */
1778  if (obj->as.basic.flags & FL_MARK) return; /* already marked */
1779  obj->as.basic.flags |= FL_MARK;
1780  objspace->heap.live_num++;
1781 
1782  marking:
1783  if (FL_TEST(obj, FL_EXIVAR)) {
1784  rb_mark_generic_ivar(ptr);
1785  }
1786 
1787  switch (BUILTIN_TYPE(obj)) {
1788  case T_NIL:
1789  case T_FIXNUM:
1790  rb_bug("rb_gc_mark() called for broken object");
1791  break;
1792 
1793  case T_NODE:
1794  switch (nd_type(obj)) {
1795  case NODE_IF: /* 1,2,3 */
1796  case NODE_FOR:
1797  case NODE_ITER:
1798  case NODE_WHEN:
1799  case NODE_MASGN:
1800  case NODE_RESCUE:
1801  case NODE_RESBODY:
1802  case NODE_CLASS:
1803  case NODE_BLOCK_PASS:
1804  gc_mark(objspace, (VALUE)obj->as.node.u2.node);
1805  /* fall through */
1806  case NODE_BLOCK: /* 1,3 */
1807  case NODE_OPTBLOCK:
1808  case NODE_ARRAY:
1809  case NODE_DSTR:
1810  case NODE_DXSTR:
1811  case NODE_DREGX:
1812  case NODE_DREGX_ONCE:
1813  case NODE_ENSURE:
1814  case NODE_CALL:
1815  case NODE_DEFS:
1816  case NODE_OP_ASGN1:
1817  case NODE_ARGS:
1818  gc_mark(objspace, (VALUE)obj->as.node.u1.node);
1819  /* fall through */
1820  case NODE_SUPER: /* 3 */
1821  case NODE_FCALL:
1822  case NODE_DEFN:
1823  case NODE_ARGS_AUX:
1824  ptr = (VALUE)obj->as.node.u3.node;
1825  goto again;
1826 
1827  case NODE_WHILE: /* 1,2 */
1828  case NODE_UNTIL:
1829  case NODE_AND:
1830  case NODE_OR:
1831  case NODE_CASE:
1832  case NODE_SCLASS:
1833  case NODE_DOT2:
1834  case NODE_DOT3:
1835  case NODE_FLIP2:
1836  case NODE_FLIP3:
1837  case NODE_MATCH2:
1838  case NODE_MATCH3:
1839  case NODE_OP_ASGN_OR:
1840  case NODE_OP_ASGN_AND:
1841  case NODE_MODULE:
1842  case NODE_ALIAS:
1843  case NODE_VALIAS:
1844  case NODE_ARGSCAT:
1845  gc_mark(objspace, (VALUE)obj->as.node.u1.node);
1846  /* fall through */
1847  case NODE_GASGN: /* 2 */
1848  case NODE_LASGN:
1849  case NODE_DASGN:
1850  case NODE_DASGN_CURR:
1851  case NODE_IASGN:
1852  case NODE_IASGN2:
1853  case NODE_CVASGN:
1854  case NODE_COLON3:
1855  case NODE_OPT_N:
1856  case NODE_EVSTR:
1857  case NODE_UNDEF:
1858  case NODE_POSTEXE:
1859  ptr = (VALUE)obj->as.node.u2.node;
1860  goto again;
1861 
1862  case NODE_HASH: /* 1 */
1863  case NODE_LIT:
1864  case NODE_STR:
1865  case NODE_XSTR:
1866  case NODE_DEFINED:
1867  case NODE_MATCH:
1868  case NODE_RETURN:
1869  case NODE_BREAK:
1870  case NODE_NEXT:
1871  case NODE_YIELD:
1872  case NODE_COLON2:
1873  case NODE_SPLAT:
1874  case NODE_TO_ARY:
1875  ptr = (VALUE)obj->as.node.u1.node;
1876  goto again;
1877 
1878  case NODE_SCOPE: /* 2,3 */
1879  case NODE_CDECL:
1880  case NODE_OPT_ARG:
1881  gc_mark(objspace, (VALUE)obj->as.node.u3.node);
1882  ptr = (VALUE)obj->as.node.u2.node;
1883  goto again;
1884 
1885  case NODE_ZARRAY: /* - */
1886  case NODE_ZSUPER:
1887  case NODE_VCALL:
1888  case NODE_GVAR:
1889  case NODE_LVAR:
1890  case NODE_DVAR:
1891  case NODE_IVAR:
1892  case NODE_CVAR:
1893  case NODE_NTH_REF:
1894  case NODE_BACK_REF:
1895  case NODE_REDO:
1896  case NODE_RETRY:
1897  case NODE_SELF:
1898  case NODE_NIL:
1899  case NODE_TRUE:
1900  case NODE_FALSE:
1901  case NODE_ERRINFO:
1902  case NODE_BLOCK_ARG:
1903  break;
1904  case NODE_ALLOCA:
1905  mark_locations_array(objspace,
1906  (VALUE*)obj->as.node.u1.value,
1907  obj->as.node.u3.cnt);
1908  ptr = (VALUE)obj->as.node.u2.node;
1909  goto again;
1910 
1911  default: /* unlisted NODE */
1912  if (is_pointer_to_heap(objspace, obj->as.node.u1.node)) {
1913  gc_mark(objspace, (VALUE)obj->as.node.u1.node);
1914  }
1915  if (is_pointer_to_heap(objspace, obj->as.node.u2.node)) {
1916  gc_mark(objspace, (VALUE)obj->as.node.u2.node);
1917  }
1918  if (is_pointer_to_heap(objspace, obj->as.node.u3.node)) {
1919  gc_mark(objspace, (VALUE)obj->as.node.u3.node);
1920  }
1921  }
1922  return; /* no need to mark class. */
1923  }
1924 
1925  gc_mark(objspace, obj->as.basic.klass);
1926  switch (BUILTIN_TYPE(obj)) {
1927  case T_ICLASS:
1928  case T_CLASS:
1929  case T_MODULE:
1930  mark_m_tbl(objspace, RCLASS_M_TBL(obj));
1931  mark_tbl(objspace, RCLASS_IV_TBL(obj));
1932  mark_const_tbl(objspace, RCLASS_CONST_TBL(obj));
1933  ptr = RCLASS_SUPER(obj);
1934  goto again;
1935 
1936  case T_ARRAY:
1937  if (FL_TEST(obj, ELTS_SHARED)) {
1938  ptr = obj->as.array.as.heap.aux.shared;
1939  goto again;
1940  }
1941  else {
1942  long i, len = RARRAY_LEN(obj);
1943  VALUE *ptr = RARRAY_PTR(obj);
1944  for (i=0; i < len; i++) {
1945  gc_mark(objspace, *ptr++);
1946  }
1947  }
1948  break;
1949 
1950  case T_HASH:
1951  mark_hash(objspace, obj->as.hash.ntbl);
1952  ptr = obj->as.hash.ifnone;
1953  goto again;
1954 
1955  case T_STRING:
1956 #define STR_ASSOC FL_USER3 /* copied from string.c */
1957  if (FL_TEST(obj, RSTRING_NOEMBED) && FL_ANY(obj, ELTS_SHARED|STR_ASSOC)) {
1958  ptr = obj->as.string.as.heap.aux.shared;
1959  goto again;
1960  }
1961  break;
1962 
1963  case T_DATA:
1964  if (RTYPEDDATA_P(obj)) {
1965  RUBY_DATA_FUNC mark_func = obj->as.typeddata.type->function.dmark;
1966  if (mark_func) (*mark_func)(DATA_PTR(obj));
1967  }
1968  else {
1969  if (obj->as.data.dmark) (*obj->as.data.dmark)(DATA_PTR(obj));
1970  }
1971  break;
1972 
1973  case T_OBJECT:
1974  {
1975  long i, len = ROBJECT_NUMIV(obj);
1976  VALUE *ptr = ROBJECT_IVPTR(obj);
1977  for (i = 0; i < len; i++) {
1978  gc_mark(objspace, *ptr++);
1979  }
1980  }
1981  break;
1982 
1983  case T_FILE:
1984  if (obj->as.file.fptr) {
1985  gc_mark(objspace, obj->as.file.fptr->pathv);
1986  gc_mark(objspace, obj->as.file.fptr->tied_io_for_writing);
1987  gc_mark(objspace, obj->as.file.fptr->writeconv_asciicompat);
1988  gc_mark(objspace, obj->as.file.fptr->writeconv_pre_ecopts);
1989  gc_mark(objspace, obj->as.file.fptr->encs.ecopts);
1990  gc_mark(objspace, obj->as.file.fptr->write_lock);
1991  }
1992  break;
1993 
1994  case T_REGEXP:
1995  ptr = obj->as.regexp.src;
1996  goto again;
1997 
1998  case T_FLOAT:
1999  case T_BIGNUM:
2000  case T_ZOMBIE:
2001  break;
2002 
2003  case T_MATCH:
2004  gc_mark(objspace, obj->as.match.regexp);
2005  if (obj->as.match.str) {
2006  ptr = obj->as.match.str;
2007  goto again;
2008  }
2009  break;
2010 
2011  case T_RATIONAL:
2012  gc_mark(objspace, obj->as.rational.num);
2013  ptr = obj->as.rational.den;
2014  goto again;
2015 
2016  case T_COMPLEX:
2017  gc_mark(objspace, obj->as.complex.real);
2018  ptr = obj->as.complex.imag;
2019  goto again;
2020 
2021  case T_STRUCT:
2022  {
2023  long len = RSTRUCT_LEN(obj);
2024  VALUE *ptr = RSTRUCT_PTR(obj);
2025 
2026  while (len--) {
2027  gc_mark(objspace, *ptr++);
2028  }
2029  }
2030  break;
2031 
2032  default:
2033  rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
2034  BUILTIN_TYPE(obj), (void *)obj,
2035  is_pointer_to_heap(objspace, obj) ? "corrupted object" : "non object");
2036  }
2037 }
2038 
2039 static int obj_free(rb_objspace_t *, VALUE);
2040 
2041 static inline void
2043 {
2044  VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
2045  p->as.free.flags = 0;
2046  p->as.free.next = freelist;
2047  freelist = p;
2048 }
2049 
2050 static void
2052 {
2053  while (p) {
2054  RVALUE *tmp = p->as.free.next;
2055  run_final(objspace, (VALUE)p);
2056  if (!FL_TEST(p, FL_SINGLETON)) { /* not freeing page */
2057  if (objspace->heap.sweep_slots) {
2058  p->as.free.flags = 0;
2059  }
2060  else {
2062  add_freelist(objspace, p);
2063  }
2064  }
2065  else {
2066  struct heaps_slot *slot = (struct heaps_slot *)(VALUE)RDATA(p)->dmark;
2067  slot->limit--;
2068  }
2069  p = tmp;
2070  }
2071 }
2072 
2073 static void
2075 {
2076  if (slot->prev)
2077  slot->prev->next = slot->next;
2078  if (slot->next)
2079  slot->next->prev = slot->prev;
2080  if (heaps == slot)
2081  heaps = slot->next;
2082  if (objspace->heap.sweep_slots == slot)
2083  objspace->heap.sweep_slots = slot->next;
2084  slot->prev = NULL;
2085  slot->next = NULL;
2086 }
2087 
2088 
2089 static void
2091 {
2092  size_t i, j;
2093  RVALUE *last = 0;
2094 
2095  for (i = j = 1; j < heaps_used; i++) {
2096  if (objspace->heap.sorted[i].slot->limit == 0) {
2097  if (!last) {
2098  last = objspace->heap.sorted[i].slot->membase;
2099  }
2100  else {
2101  free(objspace->heap.sorted[i].slot->membase);
2102  }
2103  free(objspace->heap.sorted[i].slot);
2104  heaps_used--;
2105  }
2106  else {
2107  if (i != j) {
2108  objspace->heap.sorted[j] = objspace->heap.sorted[i];
2109  }
2110  j++;
2111  }
2112  }
2113  if (last) {
2114  if (last < heaps_freed) {
2115  free(heaps_freed);
2116  heaps_freed = last;
2117  }
2118  else {
2119  free(last);
2120  }
2121  }
2122 }
2123 
2124 static void
2125 slot_sweep(rb_objspace_t *objspace, struct heaps_slot *sweep_slot)
2126 {
2127  size_t free_num = 0, final_num = 0;
2128  RVALUE *p, *pend;
2129  RVALUE *free = freelist, *final = deferred_final_list;
2130  int deferred;
2131 
2132  p = sweep_slot->slot; pend = p + sweep_slot->limit;
2133  while (p < pend) {
2134  if (!(p->as.basic.flags & FL_MARK)) {
2135  if (p->as.basic.flags &&
2136  ((deferred = obj_free(objspace, (VALUE)p)) ||
2137  (FL_TEST(p, FL_FINALIZE)))) {
2138  if (!deferred) {
2139  p->as.free.flags = T_ZOMBIE;
2140  RDATA(p)->dfree = 0;
2141  }
2142  p->as.free.flags |= FL_MARK;
2143  p->as.free.next = deferred_final_list;
2145  final_num++;
2146  }
2147  else {
2148  add_freelist(objspace, p);
2149  free_num++;
2150  }
2151  }
2152  else if (BUILTIN_TYPE(p) == T_ZOMBIE) {
2153  /* objects to be finalized */
2154  /* do nothing remain marked */
2155  }
2156  else {
2157  RBASIC(p)->flags &= ~FL_MARK;
2158  }
2159  p++;
2160  }
2161  if (final_num + free_num == sweep_slot->limit &&
2162  objspace->heap.free_num > objspace->heap.do_heap_free) {
2163  RVALUE *pp;
2164 
2165  for (pp = deferred_final_list; pp != final; pp = pp->as.free.next) {
2166  RDATA(pp)->dmark = (void (*)(void *))(VALUE)sweep_slot;
2167  pp->as.free.flags |= FL_SINGLETON; /* freeing page mark */
2168  }
2169  sweep_slot->limit = final_num;
2170  freelist = free; /* cancel this page from freelist */
2171  unlink_heap_slot(objspace, sweep_slot);
2172  }
2173  else {
2174  objspace->heap.free_num += free_num;
2175  }
2176  objspace->heap.final_num += final_num;
2177 
2178  if (deferred_final_list) {
2179  rb_thread_t *th = GET_THREAD();
2180  if (th) {
2182  }
2183  }
2184 }
2185 
2186 static int
2188 {
2189  if (dont_gc || during_gc) {
2190  if (!freelist) {
2191  if (!heaps_increment(objspace)) {
2192  set_heaps_increment(objspace);
2193  heaps_increment(objspace);
2194  }
2195  }
2196  return FALSE;
2197  }
2198  return TRUE;
2199 }
2200 
2201 static void
2203 {
2204  freelist = 0;
2205  objspace->heap.do_heap_free = (size_t)((heaps_used * HEAP_OBJ_LIMIT) * 0.65);
2206  objspace->heap.free_min = (size_t)((heaps_used * HEAP_OBJ_LIMIT) * 0.2);
2207  if (objspace->heap.free_min < initial_free_min) {
2209  objspace->heap.free_min = initial_free_min;
2210  }
2211  objspace->heap.sweep_slots = heaps;
2212  objspace->heap.free_num = 0;
2213 
2214  /* sweep unlinked method entries */
2215  if (GET_VM()->unlinked_method_entry_list) {
2217  }
2218 }
2219 
2220 static void
2222 {
2224 
2225  if (objspace->heap.free_num < objspace->heap.free_min) {
2226  set_heaps_increment(objspace);
2227  heaps_increment(objspace);
2228  }
2229 
2230  if (malloc_increase > malloc_limit) {
2231  malloc_limit += (size_t)((malloc_increase - malloc_limit) * (double)objspace->heap.live_num / (heaps_used * HEAP_OBJ_LIMIT));
2233  }
2234  malloc_increase = 0;
2235 
2236  free_unused_heaps(objspace);
2237 }
2238 
2239 static int
2241 {
2242  struct heaps_slot *next;
2243 
2244  heaps_increment(objspace);
2245  while (objspace->heap.sweep_slots) {
2246  next = objspace->heap.sweep_slots->next;
2247  slot_sweep(objspace, objspace->heap.sweep_slots);
2248  objspace->heap.sweep_slots = next;
2249  if (freelist) {
2250  during_gc = 0;
2251  return TRUE;
2252  }
2253  }
2254  return FALSE;
2255 }
2256 
2257 static void
2259 {
2260  if (objspace->heap.sweep_slots) {
2261  while (objspace->heap.sweep_slots) {
2262  lazy_sweep(objspace);
2263  }
2264  after_gc_sweep(objspace);
2265  }
2266 }
2267 
2268 static void gc_marks(rb_objspace_t *objspace);
2269 
2270 static int
2272 {
2273  int res;
2275 
2276  if (objspace->flags.dont_lazy_sweep)
2277  return garbage_collect(objspace);
2278 
2279 
2280  if (!ready_to_gc(objspace)) return TRUE;
2281 
2282  during_gc++;
2285 
2286  if (objspace->heap.sweep_slots) {
2287  res = lazy_sweep(objspace);
2288  if (res) {
2292  return res;
2293  }
2294  after_gc_sweep(objspace);
2295  }
2296  else {
2297  if (heaps_increment(objspace)) {
2298  during_gc = 0;
2299  return TRUE;
2300  }
2301  }
2302 
2303  gc_marks(objspace);
2304 
2305  before_gc_sweep(objspace);
2306  if (objspace->heap.free_min > (heaps_used * HEAP_OBJ_LIMIT - objspace->heap.live_num)) {
2307  set_heaps_increment(objspace);
2308  }
2309 
2311  if(!(res = lazy_sweep(objspace))) {
2312  after_gc_sweep(objspace);
2313  if(freelist) {
2314  res = TRUE;
2315  during_gc = 0;
2316  }
2317  }
2319 
2321  return res;
2322 }
2323 
2324 static void
2326 {
2327  struct heaps_slot *next;
2328 
2329  before_gc_sweep(objspace);
2330 
2331  while (objspace->heap.sweep_slots) {
2332  next = objspace->heap.sweep_slots->next;
2333  slot_sweep(objspace, objspace->heap.sweep_slots);
2334  objspace->heap.sweep_slots = next;
2335  }
2336 
2337  after_gc_sweep(objspace);
2338 
2339  during_gc = 0;
2340 }
2341 
2342 void
2344 {
2345  rb_objspace_t *objspace = &rb_objspace;
2347  if (RBASIC(p)->flags & FL_MARK) {
2348  RANY(p)->as.free.flags = 0;
2349  }
2350  else {
2351  add_freelist(objspace, (RVALUE *)p);
2352  }
2353 }
2354 
2355 static inline void
2357 {
2358  p->as.basic.flags = (p->as.basic.flags & ~T_MASK) | T_ZOMBIE;
2359 }
2360 
2361 static inline void
2363 {
2364  rb_io_t *fptr = p->as.file.fptr;
2365  make_deferred(p);
2366  p->as.data.dfree = (void (*)(void*))rb_io_fptr_finalize;
2367  p->as.data.data = fptr;
2368 }
2369 
2370 static int
2372 {
2373  switch (BUILTIN_TYPE(obj)) {
2374  case T_NIL:
2375  case T_FIXNUM:
2376  case T_TRUE:
2377  case T_FALSE:
2378  rb_bug("obj_free() called for broken object");
2379  break;
2380  }
2381 
2382  if (FL_TEST(obj, FL_EXIVAR)) {
2384  FL_UNSET(obj, FL_EXIVAR);
2385  }
2386 
2387  switch (BUILTIN_TYPE(obj)) {
2388  case T_OBJECT:
2389  if (!(RANY(obj)->as.basic.flags & ROBJECT_EMBED) &&
2390  RANY(obj)->as.object.as.heap.ivptr) {
2391  xfree(RANY(obj)->as.object.as.heap.ivptr);
2392  }
2393  break;
2394  case T_MODULE:
2395  case T_CLASS:
2398  if (RCLASS_IV_TBL(obj)) {
2400  }
2401  if (RCLASS_CONST_TBL(obj)) {
2403  }
2404  if (RCLASS_IV_INDEX_TBL(obj)) {
2406  }
2407  xfree(RANY(obj)->as.klass.ptr);
2408  break;
2409  case T_STRING:
2410  rb_str_free(obj);
2411  break;
2412  case T_ARRAY:
2413  rb_ary_free(obj);
2414  break;
2415  case T_HASH:
2416  if (RANY(obj)->as.hash.ntbl) {
2417  st_free_table(RANY(obj)->as.hash.ntbl);
2418  }
2419  break;
2420  case T_REGEXP:
2421  if (RANY(obj)->as.regexp.ptr) {
2422  onig_free(RANY(obj)->as.regexp.ptr);
2423  }
2424  break;
2425  case T_DATA:
2426  if (DATA_PTR(obj)) {
2427  if (RTYPEDDATA_P(obj)) {
2428  RDATA(obj)->dfree = RANY(obj)->as.typeddata.type->function.dfree;
2429  }
2430  if (RANY(obj)->as.data.dfree == (RUBY_DATA_FUNC)-1) {
2431  xfree(DATA_PTR(obj));
2432  }
2433  else if (RANY(obj)->as.data.dfree) {
2434  make_deferred(RANY(obj));
2435  return 1;
2436  }
2437  }
2438  break;
2439  case T_MATCH:
2440  if (RANY(obj)->as.match.rmatch) {
2441  struct rmatch *rm = RANY(obj)->as.match.rmatch;
2442  onig_region_free(&rm->regs, 0);
2443  if (rm->char_offset)
2444  xfree(rm->char_offset);
2445  xfree(rm);
2446  }
2447  break;
2448  case T_FILE:
2449  if (RANY(obj)->as.file.fptr) {
2450  make_io_deferred(RANY(obj));
2451  return 1;
2452  }
2453  break;
2454  case T_RATIONAL:
2455  case T_COMPLEX:
2456  break;
2457  case T_ICLASS:
2458  /* iClass shares table with the module */
2459  xfree(RANY(obj)->as.klass.ptr);
2460  break;
2461 
2462  case T_FLOAT:
2463  break;
2464 
2465  case T_BIGNUM:
2466  if (!(RBASIC(obj)->flags & RBIGNUM_EMBED_FLAG) && RBIGNUM_DIGITS(obj)) {
2467  xfree(RBIGNUM_DIGITS(obj));
2468  }
2469  break;
2470  case T_NODE:
2471  switch (nd_type(obj)) {
2472  case NODE_SCOPE:
2473  if (RANY(obj)->as.node.u1.tbl) {
2474  xfree(RANY(obj)->as.node.u1.tbl);
2475  }
2476  break;
2477  case NODE_ALLOCA:
2478  xfree(RANY(obj)->as.node.u1.node);
2479  break;
2480  }
2481  break; /* no need to free iv_tbl */
2482 
2483  case T_STRUCT:
2484  if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 &&
2485  RANY(obj)->as.rstruct.as.heap.ptr) {
2486  xfree(RANY(obj)->as.rstruct.as.heap.ptr);
2487  }
2488  break;
2489 
2490  default:
2491  rb_bug("gc_sweep(): unknown data type 0x%x(%p)",
2492  BUILTIN_TYPE(obj), (void*)obj);
2493  }
2494 
2495  return 0;
2496 }
2497 
2498 #define GC_NOTIFY 0
2499 
2500 #if STACK_GROW_DIRECTION < 0
2501 #define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_END, (end) = STACK_START)
2502 #elif STACK_GROW_DIRECTION > 0
2503 #define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_START, (end) = STACK_END+(appendix))
2504 #else
2505 #define GET_STACK_BOUNDS(start, end, appendix) \
2506  ((STACK_END < STACK_START) ? \
2507  ((start) = STACK_END, (end) = STACK_START) : ((start) = STACK_START, (end) = STACK_END+(appendix)))
2508 #endif
2509 
2510 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0]))
2511 
2512 static void
2514 {
2515  union {
2516  rb_jmp_buf j;
2517  VALUE v[sizeof(rb_jmp_buf) / sizeof(VALUE)];
2518  } save_regs_gc_mark;
2519  VALUE *stack_start, *stack_end;
2520 
2522  /* This assumes that all registers are saved into the jmp_buf (and stack) */
2523  rb_setjmp(save_regs_gc_mark.j);
2524 
2525  SET_STACK_END;
2526  GET_STACK_BOUNDS(stack_start, stack_end, 1);
2527 
2528  mark_locations_array(objspace, save_regs_gc_mark.v, numberof(save_regs_gc_mark.v));
2529 
2530  rb_gc_mark_locations(stack_start, stack_end);
2531 #ifdef __ia64
2532  rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end);
2533 #endif
2534 #if defined(__mc68000__)
2535  mark_locations_array(objspace, (VALUE*)((char*)STACK_END + 2),
2536  (STACK_START - STACK_END));
2537 #endif
2538 }
2539 
2540 static void
2542 {
2543  struct gc_list *list;
2544  rb_thread_t *th = GET_THREAD();
2546 
2547  objspace->heap.live_num = 0;
2548  objspace->count++;
2549 
2550 
2551  SET_STACK_END;
2552 
2553  th->vm->self ? rb_gc_mark(th->vm->self) : rb_vm_mark(th->vm);
2554 
2555  mark_tbl(objspace, finalizer_table);
2556  mark_current_machine_context(objspace, th);
2557 
2560 
2561  /* mark protected global variables */
2562  for (list = global_List; list; list = list->next) {
2563  rb_gc_mark_maybe(*list->varptr);
2564  }
2565  rb_mark_end_proc();
2567 
2568  mark_tbl(objspace, rb_class_tbl);
2569 
2570  /* mark generic instance variables for special constants */
2572 
2574 
2576 
2577  /* marking-loop */
2578  gc_mark_stacked_objects(objspace);
2579 
2581 }
2582 
2583 static int
2585 {
2587 
2588  if (GC_NOTIFY) printf("start garbage_collect()\n");
2589 
2590  if (!heaps) {
2591  return FALSE;
2592  }
2593  if (!ready_to_gc(objspace)) {
2594  return TRUE;
2595  }
2596 
2598 
2599  rest_sweep(objspace);
2600 
2601  during_gc++;
2602  gc_marks(objspace);
2603 
2605  gc_sweep(objspace);
2607 
2609  if (GC_NOTIFY) printf("end garbage_collect()\n");
2610  return TRUE;
2611 }
2612 
2613 int
2615 {
2616  return garbage_collect(&rb_objspace);
2617 }
2618 
2619 void
2621 {
2622  rb_objspace_t *objspace = &rb_objspace;
2623  VALUE *stack_start, *stack_end;
2624 
2625  GET_STACK_BOUNDS(stack_start, stack_end, 0);
2626  rb_gc_mark_locations(stack_start, stack_end);
2627 #ifdef __ia64
2628  rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end);
2629 #endif
2630 }
2631 
2632 
2633 /*
2634  * call-seq:
2635  * GC.start -> nil
2636  * gc.garbage_collect -> nil
2637  * ObjectSpace.garbage_collect -> nil
2638  *
2639  * Initiates garbage collection, unless manually disabled.
2640  *
2641  */
2642 
2643 VALUE
2645 {
2646  rb_gc();
2647  return Qnil;
2648 }
2649 
2650 #undef Init_stack
2651 
2652 void
2653 Init_stack(volatile VALUE *addr)
2654 {
2655  ruby_init_stack(addr);
2656 }
2657 
2658 /*
2659  * Document-class: ObjectSpace
2660  *
2661  * The <code>ObjectSpace</code> module contains a number of routines
2662  * that interact with the garbage collection facility and allow you to
2663  * traverse all living objects with an iterator.
2664  *
2665  * <code>ObjectSpace</code> also provides support for object
2666  * finalizers, procs that will be called when a specific object is
2667  * about to be destroyed by garbage collection.
2668  *
2669  * include ObjectSpace
2670  *
2671  *
2672  * a = "A"
2673  * b = "B"
2674  * c = "C"
2675  *
2676  *
2677  * define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
2678  * define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" })
2679  * define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" })
2680  *
2681  * <em>produces:</em>
2682  *
2683  * Finalizer three on 537763470
2684  * Finalizer one on 537763480
2685  * Finalizer two on 537763480
2686  *
2687  */
2688 
2689 void
2691 {
2692  init_heap(&rb_objspace);
2693 }
2694 
2695 static VALUE
2697 {
2698  rb_objspace_t *objspace = &rb_objspace;
2699 
2700  objspace->flags.dont_lazy_sweep = FALSE;
2701  return Qnil;
2702 }
2703 
2704 typedef int each_obj_callback(void *, void *, size_t, void *);
2705 
2708  void *data;
2709 };
2710 
2711 static VALUE
2713 {
2714  size_t i;
2715  RVALUE *membase = 0;
2716  RVALUE *pstart, *pend;
2717  rb_objspace_t *objspace = &rb_objspace;
2718  struct each_obj_args *args = (struct each_obj_args *)arg;
2719  volatile VALUE v;
2720 
2721  i = 0;
2722  while (i < heaps_used) {
2723  while (0 < i && (uintptr_t)membase < (uintptr_t)objspace->heap.sorted[i-1].slot->membase)
2724  i--;
2725  while (i < heaps_used && (uintptr_t)objspace->heap.sorted[i].slot->membase <= (uintptr_t)membase)
2726  i++;
2727  if (heaps_used <= i)
2728  break;
2729  membase = objspace->heap.sorted[i].slot->membase;
2730 
2731  pstart = objspace->heap.sorted[i].slot->slot;
2732  pend = pstart + objspace->heap.sorted[i].slot->limit;
2733 
2734  for (; pstart != pend; pstart++) {
2735  if (pstart->as.basic.flags) {
2736  v = (VALUE)pstart; /* acquire to save this object */
2737  break;
2738  }
2739  }
2740  if (pstart != pend) {
2741  if ((*args->callback)(pstart, pend, sizeof(RVALUE), args->data)) {
2742  break;
2743  }
2744  }
2745  }
2746 
2747  return Qnil;
2748 }
2749 
2750 /*
2751  * rb_objspace_each_objects() is special C API to walk through
2752  * Ruby object space. This C API is too difficult to use it.
2753  * To be frank, you should not use it. Or you need to read the
2754  * source code of this function and understand what this function does.
2755  *
2756  * 'callback' will be called several times (the number of heap slot,
2757  * at current implementation) with:
2758  * vstart: a pointer to the first living object of the heap_slot.
2759  * vend: a pointer to next to the valid heap_slot area.
2760  * stride: a distance to next VALUE.
2761  *
2762  * If callback() returns non-zero, the iteration will be stopped.
2763  *
2764  * This is a sample callback code to iterate liveness objects:
2765  *
2766  * int
2767  * sample_callback(void *vstart, void *vend, int stride, void *data) {
2768  * VALUE v = (VALUE)vstart;
2769  * for (; v != (VALUE)vend; v += stride) {
2770  * if (RBASIC(v)->flags) { // liveness check
2771  * // do something with live object 'v'
2772  * }
2773  * return 0; // continue to iteration
2774  * }
2775  *
2776  * Note: 'vstart' is not a top of heap_slot. This point the first
2777  * living object to grasp at least one object to avoid GC issue.
2778  * This means that you can not walk through all Ruby object slot
2779  * including freed object slot.
2780  *
2781  * Note: On this implementation, 'stride' is same as sizeof(RVALUE).
2782  * However, there are possibilities to pass variable values with
2783  * 'stride' with some reasons. You must use stride instead of
2784  * use some constant value in the iteration.
2785  */
2786 void
2788 {
2789  struct each_obj_args args;
2790  rb_objspace_t *objspace = &rb_objspace;
2791 
2792  rest_sweep(objspace);
2793  objspace->flags.dont_lazy_sweep = TRUE;
2794 
2795  args.callback = callback;
2796  args.data = data;
2798 }
2799 
2801  size_t num;
2803 };
2804 
2805 static int
2806 os_obj_of_i(void *vstart, void *vend, size_t stride, void *data)
2807 {
2808  struct os_each_struct *oes = (struct os_each_struct *)data;
2809  RVALUE *p = (RVALUE *)vstart, *pend = (RVALUE *)vend;
2810  volatile VALUE v;
2811 
2812  for (; p != pend; p++) {
2813  if (p->as.basic.flags) {
2814  switch (BUILTIN_TYPE(p)) {
2815  case T_NONE:
2816  case T_ICLASS:
2817  case T_NODE:
2818  case T_ZOMBIE:
2819  continue;
2820  case T_CLASS:
2821  if (FL_TEST(p, FL_SINGLETON))
2822  continue;
2823  default:
2824  if (!p->as.basic.klass) continue;
2825  v = (VALUE)p;
2826  if (!oes->of || rb_obj_is_kind_of(v, oes->of)) {
2827  rb_yield(v);
2828  oes->num++;
2829  }
2830  }
2831  }
2832  }
2833 
2834  return 0;
2835 }
2836 
2837 static VALUE
2839 {
2840  struct os_each_struct oes;
2841 
2842  oes.num = 0;
2843  oes.of = of;
2845  return SIZET2NUM(oes.num);
2846 }
2847 
2848 /*
2849  * call-seq:
2850  * ObjectSpace.each_object([module]) {|obj| ... } -> fixnum
2851  * ObjectSpace.each_object([module]) -> an_enumerator
2852  *
2853  * Calls the block once for each living, nonimmediate object in this
2854  * Ruby process. If <i>module</i> is specified, calls the block
2855  * for only those classes or modules that match (or are a subclass of)
2856  * <i>module</i>. Returns the number of objects found. Immediate
2857  * objects (<code>Fixnum</code>s, <code>Symbol</code>s
2858  * <code>true</code>, <code>false</code>, and <code>nil</code>) are
2859  * never returned. In the example below, <code>each_object</code>
2860  * returns both the numbers we defined and several constants defined in
2861  * the <code>Math</code> module.
2862  *
2863  * If no block is given, an enumerator is returned instead.
2864  *
2865  * a = 102.7
2866  * b = 95 # Won't be returned
2867  * c = 12345678987654321
2868  * count = ObjectSpace.each_object(Numeric) {|x| p x }
2869  * puts "Total count: #{count}"
2870  *
2871  * <em>produces:</em>
2872  *
2873  * 12345678987654321
2874  * 102.7
2875  * 2.71828182845905
2876  * 3.14159265358979
2877  * 2.22044604925031e-16
2878  * 1.7976931348623157e+308
2879  * 2.2250738585072e-308
2880  * Total count: 7
2881  *
2882  */
2883 
2884 static VALUE
2886 {
2887  VALUE of;
2888 
2889  rb_secure(4);
2890  if (argc == 0) {
2891  of = 0;
2892  }
2893  else {
2894  rb_scan_args(argc, argv, "01", &of);
2895  }
2896  RETURN_ENUMERATOR(os, 1, &of);
2897  return os_obj_of(of);
2898 }
2899 
2900 /*
2901  * call-seq:
2902  * ObjectSpace.undefine_finalizer(obj)
2903  *
2904  * Removes all finalizers for <i>obj</i>.
2905  *
2906  */
2907 
2908 static VALUE
2910 {
2911  rb_objspace_t *objspace = &rb_objspace;
2912  st_data_t data = obj;
2913  rb_check_frozen(obj);
2914  st_delete(finalizer_table, &data, 0);
2915  FL_UNSET(obj, FL_FINALIZE);
2916  return obj;
2917 }
2918 
2919 /*
2920  * call-seq:
2921  * ObjectSpace.define_finalizer(obj, aProc=proc())
2922  *
2923  * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
2924  * was destroyed.
2925  *
2926  */
2927 
2928 static VALUE
2930 {
2931  rb_objspace_t *objspace = &rb_objspace;
2932  VALUE obj, block, table;
2933  st_data_t data;
2934 
2935  rb_scan_args(argc, argv, "11", &obj, &block);
2936  rb_check_frozen(obj);
2937  if (argc == 1) {
2938  block = rb_block_proc();
2939  }
2940  else if (!rb_respond_to(block, rb_intern("call"))) {
2941  rb_raise(rb_eArgError, "wrong type argument %s (should be callable)",
2942  rb_obj_classname(block));
2943  }
2944  if (!FL_ABLE(obj)) {
2945  rb_raise(rb_eArgError, "cannot define finalizer for %s",
2946  rb_obj_classname(obj));
2947  }
2948  RBASIC(obj)->flags |= FL_FINALIZE;
2949 
2950  block = rb_ary_new3(2, INT2FIX(rb_safe_level()), block);
2951  OBJ_FREEZE(block);
2952 
2953  if (st_lookup(finalizer_table, obj, &data)) {
2954  table = (VALUE)data;
2955  rb_ary_push(table, block);
2956  }
2957  else {
2958  table = rb_ary_new3(1, block);
2959  RBASIC(table)->klass = 0;
2960  st_add_direct(finalizer_table, obj, table);
2961  }
2962  return block;
2963 }
2964 
2965 void
2967 {
2968  rb_objspace_t *objspace = &rb_objspace;
2969  VALUE table;
2970  st_data_t data;
2971 
2972  if (!FL_TEST(obj, FL_FINALIZE)) return;
2973  if (st_lookup(finalizer_table, obj, &data)) {
2974  table = (VALUE)data;
2975  st_insert(finalizer_table, dest, table);
2976  }
2977  FL_SET(dest, FL_FINALIZE);
2978 }
2979 
2980 static VALUE
2982 {
2983  VALUE *args = (VALUE *)arg;
2984  rb_eval_cmd(args[0], args[1], (int)args[2]);
2985  return Qnil;
2986 }
2987 
2988 static void
2989 run_finalizer(rb_objspace_t *objspace, VALUE objid, VALUE table)
2990 {
2991  long i;
2992  int status;
2993  VALUE args[3];
2994 
2995  if (RARRAY_LEN(table) > 0) {
2996  args[1] = rb_obj_freeze(rb_ary_new3(1, objid));
2997  }
2998  else {
2999  args[1] = 0;
3000  }
3001 
3002  args[2] = (VALUE)rb_safe_level();
3003  for (i=0; i<RARRAY_LEN(table); i++) {
3004  VALUE final = RARRAY_PTR(table)[i];
3005  args[0] = RARRAY_PTR(final)[1];
3006  args[2] = FIX2INT(RARRAY_PTR(final)[0]);
3007  status = 0;
3008  rb_protect(run_single_final, (VALUE)args, &status);
3009  if (status)
3011  }
3012 }
3013 
3014 static void
3016 {
3017  VALUE objid;
3018  RUBY_DATA_FUNC free_func = 0;
3019  st_data_t key, table;
3020 
3021  objspace->heap.final_num--;
3022 
3023  objid = rb_obj_id(obj); /* make obj into id */
3024  RBASIC(obj)->klass = 0;
3025 
3026  if (RTYPEDDATA_P(obj)) {
3027  free_func = RTYPEDDATA_TYPE(obj)->function.dfree;
3028  }
3029  else {
3030  free_func = RDATA(obj)->dfree;
3031  }
3032  if (free_func) {
3033  (*free_func)(DATA_PTR(obj));
3034  }
3035 
3036  key = (st_data_t)obj;
3037  if (st_delete(finalizer_table, &key, &table)) {
3038  run_finalizer(objspace, objid, (VALUE)table);
3039  }
3040 }
3041 
3042 static void
3044 {
3046  deferred_final_list = 0;
3047 
3048  if (p) {
3049  finalize_list(objspace, p);
3050  }
3051 }
3052 
3053 void
3055 {
3056  finalize_deferred(&rb_objspace);
3057 }
3058 
3063 };
3064 
3065 static int
3067 {
3068  struct force_finalize_list **prev = (struct force_finalize_list **)arg;
3069  struct force_finalize_list *curr = ALLOC(struct force_finalize_list);
3070  curr->obj = key;
3071  curr->table = val;
3072  curr->next = *prev;
3073  *prev = curr;
3074  return ST_CONTINUE;
3075 }
3076 
3077 void
3079 {
3080  rb_objspace_call_finalizer(&rb_objspace);
3081 }
3082 
3083 static void
3085 {
3086  RVALUE *p, *pend;
3087  RVALUE *final_list = 0;
3088  size_t i;
3089 
3090  rest_sweep(objspace);
3091 
3092  /* run finalizers */
3093  finalize_deferred(objspace);
3095 
3096  /* force to run finalizer */
3097  while (finalizer_table->num_entries) {
3098  struct force_finalize_list *list = 0;
3100  while (list) {
3101  struct force_finalize_list *curr = list;
3102  run_finalizer(objspace, rb_obj_id(curr->obj), curr->table);
3103  st_delete(finalizer_table, (st_data_t*)&curr->obj, 0);
3104  list = curr->next;
3105  xfree(curr);
3106  }
3107  }
3108 
3109  /* finalizers are part of garbage collection */
3110  during_gc++;
3111 
3112  /* run data object's finalizers */
3113  for (i = 0; i < heaps_used; i++) {
3114  p = objspace->heap.sorted[i].start; pend = objspace->heap.sorted[i].end;
3115  while (p < pend) {
3116  if (BUILTIN_TYPE(p) == T_DATA &&
3117  DATA_PTR(p) && RANY(p)->as.data.dfree &&
3119  !rb_obj_is_fiber((VALUE)p)) {
3120  p->as.free.flags = 0;
3121  if (RTYPEDDATA_P(p)) {
3122  RDATA(p)->dfree = RANY(p)->as.typeddata.type->function.dfree;
3123  }
3124  if (RANY(p)->as.data.dfree == (RUBY_DATA_FUNC)-1) {
3125  xfree(DATA_PTR(p));
3126  }
3127  else if (RANY(p)->as.data.dfree) {
3128  make_deferred(RANY(p));
3129  RANY(p)->as.free.next = final_list;
3130  final_list = p;
3131  }
3132  }
3133  else if (BUILTIN_TYPE(p) == T_FILE) {
3134  if (RANY(p)->as.file.fptr) {
3135  make_io_deferred(RANY(p));
3136  RANY(p)->as.free.next = final_list;
3137  final_list = p;
3138  }
3139  }
3140  p++;
3141  }
3142  }
3143  during_gc = 0;
3144  if (final_list) {
3145  finalize_list(objspace, final_list);
3146  }
3147 
3149  finalizer_table = 0;
3150 }
3151 
3152 void
3153 rb_gc(void)
3154 {
3155  rb_objspace_t *objspace = &rb_objspace;
3156  garbage_collect(objspace);
3157  finalize_deferred(objspace);
3158  free_unused_heaps(objspace);
3159 }
3160 
3161 /*
3162  * call-seq:
3163  * ObjectSpace._id2ref(object_id) -> an_object
3164  *
3165  * Converts an object id to a reference to the object. May not be
3166  * called on an object id passed as a parameter to a finalizer.
3167  *
3168  * s = "I am a string" #=> "I am a string"
3169  * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
3170  * r == s #=> true
3171  *
3172  */
3173 
3174 static VALUE
3176 {
3177 #if SIZEOF_LONG == SIZEOF_VOIDP
3178 #define NUM2PTR(x) NUM2ULONG(x)
3179 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
3180 #define NUM2PTR(x) NUM2ULL(x)
3181 #endif
3182  rb_objspace_t *objspace = &rb_objspace;
3183  VALUE ptr;
3184  void *p0;
3185 
3186  rb_secure(4);
3187  ptr = NUM2PTR(objid);
3188  p0 = (void *)ptr;
3189 
3190  if (ptr == Qtrue) return Qtrue;
3191  if (ptr == Qfalse) return Qfalse;
3192  if (ptr == Qnil) return Qnil;
3193  if (FIXNUM_P(ptr)) return (VALUE)ptr;
3194  ptr = obj_id_to_ref(objid);
3195 
3196  if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
3197  ID symid = ptr / sizeof(RVALUE);
3198  if (rb_id2name(symid) == 0)
3199  rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
3200  return ID2SYM(symid);
3201  }
3202 
3203  if (!is_pointer_to_heap(objspace, (void *)ptr) ||
3204  BUILTIN_TYPE(ptr) > T_FIXNUM || BUILTIN_TYPE(ptr) == T_ICLASS) {
3205  rb_raise(rb_eRangeError, "%p is not id value", p0);
3206  }
3207  if (BUILTIN_TYPE(ptr) == 0 || RBASIC(ptr)->klass == 0) {
3208  rb_raise(rb_eRangeError, "%p is recycled object", p0);
3209  }
3210  return (VALUE)ptr;
3211 }
3212 
3213 /*
3214  * Document-method: __id__
3215  * Document-method: object_id
3216  *
3217  * call-seq:
3218  * obj.__id__ -> fixnum
3219  * obj.object_id -> fixnum
3220  *
3221  * Returns an integer identifier for <i>obj</i>. The same number will
3222  * be returned on all calls to <code>id</code> for a given object, and
3223  * no two active objects will share an id.
3224  * <code>Object#object_id</code> is a different concept from the
3225  * <code>:name</code> notation, which returns the symbol id of
3226  * <code>name</code>. Replaces the deprecated <code>Object#id</code>.
3227  */
3228 
3229 /*
3230  * call-seq:
3231  * obj.hash -> fixnum
3232  *
3233  * Generates a <code>Fixnum</code> hash value for this object. This
3234  * function must have the property that <code>a.eql?(b)</code> implies
3235  * <code>a.hash == b.hash</code>. The hash value is used by class
3236  * <code>Hash</code>. Any hash value that exceeds the capacity of a
3237  * <code>Fixnum</code> will be truncated before being used.
3238  */
3239 
3240 VALUE
3242 {
3243  /*
3244  * 32-bit VALUE space
3245  * MSB ------------------------ LSB
3246  * false 00000000000000000000000000000000
3247  * true 00000000000000000000000000000010
3248  * nil 00000000000000000000000000000100
3249  * undef 00000000000000000000000000000110
3250  * symbol ssssssssssssssssssssssss00001110
3251  * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
3252  * fixnum fffffffffffffffffffffffffffffff1
3253  *
3254  * object_id space
3255  * LSB
3256  * false 00000000000000000000000000000000
3257  * true 00000000000000000000000000000010
3258  * nil 00000000000000000000000000000100
3259  * undef 00000000000000000000000000000110
3260  * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
3261  * object oooooooooooooooooooooooooooooo0 o...o % A = 0
3262  * fixnum fffffffffffffffffffffffffffffff1 bignum if required
3263  *
3264  * where A = sizeof(RVALUE)/4
3265  *
3266  * sizeof(RVALUE) is
3267  * 20 if 32-bit, double is 4-byte aligned
3268  * 24 if 32-bit, double is 8-byte aligned
3269  * 40 if 64-bit
3270  */
3271  if (SYMBOL_P(obj)) {
3272  return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
3273  }
3274  if (SPECIAL_CONST_P(obj)) {
3275  return LONG2NUM((SIGNED_VALUE)obj);
3276  }
3277  return nonspecial_obj_id(obj);
3278 }
3279 
3280 static int
3282 {
3283  VALUE k = (VALUE)key;
3284  VALUE hash = (VALUE)arg;
3285  rb_hash_aset(hash, k, INT2FIX(0));
3286  return ST_CONTINUE;
3287 }
3288 
3289 /*
3290  * call-seq:
3291  * ObjectSpace.count_objects([result_hash]) -> hash
3292  *
3293  * Counts objects for each type.
3294  *
3295  * It returns a hash as:
3296  * {:TOTAL=>10000, :FREE=>3011, :T_OBJECT=>6, :T_CLASS=>404, ...}
3297  *
3298  * If the optional argument, result_hash, is given,
3299  * it is overwritten and returned.
3300  * This is intended to avoid probe effect.
3301  *
3302  * The contents of the returned hash is implementation defined.
3303  * It may be changed in future.
3304  *
3305  * This method is not expected to work except C Ruby.
3306  *
3307  */
3308 
3309 static VALUE
3311 {
3312  rb_objspace_t *objspace = &rb_objspace;
3313  size_t counts[T_MASK+1];
3314  size_t freed = 0;
3315  size_t total = 0;
3316  size_t i;
3317  VALUE hash;
3318 
3319  if (rb_scan_args(argc, argv, "01", &hash) == 1) {
3320  if (TYPE(hash) != T_HASH)
3321  rb_raise(rb_eTypeError, "non-hash given");
3322  }
3323 
3324  for (i = 0; i <= T_MASK; i++) {
3325  counts[i] = 0;
3326  }
3327 
3328  for (i = 0; i < heaps_used; i++) {
3329  RVALUE *p, *pend;
3330 
3331  p = objspace->heap.sorted[i].start; pend = objspace->heap.sorted[i].end;
3332  for (;p < pend; p++) {
3333  if (p->as.basic.flags) {
3334  counts[BUILTIN_TYPE(p)]++;
3335  }
3336  else {
3337  freed++;
3338  }
3339  }
3340  total += objspace->heap.sorted[i].slot->limit;
3341  }
3342 
3343  if (hash == Qnil) {
3344  hash = rb_hash_new();
3345  }
3346  else if (!RHASH_EMPTY_P(hash)) {
3347  st_foreach(RHASH_TBL(hash), set_zero, hash);
3348  }
3349  rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
3350  rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed));
3351 
3352  for (i = 0; i <= T_MASK; i++) {
3353  VALUE type;
3354  switch (i) {
3355 #define COUNT_TYPE(t) case (t): type = ID2SYM(rb_intern(#t)); break;
3356  COUNT_TYPE(T_NONE);
3364  COUNT_TYPE(T_HASH);
3367  COUNT_TYPE(T_FILE);
3368  COUNT_TYPE(T_DATA);
3372  COUNT_TYPE(T_NIL);
3373  COUNT_TYPE(T_TRUE);
3378  COUNT_TYPE(T_NODE);
3381 #undef COUNT_TYPE
3382  default: type = INT2NUM(i); break;
3383  }
3384  if (counts[i])
3385  rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
3386  }
3387 
3388  return hash;
3389 }
3390 
3391 /*
3392  * call-seq:
3393  * GC.count -> Integer
3394  *
3395  * The number of times GC occurred.
3396  *
3397  * It returns the number of times GC occurred since the process started.
3398  *
3399  */
3400 
3401 static VALUE
3403 {
3404  return UINT2NUM((&rb_objspace)->count);
3405 }
3406 
3407 /*
3408  * call-seq:
3409  * GC.stat -> Hash
3410  *
3411  * Returns a Hash containing information about the GC.
3412  *
3413  * The hash includes information about internal statistics about GC such as:
3414  *
3415  * {
3416  * :count => 18,
3417  * :heap_used => 77,
3418  * :heap_length => 77,
3419  * :heap_increment => 0,
3420  * :heap_live_num => 23287,
3421  * :heap_free_num => 8115,
3422  * :heap_final_num => 0,
3423  * }
3424  *
3425  * The contents of the hash are implementation defined and may be changed in
3426  * the future.
3427  *
3428  * This method is only expected to work on C Ruby.
3429  *
3430  */
3431 
3432 static VALUE
3434 {
3435  rb_objspace_t *objspace = &rb_objspace;
3436  VALUE hash;
3437 
3438  if (rb_scan_args(argc, argv, "01", &hash) == 1) {
3439  if (TYPE(hash) != T_HASH)
3440  rb_raise(rb_eTypeError, "non-hash given");
3441  }
3442 
3443  if (hash == Qnil) {
3444  hash = rb_hash_new();
3445  }
3446 
3447  rest_sweep(objspace);
3448 
3449  rb_hash_aset(hash, ID2SYM(rb_intern("count")), SIZET2NUM(objspace->count));
3450 
3451  /* implementation dependent counters */
3452  rb_hash_aset(hash, ID2SYM(rb_intern("heap_used")), SIZET2NUM(objspace->heap.used));
3453  rb_hash_aset(hash, ID2SYM(rb_intern("heap_length")), SIZET2NUM(objspace->heap.length));
3454  rb_hash_aset(hash, ID2SYM(rb_intern("heap_increment")), SIZET2NUM(objspace->heap.increment));
3455  rb_hash_aset(hash, ID2SYM(rb_intern("heap_live_num")), SIZET2NUM(objspace->heap.live_num));
3456  rb_hash_aset(hash, ID2SYM(rb_intern("heap_free_num")), SIZET2NUM(objspace->heap.free_num));
3457  rb_hash_aset(hash, ID2SYM(rb_intern("heap_final_num")), SIZET2NUM(objspace->heap.final_num));
3458  return hash;
3459 }
3460 
3461 
3462 #if CALC_EXACT_MALLOC_SIZE
3463 /*
3464  * call-seq:
3465  * GC.malloc_allocated_size -> Integer
3466  *
3467  * The allocated size by malloc().
3468  *
3469  * It returns the allocated size by malloc().
3470  */
3471 
3472 static VALUE
3473 gc_malloc_allocated_size(VALUE self)
3474 {
3475  return UINT2NUM((&rb_objspace)->malloc_params.allocated_size);
3476 }
3477 
3478 /*
3479  * call-seq:
3480  * GC.malloc_allocations -> Integer
3481  *
3482  * The number of allocated memory object by malloc().
3483  *
3484  * It returns the number of allocated memory object by malloc().
3485  */
3486 
3487 static VALUE
3488 gc_malloc_allocations(VALUE self)
3489 {
3490  return UINT2NUM((&rb_objspace)->malloc_params.allocations);
3491 }
3492 #endif
3493 
3494 static VALUE
3496 {
3497  VALUE prof;
3498  VALUE gc_profile = rb_ary_new();
3499  size_t i;
3500  rb_objspace_t *objspace = (&rb_objspace);
3501 
3502  if (!objspace->profile.run) {
3503  return Qnil;
3504  }
3505 
3506  for (i =0; i < objspace->profile.count; i++) {
3507  prof = rb_hash_new();
3508  rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(objspace->profile.record[i].gc_time));
3509  rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(objspace->profile.record[i].gc_invoke_time));
3510  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(objspace->profile.record[i].heap_use_size));
3511  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(objspace->profile.record[i].heap_total_size));
3512  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(objspace->profile.record[i].heap_total_objects));
3513  rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), objspace->profile.record[i].is_marked);
3514 #if GC_PROFILE_MORE_DETAIL
3515  rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(objspace->profile.record[i].gc_mark_time));
3516  rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(objspace->profile.record[i].gc_sweep_time));
3517  rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(objspace->profile.record[i].allocate_increase));
3518  rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(objspace->profile.record[i].allocate_limit));
3519  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SLOTS")), SIZET2NUM(objspace->profile.record[i].heap_use_slots));
3520  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(objspace->profile.record[i].heap_live_objects));
3521  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(objspace->profile.record[i].heap_free_objects));
3522  rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), objspace->profile.record[i].have_finalize);
3523 #endif
3524  rb_ary_push(gc_profile, prof);
3525  }
3526 
3527  return gc_profile;
3528 }
3529 
3530 /*
3531  * call-seq:
3532  * GC::Profiler.result -> String
3533  *
3534  * Returns a profile data report such as:
3535  *
3536  * GC 1 invokes.
3537  * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
3538  * 1 0.012 159240 212940 10647 0.00000000000001530000
3539  */
3540 
3541 static VALUE
3543 {
3544  rb_objspace_t *objspace = &rb_objspace;
3545  VALUE record;
3546  VALUE result;
3547  int i, index;
3548 
3549  record = gc_profile_record_get();
3550  if (objspace->profile.run && objspace->profile.count) {
3551  result = rb_sprintf("GC %d invokes.\n", NUM2INT(gc_count(0)));
3552  index = 1;
3553  rb_str_cat2(result, "Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n");
3554  for (i = 0; i < (int)RARRAY_LEN(record); i++) {
3555  VALUE r = RARRAY_PTR(record)[i];
3556 #if !GC_PROFILE_MORE_DETAIL
3557  if (rb_hash_aref(r, ID2SYM(rb_intern("GC_IS_MARKED")))) {
3558 #endif
3559  rb_str_catf(result, "%5d %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
3560  index++, NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_INVOKE_TIME")))),
3561  (size_t)NUM2SIZET(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_USE_SIZE")))),
3562  (size_t)NUM2SIZET(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")))),
3563  (size_t)NUM2SIZET(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")))),
3564  NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_TIME"))))*1000);
3565 #if !GC_PROFILE_MORE_DETAIL
3566  }
3567 #endif
3568  }
3569 #if GC_PROFILE_MORE_DETAIL
3570  rb_str_cat2(result, "\n\n");
3571  rb_str_cat2(result, "More detail.\n");
3572  rb_str_cat2(result, "Index Allocate Increase Allocate Limit Use Slot Have Finalize Mark Time(ms) Sweep Time(ms)\n");
3573  index = 1;
3574  for (i = 0; i < (int)RARRAY_LEN(record); i++) {
3575  VALUE r = RARRAY_PTR(record)[i];
3576  rb_str_catf(result, "%5d %17"PRIuSIZE" %17"PRIuSIZE" %9"PRIuSIZE" %14s %25.20f %25.20f\n",
3577  index++, (size_t)NUM2SIZET(rb_hash_aref(r, ID2SYM(rb_intern("ALLOCATE_INCREASE")))),
3578  (size_t)NUM2SIZET(rb_hash_aref(r, ID2SYM(rb_intern("ALLOCATE_LIMIT")))),
3579  (size_t)NUM2SIZET(rb_hash_aref(r, ID2SYM(rb_intern("HEAP_USE_SLOTS")))),
3580  rb_hash_aref(r, ID2SYM(rb_intern("HAVE_FINALIZE")))? "true" : "false",
3581  NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_MARK_TIME"))))*1000,
3582  NUM2DBL(rb_hash_aref(r, ID2SYM(rb_intern("GC_SWEEP_TIME"))))*1000);
3583  }
3584 #endif
3585  }
3586  else {
3587  result = rb_str_new2("");
3588  }
3589  return result;
3590 }
3591 
3592 
3593 /*
3594  * call-seq:
3595  * GC::Profiler.report
3596  * GC::Profiler.report io
3597  *
3598  * Writes the GC::Profiler#result to <tt>$stdout</tt> or the given IO object.
3599  *
3600  */
3601 
3602 static VALUE
3604 {
3605  VALUE out;
3606 
3607  if (argc == 0) {
3608  out = rb_stdout;
3609  }
3610  else {
3611  rb_scan_args(argc, argv, "01", &out);
3612  }
3614 
3615  return Qnil;
3616 }
3617 
3618 /*
3619  * call-seq:
3620  * GC::Profiler.total_time -> float
3621  *
3622  * The total time used for garbage collection in milliseconds
3623  */
3624 
3625 static VALUE
3627 {
3628  double time = 0;
3629  rb_objspace_t *objspace = &rb_objspace;
3630  size_t i;
3631 
3632  if (objspace->profile.run && objspace->profile.count) {
3633  for (i = 0; i < objspace->profile.count; i++) {
3634  time += objspace->profile.record[i].gc_time;
3635  }
3636  }
3637  return DBL2NUM(time);
3638 }
3639 
3640 /* Document-class: GC::Profiler
3641  *
3642  * The GC profiler provides access to information on GC runs including time,
3643  * length and object space size.
3644  *
3645  * Example:
3646  *
3647  * GC::Profiler.enable
3648  *
3649  * require 'rdoc/rdoc'
3650  *
3651  * puts GC::Profiler.result
3652  *
3653  * GC::Profiler.disable
3654  *
3655  * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
3656  */
3657 
3658 /*
3659  * The <code>GC</code> module provides an interface to Ruby's mark and
3660  * sweep garbage collection mechanism. Some of the underlying methods
3661  * are also available via the ObjectSpace module.
3662  *
3663  * You may obtain information about the operation of the GC through
3664  * GC::Profiler.
3665  */
3666 
3667 void
3668 Init_GC(void)
3669 {
3670  VALUE rb_mObSpace;
3671  VALUE rb_mProfiler;
3672 
3673  rb_mGC = rb_define_module("GC");
3681  rb_define_method(rb_mGC, "garbage_collect", rb_gc_start, 0);
3682 
3683  rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
3684  rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
3685  rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
3686  rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
3687  rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
3688  rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
3689  rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
3690  rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
3691 
3692  rb_mObSpace = rb_define_module("ObjectSpace");
3693  rb_define_module_function(rb_mObSpace, "each_object", os_each_obj, -1);
3694  rb_define_module_function(rb_mObSpace, "garbage_collect", rb_gc_start, 0);
3695 
3696  rb_define_module_function(rb_mObSpace, "define_finalizer", define_final, -1);
3697  rb_define_module_function(rb_mObSpace, "undefine_finalizer", undefine_final, 1);
3698 
3699  rb_define_module_function(rb_mObSpace, "_id2ref", id2ref, 1);
3700 
3702  rb_obj_freeze(rb_str_new2("failed to allocate memory")));
3705 
3707  rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
3708 
3709  rb_define_module_function(rb_mObSpace, "count_objects", count_objects, -1);
3710 
3711 #if CALC_EXACT_MALLOC_SIZE
3712  rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
3713  rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
3714 #endif
3715 }
3716