Ruby  2.5.0dev(2017-10-22revision60238)
gc.c
Go to the documentation of this file.
1 /**********************************************************************
2 
3  gc.c -
4 
5  $Author$
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 #define rb_data_object_alloc rb_data_object_alloc
15 #define rb_data_typed_object_alloc rb_data_typed_object_alloc
16 
17 #include "internal.h"
18 #include "ruby/st.h"
19 #include "ruby/re.h"
20 #include "ruby/io.h"
21 #include "ruby/thread.h"
22 #include "ruby/util.h"
23 #include "ruby/debug.h"
24 #include "eval_intern.h"
25 #include "vm_core.h"
26 #include "gc.h"
27 #include "constant.h"
28 #include "ruby_atomic.h"
29 #include "probes.h"
30 #include "id_table.h"
31 #include <stdio.h>
32 #include <stdarg.h>
33 #include <setjmp.h>
34 #include <sys/types.h>
35 #include "ruby_assert.h"
36 #include "debug_counter.h"
37 
38 #undef rb_data_object_wrap
39 
40 #ifndef HAVE_MALLOC_USABLE_SIZE
41 # ifdef _WIN32
42 # define HAVE_MALLOC_USABLE_SIZE
43 # define malloc_usable_size(a) _msize(a)
44 # elif defined HAVE_MALLOC_SIZE
45 # define HAVE_MALLOC_USABLE_SIZE
46 # define malloc_usable_size(a) malloc_size(a)
47 # endif
48 #endif
49 #ifdef HAVE_MALLOC_USABLE_SIZE
50 # ifdef HAVE_MALLOC_H
51 # include <malloc.h>
52 # elif defined(HAVE_MALLOC_NP_H)
53 # include <malloc_np.h>
54 # elif defined(HAVE_MALLOC_MALLOC_H)
55 # include <malloc/malloc.h>
56 # endif
57 #endif
58 
59 #if /* is ASAN enabled? */ \
60  __has_feature(address_sanitizer) /* Clang */ || \
61  defined(__SANITIZE_ADDRESS__) /* GCC 4.8.x */
62  #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS \
63  __attribute__((no_address_safety_analysis)) \
64  __attribute__((noinline))
65 #else
66  #define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
67 #endif
68 
69 #ifdef HAVE_SYS_TIME_H
70 #include <sys/time.h>
71 #endif
72 
73 #ifdef HAVE_SYS_RESOURCE_H
74 #include <sys/resource.h>
75 #endif
76 #if defined(__native_client__) && defined(NACL_NEWLIB)
77 # include "nacl/resource.h"
78 # undef HAVE_POSIX_MEMALIGN
79 # undef HAVE_MEMALIGN
80 
81 #endif
82 
83 #if defined _WIN32 || defined __CYGWIN__
84 #include <windows.h>
85 #elif defined(HAVE_POSIX_MEMALIGN)
86 #elif defined(HAVE_MEMALIGN)
87 #include <malloc.h>
88 #endif
89 
90 #define rb_setjmp(env) RUBY_SETJMP(env)
91 #define rb_jmp_buf rb_jmpbuf_t
92 
93 #if defined(HAVE_RB_GC_GUARDED_PTR_VAL) && HAVE_RB_GC_GUARDED_PTR_VAL
94 /* trick the compiler into thinking a external signal handler uses this */
96 volatile VALUE *
98 {
100 
101  return ptr;
102 }
103 #endif
104 
105 #ifndef GC_HEAP_INIT_SLOTS
106 #define GC_HEAP_INIT_SLOTS 10000
107 #endif
108 #ifndef GC_HEAP_FREE_SLOTS
109 #define GC_HEAP_FREE_SLOTS 4096
110 #endif
111 #ifndef GC_HEAP_GROWTH_FACTOR
112 #define GC_HEAP_GROWTH_FACTOR 1.8
113 #endif
114 #ifndef GC_HEAP_GROWTH_MAX_SLOTS
115 #define GC_HEAP_GROWTH_MAX_SLOTS 0 /* 0 is disable */
116 #endif
117 #ifndef GC_HEAP_OLDOBJECT_LIMIT_FACTOR
118 #define GC_HEAP_OLDOBJECT_LIMIT_FACTOR 2.0
119 #endif
120 
121 #ifndef GC_HEAP_FREE_SLOTS_MIN_RATIO
122 #define GC_HEAP_FREE_SLOTS_MIN_RATIO 0.20
123 #endif
124 #ifndef GC_HEAP_FREE_SLOTS_GOAL_RATIO
125 #define GC_HEAP_FREE_SLOTS_GOAL_RATIO 0.40
126 #endif
127 #ifndef GC_HEAP_FREE_SLOTS_MAX_RATIO
128 #define GC_HEAP_FREE_SLOTS_MAX_RATIO 0.65
129 #endif
130 
131 #ifndef GC_MALLOC_LIMIT_MIN
132 #define GC_MALLOC_LIMIT_MIN (16 * 1024 * 1024 /* 16MB */)
133 #endif
134 #ifndef GC_MALLOC_LIMIT_MAX
135 #define GC_MALLOC_LIMIT_MAX (32 * 1024 * 1024 /* 32MB */)
136 #endif
137 #ifndef GC_MALLOC_LIMIT_GROWTH_FACTOR
138 #define GC_MALLOC_LIMIT_GROWTH_FACTOR 1.4
139 #endif
140 
141 #ifndef GC_OLDMALLOC_LIMIT_MIN
142 #define GC_OLDMALLOC_LIMIT_MIN (16 * 1024 * 1024 /* 16MB */)
143 #endif
144 #ifndef GC_OLDMALLOC_LIMIT_GROWTH_FACTOR
145 #define GC_OLDMALLOC_LIMIT_GROWTH_FACTOR 1.2
146 #endif
147 #ifndef GC_OLDMALLOC_LIMIT_MAX
148 #define GC_OLDMALLOC_LIMIT_MAX (128 * 1024 * 1024 /* 128MB */)
149 #endif
150 
151 #ifndef PRINT_MEASURE_LINE
152 #define PRINT_MEASURE_LINE 0
153 #endif
154 #ifndef PRINT_ENTER_EXIT_TICK
155 #define PRINT_ENTER_EXIT_TICK 0
156 #endif
157 #ifndef PRINT_ROOT_TICKS
158 #define PRINT_ROOT_TICKS 0
159 #endif
160 
161 #define USE_TICK_T (PRINT_ENTER_EXIT_TICK || PRINT_MEASURE_LINE || PRINT_ROOT_TICKS)
162 #define TICK_TYPE 1
163 
164 typedef struct {
169 
174 
178 
182 
185 
186 static ruby_gc_params_t gc_params = {
191 
196 
200 
204 
205  FALSE,
206 };
207 
208 /* GC_DEBUG:
209  * enable to embed GC debugging information.
210  */
211 #ifndef GC_DEBUG
212 #define GC_DEBUG 0
213 #endif
214 
215 #if USE_RGENGC
216 /* RGENGC_DEBUG:
217  * 1: basic information
218  * 2: remember set operation
219  * 3: mark
220  * 4:
221  * 5: sweep
222  */
223 #ifndef RGENGC_DEBUG
224 #ifdef RUBY_DEVEL
225 #define RGENGC_DEBUG -1
226 #else
227 #define RGENGC_DEBUG 0
228 #endif
229 #endif
230 #if RGENGC_DEBUG < 0 && !defined(_MSC_VER)
231 # define RGENGC_DEBUG_ENABLED(level) (-(RGENGC_DEBUG) >= (level) && ruby_rgengc_debug >= (level))
232 #else
233 # define RGENGC_DEBUG_ENABLED(level) ((RGENGC_DEBUG) >= (level))
234 #endif
236 
237 /* RGENGC_CHECK_MODE
238  * 0: disable all assertions
239  * 1: enable assertions (to debug RGenGC)
240  * 2: enable internal consistency check at each GC (for debugging)
241  * 3: enable internal consistency check at each GC steps (for debugging)
242  * 4: enable liveness check
243  * 5: show all references
244  */
245 #ifndef RGENGC_CHECK_MODE
246 #define RGENGC_CHECK_MODE 0
247 #endif
248 
249 #if RGENGC_CHECK_MODE > 0
250 #define GC_ASSERT(expr) RUBY_ASSERT_MESG_WHEN(RGENGC_CHECK_MODE > 0, expr, #expr)
251 #else
252 #define GC_ASSERT(expr) ((void)0)
253 #endif
254 
255 /* RGENGC_OLD_NEWOBJ_CHECK
256  * 0: disable all assertions
257  * >0: make a OLD object when new object creation.
258  *
259  * Make one OLD object per RGENGC_OLD_NEWOBJ_CHECK WB protected objects creation.
260  */
261 #ifndef RGENGC_OLD_NEWOBJ_CHECK
262 #define RGENGC_OLD_NEWOBJ_CHECK 0
263 #endif
264 
265 /* RGENGC_PROFILE
266  * 0: disable RGenGC profiling
267  * 1: enable profiling for basic information
268  * 2: enable profiling for each types
269  */
270 #ifndef RGENGC_PROFILE
271 #define RGENGC_PROFILE 0
272 #endif
273 
274 /* RGENGC_ESTIMATE_OLDMALLOC
275  * Enable/disable to estimate increase size of malloc'ed size by old objects.
276  * If estimation exceeds threshold, then will invoke full GC.
277  * 0: disable estimation.
278  * 1: enable estimation.
279  */
280 #ifndef RGENGC_ESTIMATE_OLDMALLOC
281 #define RGENGC_ESTIMATE_OLDMALLOC 1
282 #endif
283 
284 /* RGENGC_FORCE_MAJOR_GC
285  * Force major/full GC if this macro is not 0.
286  */
287 #ifndef RGENGC_FORCE_MAJOR_GC
288 #define RGENGC_FORCE_MAJOR_GC 0
289 #endif
290 
291 #else /* USE_RGENGC */
292 
293 #ifdef RGENGC_DEBUG
294 #undef RGENGC_DEBUG
295 #endif
296 #define RGENGC_DEBUG 0
297 #ifdef RGENGC_CHECK_MODE
298 #undef RGENGC_CHECK_MODE
299 #endif
300 #define RGENGC_CHECK_MODE 0
301 #define RGENGC_PROFILE 0
302 #define RGENGC_ESTIMATE_OLDMALLOC 0
303 #define RGENGC_FORCE_MAJOR_GC 0
304 
305 #endif /* USE_RGENGC */
306 
307 #ifndef GC_PROFILE_MORE_DETAIL
308 #define GC_PROFILE_MORE_DETAIL 0
309 #endif
310 #ifndef GC_PROFILE_DETAIL_MEMORY
311 #define GC_PROFILE_DETAIL_MEMORY 0
312 #endif
313 #ifndef GC_ENABLE_INCREMENTAL_MARK
314 #define GC_ENABLE_INCREMENTAL_MARK USE_RINCGC
315 #endif
316 #ifndef GC_ENABLE_LAZY_SWEEP
317 #define GC_ENABLE_LAZY_SWEEP 1
318 #endif
319 #ifndef CALC_EXACT_MALLOC_SIZE
320 #define CALC_EXACT_MALLOC_SIZE 0
321 #endif
322 #if defined(HAVE_MALLOC_USABLE_SIZE) || CALC_EXACT_MALLOC_SIZE > 0
323 #ifndef MALLOC_ALLOCATED_SIZE
324 #define MALLOC_ALLOCATED_SIZE 0
325 #endif
326 #else
327 #define MALLOC_ALLOCATED_SIZE 0
328 #endif
329 #ifndef MALLOC_ALLOCATED_SIZE_CHECK
330 #define MALLOC_ALLOCATED_SIZE_CHECK 0
331 #endif
332 
333 #ifndef GC_DEBUG_STRESS_TO_CLASS
334 #define GC_DEBUG_STRESS_TO_CLASS 0
335 #endif
336 
337 #ifndef RGENGC_OBJ_INFO
338 #define RGENGC_OBJ_INFO (RGENGC_DEBUG | RGENGC_CHECK_MODE)
339 #endif
340 
341 typedef enum {
342  GPR_FLAG_NONE = 0x000,
343  /* major reason */
348 #if RGENGC_ESTIMATE_OLDMALLOC
350 #endif
352 
353  /* gc reason */
357  GPR_FLAG_CAPI = 0x800,
358  GPR_FLAG_STRESS = 0x1000,
359 
360  /* others */
364 
365 typedef struct gc_profile_record {
366  int flags;
367 
368  double gc_time;
370 
374 
375 #if GC_PROFILE_MORE_DETAIL
376  double gc_mark_time;
377  double gc_sweep_time;
378 
379  size_t heap_use_pages;
380  size_t heap_live_objects;
381  size_t heap_free_objects;
382 
383  size_t allocate_increase;
384  size_t allocate_limit;
385 
386  double prepare_time;
387  size_t removing_objects;
388  size_t empty_objects;
389 #if GC_PROFILE_DETAIL_MEMORY
390  long maxrss;
391  long minflt;
392  long majflt;
393 #endif
394 #endif
395 #if MALLOC_ALLOCATED_SIZE
396  size_t allocated_size;
397 #endif
398 
399 #if RGENGC_PROFILE > 0
400  size_t old_objects;
401  size_t remembered_normal_objects;
402  size_t remembered_shady_objects;
403 #endif
405 
406 #if defined(_MSC_VER) || defined(__CYGWIN__)
407 #pragma pack(push, 1) /* magic for reducing sizeof(RVALUE): 24 -> 20 */
408 #endif
409 
410 typedef struct RVALUE {
411  union {
412  struct {
413  VALUE flags; /* always 0 for freed obj */
414  struct RVALUE *next;
415  } free;
416  struct RBasic basic;
417  struct RObject object;
418  struct RClass klass;
419  struct RFloat flonum;
420  struct RString string;
421  struct RArray array;
422  struct RRegexp regexp;
423  struct RHash hash;
424  struct RData data;
425  struct RTypedData typeddata;
426  struct RStruct rstruct;
427  struct RBignum bignum;
428  struct RFile file;
429  struct RNode node;
430  struct RMatch match;
431  struct RRational rational;
432  struct RComplex complex;
433  union {
435  struct vm_svar svar;
436  struct vm_throw_data throw_data;
437  struct vm_ifunc ifunc;
438  struct MEMO memo;
442  struct rb_imemo_alloc_struct alloc;
443  } imemo;
444  struct {
445  struct RBasic basic;
449  } values;
450  } as;
451 #if GC_DEBUG
452  const char *file;
453  int line;
454 #endif
455 } RVALUE;
456 
457 #if defined(_MSC_VER) || defined(__CYGWIN__)
458 #pragma pack(pop)
459 #endif
460 
462 enum {
463  BITS_SIZE = sizeof(bits_t),
465 };
466 
468  struct heap_page *page;
469 };
470 
472  struct heap_page_header header;
473  /* char gap[]; */
474  /* RVALUE values[]; */
475 };
476 
477 struct gc_list {
479  struct gc_list *next;
480 };
481 
482 #define STACK_CHUNK_SIZE 500
483 
484 typedef struct stack_chunk {
486  struct stack_chunk *next;
487 } stack_chunk_t;
488 
489 typedef struct mark_stack {
492  int index;
493  int limit;
494  size_t cache_size;
496 } mark_stack_t;
497 
498 typedef struct rb_heap_struct {
500 
503  struct heap_page *pages;
505 #if GC_ENABLE_INCREMENTAL_MARK
507 #endif
508  size_t total_pages; /* total page count in a heap */
509  size_t total_slots; /* total slot count (about total_pages * HEAP_PAGE_OBJ_LIMIT) */
510 } rb_heap_t;
511 
512 enum gc_mode {
516 };
517 
518 typedef struct rb_objspace {
519  struct {
520  size_t limit;
521  size_t increase;
522 #if MALLOC_ALLOCATED_SIZE
523  size_t allocated_size;
524  size_t allocations;
525 #endif
526  } malloc_params;
527 
528  struct {
529  unsigned int mode : 2;
530  unsigned int immediate_sweep : 1;
531  unsigned int dont_gc : 1;
532  unsigned int dont_incremental : 1;
533  unsigned int during_gc : 1;
534  unsigned int gc_stressful: 1;
535  unsigned int has_hook: 1;
536 #if USE_RGENGC
537  unsigned int during_minor_gc : 1;
538 #endif
539 #if GC_ENABLE_INCREMENTAL_MARK
540  unsigned int during_incremental_marking : 1;
541 #endif
542  } flags;
543 
546 
548  rb_heap_t tomb_heap; /* heap for zombies and ghosts */
549 
550  struct {
552  } atomic_flags;
553 
555  void *data;
556  void (*mark_func)(VALUE v, void *data);
557  } *mark_func_data;
558 
560  size_t marked_slots;
561 
562  struct {
563  struct heap_page **sorted;
569 
570  /* final */
571  size_t final_slots;
573  } heap_pages;
574 
576 
577  struct {
578  int run;
582  size_t next_index;
583  size_t size;
584 
585 #if GC_PROFILE_MORE_DETAIL
586  double prepare_time;
587 #endif
588  double invoke_time;
589 
590 #if USE_RGENGC
593 #if RGENGC_PROFILE > 0
594  size_t total_generated_normal_object_count;
595  size_t total_generated_shady_object_count;
596  size_t total_shade_operation_count;
597  size_t total_promoted_count;
598  size_t total_remembered_normal_object_count;
599  size_t total_remembered_shady_object_count;
600 
601 #if RGENGC_PROFILE >= 2
602  size_t generated_normal_object_count_types[RUBY_T_MASK];
603  size_t generated_shady_object_count_types[RUBY_T_MASK];
604  size_t shade_operation_count_types[RUBY_T_MASK];
605  size_t promoted_types[RUBY_T_MASK];
606  size_t remembered_normal_object_count_types[RUBY_T_MASK];
607  size_t remembered_shady_object_count_types[RUBY_T_MASK];
608 #endif
609 #endif /* RGENGC_PROFILE */
610 #endif /* USE_RGENGC */
611 
612  /* temporary profiling space */
616 
617  /* basic statistics */
618  size_t count;
622  } profile;
624 
626 
627 #if USE_RGENGC
628  struct {
634  size_t old_objects;
636 
637 #if RGENGC_ESTIMATE_OLDMALLOC
640 #endif
641 
642 #if RGENGC_CHECK_MODE >= 2
643  struct st_table *allrefs_table;
644  size_t error_count;
645 #endif
646  } rgengc;
647 #if GC_ENABLE_INCREMENTAL_MARK
648  struct {
649  size_t pooled_slots;
650  size_t step_slots;
651  } rincgc;
652 #endif
653 #endif /* USE_RGENGC */
654 
655 #if GC_DEBUG_STRESS_TO_CLASS
657 #endif
658 } rb_objspace_t;
659 
660 
661 #ifndef HEAP_PAGE_ALIGN_LOG
662 /* default tiny heap size: 16KB */
663 #define HEAP_PAGE_ALIGN_LOG 14
664 #endif
665 #define CEILDIV(i, mod) (((i) + (mod) - 1)/(mod))
666 enum {
669  REQUIRED_SIZE_BY_MALLOC = (sizeof(size_t) * 5),
671  HEAP_PAGE_OBJ_LIMIT = (unsigned int)((HEAP_PAGE_SIZE - sizeof(struct heap_page_header))/sizeof(struct RVALUE)),
674  HEAP_PAGE_BITMAP_PLANES = USE_RGENGC ? 4 : 1 /* RGENGC: mark, unprotected, uncollectible, marking */
675 };
676 
677 struct heap_page {
678  struct heap_page *prev;
679  short total_slots;
680  short free_slots;
681  short final_slots;
682  struct {
683  unsigned int before_sweep : 1;
684  unsigned int has_remembered_objects : 1;
686  unsigned int in_tomb : 1;
687  } flags;
688 
692  struct heap_page *next;
693 
694 #if USE_RGENGC
696 #endif
697  /* the following three bitmaps are cleared at the beginning of full GC */
699 #if USE_RGENGC
702 #endif
703 };
704 
705 #define GET_PAGE_BODY(x) ((struct heap_page_body *)((bits_t)(x) & ~(HEAP_PAGE_ALIGN_MASK)))
706 #define GET_PAGE_HEADER(x) (&GET_PAGE_BODY(x)->header)
707 #define GET_HEAP_PAGE(x) (GET_PAGE_HEADER(x)->page)
708 
709 #define NUM_IN_PAGE(p) (((bits_t)(p) & HEAP_PAGE_ALIGN_MASK)/sizeof(RVALUE))
710 #define BITMAP_INDEX(p) (NUM_IN_PAGE(p) / BITS_BITLENGTH )
711 #define BITMAP_OFFSET(p) (NUM_IN_PAGE(p) & (BITS_BITLENGTH-1))
712 #define BITMAP_BIT(p) ((bits_t)1 << BITMAP_OFFSET(p))
713 
714 /* Bitmap Operations */
715 #define MARKED_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] & BITMAP_BIT(p))
716 #define MARK_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] = (bits)[BITMAP_INDEX(p)] | BITMAP_BIT(p))
717 #define CLEAR_IN_BITMAP(bits, p) ((bits)[BITMAP_INDEX(p)] = (bits)[BITMAP_INDEX(p)] & ~BITMAP_BIT(p))
718 
719 /* getting bitmap */
720 #define GET_HEAP_MARK_BITS(x) (&GET_HEAP_PAGE(x)->mark_bits[0])
721 #if USE_RGENGC
722 #define GET_HEAP_UNCOLLECTIBLE_BITS(x) (&GET_HEAP_PAGE(x)->uncollectible_bits[0])
723 #define GET_HEAP_WB_UNPROTECTED_BITS(x) (&GET_HEAP_PAGE(x)->wb_unprotected_bits[0])
724 #define GET_HEAP_MARKING_BITS(x) (&GET_HEAP_PAGE(x)->marking_bits[0])
725 #endif
726 
727 /* Aliases */
728 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
729 #define rb_objspace (*rb_objspace_of(GET_VM()))
730 #define rb_objspace_of(vm) ((vm)->objspace)
731 #else
733 #define rb_objspace_of(vm) (&rb_objspace)
734 #endif
735 
736 #define ruby_initial_gc_stress gc_params.gc_stress
737 
739 
740 #define malloc_limit objspace->malloc_params.limit
741 #define malloc_increase objspace->malloc_params.increase
742 #define malloc_allocated_size objspace->malloc_params.allocated_size
743 #define heap_pages_sorted objspace->heap_pages.sorted
744 #define heap_allocated_pages objspace->heap_pages.allocated_pages
745 #define heap_pages_sorted_length objspace->heap_pages.sorted_length
746 #define heap_pages_lomem objspace->heap_pages.range[0]
747 #define heap_pages_himem objspace->heap_pages.range[1]
748 #define heap_allocatable_pages objspace->heap_pages.allocatable_pages
749 #define heap_pages_freeable_pages objspace->heap_pages.freeable_pages
750 #define heap_pages_final_slots objspace->heap_pages.final_slots
751 #define heap_pages_deferred_final objspace->heap_pages.deferred_final
752 #define heap_eden (&objspace->eden_heap)
753 #define heap_tomb (&objspace->tomb_heap)
754 #define dont_gc objspace->flags.dont_gc
755 #define during_gc objspace->flags.during_gc
756 #define finalizing objspace->atomic_flags.finalizing
757 #define finalizer_table objspace->finalizer_table
758 #define global_list objspace->global_list
759 #define ruby_gc_stressful objspace->flags.gc_stressful
760 #define ruby_gc_stress_mode objspace->gc_stress_mode
761 #if GC_DEBUG_STRESS_TO_CLASS
762 #define stress_to_class objspace->stress_to_class
763 #else
764 #define stress_to_class 0
765 #endif
766 
767 static inline enum gc_mode
768 gc_mode_verify(enum gc_mode mode)
769 {
770 #if RGENGC_CHECK_MODE > 0
771  switch (mode) {
772  case gc_mode_none:
773  case gc_mode_marking:
774  case gc_mode_sweeping:
775  break;
776  default:
777  rb_bug("gc_mode_verify: unreachable (%d)", (int)mode);
778  }
779 #endif
780  return mode;
781 }
782 
783 #define gc_mode(objspace) gc_mode_verify((enum gc_mode)(objspace)->flags.mode)
784 #define gc_mode_set(objspace, mode) ((objspace)->flags.mode = (unsigned int)gc_mode_verify(mode))
785 
786 #define is_marking(objspace) (gc_mode(objspace) == gc_mode_marking)
787 #define is_sweeping(objspace) (gc_mode(objspace) == gc_mode_sweeping)
788 #if USE_RGENGC
789 #define is_full_marking(objspace) ((objspace)->flags.during_minor_gc == FALSE)
790 #else
791 #define is_full_marking(objspace) TRUE
792 #endif
793 #if GC_ENABLE_INCREMENTAL_MARK
794 #define is_incremental_marking(objspace) ((objspace)->flags.during_incremental_marking != FALSE)
795 #else
796 #define is_incremental_marking(objspace) FALSE
797 #endif
798 #if GC_ENABLE_INCREMENTAL_MARK
799 #define will_be_incremental_marking(objspace) ((objspace)->rgengc.need_major_gc != GPR_FLAG_NONE)
800 #else
801 #define will_be_incremental_marking(objspace) FALSE
802 #endif
803 #define has_sweeping_pages(heap) ((heap)->sweep_pages != 0)
804 #define is_lazy_sweeping(heap) (GC_ENABLE_LAZY_SWEEP && has_sweeping_pages(heap))
805 
806 #if SIZEOF_LONG == SIZEOF_VOIDP
807 # define nonspecial_obj_id(obj) (VALUE)((SIGNED_VALUE)(obj)|FIXNUM_FLAG)
808 # define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG) /* unset FIXNUM_FLAG */
809 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
810 # define nonspecial_obj_id(obj) LL2NUM((SIGNED_VALUE)(obj) / 2)
811 # define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \
812  ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1))
813 #else
814 # error not supported
815 #endif
816 
817 #define RANY(o) ((RVALUE*)(o))
818 
819 struct RZombie {
820  struct RBasic basic;
822  void (*dfree)(void *);
823  void *data;
824 };
825 
826 #define RZOMBIE(o) ((struct RZombie *)(o))
827 
828 #define nomem_error GET_VM()->special_exceptions[ruby_error_nomemory]
829 
833 
834 void rb_iseq_mark(const rb_iseq_t *iseq);
835 void rb_iseq_free(const rb_iseq_t *iseq);
836 
838 
839 static void rb_objspace_call_finalizer(rb_objspace_t *objspace);
840 static VALUE define_final0(VALUE obj, VALUE block);
841 
842 static void negative_size_allocation_error(const char *);
843 static void *aligned_malloc(size_t, size_t);
844 static void aligned_free(void *);
845 
846 static void init_mark_stack(mark_stack_t *stack);
847 
848 static int ready_to_gc(rb_objspace_t *objspace);
849 
850 static int garbage_collect(rb_objspace_t *, int full_mark, int immediate_mark, int immediate_sweep, int reason);
851 
852 static int gc_start(rb_objspace_t *objspace, const int full_mark, const int immediate_mark, const unsigned int immediate_sweep, int reason);
853 static void gc_rest(rb_objspace_t *objspace);
854 static inline void gc_enter(rb_objspace_t *objspace, const char *event);
855 static inline void gc_exit(rb_objspace_t *objspace, const char *event);
856 
857 static void gc_marks(rb_objspace_t *objspace, int full_mark);
858 static void gc_marks_start(rb_objspace_t *objspace, int full);
859 static int gc_marks_finish(rb_objspace_t *objspace);
860 static void gc_marks_rest(rb_objspace_t *objspace);
861 #if GC_ENABLE_INCREMENTAL_MARK
862 static void gc_marks_step(rb_objspace_t *objspace, int slots);
863 static void gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap);
864 #endif
865 
866 static void gc_sweep(rb_objspace_t *objspace);
867 static void gc_sweep_start(rb_objspace_t *objspace);
868 static void gc_sweep_finish(rb_objspace_t *objspace);
869 static int gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap);
870 static void gc_sweep_rest(rb_objspace_t *objspace);
871 #if GC_ENABLE_LAZY_SWEEP
872 static void gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *heap);
873 #endif
874 
875 static inline void gc_mark(rb_objspace_t *objspace, VALUE ptr);
876 static void gc_mark_ptr(rb_objspace_t *objspace, VALUE ptr);
877 static void gc_mark_maybe(rb_objspace_t *objspace, VALUE ptr);
878 static void gc_mark_children(rb_objspace_t *objspace, VALUE ptr);
879 
880 static int gc_mark_stacked_objects_incremental(rb_objspace_t *, size_t count);
881 static int gc_mark_stacked_objects_all(rb_objspace_t *);
882 static void gc_grey(rb_objspace_t *objspace, VALUE ptr);
883 
884 static inline int gc_mark_set(rb_objspace_t *objspace, VALUE obj);
885 static inline int is_pointer_to_heap(rb_objspace_t *objspace, void *ptr);
886 
887 static void push_mark_stack(mark_stack_t *, VALUE);
888 static int pop_mark_stack(mark_stack_t *, VALUE *);
889 static size_t mark_stack_size(mark_stack_t *stack);
890 static void shrink_stack_chunk_cache(mark_stack_t *stack);
891 
892 static size_t obj_memsize_of(VALUE obj, int use_all_types);
893 static VALUE gc_verify_internal_consistency(VALUE self);
894 static int gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj);
895 static int gc_verify_heap_pages(rb_objspace_t *objspace);
896 
897 static void gc_stress_set(rb_objspace_t *objspace, VALUE flag);
898 
899 static double getrusage_time(void);
900 static inline void gc_prof_setup_new_record(rb_objspace_t *objspace, int reason);
901 static inline void gc_prof_timer_start(rb_objspace_t *);
902 static inline void gc_prof_timer_stop(rb_objspace_t *);
903 static inline void gc_prof_mark_timer_start(rb_objspace_t *);
904 static inline void gc_prof_mark_timer_stop(rb_objspace_t *);
905 static inline void gc_prof_sweep_timer_start(rb_objspace_t *);
906 static inline void gc_prof_sweep_timer_stop(rb_objspace_t *);
907 static inline void gc_prof_set_malloc_info(rb_objspace_t *);
908 static inline void gc_prof_set_heap_info(rb_objspace_t *);
909 
910 #define gc_prof_record(objspace) (objspace)->profile.current_record
911 #define gc_prof_enabled(objspace) ((objspace)->profile.run && (objspace)->profile.current_record)
912 
913 #ifdef HAVE_VA_ARGS_MACRO
914 # define gc_report(level, objspace, ...) \
915  if (!RGENGC_DEBUG_ENABLED(level)) {} else gc_report_body(level, objspace, __VA_ARGS__)
916 #else
917 # define gc_report if (!RGENGC_DEBUG_ENABLED(0)) {} else gc_report_body
918 #endif
919 PRINTF_ARGS(static void gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...), 3, 4);
920 static const char *obj_info(VALUE obj);
921 
922 #define PUSH_MARK_FUNC_DATA(v) do { \
923  struct mark_func_data_struct *prev_mark_func_data = objspace->mark_func_data; \
924  objspace->mark_func_data = (v);
925 
926 #define POP_MARK_FUNC_DATA() objspace->mark_func_data = prev_mark_func_data;} while (0)
927 
928 /*
929  * 1 - TSC (H/W Time Stamp Counter)
930  * 2 - getrusage
931  */
932 #ifndef TICK_TYPE
933 #define TICK_TYPE 1
934 #endif
935 
936 #if USE_TICK_T
937 
938 #if TICK_TYPE == 1
939 /* the following code is only for internal tuning. */
940 
941 /* Source code to use RDTSC is quoted and modified from
942  * http://www.mcs.anl.gov/~kazutomo/rdtsc.html
943  * written by Kazutomo Yoshii <kazutomo@mcs.anl.gov>
944  */
945 
946 #if defined(__GNUC__) && defined(__i386__)
947 typedef unsigned long long tick_t;
948 #define PRItick "llu"
949 static inline tick_t
950 tick(void)
951 {
952  unsigned long long int x;
953  __asm__ __volatile__ ("rdtsc" : "=A" (x));
954  return x;
955 }
956 
957 #elif defined(__GNUC__) && defined(__x86_64__)
958 typedef unsigned long long tick_t;
959 #define PRItick "llu"
960 
961 static __inline__ tick_t
962 tick(void)
963 {
964  unsigned long hi, lo;
965  __asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
966  return ((unsigned long long)lo)|( ((unsigned long long)hi)<<32);
967 }
968 
969 #elif defined(__powerpc64__) && GCC_VERSION_SINCE(4,8,0)
970 typedef unsigned long long tick_t;
971 #define PRItick "llu"
972 
973 static __inline__ tick_t
974 tick(void)
975 {
976  unsigned long long val = __builtin_ppc_get_timebase();
977  return val;
978 }
979 
980 #elif defined(_WIN32) && defined(_MSC_VER)
981 #include <intrin.h>
982 typedef unsigned __int64 tick_t;
983 #define PRItick "llu"
984 
985 static inline tick_t
986 tick(void)
987 {
988  return __rdtsc();
989 }
990 
991 #else /* use clock */
992 typedef clock_t tick_t;
993 #define PRItick "llu"
994 
995 static inline tick_t
996 tick(void)
997 {
998  return clock();
999 }
1000 #endif /* TSC */
1001 
1002 #elif TICK_TYPE == 2
1003 typedef double tick_t;
1004 #define PRItick "4.9f"
1005 
1006 static inline tick_t
1007 tick(void)
1008 {
1009  return getrusage_time();
1010 }
1011 #else /* TICK_TYPE */
1012 #error "choose tick type"
1013 #endif /* TICK_TYPE */
1014 
1015 #define MEASURE_LINE(expr) do { \
1016  volatile tick_t start_time = tick(); \
1017  volatile tick_t end_time; \
1018  expr; \
1019  end_time = tick(); \
1020  fprintf(stderr, "0\t%"PRItick"\t%s\n", end_time - start_time, #expr); \
1021 } while (0)
1022 
1023 #else /* USE_TICK_T */
1024 #define MEASURE_LINE(expr) expr
1025 #endif /* USE_TICK_T */
1026 
1027 #define FL_CHECK2(name, x, pred) \
1028  ((RGENGC_CHECK_MODE && SPECIAL_CONST_P(x)) ? \
1029  (rb_bug(name": SPECIAL_CONST (%p)", (void *)(x)), 0) : (pred))
1030 #define FL_TEST2(x,f) FL_CHECK2("FL_TEST2", x, FL_TEST_RAW((x),(f)) != 0)
1031 #define FL_SET2(x,f) FL_CHECK2("FL_SET2", x, RBASIC(x)->flags |= (f))
1032 #define FL_UNSET2(x,f) FL_CHECK2("FL_UNSET2", x, RBASIC(x)->flags &= ~(f))
1033 
1034 #define RVALUE_MARK_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), (obj))
1035 #define RVALUE_PAGE_MARKED(page, obj) MARKED_IN_BITMAP((page)->mark_bits, (obj))
1036 
1037 #if USE_RGENGC
1038 #define RVALUE_WB_UNPROTECTED_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), (obj))
1039 #define RVALUE_UNCOLLECTIBLE_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_UNCOLLECTIBLE_BITS(obj), (obj))
1040 #define RVALUE_MARKING_BITMAP(obj) MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), (obj))
1041 
1042 #define RVALUE_PAGE_WB_UNPROTECTED(page, obj) MARKED_IN_BITMAP((page)->wb_unprotected_bits, (obj))
1043 #define RVALUE_PAGE_UNCOLLECTIBLE(page, obj) MARKED_IN_BITMAP((page)->uncollectible_bits, (obj))
1044 #define RVALUE_PAGE_MARKING(page, obj) MARKED_IN_BITMAP((page)->marking_bits, (obj))
1045 
1046 #define RVALUE_OLD_AGE 3
1047 #define RVALUE_AGE_SHIFT 5 /* FL_PROMOTED0 bit */
1048 
1049 static int rgengc_remembered(rb_objspace_t *objspace, VALUE obj);
1050 static int rgengc_remember(rb_objspace_t *objspace, VALUE obj);
1051 static void rgengc_mark_and_rememberset_clear(rb_objspace_t *objspace, rb_heap_t *heap);
1052 static void rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap);
1053 
1054 static inline int
1055 RVALUE_FLAGS_AGE(VALUE flags)
1056 {
1057  return (int)((flags & (FL_PROMOTED0 | FL_PROMOTED1)) >> RVALUE_AGE_SHIFT);
1058 }
1059 
1060 #endif /* USE_RGENGC */
1061 
1062 
1063 #if RGENGC_CHECK_MODE == 0
1064 static inline VALUE
1065 check_rvalue_consistency(const VALUE obj)
1066 {
1067  return obj;
1068 }
1069 #else
1070 static VALUE
1071 check_rvalue_consistency(const VALUE obj)
1072 {
1073  rb_objspace_t *objspace = &rb_objspace;
1074 
1075  if (SPECIAL_CONST_P(obj)) {
1076  rb_bug("check_rvalue_consistency: %p is a special const.", (void *)obj);
1077  }
1078  else if (!is_pointer_to_heap(objspace, (void *)obj)) {
1079  rb_bug("check_rvalue_consistency: %p is not a Ruby object.", (void *)obj);
1080  }
1081  else {
1082  const int wb_unprotected_bit = RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1083  const int uncollectible_bit = RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1084  const int mark_bit = RVALUE_MARK_BITMAP(obj) != 0;
1085  const int marking_bit = RVALUE_MARKING_BITMAP(obj) != 0, remembered_bit = marking_bit;
1086  const int age = RVALUE_FLAGS_AGE(RBASIC(obj)->flags);
1087 
1088  if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("check_rvalue_consistency: %s is T_NONE", obj_info(obj));
1089  if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("check_rvalue_consistency: %s is T_ZOMBIE", obj_info(obj));
1090  obj_memsize_of((VALUE)obj, FALSE);
1091 
1092  /* check generation
1093  *
1094  * OLD == age == 3 && old-bitmap && mark-bit (except incremental marking)
1095  */
1096  if (age > 0 && wb_unprotected_bit) {
1097  rb_bug("check_rvalue_consistency: %s is not WB protected, but age is %d > 0.", obj_info(obj), age);
1098  }
1099 
1100  if (!is_marking(objspace) && uncollectible_bit && !mark_bit) {
1101  rb_bug("check_rvalue_consistency: %s is uncollectible, but is not marked while !gc.", obj_info(obj));
1102  }
1103 
1104  if (!is_full_marking(objspace)) {
1105  if (uncollectible_bit && age != RVALUE_OLD_AGE && !wb_unprotected_bit) {
1106  rb_bug("check_rvalue_consistency: %s is uncollectible, but not old (age: %d) and not WB unprotected.", obj_info(obj), age);
1107  }
1108  if (remembered_bit && age != RVALUE_OLD_AGE) {
1109  rb_bug("check_rvalue_consistency: %s is rememberd, but not old (age: %d).", obj_info(obj), age);
1110  }
1111  }
1112 
1113  /*
1114  * check coloring
1115  *
1116  * marking:false marking:true
1117  * marked:false white *invalid*
1118  * marked:true black grey
1119  */
1120  if (is_incremental_marking(objspace) && marking_bit) {
1121  if (!is_marking(objspace) && !mark_bit) rb_bug("check_rvalue_consistency: %s is marking, but not marked.", obj_info(obj));
1122  }
1123  }
1124  return obj;
1125 }
1126 #endif
1127 
1128 static inline int
1129 RVALUE_MARKED(VALUE obj)
1130 {
1131  check_rvalue_consistency(obj);
1132  return RVALUE_MARK_BITMAP(obj) != 0;
1133 }
1134 
1135 #if USE_RGENGC
1136 static inline int
1137 RVALUE_WB_UNPROTECTED(VALUE obj)
1138 {
1139  check_rvalue_consistency(obj);
1140  return RVALUE_WB_UNPROTECTED_BITMAP(obj) != 0;
1141 }
1142 
1143 static inline int
1144 RVALUE_MARKING(VALUE obj)
1145 {
1146  check_rvalue_consistency(obj);
1147  return RVALUE_MARKING_BITMAP(obj) != 0;
1148 }
1149 
1150 static inline int
1151 RVALUE_REMEMBERED(VALUE obj)
1152 {
1153  check_rvalue_consistency(obj);
1154  return RVALUE_MARKING_BITMAP(obj) != 0;
1155 }
1156 
1157 static inline int
1158 RVALUE_UNCOLLECTIBLE(VALUE obj)
1159 {
1160  check_rvalue_consistency(obj);
1161  return RVALUE_UNCOLLECTIBLE_BITMAP(obj) != 0;
1162 }
1163 
1164 static inline int
1165 RVALUE_OLD_P_RAW(VALUE obj)
1166 {
1167  const VALUE promoted = FL_PROMOTED0 | FL_PROMOTED1;
1168  return (RBASIC(obj)->flags & promoted) == promoted;
1169 }
1170 
1171 static inline int
1172 RVALUE_OLD_P(VALUE obj)
1173 {
1174  check_rvalue_consistency(obj);
1175  return RVALUE_OLD_P_RAW(obj);
1176 }
1177 
1178 #if RGENGC_CHECK_MODE || GC_DEBUG
1179 static inline int
1180 RVALUE_AGE(VALUE obj)
1181 {
1182  check_rvalue_consistency(obj);
1183  return RVALUE_FLAGS_AGE(RBASIC(obj)->flags);
1184 }
1185 #endif
1186 
1187 static inline void
1188 RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
1189 {
1190  MARK_IN_BITMAP(&page->uncollectible_bits[0], obj);
1191  objspace->rgengc.old_objects++;
1192 
1193 #if RGENGC_PROFILE >= 2
1194  objspace->profile.total_promoted_count++;
1195  objspace->profile.promoted_types[BUILTIN_TYPE(obj)]++;
1196 #endif
1197 }
1198 
1199 static inline void
1200 RVALUE_OLD_UNCOLLECTIBLE_SET(rb_objspace_t *objspace, VALUE obj)
1201 {
1202  RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, GET_HEAP_PAGE(obj), obj);
1203 }
1204 
1205 static inline VALUE
1206 RVALUE_FLAGS_AGE_SET(VALUE flags, int age)
1207 {
1208  flags &= ~(FL_PROMOTED0 | FL_PROMOTED1);
1209  flags |= (age << RVALUE_AGE_SHIFT);
1210  return flags;
1211 }
1212 
1213 /* set age to age+1 */
1214 static inline void
1215 RVALUE_AGE_INC(rb_objspace_t *objspace, VALUE obj)
1216 {
1217  VALUE flags = RBASIC(obj)->flags;
1218  int age = RVALUE_FLAGS_AGE(flags);
1219 
1220  if (RGENGC_CHECK_MODE && age == RVALUE_OLD_AGE) {
1221  rb_bug("RVALUE_AGE_INC: can not increment age of OLD object %s.", obj_info(obj));
1222  }
1223 
1224  age++;
1225  RBASIC(obj)->flags = RVALUE_FLAGS_AGE_SET(flags, age);
1226 
1227  if (age == RVALUE_OLD_AGE) {
1228  RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
1229  }
1230  check_rvalue_consistency(obj);
1231 }
1232 
1233 /* set age to RVALUE_OLD_AGE */
1234 static inline void
1235 RVALUE_AGE_SET_OLD(rb_objspace_t *objspace, VALUE obj)
1236 {
1237  check_rvalue_consistency(obj);
1238  GC_ASSERT(!RVALUE_OLD_P(obj));
1239 
1240  RBASIC(obj)->flags = RVALUE_FLAGS_AGE_SET(RBASIC(obj)->flags, RVALUE_OLD_AGE);
1241  RVALUE_OLD_UNCOLLECTIBLE_SET(objspace, obj);
1242 
1243  check_rvalue_consistency(obj);
1244 }
1245 
1246 /* set age to RVALUE_OLD_AGE - 1 */
1247 static inline void
1248 RVALUE_AGE_SET_CANDIDATE(rb_objspace_t *objspace, VALUE obj)
1249 {
1250  check_rvalue_consistency(obj);
1251  GC_ASSERT(!RVALUE_OLD_P(obj));
1252 
1253  RBASIC(obj)->flags = RVALUE_FLAGS_AGE_SET(RBASIC(obj)->flags, RVALUE_OLD_AGE - 1);
1254 
1255  check_rvalue_consistency(obj);
1256 }
1257 
1258 static inline void
1259 RVALUE_DEMOTE_RAW(rb_objspace_t *objspace, VALUE obj)
1260 {
1261  RBASIC(obj)->flags = RVALUE_FLAGS_AGE_SET(RBASIC(obj)->flags, 0);
1263 }
1264 
1265 static inline void
1266 RVALUE_DEMOTE(rb_objspace_t *objspace, VALUE obj)
1267 {
1268  check_rvalue_consistency(obj);
1269  GC_ASSERT(RVALUE_OLD_P(obj));
1270 
1271  if (!is_incremental_marking(objspace) && RVALUE_REMEMBERED(obj)) {
1273  }
1274 
1275  RVALUE_DEMOTE_RAW(objspace, obj);
1276 
1277  if (RVALUE_MARKED(obj)) {
1278  objspace->rgengc.old_objects--;
1279  }
1280 
1281  check_rvalue_consistency(obj);
1282 }
1283 
1284 static inline void
1285 RVALUE_AGE_RESET_RAW(VALUE obj)
1286 {
1287  RBASIC(obj)->flags = RVALUE_FLAGS_AGE_SET(RBASIC(obj)->flags, 0);
1288 }
1289 
1290 static inline void
1291 RVALUE_AGE_RESET(VALUE obj)
1292 {
1293  check_rvalue_consistency(obj);
1294  GC_ASSERT(!RVALUE_OLD_P(obj));
1295 
1296  RVALUE_AGE_RESET_RAW(obj);
1297  check_rvalue_consistency(obj);
1298 }
1299 
1300 static inline int
1301 RVALUE_BLACK_P(VALUE obj)
1302 {
1303  return RVALUE_MARKED(obj) && !RVALUE_MARKING(obj);
1304 }
1305 
1306 #if 0
1307 static inline int
1308 RVALUE_GREY_P(VALUE obj)
1309 {
1310  return RVALUE_MARKED(obj) && RVALUE_MARKING(obj);
1311 }
1312 #endif
1313 
1314 static inline int
1315 RVALUE_WHITE_P(VALUE obj)
1316 {
1317  return RVALUE_MARKED(obj) == FALSE;
1318 }
1319 
1320 #endif /* USE_RGENGC */
1321 
1322 /*
1323  --------------------------- ObjectSpace -----------------------------
1324 */
1325 
1326 rb_objspace_t *
1328 {
1329 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE
1330  rb_objspace_t *objspace = calloc(1, sizeof(rb_objspace_t));
1331 #else
1332  rb_objspace_t *objspace = &rb_objspace;
1333 #endif
1334  malloc_limit = gc_params.malloc_limit_min;
1335 
1336  return objspace;
1337 }
1338 
1339 static void free_stack_chunks(mark_stack_t *);
1340 static void heap_page_free(rb_objspace_t *objspace, struct heap_page *page);
1341 
1342 void
1344 {
1346  rb_bug("lazy sweeping underway when freeing object space");
1347 
1348  if (objspace->profile.records) {
1349  free(objspace->profile.records);
1350  objspace->profile.records = 0;
1351  }
1352 
1353  if (global_list) {
1354  struct gc_list *list, *next;
1355  for (list = global_list; list; list = next) {
1356  next = list->next;
1357  xfree(list);
1358  }
1359  }
1360  if (heap_pages_sorted) {
1361  size_t i;
1362  for (i = 0; i < heap_allocated_pages; ++i) {
1363  heap_page_free(objspace, heap_pages_sorted[i]);
1364  }
1366  heap_allocated_pages = 0;
1368  heap_pages_lomem = 0;
1369  heap_pages_himem = 0;
1370 
1371  objspace->eden_heap.total_pages = 0;
1372  objspace->eden_heap.total_slots = 0;
1373  objspace->eden_heap.pages = NULL;
1374  }
1375  free_stack_chunks(&objspace->mark_stack);
1376 #if !(defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE)
1377  if (objspace == &rb_objspace) return;
1378 #endif
1379  free(objspace);
1380 }
1381 
1382 static void
1383 heap_pages_expand_sorted_to(rb_objspace_t *objspace, size_t next_length)
1384 {
1385  struct heap_page **sorted;
1386  size_t size = next_length * sizeof(struct heap_page *);
1387 
1388  gc_report(3, objspace, "heap_pages_expand_sorted: next_length: %d, size: %d\n", (int)next_length, (int)size);
1389 
1390  if (heap_pages_sorted_length > 0) {
1391  sorted = (struct heap_page **)realloc(heap_pages_sorted, size);
1392  if (sorted) heap_pages_sorted = sorted;
1393  }
1394  else {
1395  sorted = heap_pages_sorted = (struct heap_page **)malloc(size);
1396  }
1397 
1398  if (sorted == 0) {
1399  rb_memerror();
1400  }
1401 
1402  heap_pages_sorted_length = next_length;
1403 }
1404 
1405 static void
1406 heap_pages_expand_sorted(rb_objspace_t *objspace)
1407 {
1408  /* usually heap_allocatable_pages + heap_eden->total_pages == heap_pages_sorted_length
1409  * beacuse heap_allocatable_pages contains heap_tomb->total_pages (recycle heap_tomb pages).
1410  * howerver, if there are pages which do not have empty slots, then try to create new pages
1411  * so that the additional allocatable_pages counts (heap_tomb->total_pages) are added.
1412  */
1413  size_t next_length = heap_allocatable_pages;
1414  next_length += heap_eden->total_pages;
1415  next_length += heap_tomb->total_pages;
1416 
1417  if (next_length > heap_pages_sorted_length) {
1418  heap_pages_expand_sorted_to(objspace, next_length);
1419  }
1420 
1423 }
1424 
1425 static void
1426 heap_allocatable_pages_set(rb_objspace_t *objspace, size_t s)
1427 {
1429  heap_pages_expand_sorted(objspace);
1430 }
1431 
1432 
1433 static inline void
1434 heap_page_add_freeobj(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
1435 {
1436  RVALUE *p = (RVALUE *)obj;
1437  p->as.free.flags = 0;
1438  p->as.free.next = page->freelist;
1439  page->freelist = p;
1440 
1441  if (RGENGC_CHECK_MODE && !is_pointer_to_heap(objspace, p)) {
1442  rb_bug("heap_page_add_freeobj: %p is not rvalue.", p);
1443  }
1444 
1445  gc_report(3, objspace, "heap_page_add_freeobj: add %p to freelist\n", (void *)obj);
1446 }
1447 
1448 static inline void
1449 heap_add_freepage(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1450 {
1451  if (page->freelist) {
1452  page->free_next = heap->free_pages;
1453  heap->free_pages = page;
1454  }
1455 }
1456 
1457 #if GC_ENABLE_INCREMENTAL_MARK
1458 static inline int
1459 heap_add_poolpage(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1460 {
1461  if (page->freelist) {
1462  page->free_next = heap->pooled_pages;
1463  heap->pooled_pages = page;
1464  objspace->rincgc.pooled_slots += page->free_slots;
1465  return TRUE;
1466  }
1467  else {
1468  return FALSE;
1469  }
1470 }
1471 #endif
1472 
1473 static void
1474 heap_unlink_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1475 {
1476  if (page->prev) page->prev->next = page->next;
1477  if (page->next) page->next->prev = page->prev;
1478  if (heap->pages == page) heap->pages = page->next;
1479  page->prev = NULL;
1480  page->next = NULL;
1481  heap->total_pages--;
1482  heap->total_slots -= page->total_slots;
1483 }
1484 
1485 static void
1486 heap_page_free(rb_objspace_t *objspace, struct heap_page *page)
1487 {
1489  objspace->profile.total_freed_pages++;
1490  aligned_free(GET_PAGE_BODY(page->start));
1491  free(page);
1492 }
1493 
1494 static void
1495 heap_pages_free_unused_pages(rb_objspace_t *objspace)
1496 {
1497  size_t i, j;
1498 
1499  if (heap_tomb->pages) {
1500  for (i = j = 1; j < heap_allocated_pages; i++) {
1501  struct heap_page *page = heap_pages_sorted[i];
1502 
1503  if (page->flags.in_tomb && page->free_slots == page->total_slots) {
1504  heap_unlink_page(objspace, heap_tomb, page);
1505  heap_page_free(objspace, page);
1506  }
1507  else {
1508  if (i != j) {
1509  heap_pages_sorted[j] = page;
1510  }
1511  j++;
1512  }
1513  }
1514  GC_ASSERT(j == heap_allocated_pages);
1515  }
1516 }
1517 
1518 static struct heap_page *
1519 heap_page_allocate(rb_objspace_t *objspace)
1520 {
1521  RVALUE *start, *end, *p;
1522  struct heap_page *page;
1523  struct heap_page_body *page_body = 0;
1524  size_t hi, lo, mid;
1525  int limit = HEAP_PAGE_OBJ_LIMIT;
1526 
1527  /* assign heap_page body (contains heap_page_header and RVALUEs) */
1528  page_body = (struct heap_page_body *)aligned_malloc(HEAP_PAGE_ALIGN, HEAP_PAGE_SIZE);
1529  if (page_body == 0) {
1530  rb_memerror();
1531  }
1532 
1533  /* assign heap_page entry */
1534  page = (struct heap_page *)calloc(1, sizeof(struct heap_page));
1535  if (page == 0) {
1536  aligned_free(page_body);
1537  rb_memerror();
1538  }
1539 
1540  /* adjust obj_limit (object number available in this page) */
1541  start = (RVALUE*)((VALUE)page_body + sizeof(struct heap_page_header));
1542  if ((VALUE)start % sizeof(RVALUE) != 0) {
1543  int delta = (int)(sizeof(RVALUE) - ((VALUE)start % sizeof(RVALUE)));
1544  start = (RVALUE*)((VALUE)start + delta);
1545  limit = (HEAP_PAGE_SIZE - (int)((VALUE)start - (VALUE)page_body))/(int)sizeof(RVALUE);
1546  }
1547  end = start + limit;
1548 
1549  /* setup heap_pages_sorted */
1550  lo = 0;
1551  hi = heap_allocated_pages;
1552  while (lo < hi) {
1553  struct heap_page *mid_page;
1554 
1555  mid = (lo + hi) / 2;
1556  mid_page = heap_pages_sorted[mid];
1557  if (mid_page->start < start) {
1558  lo = mid + 1;
1559  }
1560  else if (mid_page->start > start) {
1561  hi = mid;
1562  }
1563  else {
1564  rb_bug("same heap page is allocated: %p at %"PRIuVALUE, (void *)page_body, (VALUE)mid);
1565  }
1566  }
1567 
1568  if (hi < heap_allocated_pages) {
1570  }
1571 
1572  heap_pages_sorted[hi] = page;
1573 
1575 
1577  GC_ASSERT(heap_eden->total_pages + heap_tomb->total_pages == heap_allocated_pages - 1);
1579 
1580  objspace->profile.total_allocated_pages++;
1581 
1583  rb_bug("heap_page_allocate: allocated(%"PRIdSIZE") > sorted(%"PRIdSIZE")",
1585  }
1586 
1588  if (heap_pages_himem < end) heap_pages_himem = end;
1589 
1590  page->start = start;
1591  page->total_slots = limit;
1592  page_body->header.page = page;
1593 
1594  for (p = start; p != end; p++) {
1595  gc_report(3, objspace, "assign_heap_page: %p is added to freelist\n", p);
1596  heap_page_add_freeobj(objspace, page, (VALUE)p);
1597  }
1598  page->free_slots = limit;
1599 
1600  return page;
1601 }
1602 
1603 static struct heap_page *
1604 heap_page_resurrect(rb_objspace_t *objspace)
1605 {
1606  struct heap_page *page = heap_tomb->pages;
1607 
1608  while (page) {
1609  if (page->freelist != NULL) {
1610  heap_unlink_page(objspace, heap_tomb, page);
1611  return page;
1612  }
1613  page = page->next;
1614  }
1615 
1616 
1617 
1618  return NULL;
1619 }
1620 
1621 static struct heap_page *
1622 heap_page_create(rb_objspace_t *objspace)
1623 {
1624  struct heap_page *page;
1625  const char *method = "recycle";
1626 
1628 
1629  page = heap_page_resurrect(objspace);
1630 
1631  if (page == NULL) {
1632  page = heap_page_allocate(objspace);
1633  method = "allocate";
1634  }
1635  if (0) fprintf(stderr, "heap_page_create: %s - %p, heap_allocated_pages: %d, heap_allocated_pages: %d, tomb->total_pages: %d\n",
1636  method, page, (int)heap_pages_sorted_length, (int)heap_allocated_pages, (int)heap_tomb->total_pages);
1637  return page;
1638 }
1639 
1640 static void
1641 heap_add_page(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *page)
1642 {
1643  page->flags.in_tomb = (heap == heap_tomb);
1644  page->next = heap->pages;
1645  if (heap->pages) heap->pages->prev = page;
1646  heap->pages = page;
1647  heap->total_pages++;
1648  heap->total_slots += page->total_slots;
1649 }
1650 
1651 static void
1652 heap_assign_page(rb_objspace_t *objspace, rb_heap_t *heap)
1653 {
1654  struct heap_page *page = heap_page_create(objspace);
1655  heap_add_page(objspace, heap, page);
1656  heap_add_freepage(objspace, heap, page);
1657 }
1658 
1659 static void
1660 heap_add_pages(rb_objspace_t *objspace, rb_heap_t *heap, size_t add)
1661 {
1662  size_t i;
1663 
1664  heap_allocatable_pages_set(objspace, add);
1665 
1666  for (i = 0; i < add; i++) {
1667  heap_assign_page(objspace, heap);
1668  }
1669 
1671 }
1672 
1673 static size_t
1674 heap_extend_pages(rb_objspace_t *objspace, size_t free_slots, size_t total_slots)
1675 {
1676  double goal_ratio = gc_params.heap_free_slots_goal_ratio;
1678  size_t next_used;
1679 
1680  if (goal_ratio == 0.0) {
1681  next_used = (size_t)(used * gc_params.growth_factor);
1682  }
1683  else {
1684  /* Find `f' where free_slots = f * total_slots * goal_ratio
1685  * => f = (total_slots - free_slots) / ((1 - goal_ratio) * total_slots)
1686  */
1687  double f = (double)(total_slots - free_slots) / ((1 - goal_ratio) * total_slots);
1688 
1689  if (f > gc_params.growth_factor) f = gc_params.growth_factor;
1690  if (f < 1.0) f = 1.1;
1691 
1692  next_used = (size_t)(f * used);
1693 
1694  if (0) {
1695  fprintf(stderr,
1696  "free_slots(%8"PRIuSIZE")/total_slots(%8"PRIuSIZE")=%1.2f,"
1697  " G(%1.2f), f(%1.2f),"
1698  " used(%8"PRIuSIZE") => next_used(%8"PRIuSIZE")\n",
1699  free_slots, total_slots, free_slots/(double)total_slots,
1700  goal_ratio, f, used, next_used);
1701  }
1702  }
1703 
1704  if (gc_params.growth_max_slots > 0) {
1705  size_t max_used = (size_t)(used + gc_params.growth_max_slots/HEAP_PAGE_OBJ_LIMIT);
1706  if (next_used > max_used) next_used = max_used;
1707  }
1708 
1709  return next_used - used;
1710 }
1711 
1712 static void
1713 heap_set_increment(rb_objspace_t *objspace, size_t additional_pages)
1714 {
1715  size_t used = heap_eden->total_pages;
1716  size_t next_used_limit = used + additional_pages;
1717 
1718  if (next_used_limit == heap_allocated_pages) next_used_limit++;
1719 
1720  heap_allocatable_pages_set(objspace, next_used_limit - used);
1721 
1722  gc_report(1, objspace, "heap_set_increment: heap_allocatable_pages is %d\n", (int)heap_allocatable_pages);
1723 }
1724 
1725 static int
1726 heap_increment(rb_objspace_t *objspace, rb_heap_t *heap)
1727 {
1728  if (heap_allocatable_pages > 0) {
1729  gc_report(1, objspace, "heap_increment: heap_pages_sorted_length: %d, heap_pages_inc: %d, heap->total_pages: %d\n",
1731 
1732  GC_ASSERT(heap_allocatable_pages + heap_eden->total_pages <= heap_pages_sorted_length);
1733  GC_ASSERT(heap_allocated_pages <= heap_pages_sorted_length);
1734 
1735  heap_assign_page(objspace, heap);
1736  return TRUE;
1737  }
1738  return FALSE;
1739 }
1740 
1741 static void
1742 heap_prepare(rb_objspace_t *objspace, rb_heap_t *heap)
1743 {
1744  GC_ASSERT(heap->free_pages == NULL);
1745 
1746 #if GC_ENABLE_LAZY_SWEEP
1747  if (is_lazy_sweeping(heap)) {
1748  gc_sweep_continue(objspace, heap);
1749  }
1750 #endif
1751 #if GC_ENABLE_INCREMENTAL_MARK
1752  else if (is_incremental_marking(objspace)) {
1753  gc_marks_continue(objspace, heap);
1754  }
1755 #endif
1756 
1757  if (heap->free_pages == NULL &&
1758  (will_be_incremental_marking(objspace) || heap_increment(objspace, heap) == FALSE) &&
1759  gc_start(objspace, FALSE, FALSE, FALSE, GPR_FLAG_NEWOBJ) == FALSE) {
1760  rb_memerror();
1761  }
1762 }
1763 
1764 static RVALUE *
1765 heap_get_freeobj_from_next_freepage(rb_objspace_t *objspace, rb_heap_t *heap)
1766 {
1767  struct heap_page *page;
1768  RVALUE *p;
1769 
1770  while (heap->free_pages == NULL) {
1771  heap_prepare(objspace, heap);
1772  }
1773  page = heap->free_pages;
1774  heap->free_pages = page->free_next;
1775  heap->using_page = page;
1776 
1777  GC_ASSERT(page->free_slots != 0);
1778  p = page->freelist;
1779  page->freelist = NULL;
1780  page->free_slots = 0;
1781  return p;
1782 }
1783 
1784 static inline VALUE
1785 heap_get_freeobj_head(rb_objspace_t *objspace, rb_heap_t *heap)
1786 {
1787  RVALUE *p = heap->freelist;
1788  if (LIKELY(p != NULL)) {
1789  heap->freelist = p->as.free.next;
1790  }
1791  return (VALUE)p;
1792 }
1793 
1794 static inline VALUE
1795 heap_get_freeobj(rb_objspace_t *objspace, rb_heap_t *heap)
1796 {
1797  RVALUE *p = heap->freelist;
1798 
1799  while (1) {
1800  if (LIKELY(p != NULL)) {
1801  heap->freelist = p->as.free.next;
1802  return (VALUE)p;
1803  }
1804  else {
1805  p = heap_get_freeobj_from_next_freepage(objspace, heap);
1806  }
1807  }
1808 }
1809 
1810 void
1812 {
1813  rb_objspace_t *objspace = &rb_objspace;
1814  objspace->hook_events = event & RUBY_INTERNAL_EVENT_OBJSPACE_MASK;
1815  objspace->flags.has_hook = (objspace->hook_events != 0);
1816 }
1817 
1818 static void
1819 gc_event_hook_body(rb_thread_t *th, rb_objspace_t *objspace, const rb_event_flag_t event, VALUE data)
1820 {
1821  EXEC_EVENT_HOOK(th, event, th->ec.cfp->self, 0, 0, 0, data);
1822 }
1823 
1824 #define gc_event_hook_available_p(objspace) ((objspace)->flags.has_hook)
1825 #define gc_event_hook_needed_p(objspace, event) ((objspace)->hook_events & (event))
1826 
1827 #define gc_event_hook(objspace, event, data) do { \
1828  if (UNLIKELY(gc_event_hook_needed_p(objspace, event))) { \
1829  gc_event_hook_body(GET_THREAD(), (objspace), (event), (data)); \
1830  } \
1831 } while (0)
1832 
1833 static inline VALUE
1834 newobj_init(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, int wb_protected, rb_objspace_t *objspace, VALUE obj)
1835 {
1836  GC_ASSERT(BUILTIN_TYPE(obj) == T_NONE);
1837  GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
1838 
1839  /* OBJSETUP */
1840  RBASIC(obj)->flags = flags;
1841  RBASIC_SET_CLASS_RAW(obj, klass);
1842  RANY(obj)->as.values.v1 = v1;
1843  RANY(obj)->as.values.v2 = v2;
1844  RANY(obj)->as.values.v3 = v3;
1845 
1846 #if RGENGC_CHECK_MODE
1847  GC_ASSERT(RVALUE_MARKED(obj) == FALSE);
1848  GC_ASSERT(RVALUE_MARKING(obj) == FALSE);
1849  GC_ASSERT(RVALUE_OLD_P(obj) == FALSE);
1850  GC_ASSERT(RVALUE_WB_UNPROTECTED(obj) == FALSE);
1851 
1852  if (flags & FL_PROMOTED1) {
1853  if (RVALUE_AGE(obj) != 2) rb_bug("newobj: %s of age (%d) != 2.", obj_info(obj), RVALUE_AGE(obj));
1854  }
1855  else {
1856  if (RVALUE_AGE(obj) > 0) rb_bug("newobj: %s of age (%d) > 0.", obj_info(obj), RVALUE_AGE(obj));
1857  }
1858  if (rgengc_remembered(objspace, (VALUE)obj)) rb_bug("newobj: %s is remembered.", obj_info(obj));
1859 #endif
1860 
1861 #if USE_RGENGC
1862  if (UNLIKELY(wb_protected == FALSE)) {
1864  }
1865 #endif
1866 
1867 #if RGENGC_PROFILE
1868  if (wb_protected) {
1869  objspace->profile.total_generated_normal_object_count++;
1870 #if RGENGC_PROFILE >= 2
1871  objspace->profile.generated_normal_object_count_types[BUILTIN_TYPE(obj)]++;
1872 #endif
1873  }
1874  else {
1875  objspace->profile.total_generated_shady_object_count++;
1876 #if RGENGC_PROFILE >= 2
1877  objspace->profile.generated_shady_object_count_types[BUILTIN_TYPE(obj)]++;
1878 #endif
1879  }
1880 #endif
1881 
1882 #if GC_DEBUG
1883  RANY(obj)->file = rb_source_loc(&RANY(obj)->line);
1884  GC_ASSERT(!SPECIAL_CONST_P(obj)); /* check alignment */
1885 #endif
1886 
1887  objspace->total_allocated_objects++;
1888 
1889  gc_report(5, objspace, "newobj: %s\n", obj_info(obj));
1890 
1891 #if RGENGC_OLD_NEWOBJ_CHECK > 0
1892  {
1893  static int newobj_cnt = RGENGC_OLD_NEWOBJ_CHECK;
1894 
1895  if (!is_incremental_marking(objspace) &&
1896  flags & FL_WB_PROTECTED && /* do not promote WB unprotected objects */
1897  ! RB_TYPE_P(obj, T_ARRAY)) { /* array.c assumes that allocated objects are new */
1898  if (--newobj_cnt == 0) {
1899  newobj_cnt = RGENGC_OLD_NEWOBJ_CHECK;
1900 
1901  gc_mark_set(objspace, obj);
1902  RVALUE_AGE_SET_OLD(objspace, obj);
1903 
1905  }
1906  }
1907  }
1908 #endif
1909  check_rvalue_consistency(obj);
1910  return obj;
1911 }
1912 
1913 static inline VALUE
1914 newobj_slowpath(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, rb_objspace_t *objspace, int wb_protected)
1915 {
1916  VALUE obj;
1917 
1919  if (during_gc) {
1920  dont_gc = 1;
1921  during_gc = 0;
1922  rb_bug("object allocation during garbage collection phase");
1923  }
1924 
1925  if (ruby_gc_stressful) {
1926  if (!garbage_collect(objspace, FALSE, FALSE, FALSE, GPR_FLAG_NEWOBJ)) {
1927  rb_memerror();
1928  }
1929  }
1930  }
1931 
1932  obj = heap_get_freeobj(objspace, heap_eden);
1933  newobj_init(klass, flags, v1, v2, v3, wb_protected, objspace, obj);
1934  gc_event_hook(objspace, RUBY_INTERNAL_EVENT_NEWOBJ, obj);
1935  return obj;
1936 }
1937 
1938 NOINLINE(static VALUE newobj_slowpath_wb_protected(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, rb_objspace_t *objspace));
1939 NOINLINE(static VALUE newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, rb_objspace_t *objspace));
1940 
1941 static VALUE
1942 newobj_slowpath_wb_protected(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, rb_objspace_t *objspace)
1943 {
1944  return newobj_slowpath(klass, flags, v1, v2, v3, objspace, TRUE);
1945 }
1946 
1947 static VALUE
1948 newobj_slowpath_wb_unprotected(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, rb_objspace_t *objspace)
1949 {
1950  return newobj_slowpath(klass, flags, v1, v2, v3, objspace, FALSE);
1951 }
1952 
1953 static inline VALUE
1954 newobj_of(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, int wb_protected)
1955 {
1956  rb_objspace_t *objspace = &rb_objspace;
1957  VALUE obj;
1958 
1959 #if GC_DEBUG_STRESS_TO_CLASS
1960  if (UNLIKELY(stress_to_class)) {
1961  long i, cnt = RARRAY_LEN(stress_to_class);
1962  const VALUE *ptr = RARRAY_CONST_PTR(stress_to_class);
1963  for (i = 0; i < cnt; ++i) {
1964  if (klass == ptr[i]) rb_memerror();
1965  }
1966  }
1967 #endif
1968  if (!(during_gc ||
1970  gc_event_hook_available_p(objspace)) &&
1971  (obj = heap_get_freeobj_head(objspace, heap_eden)) != Qfalse) {
1972  return newobj_init(klass, flags, v1, v2, v3, wb_protected, objspace, obj);
1973  }
1974  else {
1975  return wb_protected ?
1976  newobj_slowpath_wb_protected(klass, flags, v1, v2, v3, objspace) :
1977  newobj_slowpath_wb_unprotected(klass, flags, v1, v2, v3, objspace);
1978  }
1979 }
1980 
1981 VALUE
1983 {
1984  GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
1985  return newobj_of(klass, flags, 0, 0, 0, FALSE);
1986 }
1987 
1988 VALUE
1990 {
1991  GC_ASSERT((flags & FL_WB_PROTECTED) == 0);
1992  return newobj_of(klass, flags, 0, 0, 0, TRUE);
1993 }
1994 
1995 /* for compatibility */
1996 
1997 VALUE
1999 {
2000  return newobj_of(0, T_NONE, 0, 0, 0, FALSE);
2001 }
2002 
2003 VALUE
2004 rb_newobj_of(VALUE klass, VALUE flags)
2005 {
2006  return newobj_of(klass, flags & ~FL_WB_PROTECTED, 0, 0, 0, flags & FL_WB_PROTECTED);
2007 }
2008 
2009 NODE*
2011 {
2012  NODE *n = (NODE *)newobj_of(0, T_NODE, a0, a1, a2, FALSE); /* TODO: node also should be wb protected */
2013  nd_set_type(n, type);
2014  return n;
2015 }
2016 
2017 #undef rb_imemo_new
2018 
2019 VALUE
2020 rb_imemo_new(enum imemo_type type, VALUE v1, VALUE v2, VALUE v3, VALUE v0)
2021 {
2022  VALUE flags = T_IMEMO | (type << FL_USHIFT);
2023  return newobj_of(v0, flags, v1, v2, v3, TRUE);
2024 }
2025 
2026 #if IMEMO_DEBUG
2027 VALUE
2028 rb_imemo_new_debug(enum imemo_type type, VALUE v1, VALUE v2, VALUE v3, VALUE v0, const char *file, int line)
2029 {
2030  VALUE memo = rb_imemo_new(type, v1, v2, v3, v0);
2031  fprintf(stderr, "memo %p (type: %d) @ %s:%d\n", memo, imemo_type(memo), file, line);
2032  return memo;
2033 }
2034 #endif
2035 
2036 VALUE
2037 rb_data_object_wrap(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
2038 {
2039  if (klass) Check_Type(klass, T_CLASS);
2040  return newobj_of(klass, T_DATA, (VALUE)dmark, (VALUE)dfree, (VALUE)datap, FALSE);
2041 }
2042 
2043 #undef rb_data_object_alloc
2045  RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree),
2046  rb_data_object_wrap, (klass, datap, dmark, dfree))
2047 
2048 
2049 VALUE
2050 rb_data_object_zalloc(VALUE klass, size_t size, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
2051 {
2052  VALUE obj = rb_data_object_wrap(klass, 0, dmark, dfree);
2053  DATA_PTR(obj) = xcalloc(1, size);
2054  return obj;
2055 }
2056 
2057 VALUE
2058 rb_data_typed_object_wrap(VALUE klass, void *datap, const rb_data_type_t *type)
2059 {
2060  if (klass) Check_Type(klass, T_CLASS);
2061  return newobj_of(klass, T_DATA, (VALUE)type, (VALUE)1, (VALUE)datap, type->flags & RUBY_FL_WB_PROTECTED);
2062 }
2063 
2064 #undef rb_data_typed_object_alloc
2066  const rb_data_type_t *type),
2067  rb_data_typed_object_wrap, (klass, datap, type))
2068 
2069 VALUE
2070 rb_data_typed_object_zalloc(VALUE klass, size_t size, const rb_data_type_t *type)
2071 {
2072  VALUE obj = rb_data_typed_object_wrap(klass, 0, type);
2073  DATA_PTR(obj) = xcalloc(1, size);
2074  return obj;
2075 }
2076 
2077 size_t
2079 {
2080  if (RTYPEDDATA_P(obj)) {
2081  const rb_data_type_t *type = RTYPEDDATA_TYPE(obj);
2082  const void *ptr = RTYPEDDATA_DATA(obj);
2083  if (ptr && type->function.dsize) {
2084  return type->function.dsize(ptr);
2085  }
2086  }
2087  return 0;
2088 }
2089 
2090 const char *
2092 {
2093  if (RTYPEDDATA_P(obj)) {
2094  return RTYPEDDATA_TYPE(obj)->wrap_struct_name;
2095  }
2096  else {
2097  return 0;
2098  }
2099 }
2100 
2101 PUREFUNC(static inline int is_pointer_to_heap(rb_objspace_t *objspace, void *ptr);)
2102 static inline int
2103 is_pointer_to_heap(rb_objspace_t *objspace, void *ptr)
2104 {
2105  register RVALUE *p = RANY(ptr);
2106  register struct heap_page *page;
2107  register size_t hi, lo, mid;
2108 
2109  if (p < heap_pages_lomem || p > heap_pages_himem) return FALSE;
2110  if ((VALUE)p % sizeof(RVALUE) != 0) return FALSE;
2111 
2112  /* check if p looks like a pointer using bsearch*/
2113  lo = 0;
2114  hi = heap_allocated_pages;
2115  while (lo < hi) {
2116  mid = (lo + hi) / 2;
2117  page = heap_pages_sorted[mid];
2118  if (page->start <= p) {
2119  if (p < page->start + page->total_slots) {
2120  return TRUE;
2121  }
2122  lo = mid + 1;
2123  }
2124  else {
2125  hi = mid;
2126  }
2127  }
2128  return FALSE;
2129 }
2130 
2131 static enum rb_id_table_iterator_result
2132 free_const_entry_i(VALUE value, void *data)
2133 {
2134  rb_const_entry_t *ce = (rb_const_entry_t *)value;
2135  xfree(ce);
2136  return ID_TABLE_CONTINUE;
2137 }
2138 
2139 void
2141 {
2142  rb_id_table_foreach_values(tbl, free_const_entry_i, 0);
2143  rb_id_table_free(tbl);
2144 }
2145 
2146 static inline void
2147 make_zombie(rb_objspace_t *objspace, VALUE obj, void (*dfree)(void *), void *data)
2148 {
2149  struct RZombie *zombie = RZOMBIE(obj);
2150  zombie->basic.flags = T_ZOMBIE;
2151  zombie->dfree = dfree;
2152  zombie->data = data;
2153  zombie->next = heap_pages_deferred_final;
2154  heap_pages_deferred_final = (VALUE)zombie;
2155 }
2156 
2157 static inline void
2158 make_io_zombie(rb_objspace_t *objspace, VALUE obj)
2159 {
2160  rb_io_t *fptr = RANY(obj)->as.file.fptr;
2161  make_zombie(objspace, obj, (void (*)(void*))rb_io_fptr_finalize, fptr);
2162 }
2163 
2164 static int
2165 obj_free(rb_objspace_t *objspace, VALUE obj)
2166 {
2167  RB_DEBUG_COUNTER_INC(obj_free);
2168 
2170 
2171  switch (BUILTIN_TYPE(obj)) {
2172  case T_NIL:
2173  case T_FIXNUM:
2174  case T_TRUE:
2175  case T_FALSE:
2176  rb_bug("obj_free() called for broken object");
2177  break;
2178  }
2179 
2180  if (FL_TEST(obj, FL_EXIVAR)) {
2182  FL_UNSET(obj, FL_EXIVAR);
2183  }
2184 
2185 #if USE_RGENGC
2186  if (RVALUE_WB_UNPROTECTED(obj)) CLEAR_IN_BITMAP(GET_HEAP_WB_UNPROTECTED_BITS(obj), obj);
2187 
2188 #if RGENGC_CHECK_MODE
2189 #define CHECK(x) if (x(obj) != FALSE) rb_bug("obj_free: " #x "(%s) != FALSE", obj_info(obj))
2190  CHECK(RVALUE_WB_UNPROTECTED);
2191  CHECK(RVALUE_MARKED);
2192  CHECK(RVALUE_MARKING);
2193  CHECK(RVALUE_UNCOLLECTIBLE);
2194 #undef CHECK
2195 #endif
2196 #endif
2197 
2198  switch (BUILTIN_TYPE(obj)) {
2199  case T_OBJECT:
2200  if (!(RANY(obj)->as.basic.flags & ROBJECT_EMBED) &&
2201  RANY(obj)->as.object.as.heap.ivptr) {
2202  xfree(RANY(obj)->as.object.as.heap.ivptr);
2203  RB_DEBUG_COUNTER_INC(obj_obj_ptr);
2204  }
2205  else {
2206  RB_DEBUG_COUNTER_INC(obj_obj_embed);
2207  }
2208  break;
2209  case T_MODULE:
2210  case T_CLASS:
2212  if (RCLASS_IV_TBL(obj)) {
2214  }
2215  if (RCLASS_CONST_TBL(obj)) {
2217  }
2218  if (RCLASS_IV_INDEX_TBL(obj)) {
2220  }
2221  if (RCLASS_EXT(obj)->subclasses) {
2222  if (BUILTIN_TYPE(obj) == T_MODULE) {
2224  }
2225  else {
2227  }
2228  RCLASS_EXT(obj)->subclasses = NULL;
2229  }
2232  if (RANY(obj)->as.klass.ptr)
2233  xfree(RANY(obj)->as.klass.ptr);
2234  RANY(obj)->as.klass.ptr = NULL;
2235  break;
2236  case T_STRING:
2237  rb_str_free(obj);
2238  break;
2239  case T_ARRAY:
2240  rb_ary_free(obj);
2241  break;
2242  case T_HASH:
2243  if (RANY(obj)->as.hash.ntbl) {
2244  st_free_table(RANY(obj)->as.hash.ntbl);
2245  }
2246  break;
2247  case T_REGEXP:
2248  if (RANY(obj)->as.regexp.ptr) {
2249  onig_free(RANY(obj)->as.regexp.ptr);
2250  }
2251  break;
2252  case T_DATA:
2253  if (DATA_PTR(obj)) {
2254  int free_immediately = FALSE;
2255  void (*dfree)(void *);
2256  void *data = DATA_PTR(obj);
2257 
2258  if (RTYPEDDATA_P(obj)) {
2259  free_immediately = (RANY(obj)->as.typeddata.type->flags & RUBY_TYPED_FREE_IMMEDIATELY) != 0;
2260  dfree = RANY(obj)->as.typeddata.type->function.dfree;
2261  if (0 && free_immediately == 0) {
2262  /* to expose non-free-immediate T_DATA */
2263  fprintf(stderr, "not immediate -> %s\n", RANY(obj)->as.typeddata.type->wrap_struct_name);
2264  }
2265  }
2266  else {
2267  dfree = RANY(obj)->as.data.dfree;
2268  }
2269 
2270  if (dfree) {
2271  if (dfree == RUBY_DEFAULT_FREE) {
2272  xfree(data);
2273  }
2274  else if (free_immediately) {
2275  (*dfree)(data);
2276  }
2277  else {
2278  make_zombie(objspace, obj, dfree, data);
2279  return 1;
2280  }
2281  }
2282  }
2283  break;
2284  case T_MATCH:
2285  if (RANY(obj)->as.match.rmatch) {
2286  struct rmatch *rm = RANY(obj)->as.match.rmatch;
2287  onig_region_free(&rm->regs, 0);
2288  if (rm->char_offset)
2289  xfree(rm->char_offset);
2290  xfree(rm);
2291  }
2292  break;
2293  case T_FILE:
2294  if (RANY(obj)->as.file.fptr) {
2295  make_io_zombie(objspace, obj);
2296  return 1;
2297  }
2298  break;
2299  case T_RATIONAL:
2300  case T_COMPLEX:
2301  break;
2302  case T_ICLASS:
2303  /* Basically , T_ICLASS shares table with the module */
2304  if (FL_TEST(obj, RICLASS_IS_ORIGIN)) {
2306  }
2307  if (RCLASS_CALLABLE_M_TBL(obj) != NULL) {
2309  }
2310  if (RCLASS_EXT(obj)->subclasses) {
2312  RCLASS_EXT(obj)->subclasses = NULL;
2313  }
2316  xfree(RANY(obj)->as.klass.ptr);
2317  RANY(obj)->as.klass.ptr = NULL;
2318  break;
2319 
2320  case T_FLOAT:
2321  break;
2322 
2323  case T_BIGNUM:
2324  if (!(RBASIC(obj)->flags & BIGNUM_EMBED_FLAG) && BIGNUM_DIGITS(obj)) {
2325  xfree(BIGNUM_DIGITS(obj));
2326  }
2327  break;
2328 
2329  case T_NODE:
2330  rb_gc_free_node(obj);
2331  break; /* no need to free iv_tbl */
2332 
2333  case T_STRUCT:
2334  if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 &&
2335  RANY(obj)->as.rstruct.as.heap.ptr) {
2336  xfree((void *)RANY(obj)->as.rstruct.as.heap.ptr);
2337  }
2338  break;
2339 
2340  case T_SYMBOL:
2341  {
2342  rb_gc_free_dsymbol(obj);
2343  }
2344  break;
2345 
2346  case T_IMEMO:
2347  switch (imemo_type(obj)) {
2348  case imemo_ment:
2349  rb_free_method_entry(&RANY(obj)->as.imemo.ment);
2350  break;
2351  case imemo_iseq:
2352  rb_iseq_free(&RANY(obj)->as.imemo.iseq);
2353  break;
2354  case imemo_env:
2355  GC_ASSERT(VM_ENV_ESCAPED_P(RANY(obj)->as.imemo.env.ep));
2356  xfree((VALUE *)RANY(obj)->as.imemo.env.env);
2357  break;
2358  case imemo_alloc:
2359  xfree(RANY(obj)->as.imemo.alloc.ptr);
2360  break;
2361  default:
2362  break;
2363  }
2364  return 0;
2365 
2366  default:
2367  rb_bug("gc_sweep(): unknown data type 0x%x(%p) 0x%"PRIxVALUE,
2368  BUILTIN_TYPE(obj), (void*)obj, RBASIC(obj)->flags);
2369  }
2370 
2371  if (FL_TEST(obj, FL_FINALIZE)) {
2372  make_zombie(objspace, obj, 0, 0);
2373  return 1;
2374  }
2375  else {
2376  return 0;
2377  }
2378 }
2379 
2380 void
2382 {
2383  rb_objspace_t *objspace = &rb_objspace;
2384 
2385  gc_stress_set(objspace, ruby_initial_gc_stress);
2386 
2387 #if RGENGC_ESTIMATE_OLDMALLOC
2388  objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
2389 #endif
2390 
2391  heap_add_pages(objspace, heap_eden, gc_params.heap_init_slots / HEAP_PAGE_OBJ_LIMIT);
2392  init_mark_stack(&objspace->mark_stack);
2393 
2394 #ifdef USE_SIGALTSTACK
2395  {
2396  /* altstack of another threads are allocated in another place */
2397  rb_thread_t *th = GET_THREAD();
2398  void *tmp = th->altstack;
2399  th->altstack = malloc(rb_sigaltstack_size());
2400  free(tmp); /* free previously allocated area */
2401  }
2402 #endif
2403 
2404  objspace->profile.invoke_time = getrusage_time();
2406 }
2407 
2408 typedef int each_obj_callback(void *, void *, size_t, void *);
2409 
2412  void *data;
2413 };
2414 
2415 static VALUE
2416 objspace_each_objects(VALUE arg)
2417 {
2418  size_t i;
2419  struct heap_page *page;
2420  RVALUE *pstart = NULL, *pend;
2421  rb_objspace_t *objspace = &rb_objspace;
2422  struct each_obj_args *args = (struct each_obj_args *)arg;
2423 
2424  i = 0;
2425  while (i < heap_allocated_pages) {
2426  while (0 < i && pstart < heap_pages_sorted[i-1]->start) i--;
2427  while (i < heap_allocated_pages && heap_pages_sorted[i]->start <= pstart) i++;
2428  if (heap_allocated_pages <= i) break;
2429 
2430  page = heap_pages_sorted[i];
2431 
2432  pstart = page->start;
2433  pend = pstart + page->total_slots;
2434 
2435  if ((*args->callback)(pstart, pend, sizeof(RVALUE), args->data)) {
2436  break;
2437  }
2438  }
2439 
2440  return Qnil;
2441 }
2442 
2443 static VALUE
2444 incremental_enable(void)
2445 {
2446  rb_objspace_t *objspace = &rb_objspace;
2447 
2448  objspace->flags.dont_incremental = FALSE;
2449  return Qnil;
2450 }
2451 
2452 /*
2453  * rb_objspace_each_objects() is special C API to walk through
2454  * Ruby object space. This C API is too difficult to use it.
2455  * To be frank, you should not use it. Or you need to read the
2456  * source code of this function and understand what this function does.
2457  *
2458  * 'callback' will be called several times (the number of heap page,
2459  * at current implementation) with:
2460  * vstart: a pointer to the first living object of the heap_page.
2461  * vend: a pointer to next to the valid heap_page area.
2462  * stride: a distance to next VALUE.
2463  *
2464  * If callback() returns non-zero, the iteration will be stopped.
2465  *
2466  * This is a sample callback code to iterate liveness objects:
2467  *
2468  * int
2469  * sample_callback(void *vstart, void *vend, int stride, void *data) {
2470  * VALUE v = (VALUE)vstart;
2471  * for (; v != (VALUE)vend; v += stride) {
2472  * if (RBASIC(v)->flags) { // liveness check
2473  * // do something with live object 'v'
2474  * }
2475  * return 0; // continue to iteration
2476  * }
2477  *
2478  * Note: 'vstart' is not a top of heap_page. This point the first
2479  * living object to grasp at least one object to avoid GC issue.
2480  * This means that you can not walk through all Ruby object page
2481  * including freed object page.
2482  *
2483  * Note: On this implementation, 'stride' is same as sizeof(RVALUE).
2484  * However, there are possibilities to pass variable values with
2485  * 'stride' with some reasons. You must use stride instead of
2486  * use some constant value in the iteration.
2487  */
2488 void
2490 {
2491  struct each_obj_args args;
2492  rb_objspace_t *objspace = &rb_objspace;
2493  int prev_dont_incremental = objspace->flags.dont_incremental;
2494 
2495  gc_rest(objspace);
2496  objspace->flags.dont_incremental = TRUE;
2497 
2498  args.callback = callback;
2499  args.data = data;
2500 
2501  if (prev_dont_incremental) {
2502  objspace_each_objects((VALUE)&args);
2503  }
2504  else {
2505  rb_ensure(objspace_each_objects, (VALUE)&args, incremental_enable, Qnil);
2506  }
2507 }
2508 
2509 void
2511 {
2512  struct each_obj_args args;
2513  args.callback = callback;
2514  args.data = data;
2515 
2516  objspace_each_objects((VALUE)&args);
2517 }
2518 
2520  size_t num;
2522 };
2523 
2524 static int
2525 internal_object_p(VALUE obj)
2526 {
2527  RVALUE *p = (RVALUE *)obj;
2528 
2529  if (p->as.basic.flags) {
2530  switch (BUILTIN_TYPE(p)) {
2531  case T_NONE:
2532  case T_IMEMO:
2533  case T_ICLASS:
2534  case T_NODE:
2535  case T_ZOMBIE:
2536  break;
2537  case T_CLASS:
2538  if (!p->as.basic.klass) break;
2539  if (FL_TEST(obj, FL_SINGLETON)) {
2540  return rb_singleton_class_internal_p(obj);
2541  }
2542  return 0;
2543  default:
2544  if (!p->as.basic.klass) break;
2545  return 0;
2546  }
2547  }
2548  return 1;
2549 }
2550 
2551 int
2553 {
2554  return internal_object_p(obj);
2555 }
2556 
2557 static int
2558 os_obj_of_i(void *vstart, void *vend, size_t stride, void *data)
2559 {
2560  struct os_each_struct *oes = (struct os_each_struct *)data;
2561  RVALUE *p = (RVALUE *)vstart, *pend = (RVALUE *)vend;
2562 
2563  for (; p != pend; p++) {
2564  volatile VALUE v = (VALUE)p;
2565  if (!internal_object_p(v)) {
2566  if (!oes->of || rb_obj_is_kind_of(v, oes->of)) {
2567  rb_yield(v);
2568  oes->num++;
2569  }
2570  }
2571  }
2572 
2573  return 0;
2574 }
2575 
2576 static VALUE
2577 os_obj_of(VALUE of)
2578 {
2579  struct os_each_struct oes;
2580 
2581  oes.num = 0;
2582  oes.of = of;
2583  rb_objspace_each_objects(os_obj_of_i, &oes);
2584  return SIZET2NUM(oes.num);
2585 }
2586 
2587 /*
2588  * call-seq:
2589  * ObjectSpace.each_object([module]) {|obj| ... } -> integer
2590  * ObjectSpace.each_object([module]) -> an_enumerator
2591  *
2592  * Calls the block once for each living, nonimmediate object in this
2593  * Ruby process. If <i>module</i> is specified, calls the block
2594  * for only those classes or modules that match (or are a subclass of)
2595  * <i>module</i>. Returns the number of objects found. Immediate
2596  * objects (<code>Fixnum</code>s, <code>Symbol</code>s
2597  * <code>true</code>, <code>false</code>, and <code>nil</code>) are
2598  * never returned. In the example below, <code>each_object</code>
2599  * returns both the numbers we defined and several constants defined in
2600  * the <code>Math</code> module.
2601  *
2602  * If no block is given, an enumerator is returned instead.
2603  *
2604  * a = 102.7
2605  * b = 95 # Won't be returned
2606  * c = 12345678987654321
2607  * count = ObjectSpace.each_object(Numeric) {|x| p x }
2608  * puts "Total count: #{count}"
2609  *
2610  * <em>produces:</em>
2611  *
2612  * 12345678987654321
2613  * 102.7
2614  * 2.71828182845905
2615  * 3.14159265358979
2616  * 2.22044604925031e-16
2617  * 1.7976931348623157e+308
2618  * 2.2250738585072e-308
2619  * Total count: 7
2620  *
2621  */
2622 
2623 static VALUE
2624 os_each_obj(int argc, VALUE *argv, VALUE os)
2625 {
2626  VALUE of;
2627 
2628  if (argc == 0) {
2629  of = 0;
2630  }
2631  else {
2632  rb_scan_args(argc, argv, "01", &of);
2633  }
2634  RETURN_ENUMERATOR(os, 1, &of);
2635  return os_obj_of(of);
2636 }
2637 
2638 /*
2639  * call-seq:
2640  * ObjectSpace.undefine_finalizer(obj)
2641  *
2642  * Removes all finalizers for <i>obj</i>.
2643  *
2644  */
2645 
2646 static VALUE
2647 undefine_final(VALUE os, VALUE obj)
2648 {
2649  return rb_undefine_finalizer(obj);
2650 }
2651 
2652 VALUE
2654 {
2655  rb_objspace_t *objspace = &rb_objspace;
2656  st_data_t data = obj;
2657  rb_check_frozen(obj);
2658  st_delete(finalizer_table, &data, 0);
2659  FL_UNSET(obj, FL_FINALIZE);
2660  return obj;
2661 }
2662 
2663 static void
2664 should_be_callable(VALUE block)
2665 {
2666  if (!rb_obj_respond_to(block, rb_intern("call"), TRUE)) {
2667  rb_raise(rb_eArgError, "wrong type argument %"PRIsVALUE" (should be callable)",
2668  rb_obj_class(block));
2669  }
2670 }
2671 static void
2672 should_be_finalizable(VALUE obj)
2673 {
2674  if (!FL_ABLE(obj)) {
2675  rb_raise(rb_eArgError, "cannot define finalizer for %s",
2676  rb_obj_classname(obj));
2677  }
2678  rb_check_frozen(obj);
2679 }
2680 
2681 /*
2682  * call-seq:
2683  * ObjectSpace.define_finalizer(obj, aProc=proc())
2684  *
2685  * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i>
2686  * was destroyed. The object ID of the <i>obj</i> will be passed
2687  * as an argument to <i>aProc</i>. If <i>aProc</i> is a lambda or
2688  * method, make sure it can be called with a single argument.
2689  *
2690  */
2691 
2692 static VALUE
2693 define_final(int argc, VALUE *argv, VALUE os)
2694 {
2695  VALUE obj, block;
2696 
2697  rb_scan_args(argc, argv, "11", &obj, &block);
2698  should_be_finalizable(obj);
2699  if (argc == 1) {
2700  block = rb_block_proc();
2701  }
2702  else {
2703  should_be_callable(block);
2704  }
2705 
2706  return define_final0(obj, block);
2707 }
2708 
2709 static VALUE
2710 define_final0(VALUE obj, VALUE block)
2711 {
2712  rb_objspace_t *objspace = &rb_objspace;
2713  VALUE table;
2714  st_data_t data;
2715 
2716  RBASIC(obj)->flags |= FL_FINALIZE;
2717 
2718  block = rb_ary_new3(2, INT2FIX(rb_safe_level()), block);
2719  OBJ_FREEZE(block);
2720 
2721  if (st_lookup(finalizer_table, obj, &data)) {
2722  table = (VALUE)data;
2723 
2724  /* avoid duplicate block, table is usually small */
2725  {
2726  const VALUE *ptr = RARRAY_CONST_PTR(table);
2727  long len = RARRAY_LEN(table);
2728  long i;
2729 
2730  for (i = 0; i < len; i++, ptr++) {
2731  if (rb_funcall(*ptr, idEq, 1, block)) {
2732  return *ptr;
2733  }
2734  }
2735  }
2736 
2737  rb_ary_push(table, block);
2738  }
2739  else {
2740  table = rb_ary_new3(1, block);
2741  RBASIC_CLEAR_CLASS(table);
2742  st_add_direct(finalizer_table, obj, table);
2743  }
2744  return block;
2745 }
2746 
2747 VALUE
2749 {
2750  should_be_finalizable(obj);
2751  should_be_callable(block);
2752  return define_final0(obj, block);
2753 }
2754 
2755 void
2757 {
2758  rb_objspace_t *objspace = &rb_objspace;
2759  VALUE table;
2760  st_data_t data;
2761 
2762  if (!FL_TEST(obj, FL_FINALIZE)) return;
2763  if (st_lookup(finalizer_table, obj, &data)) {
2764  table = (VALUE)data;
2765  st_insert(finalizer_table, dest, table);
2766  }
2767  FL_SET(dest, FL_FINALIZE);
2768 }
2769 
2770 static VALUE
2771 run_single_final(VALUE final, VALUE objid)
2772 {
2773  const VALUE cmd = RARRAY_AREF(final, 1);
2774  const int level = OBJ_TAINTED(cmd) ?
2776 
2777  rb_set_safe_level_force(level);
2778  return rb_check_funcall(cmd, idCall, 1, &objid);
2779 }
2780 
2781 static void
2782 run_finalizer(rb_objspace_t *objspace, VALUE obj, VALUE table)
2783 {
2784  long i;
2785  enum ruby_tag_type state;
2786  volatile struct {
2787  VALUE errinfo;
2788  VALUE objid;
2789  rb_control_frame_t *cfp;
2790  long finished;
2791  int safe;
2792  } saved;
2793  rb_thread_t *const th = GET_THREAD();
2794 #define RESTORE_FINALIZER() (\
2795  th->ec.cfp = saved.cfp, \
2796  rb_set_safe_level_force(saved.safe), \
2797  rb_set_errinfo(saved.errinfo))
2798 
2799  saved.safe = rb_safe_level();
2800  saved.errinfo = rb_errinfo();
2801  saved.objid = nonspecial_obj_id(obj);
2802  saved.cfp = th->ec.cfp;
2803  saved.finished = 0;
2804 
2805  TH_PUSH_TAG(th);
2806  state = TH_EXEC_TAG();
2807  if (state != TAG_NONE) {
2808  ++saved.finished; /* skip failed finalizer */
2809  }
2810  for (i = saved.finished;
2811  RESTORE_FINALIZER(), i<RARRAY_LEN(table);
2812  saved.finished = ++i) {
2813  run_single_final(RARRAY_AREF(table, i), saved.objid);
2814  }
2815  TH_POP_TAG();
2816 #undef RESTORE_FINALIZER
2817 }
2818 
2819 static void
2820 run_final(rb_objspace_t *objspace, VALUE zombie)
2821 {
2822  st_data_t key, table;
2823 
2824  if (RZOMBIE(zombie)->dfree) {
2825  RZOMBIE(zombie)->dfree(RZOMBIE(zombie)->data);
2826  }
2827 
2828  key = (st_data_t)zombie;
2829  if (st_delete(finalizer_table, &key, &table)) {
2830  run_finalizer(objspace, zombie, (VALUE)table);
2831  }
2832 }
2833 
2834 static void
2835 finalize_list(rb_objspace_t *objspace, VALUE zombie)
2836 {
2837  while (zombie) {
2838  VALUE next_zombie = RZOMBIE(zombie)->next;
2839  struct heap_page *page = GET_HEAP_PAGE(zombie);
2840 
2841  run_final(objspace, zombie);
2842 
2843  RZOMBIE(zombie)->basic.flags = 0;
2845  page->final_slots--;
2846  page->free_slots++;
2847  heap_page_add_freeobj(objspace, GET_HEAP_PAGE(zombie), zombie);
2848 
2849  objspace->profile.total_freed_objects++;
2850 
2851  zombie = next_zombie;
2852  }
2853 }
2854 
2855 static void
2856 finalize_deferred(rb_objspace_t *objspace)
2857 {
2858  VALUE zombie;
2859 
2860  while ((zombie = ATOMIC_VALUE_EXCHANGE(heap_pages_deferred_final, 0)) != 0) {
2861  finalize_list(objspace, zombie);
2862  }
2863 }
2864 
2865 static void
2866 gc_finalize_deferred(void *dmy)
2867 {
2868  rb_objspace_t *objspace = dmy;
2869  if (ATOMIC_EXCHANGE(finalizing, 1)) return;
2870  finalize_deferred(objspace);
2871  ATOMIC_SET(finalizing, 0);
2872 }
2873 
2874 /* TODO: to keep compatibility, maybe unused. */
2875 void
2877 {
2878  gc_finalize_deferred(0);
2879 }
2880 
2881 static void
2882 gc_finalize_deferred_register(rb_objspace_t *objspace)
2883 {
2884  if (rb_postponed_job_register_one(0, gc_finalize_deferred, objspace) == 0) {
2885  rb_bug("gc_finalize_deferred_register: can't register finalizer.");
2886  }
2887 }
2888 
2893 };
2894 
2895 static int
2896 force_chain_object(st_data_t key, st_data_t val, st_data_t arg)
2897 {
2898  struct force_finalize_list **prev = (struct force_finalize_list **)arg;
2899  struct force_finalize_list *curr = ALLOC(struct force_finalize_list);
2900  curr->obj = key;
2901  curr->table = val;
2902  curr->next = *prev;
2903  *prev = curr;
2904  return ST_CONTINUE;
2905 }
2906 
2907 void
2909 {
2910 #if RGENGC_CHECK_MODE >= 2
2911  gc_verify_internal_consistency(Qnil);
2912 #endif
2913  rb_objspace_call_finalizer(&rb_objspace);
2914 }
2915 
2916 static void
2917 rb_objspace_call_finalizer(rb_objspace_t *objspace)
2918 {
2919  RVALUE *p, *pend;
2920  size_t i;
2921 
2922  gc_rest(objspace);
2923 
2924  if (ATOMIC_EXCHANGE(finalizing, 1)) return;
2925 
2926  /* run finalizers */
2927  finalize_deferred(objspace);
2929 
2930  gc_rest(objspace);
2931  /* prohibit incremental GC */
2932  objspace->flags.dont_incremental = 1;
2933 
2934  /* force to run finalizer */
2935  while (finalizer_table->num_entries) {
2936  struct force_finalize_list *list = 0;
2937  st_foreach(finalizer_table, force_chain_object, (st_data_t)&list);
2938  while (list) {
2939  struct force_finalize_list *curr = list;
2940  st_data_t obj = (st_data_t)curr->obj;
2941  run_finalizer(objspace, curr->obj, curr->table);
2942  st_delete(finalizer_table, &obj, 0);
2943  list = curr->next;
2944  xfree(curr);
2945  }
2946  }
2947 
2948  /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
2949  dont_gc = 1;
2950 
2951  /* running data/file finalizers are part of garbage collection */
2952  gc_enter(objspace, "rb_objspace_call_finalizer");
2953 
2954  /* run data/file object's finalizers */
2955  for (i = 0; i < heap_allocated_pages; i++) {
2956  p = heap_pages_sorted[i]->start; pend = p + heap_pages_sorted[i]->total_slots;
2957  while (p < pend) {
2958  switch (BUILTIN_TYPE(p)) {
2959  case T_DATA:
2960  if (!DATA_PTR(p) || !RANY(p)->as.data.dfree) break;
2961  if (rb_obj_is_thread((VALUE)p)) break;
2962  if (rb_obj_is_mutex((VALUE)p)) break;
2963  if (rb_obj_is_fiber((VALUE)p)) break;
2964  p->as.free.flags = 0;
2965  if (RTYPEDDATA_P(p)) {
2966  RDATA(p)->dfree = RANY(p)->as.typeddata.type->function.dfree;
2967  }
2968  if (RANY(p)->as.data.dfree == (RUBY_DATA_FUNC)-1) {
2969  xfree(DATA_PTR(p));
2970  }
2971  else if (RANY(p)->as.data.dfree) {
2972  make_zombie(objspace, (VALUE)p, RANY(p)->as.data.dfree, RANY(p)->as.data.data);
2973  }
2974  break;
2975  case T_FILE:
2976  if (RANY(p)->as.file.fptr) {
2977  make_io_zombie(objspace, (VALUE)p);
2978  }
2979  break;
2980  }
2981  p++;
2982  }
2983  }
2984 
2985  gc_exit(objspace, "rb_objspace_call_finalizer");
2986 
2988  finalize_list(objspace, heap_pages_deferred_final);
2989  }
2990 
2992  finalizer_table = 0;
2993  ATOMIC_SET(finalizing, 0);
2994 }
2995 
2996 PUREFUNC(static inline int is_id_value(rb_objspace_t *objspace, VALUE ptr));
2997 static inline int
2998 is_id_value(rb_objspace_t *objspace, VALUE ptr)
2999 {
3000  if (!is_pointer_to_heap(objspace, (void *)ptr)) return FALSE;
3001  if (BUILTIN_TYPE(ptr) > T_FIXNUM) return FALSE;
3002  if (BUILTIN_TYPE(ptr) == T_ICLASS) return FALSE;
3003  return TRUE;
3004 }
3005 
3006 static inline int
3007 heap_is_swept_object(rb_objspace_t *objspace, rb_heap_t *heap, VALUE ptr)
3008 {
3009  struct heap_page *page = GET_HEAP_PAGE(ptr);
3010  return page->flags.before_sweep ? FALSE : TRUE;
3011 }
3012 
3013 static inline int
3014 is_swept_object(rb_objspace_t *objspace, VALUE ptr)
3015 {
3016  if (heap_is_swept_object(objspace, heap_eden, ptr)) {
3017  return TRUE;
3018  }
3019  else {
3020  return FALSE;
3021  }
3022 }
3023 
3024 /* garbage objects will be collected soon. */
3025 static inline int
3026 is_garbage_object(rb_objspace_t *objspace, VALUE ptr)
3027 {
3028  if (!is_lazy_sweeping(heap_eden) ||
3029  is_swept_object(objspace, ptr) ||
3030  MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(ptr), ptr)) {
3031 
3032  return FALSE;
3033  }
3034  else {
3035  return TRUE;
3036  }
3037 }
3038 
3039 static inline int
3040 is_live_object(rb_objspace_t *objspace, VALUE ptr)
3041 {
3042  switch (BUILTIN_TYPE(ptr)) {
3043  case T_NONE:
3044  case T_ZOMBIE:
3045  return FALSE;
3046  }
3047 
3048  if (!is_garbage_object(objspace, ptr)) {
3049  return TRUE;
3050  }
3051  else {
3052  return FALSE;
3053  }
3054 }
3055 
3056 static inline int
3057 is_markable_object(rb_objspace_t *objspace, VALUE obj)
3058 {
3059  if (rb_special_const_p(obj)) return FALSE; /* special const is not markable */
3060  check_rvalue_consistency(obj);
3061  return TRUE;
3062 }
3063 
3064 int
3066 {
3067  rb_objspace_t *objspace = &rb_objspace;
3068  return is_markable_object(objspace, obj) && is_live_object(objspace, obj);
3069 }
3070 
3071 int
3073 {
3074  rb_objspace_t *objspace = &rb_objspace;
3075  return is_garbage_object(objspace, obj);
3076 }
3077 
3078 /*
3079  * call-seq:
3080  * ObjectSpace._id2ref(object_id) -> an_object
3081  *
3082  * Converts an object id to a reference to the object. May not be
3083  * called on an object id passed as a parameter to a finalizer.
3084  *
3085  * s = "I am a string" #=> "I am a string"
3086  * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string"
3087  * r == s #=> true
3088  *
3089  */
3090 
3091 static VALUE
3092 id2ref(VALUE obj, VALUE objid)
3093 {
3094 #if SIZEOF_LONG == SIZEOF_VOIDP
3095 #define NUM2PTR(x) NUM2ULONG(x)
3096 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP
3097 #define NUM2PTR(x) NUM2ULL(x)
3098 #endif
3099  rb_objspace_t *objspace = &rb_objspace;
3100  VALUE ptr;
3101  void *p0;
3102 
3103  ptr = NUM2PTR(objid);
3104  p0 = (void *)ptr;
3105 
3106  if (ptr == Qtrue) return Qtrue;
3107  if (ptr == Qfalse) return Qfalse;
3108  if (ptr == Qnil) return Qnil;
3109  if (FIXNUM_P(ptr)) return (VALUE)ptr;
3110  if (FLONUM_P(ptr)) return (VALUE)ptr;
3111  ptr = obj_id_to_ref(objid);
3112 
3113  if ((ptr % sizeof(RVALUE)) == (4 << 2)) {
3114  ID symid = ptr / sizeof(RVALUE);
3115  if (rb_id2str(symid) == 0)
3116  rb_raise(rb_eRangeError, "%p is not symbol id value", p0);
3117  return ID2SYM(symid);
3118  }
3119 
3120  if (!is_id_value(objspace, ptr)) {
3121  rb_raise(rb_eRangeError, "%p is not id value", p0);
3122  }
3123  if (!is_live_object(objspace, ptr)) {
3124  rb_raise(rb_eRangeError, "%p is recycled object", p0);
3125  }
3126  if (RBASIC(ptr)->klass == 0) {
3127  rb_raise(rb_eRangeError, "%p is internal object", p0);
3128  }
3129  return (VALUE)ptr;
3130 }
3131 
3132 /*
3133  * Document-method: __id__
3134  * Document-method: object_id
3135  *
3136  * call-seq:
3137  * obj.__id__ -> integer
3138  * obj.object_id -> integer
3139  *
3140  * Returns an integer identifier for +obj+.
3141  *
3142  * The same number will be returned on all calls to +object_id+ for a given
3143  * object, and no two active objects will share an id.
3144  *
3145  * Note: that some objects of builtin classes are reused for optimization.
3146  * This is the case for immediate values and frozen string literals.
3147  *
3148  * Immediate values are not passed by reference but are passed by value:
3149  * +nil+, +true+, +false+, Fixnums, Symbols, and some Floats.
3150  *
3151  * Object.new.object_id == Object.new.object_id # => false
3152  * (21 * 2).object_id == (21 * 2).object_id # => true
3153  * "hello".object_id == "hello".object_id # => false
3154  * "hi".freeze.object_id == "hi".freeze.object_id # => true
3155  */
3156 
3157 VALUE
3159 {
3160  /*
3161  * 32-bit VALUE space
3162  * MSB ------------------------ LSB
3163  * false 00000000000000000000000000000000
3164  * true 00000000000000000000000000000010
3165  * nil 00000000000000000000000000000100
3166  * undef 00000000000000000000000000000110
3167  * symbol ssssssssssssssssssssssss00001110
3168  * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE))
3169  * fixnum fffffffffffffffffffffffffffffff1
3170  *
3171  * object_id space
3172  * LSB
3173  * false 00000000000000000000000000000000
3174  * true 00000000000000000000000000000010
3175  * nil 00000000000000000000000000000100
3176  * undef 00000000000000000000000000000110
3177  * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4)
3178  * object oooooooooooooooooooooooooooooo0 o...o % A = 0
3179  * fixnum fffffffffffffffffffffffffffffff1 bignum if required
3180  *
3181  * where A = sizeof(RVALUE)/4
3182  *
3183  * sizeof(RVALUE) is
3184  * 20 if 32-bit, double is 4-byte aligned
3185  * 24 if 32-bit, double is 8-byte aligned
3186  * 40 if 64-bit
3187  */
3188  if (STATIC_SYM_P(obj)) {
3189  return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG;
3190  }
3191  else if (FLONUM_P(obj)) {
3192 #if SIZEOF_LONG == SIZEOF_VOIDP
3193  return LONG2NUM((SIGNED_VALUE)obj);
3194 #else
3195  return LL2NUM((SIGNED_VALUE)obj);
3196 #endif
3197  }
3198  else if (SPECIAL_CONST_P(obj)) {
3199  return LONG2NUM((SIGNED_VALUE)obj);
3200  }
3201  return nonspecial_obj_id(obj);
3202 }
3203 
3204 #include "regint.h"
3205 
3206 static size_t
3207 obj_memsize_of(VALUE obj, int use_all_types)
3208 {
3209  size_t size = 0;
3210 
3211  if (SPECIAL_CONST_P(obj)) {
3212  return 0;
3213  }
3214 
3215  if (FL_TEST(obj, FL_EXIVAR)) {
3216  size += rb_generic_ivar_memsize(obj);
3217  }
3218 
3219  switch (BUILTIN_TYPE(obj)) {
3220  case T_OBJECT:
3221  if (!(RBASIC(obj)->flags & ROBJECT_EMBED) &&
3222  ROBJECT(obj)->as.heap.ivptr) {
3223  size += ROBJECT(obj)->as.heap.numiv * sizeof(VALUE);
3224  }
3225  break;
3226  case T_MODULE:
3227  case T_CLASS:
3228  if (RCLASS_M_TBL(obj)) {
3229  size += rb_id_table_memsize(RCLASS_M_TBL(obj));
3230  }
3231  if (RCLASS_EXT(obj)) {
3232  if (RCLASS_IV_TBL(obj)) {
3233  size += st_memsize(RCLASS_IV_TBL(obj));
3234  }
3235  if (RCLASS_IV_INDEX_TBL(obj)) {
3236  size += st_memsize(RCLASS_IV_INDEX_TBL(obj));
3237  }
3238  if (RCLASS(obj)->ptr->iv_tbl) {
3239  size += st_memsize(RCLASS(obj)->ptr->iv_tbl);
3240  }
3241  if (RCLASS(obj)->ptr->const_tbl) {
3242  size += rb_id_table_memsize(RCLASS(obj)->ptr->const_tbl);
3243  }
3244  size += sizeof(rb_classext_t);
3245  }
3246  break;
3247  case T_ICLASS:
3248  if (FL_TEST(obj, RICLASS_IS_ORIGIN)) {
3249  if (RCLASS_M_TBL(obj)) {
3250  size += rb_id_table_memsize(RCLASS_M_TBL(obj));
3251  }
3252  }
3253  break;
3254  case T_STRING:
3255  size += rb_str_memsize(obj);
3256  break;
3257  case T_ARRAY:
3258  size += rb_ary_memsize(obj);
3259  break;
3260  case T_HASH:
3261  if (RHASH(obj)->ntbl) {
3262  size += st_memsize(RHASH(obj)->ntbl);
3263  }
3264  break;
3265  case T_REGEXP:
3266  if (RREGEXP_PTR(obj)) {
3267  size += onig_memsize(RREGEXP_PTR(obj));
3268  }
3269  break;
3270  case T_DATA:
3271  if (use_all_types) size += rb_objspace_data_type_memsize(obj);
3272  break;
3273  case T_MATCH:
3274  if (RMATCH(obj)->rmatch) {
3275  struct rmatch *rm = RMATCH(obj)->rmatch;
3276  size += onig_region_memsize(&rm->regs);
3277  size += sizeof(struct rmatch_offset) * rm->char_offset_num_allocated;
3278  size += sizeof(struct rmatch);
3279  }
3280  break;
3281  case T_FILE:
3282  if (RFILE(obj)->fptr) {
3283  size += rb_io_memsize(RFILE(obj)->fptr);
3284  }
3285  break;
3286  case T_RATIONAL:
3287  case T_COMPLEX:
3288  case T_IMEMO:
3289  if (imemo_type_p(obj, imemo_alloc)) {
3290  size += RANY(obj)->as.imemo.alloc.cnt * sizeof(VALUE);
3291  }
3292  break;
3293 
3294  case T_FLOAT:
3295  case T_SYMBOL:
3296  break;
3297 
3298  case T_BIGNUM:
3299  if (!(RBASIC(obj)->flags & BIGNUM_EMBED_FLAG) && BIGNUM_DIGITS(obj)) {
3300  size += BIGNUM_LEN(obj) * sizeof(BDIGIT);
3301  }
3302  break;
3303 
3304  case T_NODE:
3305  if (use_all_types) size += rb_node_memsize(obj);
3306  break;
3307 
3308  case T_STRUCT:
3309  if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 &&
3310  RSTRUCT(obj)->as.heap.ptr) {
3311  size += sizeof(VALUE) * RSTRUCT_LEN(obj);
3312  }
3313  break;
3314 
3315  case T_ZOMBIE:
3316  break;
3317 
3318  default:
3319  rb_bug("objspace/memsize_of(): unknown data type 0x%x(%p)",
3320  BUILTIN_TYPE(obj), (void*)obj);
3321  }
3322 
3323  return size + sizeof(RVALUE);
3324 }
3325 
3326 size_t
3328 {
3329  return obj_memsize_of(obj, TRUE);
3330 }
3331 
3332 static int
3333 set_zero(st_data_t key, st_data_t val, st_data_t arg)
3334 {
3335  VALUE k = (VALUE)key;
3336  VALUE hash = (VALUE)arg;
3337  rb_hash_aset(hash, k, INT2FIX(0));
3338  return ST_CONTINUE;
3339 }
3340 
3341 /*
3342  * call-seq:
3343  * ObjectSpace.count_objects([result_hash]) -> hash
3344  *
3345  * Counts all objects grouped by type.
3346  *
3347  * It returns a hash, such as:
3348  * {
3349  * :TOTAL=>10000,
3350  * :FREE=>3011,
3351  * :T_OBJECT=>6,
3352  * :T_CLASS=>404,
3353  * # ...
3354  * }
3355  *
3356  * The contents of the returned hash are implementation specific.
3357  * It may be changed in future.
3358  *
3359  * The keys starting with +:T_+ means live objects.
3360  * For example, +:T_ARRAY+ is the number of arrays.
3361  * +:FREE+ means object slots which is not used now.
3362  * +:TOTAL+ means sum of above.
3363  *
3364  * If the optional argument +result_hash+ is given,
3365  * it is overwritten and returned. This is intended to avoid probe effect.
3366  *
3367  * h = {}
3368  * ObjectSpace.count_objects(h)
3369  * puts h
3370  * # => { :TOTAL=>10000, :T_CLASS=>158280, :T_MODULE=>20672, :T_STRING=>527249 }
3371  *
3372  * This method is only expected to work on C Ruby.
3373  *
3374  */
3375 
3376 static VALUE
3377 count_objects(int argc, VALUE *argv, VALUE os)
3378 {
3379  rb_objspace_t *objspace = &rb_objspace;
3380  size_t counts[T_MASK+1];
3381  size_t freed = 0;
3382  size_t total = 0;
3383  size_t i;
3384  VALUE hash;
3385 
3386  if (rb_scan_args(argc, argv, "01", &hash) == 1) {
3387  if (!RB_TYPE_P(hash, T_HASH))
3388  rb_raise(rb_eTypeError, "non-hash given");
3389  }
3390 
3391  for (i = 0; i <= T_MASK; i++) {
3392  counts[i] = 0;
3393  }
3394 
3395  for (i = 0; i < heap_allocated_pages; i++) {
3396  struct heap_page *page = heap_pages_sorted[i];
3397  RVALUE *p, *pend;
3398 
3399  p = page->start; pend = p + page->total_slots;
3400  for (;p < pend; p++) {
3401  if (p->as.basic.flags) {
3402  counts[BUILTIN_TYPE(p)]++;
3403  }
3404  else {
3405  freed++;
3406  }
3407  }
3408  total += page->total_slots;
3409  }
3410 
3411  if (hash == Qnil) {
3412  hash = rb_hash_new();
3413  }
3414  else if (!RHASH_EMPTY_P(hash)) {
3415  st_foreach(RHASH_TBL_RAW(hash), set_zero, hash);
3416  }
3417  rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total));
3418  rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed));
3419 
3420  for (i = 0; i <= T_MASK; i++) {
3421  VALUE type;
3422  switch (i) {
3423 #define COUNT_TYPE(t) case (t): type = ID2SYM(rb_intern(#t)); break;
3424  COUNT_TYPE(T_NONE);
3432  COUNT_TYPE(T_HASH);
3435  COUNT_TYPE(T_FILE);
3436  COUNT_TYPE(T_DATA);
3440  COUNT_TYPE(T_NIL);
3441  COUNT_TYPE(T_TRUE);
3447  COUNT_TYPE(T_NODE);
3450 #undef COUNT_TYPE
3451  default: type = INT2NUM(i); break;
3452  }
3453  if (counts[i])
3454  rb_hash_aset(hash, type, SIZET2NUM(counts[i]));
3455  }
3456 
3457  return hash;
3458 }
3459 
3460 /*
3461  ------------------------ Garbage Collection ------------------------
3462 */
3463 
3464 /* Sweeping */
3465 
3466 static size_t
3467 objspace_available_slots(rb_objspace_t *objspace)
3468 {
3469  return heap_eden->total_slots + heap_tomb->total_slots;
3470 }
3471 
3472 static size_t
3473 objspace_live_slots(rb_objspace_t *objspace)
3474 {
3476 }
3477 
3478 static size_t
3479 objspace_free_slots(rb_objspace_t *objspace)
3480 {
3481  return objspace_available_slots(objspace) - objspace_live_slots(objspace) - heap_pages_final_slots;
3482 }
3483 
3484 static void
3485 gc_setup_mark_bits(struct heap_page *page)
3486 {
3487 #if USE_RGENGC
3488  /* copy oldgen bitmap to mark bitmap */
3489  memcpy(&page->mark_bits[0], &page->uncollectible_bits[0], HEAP_PAGE_BITMAP_SIZE);
3490 #else
3491  /* clear mark bitmap */
3492  memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
3493 #endif
3494 }
3495 
3496 static inline int
3497 gc_page_sweep(rb_objspace_t *objspace, rb_heap_t *heap, struct heap_page *sweep_page)
3498 {
3499  int i;
3500  int empty_slots = 0, freed_slots = 0, final_slots = 0;
3501  RVALUE *p, *pend,*offset;
3502  bits_t *bits, bitset;
3503 
3504  gc_report(2, objspace, "page_sweep: start.\n");
3505 
3506  sweep_page->flags.before_sweep = FALSE;
3507 
3508  p = sweep_page->start; pend = p + sweep_page->total_slots;
3509  offset = p - NUM_IN_PAGE(p);
3510  bits = sweep_page->mark_bits;
3511 
3512  /* create guard : fill 1 out-of-range */
3513  bits[BITMAP_INDEX(p)] |= BITMAP_BIT(p)-1;
3514  bits[BITMAP_INDEX(pend)] |= ~(BITMAP_BIT(pend) - 1);
3515 
3516  for (i=0; i < HEAP_PAGE_BITMAP_LIMIT; i++) {
3517  bitset = ~bits[i];
3518  if (bitset) {
3519  p = offset + i * BITS_BITLENGTH;
3520  do {
3521  if (bitset & 1) {
3522  switch (BUILTIN_TYPE(p)) {
3523  default: { /* majority case */
3524  gc_report(2, objspace, "page_sweep: free %s\n", obj_info((VALUE)p));
3525 #if USE_RGENGC && RGENGC_CHECK_MODE
3526  if (!is_full_marking(objspace)) {
3527  if (RVALUE_OLD_P((VALUE)p)) rb_bug("page_sweep: %s - old while minor GC.", obj_info((VALUE)p));
3528  if (rgengc_remembered(objspace, (VALUE)p)) rb_bug("page_sweep: %s - remembered.", obj_info((VALUE)p));
3529  }
3530 #endif
3531  if (obj_free(objspace, (VALUE)p)) {
3532  final_slots++;
3533  }
3534  else {
3535  (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE));
3536  heap_page_add_freeobj(objspace, sweep_page, (VALUE)p);
3537  gc_report(3, objspace, "page_sweep: %s is added to freelist\n", obj_info((VALUE)p));
3538  freed_slots++;
3539  }
3540  break;
3541  }
3542 
3543  /* minor cases */
3544  case T_ZOMBIE:
3545  /* already counted */
3546  break;
3547  case T_NONE:
3548  empty_slots++; /* already freed */
3549  break;
3550  }
3551  }
3552  p++;
3553  bitset >>= 1;
3554  } while (bitset);
3555  }
3556  }
3557 
3558  gc_setup_mark_bits(sweep_page);
3559 
3560 #if GC_PROFILE_MORE_DETAIL
3561  if (gc_prof_enabled(objspace)) {
3562  gc_profile_record *record = gc_prof_record(objspace);
3563  record->removing_objects += final_slots + freed_slots;
3564  record->empty_objects += empty_slots;
3565  }
3566 #endif
3567  if (0) fprintf(stderr, "gc_page_sweep(%d): total_slots: %d, freed_slots: %d, empty_slots: %d, final_slots: %d\n",
3568  (int)rb_gc_count(),
3569  (int)sweep_page->total_slots,
3570  freed_slots, empty_slots, final_slots);
3571 
3572  sweep_page->free_slots = freed_slots + empty_slots;
3573  objspace->profile.total_freed_objects += freed_slots;
3575  sweep_page->final_slots += final_slots;
3576 
3578  rb_thread_t *th = GET_THREAD();
3579  if (th) {
3580  gc_finalize_deferred_register(objspace);
3581  }
3582  }
3583 
3584  gc_report(2, objspace, "page_sweep: end.\n");
3585 
3586  return freed_slots + empty_slots;
3587 }
3588 
3589 /* allocate additional minimum page to work */
3590 static void
3591 gc_heap_prepare_minimum_pages(rb_objspace_t *objspace, rb_heap_t *heap)
3592 {
3593  if (!heap->free_pages && heap_increment(objspace, heap) == FALSE) {
3594  /* there is no free after page_sweep() */
3595  heap_set_increment(objspace, 1);
3596  if (!heap_increment(objspace, heap)) { /* can't allocate additional free objects */
3597  rb_memerror();
3598  }
3599  }
3600 }
3601 
3602 static const char *
3603 gc_mode_name(enum gc_mode mode)
3604 {
3605  switch (mode) {
3606  case gc_mode_none: return "none";
3607  case gc_mode_marking: return "marking";
3608  case gc_mode_sweeping: return "sweeping";
3609  default: rb_bug("gc_mode_name: unknown mode: %d", (int)mode);
3610  }
3611 }
3612 
3613 static void
3614 gc_mode_transition(rb_objspace_t *objspace, enum gc_mode mode)
3615 {
3616 #if RGENGC_CHECK_MODE
3617  enum gc_mode prev_mode = gc_mode(objspace);
3618  switch (prev_mode) {
3619  case gc_mode_none: GC_ASSERT(mode == gc_mode_marking); break;
3620  case gc_mode_marking: GC_ASSERT(mode == gc_mode_sweeping); break;
3621  case gc_mode_sweeping: GC_ASSERT(mode == gc_mode_none); break;
3622  }
3623 #endif
3624  if (0) fprintf(stderr, "gc_mode_transition: %s->%s\n", gc_mode_name(gc_mode(objspace)), gc_mode_name(mode));
3625  gc_mode_set(objspace, mode);
3626 }
3627 
3628 static void
3629 gc_sweep_start_heap(rb_objspace_t *objspace, rb_heap_t *heap)
3630 {
3631  heap->sweep_pages = heap->pages;
3632  heap->free_pages = NULL;
3633 #if GC_ENABLE_INCREMENTAL_MARK
3634  heap->pooled_pages = NULL;
3635  objspace->rincgc.pooled_slots = 0;
3636 #endif
3637  if (heap->using_page) {
3638  RVALUE **p = &heap->using_page->freelist;
3639  while (*p) {
3640  p = &(*p)->as.free.next;
3641  }
3642  *p = heap->freelist;
3643  heap->using_page = NULL;
3644  }
3645  heap->freelist = NULL;
3646 }
3647 
3648 #if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ == 4
3649 __attribute__((noinline))
3650 #endif
3651 static void
3652 gc_sweep_start(rb_objspace_t *objspace)
3653 {
3654  gc_mode_transition(objspace, gc_mode_sweeping);
3655  gc_sweep_start_heap(objspace, heap_eden);
3656 }
3657 
3658 static void
3659 gc_sweep_finish(rb_objspace_t *objspace)
3660 {
3661  gc_report(1, objspace, "gc_sweep_finish\n");
3662 
3663  gc_prof_set_heap_info(objspace);
3664  heap_pages_free_unused_pages(objspace);
3665 
3666  /* if heap_pages has unused pages, then assign them to increment */
3667  if (heap_allocatable_pages < heap_tomb->total_pages) {
3668  heap_allocatable_pages_set(objspace, heap_tomb->total_pages);
3669  }
3670 
3672  gc_mode_transition(objspace, gc_mode_none);
3673 
3674 #if RGENGC_CHECK_MODE >= 2
3675  gc_verify_internal_consistency(Qnil);
3676 #endif
3677 }
3678 
3679 static int
3680 gc_sweep_step(rb_objspace_t *objspace, rb_heap_t *heap)
3681 {
3682  struct heap_page *sweep_page = heap->sweep_pages;
3683  int unlink_limit = 3;
3684 #if GC_ENABLE_INCREMENTAL_MARK
3685  int need_pool = will_be_incremental_marking(objspace) ? TRUE : FALSE;
3686 
3687  gc_report(2, objspace, "gc_sweep_step (need_pool: %d)\n", need_pool);
3688 #else
3689  gc_report(2, objspace, "gc_sweep_step\n");
3690 #endif
3691 
3692  if (sweep_page == NULL) return FALSE;
3693 
3694 #if GC_ENABLE_LAZY_SWEEP
3695  gc_prof_sweep_timer_start(objspace);
3696 #endif
3697 
3698  while (sweep_page) {
3699  struct heap_page *next_sweep_page = heap->sweep_pages = sweep_page->next;
3700  int free_slots = gc_page_sweep(objspace, heap, sweep_page);
3701 
3702  if (sweep_page->final_slots + free_slots == sweep_page->total_slots &&
3704  unlink_limit > 0) {
3706  unlink_limit--;
3707  /* there are no living objects -> move this page to tomb heap */
3708  heap_unlink_page(objspace, heap, sweep_page);
3709  heap_add_page(objspace, heap_tomb, sweep_page);
3710  }
3711  else if (free_slots > 0) {
3712 #if GC_ENABLE_INCREMENTAL_MARK
3713  if (need_pool) {
3714  if (heap_add_poolpage(objspace, heap, sweep_page)) {
3715  need_pool = FALSE;
3716  }
3717  }
3718  else {
3719  heap_add_freepage(objspace, heap, sweep_page);
3720  break;
3721  }
3722 #else
3723  heap_add_freepage(objspace, heap, sweep_page);
3724  break;
3725 #endif
3726  }
3727  else {
3728  sweep_page->free_next = NULL;
3729  }
3730 
3731  sweep_page = next_sweep_page;
3732  }
3733 
3734  if (heap->sweep_pages == NULL) {
3735  gc_sweep_finish(objspace);
3736  }
3737 
3738 #if GC_ENABLE_LAZY_SWEEP
3739  gc_prof_sweep_timer_stop(objspace);
3740 #endif
3741 
3742  return heap->free_pages != NULL;
3743 }
3744 
3745 static void
3746 gc_sweep_rest(rb_objspace_t *objspace)
3747 {
3748  rb_heap_t *heap = heap_eden; /* lazy sweep only for eden */
3749 
3750  while (has_sweeping_pages(heap)) {
3751  gc_sweep_step(objspace, heap);
3752  }
3753 }
3754 
3755 #if GC_ENABLE_LAZY_SWEEP
3756 static void
3757 gc_sweep_continue(rb_objspace_t *objspace, rb_heap_t *heap)
3758 {
3759  GC_ASSERT(dont_gc == FALSE);
3760 
3761  gc_enter(objspace, "sweep_continue");
3762 #if USE_RGENGC
3763  if (objspace->rgengc.need_major_gc == GPR_FLAG_NONE && heap_increment(objspace, heap)) {
3764  gc_report(3, objspace, "gc_sweep_continue: success heap_increment().\n");
3765  }
3766 #endif
3767  gc_sweep_step(objspace, heap);
3768  gc_exit(objspace, "sweep_continue");
3769 }
3770 #endif
3771 
3772 static void
3773 gc_sweep(rb_objspace_t *objspace)
3774 {
3775  const unsigned int immediate_sweep = objspace->flags.immediate_sweep;
3776 
3777  gc_report(1, objspace, "gc_sweep: immediate: %d\n", immediate_sweep);
3778 
3779  if (immediate_sweep) {
3780 #if !GC_ENABLE_LAZY_SWEEP
3781  gc_prof_sweep_timer_start(objspace);
3782 #endif
3783  gc_sweep_start(objspace);
3784  gc_sweep_rest(objspace);
3785 #if !GC_ENABLE_LAZY_SWEEP
3786  gc_prof_sweep_timer_stop(objspace);
3787 #endif
3788  }
3789  else {
3790  struct heap_page *page;
3791  gc_sweep_start(objspace);
3792  page = heap_eden->sweep_pages;
3793  while (page) {
3794  page->flags.before_sweep = TRUE;
3795  page = page->next;
3796  }
3797  gc_sweep_step(objspace, heap_eden);
3798  }
3799 
3800  gc_heap_prepare_minimum_pages(objspace, heap_eden);
3801 }
3802 
3803 /* Marking - Marking stack */
3804 
3805 static stack_chunk_t *
3806 stack_chunk_alloc(void)
3807 {
3808  stack_chunk_t *res;
3809 
3810  res = malloc(sizeof(stack_chunk_t));
3811  if (!res)
3812  rb_memerror();
3813 
3814  return res;
3815 }
3816 
3817 static inline int
3818 is_mark_stack_empty(mark_stack_t *stack)
3819 {
3820  return stack->chunk == NULL;
3821 }
3822 
3823 static size_t
3824 mark_stack_size(mark_stack_t *stack)
3825 {
3826  size_t size = stack->index;
3827  stack_chunk_t *chunk = stack->chunk ? stack->chunk->next : NULL;
3828 
3829  while (chunk) {
3830  size += stack->limit;
3831  chunk = chunk->next;
3832  }
3833  return size;
3834 }
3835 
3836 static void
3837 add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk)
3838 {
3839  chunk->next = stack->cache;
3840  stack->cache = chunk;
3841  stack->cache_size++;
3842 }
3843 
3844 static void
3845 shrink_stack_chunk_cache(mark_stack_t *stack)
3846 {
3847  stack_chunk_t *chunk;
3848 
3849  if (stack->unused_cache_size > (stack->cache_size/2)) {
3850  chunk = stack->cache;
3851  stack->cache = stack->cache->next;
3852  stack->cache_size--;
3853  free(chunk);
3854  }
3855  stack->unused_cache_size = stack->cache_size;
3856 }
3857 
3858 static void
3859 push_mark_stack_chunk(mark_stack_t *stack)
3860 {
3862 
3863  GC_ASSERT(stack->index == stack->limit);
3864 
3865  if (stack->cache_size > 0) {
3866  next = stack->cache;
3867  stack->cache = stack->cache->next;
3868  stack->cache_size--;
3869  if (stack->unused_cache_size > stack->cache_size)
3870  stack->unused_cache_size = stack->cache_size;
3871  }
3872  else {
3873  next = stack_chunk_alloc();
3874  }
3875  next->next = stack->chunk;
3876  stack->chunk = next;
3877  stack->index = 0;
3878 }
3879 
3880 static void
3881 pop_mark_stack_chunk(mark_stack_t *stack)
3882 {
3884 
3885  prev = stack->chunk->next;
3886  GC_ASSERT(stack->index == 0);
3887  add_stack_chunk_cache(stack, stack->chunk);
3888  stack->chunk = prev;
3889  stack->index = stack->limit;
3890 }
3891 
3892 static void
3893 free_stack_chunks(mark_stack_t *stack)
3894 {
3895  stack_chunk_t *chunk = stack->chunk;
3896  stack_chunk_t *next = NULL;
3897 
3898  while (chunk != NULL) {
3899  next = chunk->next;
3900  free(chunk);
3901  chunk = next;
3902  }
3903 }
3904 
3905 static void
3906 push_mark_stack(mark_stack_t *stack, VALUE data)
3907 {
3908  if (stack->index == stack->limit) {
3909  push_mark_stack_chunk(stack);
3910  }
3911  stack->chunk->data[stack->index++] = data;
3912 }
3913 
3914 static int
3915 pop_mark_stack(mark_stack_t *stack, VALUE *data)
3916 {
3917  if (is_mark_stack_empty(stack)) {
3918  return FALSE;
3919  }
3920  if (stack->index == 1) {
3921  *data = stack->chunk->data[--stack->index];
3922  pop_mark_stack_chunk(stack);
3923  }
3924  else {
3925  *data = stack->chunk->data[--stack->index];
3926  }
3927  return TRUE;
3928 }
3929 
3930 #if GC_ENABLE_INCREMENTAL_MARK
3931 static int
3932 invalidate_mark_stack_chunk(stack_chunk_t *chunk, int limit, VALUE obj)
3933 {
3934  int i;
3935  for (i=0; i<limit; i++) {
3936  if (chunk->data[i] == obj) {
3937  chunk->data[i] = Qundef;
3938  return TRUE;
3939  }
3940  }
3941  return FALSE;
3942 }
3943 
3944 static void
3945 invalidate_mark_stack(mark_stack_t *stack, VALUE obj)
3946 {
3947  stack_chunk_t *chunk = stack->chunk;
3948  int limit = stack->index;
3949 
3950  while (chunk) {
3951  if (invalidate_mark_stack_chunk(chunk, limit, obj)) return;
3952  chunk = chunk->next;
3953  limit = stack->limit;
3954  }
3955  rb_bug("invalid_mark_stack: unreachable");
3956 }
3957 #endif
3958 
3959 static void
3960 init_mark_stack(mark_stack_t *stack)
3961 {
3962  int i;
3963 
3964  MEMZERO(stack, mark_stack_t, 1);
3965  stack->index = stack->limit = STACK_CHUNK_SIZE;
3966  stack->cache_size = 0;
3967 
3968  for (i=0; i < 4; i++) {
3969  add_stack_chunk_cache(stack, stack_chunk_alloc());
3970  }
3971  stack->unused_cache_size = stack->cache_size;
3972 }
3973 
3974 /* Marking */
3975 
3976 #ifdef __ia64
3977 #define SET_STACK_END (SET_MACHINE_STACK_END(&ec->machine.stack_end), ec->machine.register_stack_end = rb_ia64_bsp())
3978 #else
3979 #define SET_STACK_END SET_MACHINE_STACK_END(&ec->machine.stack_end)
3980 #endif
3981 
3982 #define STACK_START (ec->machine.stack_start)
3983 #define STACK_END (ec->machine.stack_end)
3984 #define STACK_LEVEL_MAX (ec->machine.stack_maxsize/sizeof(VALUE))
3985 
3986 #if STACK_GROW_DIRECTION < 0
3987 # define STACK_LENGTH (size_t)(STACK_START - STACK_END)
3988 #elif STACK_GROW_DIRECTION > 0
3989 # define STACK_LENGTH (size_t)(STACK_END - STACK_START + 1)
3990 #else
3991 # define STACK_LENGTH ((STACK_END < STACK_START) ? (size_t)(STACK_START - STACK_END) \
3992  : (size_t)(STACK_END - STACK_START + 1))
3993 #endif
3994 #if !STACK_GROW_DIRECTION
3996 int
3998 {
3999  VALUE *end;
4000  SET_MACHINE_STACK_END(&end);
4001 
4002  if (end > addr) return ruby_stack_grow_direction = 1;
4003  return ruby_stack_grow_direction = -1;
4004 }
4005 #endif
4006 
4007 size_t
4009 {
4010  rb_execution_context_t *ec = &GET_THREAD()->ec;
4011  SET_STACK_END;
4012  if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END);
4013  return STACK_LENGTH;
4014 }
4015 
4016 #define PREVENT_STACK_OVERFLOW 1
4017 #ifndef PREVENT_STACK_OVERFLOW
4018 #if !(defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK))
4019 # define PREVENT_STACK_OVERFLOW 1
4020 #else
4021 # define PREVENT_STACK_OVERFLOW 0
4022 #endif
4023 #endif
4024 #if PREVENT_STACK_OVERFLOW
4025 static int
4026 stack_check(rb_thread_t *th, int water_mark)
4027 {
4028  rb_execution_context_t *ec = &th->ec;
4029  int ret;
4030  SET_STACK_END;
4031  ret = STACK_LENGTH > STACK_LEVEL_MAX - water_mark;
4032 #ifdef __ia64
4033  if (!ret) {
4034  ret = (VALUE*)rb_ia64_bsp() - ec->machine.register_stack_start >
4035  ec->machine.register_stack_maxsize/sizeof(VALUE) - water_mark;
4036  }
4037 #endif
4038  return ret;
4039 }
4040 #else
4041 #define stack_check(th, water_mark) FALSE
4042 #endif
4043 
4044 #define STACKFRAME_FOR_CALL_CFUNC 838
4045 
4046 int
4048 {
4049  return stack_check(th, STACKFRAME_FOR_CALL_CFUNC);
4050 }
4051 
4052 int
4054 {
4055  return stack_check(GET_THREAD(), STACKFRAME_FOR_CALL_CFUNC);
4056 }
4057 
4059 static void
4060 mark_locations_array(rb_objspace_t *objspace, register const VALUE *x, register long n)
4061 {
4062  VALUE v;
4063  while (n--) {
4064  v = *x;
4065  gc_mark_maybe(objspace, v);
4066  x++;
4067  }
4068 }
4069 
4070 static void
4071 gc_mark_locations(rb_objspace_t *objspace, const VALUE *start, const VALUE *end)
4072 {
4073  long n;
4074 
4075  if (end <= start) return;
4076  n = end - start;
4077  mark_locations_array(objspace, start, n);
4078 }
4079 
4080 void
4081 rb_gc_mark_locations(const VALUE *start, const VALUE *end)
4082 {
4083  gc_mark_locations(&rb_objspace, start, end);
4084 }
4085 
4086 static void
4087 gc_mark_values(rb_objspace_t *objspace, long n, const VALUE *values)
4088 {
4089  long i;
4090 
4091  for (i=0; i<n; i++) {
4092  gc_mark(objspace, values[i]);
4093  }
4094 }
4095 
4096 void
4097 rb_gc_mark_values(long n, const VALUE *values)
4098 {
4099  rb_objspace_t *objspace = &rb_objspace;
4100  gc_mark_values(objspace, n, values);
4101 }
4102 
4103 static int
4104 mark_entry(st_data_t key, st_data_t value, st_data_t data)
4105 {
4106  rb_objspace_t *objspace = (rb_objspace_t *)data;
4107  gc_mark(objspace, (VALUE)value);
4108  return ST_CONTINUE;
4109 }
4110 
4111 static void
4112 mark_tbl(rb_objspace_t *objspace, st_table *tbl)
4113 {
4114  if (!tbl || tbl->num_entries == 0) return;
4115  st_foreach(tbl, mark_entry, (st_data_t)objspace);
4116 }
4117 
4118 static int
4119 mark_key(st_data_t key, st_data_t value, st_data_t data)
4120 {
4121  rb_objspace_t *objspace = (rb_objspace_t *)data;
4122  gc_mark(objspace, (VALUE)key);
4123  return ST_CONTINUE;
4124 }
4125 
4126 static void
4127 mark_set(rb_objspace_t *objspace, st_table *tbl)
4128 {
4129  if (!tbl) return;
4130  st_foreach(tbl, mark_key, (st_data_t)objspace);
4131 }
4132 
4133 void
4135 {
4136  mark_set(&rb_objspace, tbl);
4137 }
4138 
4139 static int
4140 mark_keyvalue(st_data_t key, st_data_t value, st_data_t data)
4141 {
4142  rb_objspace_t *objspace = (rb_objspace_t *)data;
4143 
4144  gc_mark(objspace, (VALUE)key);
4145  gc_mark(objspace, (VALUE)value);
4146  return ST_CONTINUE;
4147 }
4148 
4149 static void
4150 mark_hash(rb_objspace_t *objspace, st_table *tbl)
4151 {
4152  if (!tbl) return;
4153  st_foreach(tbl, mark_keyvalue, (st_data_t)objspace);
4154 }
4155 
4156 void
4158 {
4159  mark_hash(&rb_objspace, tbl);
4160 }
4161 
4162 static void
4163 mark_method_entry(rb_objspace_t *objspace, const rb_method_entry_t *me)
4164 {
4165  const rb_method_definition_t *def = me->def;
4166 
4167  gc_mark(objspace, me->owner);
4168  gc_mark(objspace, me->defined_class);
4169 
4170  if (def) {
4171  switch (def->type) {
4172  case VM_METHOD_TYPE_ISEQ:
4173  if (def->body.iseq.iseqptr) gc_mark(objspace, (VALUE)def->body.iseq.iseqptr);
4174  gc_mark(objspace, (VALUE)def->body.iseq.cref);
4175  break;
4177  case VM_METHOD_TYPE_IVAR:
4178  gc_mark(objspace, def->body.attr.location);
4179  break;
4181  gc_mark(objspace, def->body.proc);
4182  break;
4183  case VM_METHOD_TYPE_ALIAS:
4184  gc_mark(objspace, (VALUE)def->body.alias.original_me);
4185  return;
4187  gc_mark(objspace, (VALUE)def->body.refined.orig_me);
4188  gc_mark(objspace, (VALUE)def->body.refined.owner);
4189  break;
4190  case VM_METHOD_TYPE_CFUNC:
4191  case VM_METHOD_TYPE_ZSUPER:
4194  case VM_METHOD_TYPE_UNDEF:
4196  break;
4197  }
4198  }
4199 }
4200 
4201 static enum rb_id_table_iterator_result
4202 mark_method_entry_i(VALUE me, void *data)
4203 {
4204  rb_objspace_t *objspace = (rb_objspace_t *)data;
4205 
4206  gc_mark(objspace, me);
4207  return ID_TABLE_CONTINUE;
4208 }
4209 
4210 static void
4211 mark_m_tbl(rb_objspace_t *objspace, struct rb_id_table *tbl)
4212 {
4213  if (tbl) {
4214  rb_id_table_foreach_values(tbl, mark_method_entry_i, objspace);
4215  }
4216 }
4217 
4218 static enum rb_id_table_iterator_result
4219 mark_const_entry_i(VALUE value, void *data)
4220 {
4221  const rb_const_entry_t *ce = (const rb_const_entry_t *)value;
4222  rb_objspace_t *objspace = data;
4223 
4224  gc_mark(objspace, ce->value);
4225  gc_mark(objspace, ce->file);
4226  return ID_TABLE_CONTINUE;
4227 }
4228 
4229 static void
4230 mark_const_tbl(rb_objspace_t *objspace, struct rb_id_table *tbl)
4231 {
4232  if (!tbl) return;
4233  rb_id_table_foreach_values(tbl, mark_const_entry_i, objspace);
4234 }
4235 
4236 #if STACK_GROW_DIRECTION < 0
4237 #define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_END, (end) = STACK_START)
4238 #elif STACK_GROW_DIRECTION > 0
4239 #define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_START, (end) = STACK_END+(appendix))
4240 #else
4241 #define GET_STACK_BOUNDS(start, end, appendix) \
4242  ((STACK_END < STACK_START) ? \
4243  ((start) = STACK_END, (end) = STACK_START) : ((start) = STACK_START, (end) = STACK_END+(appendix)))
4244 #endif
4245 
4246 static void mark_stack_locations(rb_objspace_t *objspace, const rb_execution_context_t *ec,
4247  const VALUE *stack_start, const VALUE *stack_end);
4248 
4249 static void
4250 mark_current_machine_context(rb_objspace_t *objspace, rb_execution_context_t *ec)
4251 {
4252  union {
4253  rb_jmp_buf j;
4254  VALUE v[sizeof(rb_jmp_buf) / sizeof(VALUE)];
4255  } save_regs_gc_mark;
4256  VALUE *stack_start, *stack_end;
4257 
4259  /* This assumes that all registers are saved into the jmp_buf (and stack) */
4260  rb_setjmp(save_regs_gc_mark.j);
4261 
4262  /* SET_STACK_END must be called in this function because
4263  * the stack frame of this function may contain
4264  * callee save registers and they should be marked. */
4265  SET_STACK_END;
4266  GET_STACK_BOUNDS(stack_start, stack_end, 1);
4267 
4268  mark_locations_array(objspace, save_regs_gc_mark.v, numberof(save_regs_gc_mark.v));
4269 
4270  mark_stack_locations(objspace, ec, stack_start, stack_end);
4271 }
4272 
4273 void
4275 {
4276  rb_objspace_t *objspace = &rb_objspace;
4277  VALUE *stack_start, *stack_end;
4278 
4279  GET_STACK_BOUNDS(stack_start, stack_end, 0);
4280  mark_stack_locations(objspace, ec, stack_start, stack_end);
4281 }
4282 
4283 static void
4284 mark_stack_locations(rb_objspace_t *objspace, const rb_execution_context_t *ec,
4285  const VALUE *stack_start, const VALUE *stack_end)
4286 {
4287 
4288  gc_mark_locations(objspace, stack_start, stack_end);
4289 #ifdef __ia64
4290  gc_mark_locations(objspace,
4291  ec->machine.register_stack_start,
4292  ec->machine.register_stack_end);
4293 #endif
4294 #if defined(__mc68000__)
4295  gc_mark_locations(objspace,
4296  (VALUE*)((char*)stack_start + 2),
4297  (VALUE*)((char*)stack_end - 2));
4298 #endif
4299 }
4300 
4301 void
4303 {
4304  mark_tbl(&rb_objspace, tbl);
4305 }
4306 
4307 static void
4308 gc_mark_maybe(rb_objspace_t *objspace, VALUE obj)
4309 {
4310  (void)VALGRIND_MAKE_MEM_DEFINED(&obj, sizeof(obj));
4311  if (is_pointer_to_heap(objspace, (void *)obj)) {
4312  int type = BUILTIN_TYPE(obj);
4313  if (type != T_ZOMBIE && type != T_NONE) {
4314  gc_mark_ptr(objspace, obj);
4315  }
4316  }
4317 }
4318 
4319 void
4321 {
4322  gc_mark_maybe(&rb_objspace, obj);
4323 }
4324 
4325 static inline int
4326 gc_mark_set(rb_objspace_t *objspace, VALUE obj)
4327 {
4328  if (RVALUE_MARKED(obj)) return 0;
4330  return 1;
4331 }
4332 
4333 #if USE_RGENGC
4334 static int
4335 gc_remember_unprotected(rb_objspace_t *objspace, VALUE obj)
4336 {
4337  struct heap_page *page = GET_HEAP_PAGE(obj);
4339 
4340  if (!MARKED_IN_BITMAP(uncollectible_bits, obj)) {
4342  MARK_IN_BITMAP(uncollectible_bits, obj);
4344 
4345 #if RGENGC_PROFILE > 0
4346  objspace->profile.total_remembered_shady_object_count++;
4347 #if RGENGC_PROFILE >= 2
4348  objspace->profile.remembered_shady_object_count_types[BUILTIN_TYPE(obj)]++;
4349 #endif
4350 #endif
4351  return TRUE;
4352  }
4353  else {
4354  return FALSE;
4355  }
4356 }
4357 #endif
4358 
4359 static void
4360 rgengc_check_relation(rb_objspace_t *objspace, VALUE obj)
4361 {
4362 #if USE_RGENGC
4363  const VALUE old_parent = objspace->rgengc.parent_object;
4364 
4365  if (old_parent) { /* parent object is old */
4366  if (RVALUE_WB_UNPROTECTED(obj)) {
4367  if (gc_remember_unprotected(objspace, obj)) {
4368  gc_report(2, objspace, "relation: (O->S) %s -> %s\n", obj_info(old_parent), obj_info(obj));
4369  }
4370  }
4371  else {
4372  if (!RVALUE_OLD_P(obj)) {
4373  if (RVALUE_MARKED(obj)) {
4374  /* An object pointed from an OLD object should be OLD. */
4375  gc_report(2, objspace, "relation: (O->unmarked Y) %s -> %s\n", obj_info(old_parent), obj_info(obj));
4376  RVALUE_AGE_SET_OLD(objspace, obj);
4377  if (is_incremental_marking(objspace)) {
4378  if (!RVALUE_MARKING(obj)) {
4379  gc_grey(objspace, obj);
4380  }
4381  }
4382  else {
4383  rgengc_remember(objspace, obj);
4384  }
4385  }
4386  else {
4387  gc_report(2, objspace, "relation: (O->Y) %s -> %s\n", obj_info(old_parent), obj_info(obj));
4388  RVALUE_AGE_SET_CANDIDATE(objspace, obj);
4389  }
4390  }
4391  }
4392  }
4393 
4394  GC_ASSERT(old_parent == objspace->rgengc.parent_object);
4395 #endif
4396 }
4397 
4398 static void
4399 gc_grey(rb_objspace_t *objspace, VALUE obj)
4400 {
4401 #if RGENGC_CHECK_MODE
4402  if (RVALUE_MARKED(obj) == FALSE) rb_bug("gc_grey: %s is not marked.", obj_info(obj));
4403  if (RVALUE_MARKING(obj) == TRUE) rb_bug("gc_grey: %s is marking/remembered.", obj_info(obj));
4404 #endif
4405 
4406 #if GC_ENABLE_INCREMENTAL_MARK
4407  if (is_incremental_marking(objspace)) {
4409  }
4410 #endif
4411 
4412  push_mark_stack(&objspace->mark_stack, obj);
4413 }
4414 
4415 static void
4416 gc_aging(rb_objspace_t *objspace, VALUE obj)
4417 {
4418 #if USE_RGENGC
4419  struct heap_page *page = GET_HEAP_PAGE(obj);
4420 
4421  GC_ASSERT(RVALUE_MARKING(obj) == FALSE);
4422  check_rvalue_consistency(obj);
4423 
4424  if (!RVALUE_PAGE_WB_UNPROTECTED(page, obj)) {
4425  if (!RVALUE_OLD_P(obj)) {
4426  gc_report(3, objspace, "gc_aging: YOUNG: %s\n", obj_info(obj));
4427  RVALUE_AGE_INC(objspace, obj);
4428  }
4429  else if (is_full_marking(objspace)) {
4430  GC_ASSERT(RVALUE_PAGE_UNCOLLECTIBLE(page, obj) == FALSE);
4431  RVALUE_PAGE_OLD_UNCOLLECTIBLE_SET(objspace, page, obj);
4432  }
4433  }
4434  check_rvalue_consistency(obj);
4435 #endif /* USE_RGENGC */
4436 
4437  objspace->marked_slots++;
4438 }
4439 
4440 NOINLINE(static void gc_mark_ptr(rb_objspace_t *objspace, VALUE obj));
4441 
4442 static void
4443 gc_mark_ptr(rb_objspace_t *objspace, VALUE obj)
4444 {
4445  if (LIKELY(objspace->mark_func_data == NULL)) {
4446  rgengc_check_relation(objspace, obj);
4447  if (!gc_mark_set(objspace, obj)) return; /* already marked */
4448  gc_aging(objspace, obj);
4449  gc_grey(objspace, obj);
4450  }
4451  else {
4452  objspace->mark_func_data->mark_func(obj, objspace->mark_func_data->data);
4453  }
4454 }
4455 
4456 static inline void
4457 gc_mark(rb_objspace_t *objspace, VALUE obj)
4458 {
4459  if (!is_markable_object(objspace, obj)) return;
4460  gc_mark_ptr(objspace, obj);
4461 }
4462 
4463 void
4465 {
4466  gc_mark(&rb_objspace, ptr);
4467 }
4468 
4469 /* CAUTION: THIS FUNCTION ENABLE *ONLY BEFORE* SWEEPING.
4470  * This function is only for GC_END_MARK timing.
4471  */
4472 
4473 int
4475 {
4476  return RVALUE_MARKED(obj) ? TRUE : FALSE;
4477 }
4478 
4479 static inline void
4480 gc_mark_set_parent(rb_objspace_t *objspace, VALUE obj)
4481 {
4482 #if USE_RGENGC
4483  if (RVALUE_OLD_P(obj)) {
4484  objspace->rgengc.parent_object = obj;
4485  }
4486  else {
4487  objspace->rgengc.parent_object = Qfalse;
4488  }
4489 #endif
4490 }
4491 
4492 static void
4493 gc_mark_imemo(rb_objspace_t *objspace, VALUE obj)
4494 {
4495  switch (imemo_type(obj)) {
4496  case imemo_env:
4497  {
4498  const rb_env_t *env = (const rb_env_t *)obj;
4499  GC_ASSERT(VM_ENV_ESCAPED_P(env->ep));
4500  gc_mark_values(objspace, (long)env->env_size, env->env);
4501  VM_ENV_FLAGS_SET(env->ep, VM_ENV_FLAG_WB_REQUIRED);
4502  gc_mark(objspace, (VALUE)rb_vm_env_prev_env(env));
4503  gc_mark(objspace, (VALUE)env->iseq);
4504  }
4505  return;
4506  case imemo_cref:
4507  gc_mark(objspace, RANY(obj)->as.imemo.cref.klass);
4508  gc_mark(objspace, (VALUE)RANY(obj)->as.imemo.cref.next);
4509  gc_mark(objspace, RANY(obj)->as.imemo.cref.refinements);
4510  return;
4511  case imemo_svar:
4512  gc_mark(objspace, RANY(obj)->as.imemo.svar.cref_or_me);
4513  gc_mark(objspace, RANY(obj)->as.imemo.svar.lastline);
4514  gc_mark(objspace, RANY(obj)->as.imemo.svar.backref);
4515  gc_mark(objspace, RANY(obj)->as.imemo.svar.others);
4516  return;
4517  case imemo_throw_data:
4518  gc_mark(objspace, RANY(obj)->as.imemo.throw_data.throw_obj);
4519  return;
4520  case imemo_ifunc:
4521  gc_mark_maybe(objspace, (VALUE)RANY(obj)->as.imemo.ifunc.data);
4522  return;
4523  case imemo_memo:
4524  gc_mark(objspace, RANY(obj)->as.imemo.memo.v1);
4525  gc_mark(objspace, RANY(obj)->as.imemo.memo.v2);
4526  gc_mark_maybe(objspace, RANY(obj)->as.imemo.memo.u3.value);
4527  return;
4528  case imemo_ment:
4529  mark_method_entry(objspace, &RANY(obj)->as.imemo.ment);
4530  return;
4531  case imemo_iseq:
4532  rb_iseq_mark((rb_iseq_t *)obj);
4533  return;
4534  case imemo_alloc:
4535  {
4536  const rb_imemo_alloc_t *m = &RANY(obj)->as.imemo.alloc;
4537  do {
4538  rb_gc_mark_locations(m->ptr, m->ptr + m->cnt);
4539  } while ((m = m->next) != NULL);
4540  }
4541  return;
4542 #if VM_CHECK_MODE > 0
4543  default:
4544  VM_UNREACHABLE(gc_mark_imemo);
4545 #endif
4546  }
4547 }
4548 
4549 static void
4550 gc_mark_children(rb_objspace_t *objspace, VALUE obj)
4551 {
4552  register RVALUE *any = RANY(obj);
4553  gc_mark_set_parent(objspace, obj);
4554 
4555  if (FL_TEST(obj, FL_EXIVAR)) {
4556  rb_mark_generic_ivar(obj);
4557  }
4558 
4559  switch (BUILTIN_TYPE(obj)) {
4560  case T_NIL:
4561  case T_FIXNUM:
4562  rb_bug("rb_gc_mark() called for broken object");
4563  break;
4564 
4565  case T_NODE:
4566  obj = rb_gc_mark_node(&any->as.node);
4567  if (obj) gc_mark(objspace, obj);
4568  return; /* no need to mark class. */
4569 
4570  case T_IMEMO:
4571  gc_mark_imemo(objspace, obj);
4572  return;
4573  }
4574 
4575  gc_mark(objspace, any->as.basic.klass);
4576 
4577  switch (BUILTIN_TYPE(obj)) {
4578  case T_CLASS:
4579  case T_MODULE:
4580  mark_m_tbl(objspace, RCLASS_M_TBL(obj));
4581  if (!RCLASS_EXT(obj)) break;
4582  mark_tbl(objspace, RCLASS_IV_TBL(obj));
4583  mark_const_tbl(objspace, RCLASS_CONST_TBL(obj));
4584  gc_mark(objspace, RCLASS_SUPER((VALUE)obj));
4585  break;
4586 
4587  case T_ICLASS:
4588  if (FL_TEST(obj, RICLASS_IS_ORIGIN)) {
4589  mark_m_tbl(objspace, RCLASS_M_TBL(obj));
4590  }
4591  if (!RCLASS_EXT(obj)) break;
4592  mark_m_tbl(objspace, RCLASS_CALLABLE_M_TBL(obj));
4593  gc_mark(objspace, RCLASS_SUPER((VALUE)obj));
4594  break;
4595 
4596  case T_ARRAY:
4597  if (FL_TEST(obj, ELTS_SHARED)) {
4598  gc_mark(objspace, any->as.array.as.heap.aux.shared);
4599  }
4600  else {
4601  long i, len = RARRAY_LEN(obj);
4602  const VALUE *ptr = RARRAY_CONST_PTR(obj);
4603  for (i=0; i < len; i++) {
4604  gc_mark(objspace, *ptr++);
4605  }
4606  }
4607  break;
4608 
4609  case T_HASH:
4610  mark_hash(objspace, any->as.hash.ntbl);
4611  gc_mark(objspace, any->as.hash.ifnone);
4612  break;
4613 
4614  case T_STRING:
4615  if (STR_SHARED_P(obj)) {
4616  gc_mark(objspace, any->as.string.as.heap.aux.shared);
4617  }
4618  break;
4619 
4620  case T_DATA:
4621  {
4622  void *const ptr = DATA_PTR(obj);
4623  if (ptr) {
4624  RUBY_DATA_FUNC mark_func = RTYPEDDATA_P(obj) ?
4625  any->as.typeddata.type->function.dmark :
4626  any->as.data.dmark;
4627  if (mark_func) (*mark_func)(ptr);
4628  }
4629  }
4630  break;
4631 
4632  case T_OBJECT:
4633  {
4634  uint32_t i, len = ROBJECT_NUMIV(obj);
4635  VALUE *ptr = ROBJECT_IVPTR(obj);
4636  for (i = 0; i < len; i++) {
4637  gc_mark(objspace, *ptr++);
4638  }
4639  }
4640  break;
4641 
4642  case T_FILE:
4643  if (any->as.file.fptr) {
4644  gc_mark(objspace, any->as.file.fptr->pathv);
4645  gc_mark(objspace, any->as.file.fptr->tied_io_for_writing);
4646  gc_mark(objspace, any->as.file.fptr->writeconv_asciicompat);
4647  gc_mark(objspace, any->as.file.fptr->writeconv_pre_ecopts);
4648  gc_mark(objspace, any->as.file.fptr->encs.ecopts);
4649  gc_mark(objspace, any->as.file.fptr->write_lock);
4650  }
4651  break;
4652 
4653  case T_REGEXP:
4654  gc_mark(objspace, any->as.regexp.src);
4655  break;
4656 
4657  case T_FLOAT:
4658  case T_BIGNUM:
4659  case T_SYMBOL:
4660  break;
4661 
4662  case T_MATCH:
4663  gc_mark(objspace, any->as.match.regexp);
4664  if (any->as.match.str) {
4665  gc_mark(objspace, any->as.match.str);
4666  }
4667  break;
4668 
4669  case T_RATIONAL:
4670  gc_mark(objspace, any->as.rational.num);
4671  gc_mark(objspace, any->as.rational.den);
4672  break;
4673 
4674  case T_COMPLEX:
4675  gc_mark(objspace, any->as.complex.real);
4676  gc_mark(objspace, any->as.complex.imag);
4677  break;
4678 
4679  case T_STRUCT:
4680  {
4681  long len = RSTRUCT_LEN(obj);
4682  const VALUE *ptr = RSTRUCT_CONST_PTR(obj);
4683 
4684  while (len--) {
4685  gc_mark(objspace, *ptr++);
4686  }
4687  }
4688  break;
4689 
4690  default:
4691 #if GC_DEBUG
4693 #endif
4694  if (BUILTIN_TYPE(obj) == T_NONE) rb_bug("rb_gc_mark(): %p is T_NONE", (void *)obj);
4695  if (BUILTIN_TYPE(obj) == T_ZOMBIE) rb_bug("rb_gc_mark(): %p is T_ZOMBIE", (void *)obj);
4696  rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s",
4697  BUILTIN_TYPE(obj), any,
4698  is_pointer_to_heap(objspace, any) ? "corrupted object" : "non object");
4699  }
4700 }
4701 
4706 static inline int
4707 gc_mark_stacked_objects(rb_objspace_t *objspace, int incremental, size_t count)
4708 {
4709  mark_stack_t *mstack = &objspace->mark_stack;
4710  VALUE obj;
4711 #if GC_ENABLE_INCREMENTAL_MARK
4712  size_t marked_slots_at_the_beginning = objspace->marked_slots;
4713  size_t popped_count = 0;
4714 #endif
4715 
4716  while (pop_mark_stack(mstack, &obj)) {
4717  if (obj == Qundef) continue; /* skip */
4718 
4719  if (RGENGC_CHECK_MODE && !RVALUE_MARKED(obj)) {
4720  rb_bug("gc_mark_stacked_objects: %s is not marked.", obj_info(obj));
4721  }
4722  gc_mark_children(objspace, obj);
4723 
4724 #if GC_ENABLE_INCREMENTAL_MARK
4725  if (incremental) {
4726  if (RGENGC_CHECK_MODE && !RVALUE_MARKING(obj)) {
4727  rb_bug("gc_mark_stacked_objects: incremental, but marking bit is 0");
4728  }
4730  popped_count++;
4731 
4732  if (popped_count + (objspace->marked_slots - marked_slots_at_the_beginning) > count) {
4733  break;
4734  }
4735  }
4736  else {
4737  /* just ignore marking bits */
4738  }
4739 #endif
4740  }
4741 
4742  if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(Qnil);
4743 
4744  if (is_mark_stack_empty(mstack)) {
4745  shrink_stack_chunk_cache(mstack);
4746  return TRUE;
4747  }
4748  else {
4749  return FALSE;
4750  }
4751 }
4752 
4753 static int
4754 gc_mark_stacked_objects_incremental(rb_objspace_t *objspace, size_t count)
4755 {
4756  return gc_mark_stacked_objects(objspace, TRUE, count);
4757 }
4758 
4759 static int
4760 gc_mark_stacked_objects_all(rb_objspace_t *objspace)
4761 {
4762  return gc_mark_stacked_objects(objspace, FALSE, 0);
4763 }
4764 
4765 #if PRINT_ROOT_TICKS
4766 #define MAX_TICKS 0x100
4767 static tick_t mark_ticks[MAX_TICKS];
4768 static const char *mark_ticks_categories[MAX_TICKS];
4769 
4770 static void
4771 show_mark_ticks(void)
4772 {
4773  int i;
4774  fprintf(stderr, "mark ticks result:\n");
4775  for (i=0; i<MAX_TICKS; i++) {
4776  const char *category = mark_ticks_categories[i];
4777  if (category) {
4778  fprintf(stderr, "%s\t%8lu\n", category, (unsigned long)mark_ticks[i]);
4779  }
4780  else {
4781  break;
4782  }
4783  }
4784 }
4785 
4786 #endif /* PRITNT_ROOT_TICKS */
4787 
4788 static void
4789 gc_mark_roots(rb_objspace_t *objspace, const char **categoryp)
4790 {
4791  struct gc_list *list;
4792  rb_thread_t *th = GET_THREAD();
4793  rb_execution_context_t *ec = &th->ec;
4794 
4795 #if PRINT_ROOT_TICKS
4796  tick_t start_tick = tick();
4797  int tick_count = 0;
4798  const char *prev_category = 0;
4799 
4800  if (mark_ticks_categories[0] == 0) {
4801  atexit(show_mark_ticks);
4802  }
4803 #endif
4804 
4805  if (categoryp) *categoryp = "xxx";
4806 
4807 #if USE_RGENGC
4808  objspace->rgengc.parent_object = Qfalse;
4809 #endif
4810 
4811 #if PRINT_ROOT_TICKS
4812 #define MARK_CHECKPOINT_PRINT_TICK(category) do { \
4813  if (prev_category) { \
4814  tick_t t = tick(); \
4815  mark_ticks[tick_count] = t - start_tick; \
4816  mark_ticks_categories[tick_count] = prev_category; \
4817  tick_count++; \
4818  } \
4819  prev_category = category; \
4820  start_tick = tick(); \
4821 } while (0)
4822 #else /* PRITNT_ROOT_TICKS */
4823 #define MARK_CHECKPOINT_PRINT_TICK(category)
4824 #endif
4825 
4826 #define MARK_CHECKPOINT(category) do { \
4827  if (categoryp) *categoryp = category; \
4828  MARK_CHECKPOINT_PRINT_TICK(category); \
4829 } while (0)
4830 
4831  MARK_CHECKPOINT("vm");
4832  SET_STACK_END;
4833  rb_vm_mark(th->vm);
4834  if (th->vm->self) gc_mark(objspace, th->vm->self);
4835 
4836  MARK_CHECKPOINT("finalizers");
4837  mark_tbl(objspace, finalizer_table);
4838 
4839  MARK_CHECKPOINT("machine_context");
4840  mark_current_machine_context(objspace, &th->ec);
4841 
4842  MARK_CHECKPOINT("encodings");
4844 
4845  /* mark protected global variables */
4846  MARK_CHECKPOINT("global_list");
4847  for (list = global_list; list; list = list->next) {
4848  rb_gc_mark_maybe(*list->varptr);
4849  }
4850 
4851  MARK_CHECKPOINT("end_proc");
4852  rb_mark_end_proc();
4853 
4854  MARK_CHECKPOINT("global_tbl");
4856 
4858 
4859  MARK_CHECKPOINT("finish");
4860 #undef MARK_CHECKPOINT
4861 }
4862 
4863 #if RGENGC_CHECK_MODE >= 4
4864 
4865 #define MAKE_ROOTSIG(obj) (((VALUE)(obj) << 1) | 0x01)
4866 #define IS_ROOTSIG(obj) ((VALUE)(obj) & 0x01)
4867 #define GET_ROOTSIG(obj) ((const char *)((VALUE)(obj) >> 1))
4868 
4869 struct reflist {
4870  VALUE *list;
4871  int pos;
4872  int size;
4873 };
4874 
4875 static struct reflist *
4876 reflist_create(VALUE obj)
4877 {
4878  struct reflist *refs = xmalloc(sizeof(struct reflist));
4879  refs->size = 1;
4880  refs->list = ALLOC_N(VALUE, refs->size);
4881  refs->list[0] = obj;
4882  refs->pos = 1;
4883  return refs;
4884 }
4885 
4886 static void
4887 reflist_destruct(struct reflist *refs)
4888 {
4889  xfree(refs->list);
4890  xfree(refs);
4891 }
4892 
4893 static void
4894 reflist_add(struct reflist *refs, VALUE obj)
4895 {
4896  if (refs->pos == refs->size) {
4897  refs->size *= 2;
4898  SIZED_REALLOC_N(refs->list, VALUE, refs->size, refs->size/2);
4899  }
4900 
4901  refs->list[refs->pos++] = obj;
4902 }
4903 
4904 static void
4905 reflist_dump(struct reflist *refs)
4906 {
4907  int i;
4908  for (i=0; i<refs->pos; i++) {
4909  VALUE obj = refs->list[i];
4910  if (IS_ROOTSIG(obj)) { /* root */
4911  fprintf(stderr, "<root@%s>", GET_ROOTSIG(obj));
4912  }
4913  else {
4914  fprintf(stderr, "<%s>", obj_info(obj));
4915  }
4916  if (i+1 < refs->pos) fprintf(stderr, ", ");
4917  }
4918 }
4919 
4920 static int
4921 reflist_refered_from_machine_context(struct reflist *refs)
4922 {
4923  int i;
4924  for (i=0; i<refs->pos; i++) {
4925  VALUE obj = refs->list[i];
4926  if (IS_ROOTSIG(obj) && strcmp(GET_ROOTSIG(obj), "machine_context") == 0) return 1;
4927  }
4928  return 0;
4929 }
4930 
4931 struct allrefs {
4932  rb_objspace_t *objspace;
4933  /* a -> obj1
4934  * b -> obj1
4935  * c -> obj1
4936  * c -> obj2
4937  * d -> obj3
4938  * #=> {obj1 => [a, b, c], obj2 => [c, d]}
4939  */
4940  struct st_table *references;
4941  const char *category;
4942  VALUE root_obj;
4944 };
4945 
4946 static int
4947 allrefs_add(struct allrefs *data, VALUE obj)
4948 {
4949  struct reflist *refs;
4950 
4951  if (st_lookup(data->references, obj, (st_data_t *)&refs)) {
4952  reflist_add(refs, data->root_obj);
4953  return 0;
4954  }
4955  else {
4956  refs = reflist_create(data->root_obj);
4957  st_insert(data->references, obj, (st_data_t)refs);
4958  return 1;
4959  }
4960 }
4961 
4962 static void
4963 allrefs_i(VALUE obj, void *ptr)
4964 {
4965  struct allrefs *data = (struct allrefs *)ptr;
4966 
4967  if (allrefs_add(data, obj)) {
4968  push_mark_stack(&data->mark_stack, obj);
4969  }
4970 }
4971 
4972 static void
4973 allrefs_roots_i(VALUE obj, void *ptr)
4974 {
4975  struct allrefs *data = (struct allrefs *)ptr;
4976  if (strlen(data->category) == 0) rb_bug("!!!");
4977  data->root_obj = MAKE_ROOTSIG(data->category);
4978 
4979  if (allrefs_add(data, obj)) {
4980  push_mark_stack(&data->mark_stack, obj);
4981  }
4982 }
4983 
4984 static st_table *
4985 objspace_allrefs(rb_objspace_t *objspace)
4986 {
4987  struct allrefs data;
4988  struct mark_func_data_struct mfd;
4989  VALUE obj;
4990  int prev_dont_gc = dont_gc;
4991  dont_gc = TRUE;
4992 
4993  data.objspace = objspace;
4994  data.references = st_init_numtable();
4995  init_mark_stack(&data.mark_stack);
4996 
4997  mfd.mark_func = allrefs_roots_i;
4998  mfd.data = &data;
4999 
5000  /* traverse root objects */
5001  PUSH_MARK_FUNC_DATA(&mfd);
5002  objspace->mark_func_data = &mfd;
5003  gc_mark_roots(objspace, &data.category);
5005 
5006  /* traverse rest objects reachable from root objects */
5007  while (pop_mark_stack(&data.mark_stack, &obj)) {
5008  rb_objspace_reachable_objects_from(data.root_obj = obj, allrefs_i, &data);
5009  }
5010  free_stack_chunks(&data.mark_stack);
5011 
5012  dont_gc = prev_dont_gc;
5013  return data.references;
5014 }
5015 
5016 static int
5017 objspace_allrefs_destruct_i(st_data_t key, st_data_t value, void *ptr)
5018 {
5019  struct reflist *refs = (struct reflist *)value;
5020  reflist_destruct(refs);
5021  return ST_CONTINUE;
5022 }
5023 
5024 static void
5025 objspace_allrefs_destruct(struct st_table *refs)
5026 {
5027  st_foreach(refs, objspace_allrefs_destruct_i, 0);
5028  st_free_table(refs);
5029 }
5030 
5031 #if RGENGC_CHECK_MODE >= 5
5032 static int
5033 allrefs_dump_i(st_data_t k, st_data_t v, st_data_t ptr)
5034 {
5035  VALUE obj = (VALUE)k;
5036  struct reflist *refs = (struct reflist *)v;
5037  fprintf(stderr, "[allrefs_dump_i] %s <- ", obj_info(obj));
5038  reflist_dump(refs);
5039  fprintf(stderr, "\n");
5040  return ST_CONTINUE;
5041 }
5042 
5043 static void
5044 allrefs_dump(rb_objspace_t *objspace)
5045 {
5046  fprintf(stderr, "[all refs] (size: %d)\n", (int)objspace->rgengc.allrefs_table->num_entries);
5047  st_foreach(objspace->rgengc.allrefs_table, allrefs_dump_i, 0);
5048 }
5049 #endif
5050 
5051 static int
5052 gc_check_after_marks_i(st_data_t k, st_data_t v, void *ptr)
5053 {
5054  VALUE obj = k;
5055  struct reflist *refs = (struct reflist *)v;
5056  rb_objspace_t *objspace = (rb_objspace_t *)ptr;
5057 
5058  /* object should be marked or oldgen */
5059  if (!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj)) {
5060  fprintf(stderr, "gc_check_after_marks_i: %s is not marked and not oldgen.\n", obj_info(obj));
5061  fprintf(stderr, "gc_check_after_marks_i: %p is referred from ", (void *)obj);
5062  reflist_dump(refs);
5063 
5064  if (reflist_refered_from_machine_context(refs)) {
5065  fprintf(stderr, " (marked from machine stack).\n");
5066  /* marked from machine context can be false positive */
5067  }
5068  else {
5069  objspace->rgengc.error_count++;
5070  fprintf(stderr, "\n");
5071  }
5072  }
5073  return ST_CONTINUE;
5074 }
5075 
5076 static void
5077 gc_marks_check(rb_objspace_t *objspace, int (*checker_func)(ANYARGS), const char *checker_name)
5078 {
5079  size_t saved_malloc_increase = objspace->malloc_params.increase;
5080 #if RGENGC_ESTIMATE_OLDMALLOC
5081  size_t saved_oldmalloc_increase = objspace->rgengc.oldmalloc_increase;
5082 #endif
5083  VALUE already_disabled = rb_gc_disable();
5084 
5085  objspace->rgengc.allrefs_table = objspace_allrefs(objspace);
5086 
5087  if (checker_func) {
5088  st_foreach(objspace->rgengc.allrefs_table, checker_func, (st_data_t)objspace);
5089  }
5090 
5091  if (objspace->rgengc.error_count > 0) {
5092 #if RGENGC_CHECK_MODE >= 5
5093  allrefs_dump(objspace);
5094 #endif
5095  if (checker_name) rb_bug("%s: GC has problem.", checker_name);
5096  }
5097 
5098  objspace_allrefs_destruct(objspace->rgengc.allrefs_table);
5099  objspace->rgengc.allrefs_table = 0;
5100 
5101  if (already_disabled == Qfalse) rb_gc_enable();
5102  objspace->malloc_params.increase = saved_malloc_increase;
5103 #if RGENGC_ESTIMATE_OLDMALLOC
5104  objspace->rgengc.oldmalloc_increase = saved_oldmalloc_increase;
5105 #endif
5106 }
5107 #endif /* RGENGC_CHECK_MODE >= 4 */
5108 
5114 
5115 #if USE_RGENGC
5119 #endif
5120 };
5121 
5122 #if USE_RGENGC
5123 static void
5124 check_generation_i(const VALUE child, void *ptr)
5125 {
5127  const VALUE parent = data->parent;
5128 
5129  if (RGENGC_CHECK_MODE) GC_ASSERT(RVALUE_OLD_P(parent));
5130 
5131  if (!RVALUE_OLD_P(child)) {
5132  if (!RVALUE_REMEMBERED(parent) &&
5133  !RVALUE_REMEMBERED(child) &&
5134  !RVALUE_UNCOLLECTIBLE(child)) {
5135  fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (O->Y) %s -> %s\n", obj_info(parent), obj_info(child));
5136  data->err_count++;
5137  }
5138  }
5139 }
5140 
5141 static void
5142 check_color_i(const VALUE child, void *ptr)
5143 {
5145  const VALUE parent = data->parent;
5146 
5147  if (!RVALUE_WB_UNPROTECTED(parent) && RVALUE_WHITE_P(child)) {
5148  fprintf(stderr, "verify_internal_consistency_reachable_i: WB miss (B->W) - %s -> %s\n",
5149  obj_info(parent), obj_info(child));
5150  data->err_count++;
5151  }
5152 }
5153 #endif
5154 
5155 static void
5156 check_children_i(const VALUE child, void *ptr)
5157 {
5158  check_rvalue_consistency(child);
5159 }
5160 
5161 static int
5162 verify_internal_consistency_i(void *page_start, void *page_end, size_t stride, void *ptr)
5163 {
5165  VALUE obj;
5166  rb_objspace_t *objspace = data->objspace;
5167 
5168  for (obj = (VALUE)page_start; obj != (VALUE)page_end; obj += stride) {
5169  if (is_live_object(objspace, obj)) {
5170  /* count objects */
5171  data->live_object_count++;
5172 
5173  rb_objspace_reachable_objects_from(obj, check_children_i, (void *)data);
5174 
5175 #if USE_RGENGC
5176  /* check health of children */
5177  data->parent = obj;
5178 
5179  if (RVALUE_OLD_P(obj)) data->old_object_count++;
5180  if (RVALUE_WB_UNPROTECTED(obj) && RVALUE_UNCOLLECTIBLE(obj)) data->remembered_shady_count++;
5181 
5182  if (!is_marking(objspace) && RVALUE_OLD_P(obj)) {
5183  /* reachable objects from an oldgen object should be old or (young with remember) */
5184  data->parent = obj;
5185  rb_objspace_reachable_objects_from(obj, check_generation_i, (void *)data);
5186  }
5187 
5188  if (is_incremental_marking(objspace)) {
5189  if (RVALUE_BLACK_P(obj)) {
5190  /* reachable objects from black objects should be black or grey objects */
5191  data->parent = obj;
5192  rb_objspace_reachable_objects_from(obj, check_color_i, (void *)data);
5193  }
5194  }
5195 #endif
5196  }
5197  else {
5198  if (BUILTIN_TYPE(obj) == T_ZOMBIE) {
5199  GC_ASSERT(RBASIC(obj)->flags == T_ZOMBIE);
5200  data->zombie_object_count++;
5201  }
5202  }
5203  }
5204 
5205  return 0;
5206 }
5207 
5208 static int
5209 gc_verify_heap_page(rb_objspace_t *objspace, struct heap_page *page, VALUE obj)
5210 {
5211 #if USE_RGENGC
5212  int i;
5213  unsigned int has_remembered_shady = FALSE;
5214  unsigned int has_remembered_old = FALSE;
5215  int rememberd_old_objects = 0;
5216  int free_objects = 0;
5217  int zombie_objects = 0;
5218 
5219  for (i=0; i<page->total_slots; i++) {
5220  VALUE val = (VALUE)&page->start[i];
5221  if (RBASIC(val) == 0) free_objects++;
5222  if (BUILTIN_TYPE(val) == T_ZOMBIE) zombie_objects++;
5223  if (RVALUE_PAGE_UNCOLLECTIBLE(page, val) && RVALUE_PAGE_WB_UNPROTECTED(page, val)) {
5224  has_remembered_shady = TRUE;
5225  }
5226  if (RVALUE_PAGE_MARKING(page, val)) {
5227  has_remembered_old = TRUE;
5228  rememberd_old_objects++;
5229  }
5230  }
5231 
5232  if (!is_incremental_marking(objspace) &&
5233  page->flags.has_remembered_objects == FALSE && has_remembered_old == TRUE) {
5234 
5235  for (i=0; i<page->total_slots; i++) {
5236  VALUE val = (VALUE)&page->start[i];
5237  if (RVALUE_PAGE_MARKING(page, val)) {
5238  fprintf(stderr, "marking -> %s\n", obj_info(val));
5239  }
5240  }
5241  rb_bug("page %p's has_remembered_objects should be false, but there are remembered old objects (%d). %s",
5242  page, rememberd_old_objects, obj ? obj_info(obj) : "");
5243  }
5244 
5245  if (page->flags.has_uncollectible_shady_objects == FALSE && has_remembered_shady == TRUE) {
5246  rb_bug("page %p's has_remembered_shady should be false, but there are remembered shady objects. %s",
5247  page, obj ? obj_info(obj) : "");
5248  }
5249 
5250  if (0) {
5251  /* free_slots may not equal to free_objects */
5252  if (page->free_slots != free_objects) {
5253  rb_bug("page %p's free_slots should be %d, but %d\n", page, (int)page->free_slots, free_objects);
5254  }
5255  }
5256  if (page->final_slots != zombie_objects) {
5257  rb_bug("page %p's final_slots should be %d, but %d\n", page, (int)page->final_slots, zombie_objects);
5258  }
5259 
5260  return rememberd_old_objects;
5261 #else
5262  return 0;
5263 #endif
5264 }
5265 
5266 static int
5267 gc_verify_heap_pages_(rb_objspace_t *objspace, struct heap_page *page)
5268 {
5269  int rememberd_old_objects = 0;
5270 
5271  while (page) {
5272  if (page->flags.has_remembered_objects == FALSE) {
5273  rememberd_old_objects += gc_verify_heap_page(objspace, page, Qfalse);
5274  }
5275  page = page->next;
5276  }
5277 
5278  return rememberd_old_objects;
5279 }
5280 
5281 static int
5282 gc_verify_heap_pages(rb_objspace_t *objspace)
5283 {
5284  int rememberd_old_objects = 0;
5285  rememberd_old_objects = gc_verify_heap_pages_(objspace, heap_eden->pages);
5286  rememberd_old_objects = gc_verify_heap_pages_(objspace, heap_tomb->pages);
5287  return rememberd_old_objects;
5288 }
5289 
5290 /*
5291  * call-seq:
5292  * GC.verify_internal_consistency -> nil
5293  *
5294  * Verify internal consistency.
5295  *
5296  * This method is implementation specific.
5297  * Now this method checks generational consistency
5298  * if RGenGC is supported.
5299  */
5300 static VALUE
5301 gc_verify_internal_consistency(VALUE dummy)
5302 {
5303  rb_objspace_t *objspace = &rb_objspace;
5304  struct verify_internal_consistency_struct data = {0};
5305  struct each_obj_args eo_args;
5306 
5307  data.objspace = objspace;
5308  gc_report(5, objspace, "gc_verify_internal_consistency: start\n");
5309 
5310  /* check relations */
5311 
5312  eo_args.callback = verify_internal_consistency_i;
5313  eo_args.data = (void *)&data;
5314  objspace_each_objects((VALUE)&eo_args);
5315 
5316  if (data.err_count != 0) {
5317 #if RGENGC_CHECK_MODE >= 5
5318  objspace->rgengc.error_count = data.err_count;
5319  gc_marks_check(objspace, NULL, NULL);
5320  allrefs_dump(objspace);
5321 #endif
5322  rb_bug("gc_verify_internal_consistency: found internal inconsistency.");
5323  }
5324 
5325  /* check heap_page status */
5326  gc_verify_heap_pages(objspace);
5327 
5328  /* check counters */
5329 
5331  if (objspace_live_slots(objspace) != data.live_object_count) {
5332  fprintf(stderr, "heap_pages_final_slots: %d, objspace->profile.total_freed_objects: %d\n",
5333  (int)heap_pages_final_slots, (int)objspace->profile.total_freed_objects);
5334  rb_bug("inconsistent live slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", objspace_live_slots(objspace), data.live_object_count);
5335  }
5336  }
5337 
5338 #if USE_RGENGC
5339  if (!is_marking(objspace)) {
5340  if (objspace->rgengc.old_objects != data.old_object_count) {
5341  rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", objspace->rgengc.old_objects, data.old_object_count);
5342  }
5344  rb_bug("inconsistent old slot number: expect %"PRIuSIZE", but %"PRIuSIZE".", objspace->rgengc.uncollectible_wb_unprotected_objects, data.remembered_shady_count);
5345  }
5346  }
5347 #endif
5348 
5349  if (!finalizing) {
5350  size_t list_count = 0;
5351 
5352  {
5354  while (z) {
5355  list_count++;
5356  z = RZOMBIE(z)->next;
5357  }
5358  }
5359 
5361  heap_pages_final_slots != list_count) {
5362 
5363  rb_bug("inconsistent finalizing object count:\n"
5364  " expect %"PRIuSIZE"\n"
5365  " but %"PRIuSIZE" zombies\n"
5366  " heap_pages_deferred_final list has %"PRIuSIZE" items.",
5368  data.zombie_object_count,
5369  list_count);
5370  }
5371  }
5372 
5373  gc_report(5, objspace, "gc_verify_internal_consistency: OK\n");
5374 
5375  return Qnil;
5376 }
5377 
5378 void
5380 {
5381  gc_verify_internal_consistency(Qnil);
5382 }
5383 
5384 /* marks */
5385 
5386 static void
5387 gc_marks_start(rb_objspace_t *objspace, int full_mark)
5388 {
5389  /* start marking */
5390  gc_report(1, objspace, "gc_marks_start: (%s)\n", full_mark ? "full" : "minor");
5391  gc_mode_transition(objspace, gc_mode_marking);
5392 
5393 #if USE_RGENGC
5394  if (full_mark) {
5395 #if GC_ENABLE_INCREMENTAL_MARK
5396  objspace->rincgc.step_slots = (objspace->marked_slots * 2) / ((objspace->rincgc.pooled_slots / HEAP_PAGE_OBJ_LIMIT) + 1);
5397 
5398  if (0) fprintf(stderr, "objspace->marked_slots: %d, objspace->rincgc.pooled_page_num: %d, objspace->rincgc.step_slots: %d, \n",
5399  (int)objspace->marked_slots, (int)objspace->rincgc.pooled_slots, (int)objspace->rincgc.step_slots);
5400 #endif
5401  objspace->flags.during_minor_gc = FALSE;
5402  objspace->profile.major_gc_count++;
5404  objspace->rgengc.old_objects = 0;
5405  objspace->rgengc.last_major_gc = objspace->profile.count;
5406  objspace->marked_slots = 0;
5407  rgengc_mark_and_rememberset_clear(objspace, heap_eden);
5408  }
5409  else {
5410  objspace->flags.during_minor_gc = TRUE;
5411  objspace->marked_slots =
5412  objspace->rgengc.old_objects + objspace->rgengc.uncollectible_wb_unprotected_objects; /* uncollectible objects are marked already */
5413  objspace->profile.minor_gc_count++;
5414  rgengc_rememberset_mark(objspace, heap_eden);
5415  }
5416 #endif
5417 
5418  gc_mark_roots(objspace, NULL);
5419 
5420  gc_report(1, objspace, "gc_marks_start: (%s) end, stack in %d\n", full_mark ? "full" : "minor", (int)mark_stack_size(&objspace->mark_stack));
5421 }
5422 
5423 #if GC_ENABLE_INCREMENTAL_MARK
5424 static void
5425 gc_marks_wb_unprotected_objects(rb_objspace_t *objspace)
5426 {
5427  struct heap_page *page = heap_eden->pages;
5428 
5429  while (page) {
5430  bits_t *mark_bits = page->mark_bits;
5431  bits_t *wbun_bits = page->wb_unprotected_bits;
5432  RVALUE *p = page->start;
5433  RVALUE *offset = p - NUM_IN_PAGE(p);
5434  size_t j;
5435 
5436  for (j=0; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5437  bits_t bits = mark_bits[j] & wbun_bits[j];
5438 
5439  if (bits) {
5440  p = offset + j * BITS_BITLENGTH;
5441 
5442  do {
5443  if (bits & 1) {
5444  gc_report(2, objspace, "gc_marks_wb_unprotected_objects: marked shady: %s\n", obj_info((VALUE)p));
5445  GC_ASSERT(RVALUE_WB_UNPROTECTED((VALUE)p));
5446  GC_ASSERT(RVALUE_MARKED((VALUE)p));
5447  gc_mark_children(objspace, (VALUE)p);
5448  }
5449  p++;
5450  bits >>= 1;
5451  } while (bits);
5452  }
5453  }
5454 
5455  page = page->next;
5456  }
5457 
5458  gc_mark_stacked_objects_all(objspace);
5459 }
5460 
5461 static struct heap_page *
5462 heap_move_pooled_pages_to_free_pages(rb_heap_t *heap)
5463 {
5464  struct heap_page *page = heap->pooled_pages;
5465 
5466  if (page) {
5467  heap->pooled_pages = page->free_next;
5468  page->free_next = heap->free_pages;
5469  heap->free_pages = page;
5470  }
5471 
5472  return page;
5473 }
5474 #endif
5475 
5476 static int
5477 gc_marks_finish(rb_objspace_t *objspace)
5478 {
5479 #if GC_ENABLE_INCREMENTAL_MARK
5480  /* finish incremental GC */
5481  if (is_incremental_marking(objspace)) {
5482  if (heap_eden->pooled_pages) {
5483  heap_move_pooled_pages_to_free_pages(heap_eden);
5484  gc_report(1, objspace, "gc_marks_finish: pooled pages are exists. retry.\n");
5485  return FALSE; /* continue marking phase */
5486  }
5487 
5488  if (RGENGC_CHECK_MODE && is_mark_stack_empty(&objspace->mark_stack) == 0) {
5489  rb_bug("gc_marks_finish: mark stack is not empty (%d).", (int)mark_stack_size(&objspace->mark_stack));
5490  }
5491 
5492  gc_mark_roots(objspace, 0);
5493 
5494  if (is_mark_stack_empty(&objspace->mark_stack) == FALSE) {
5495  gc_report(1, objspace, "gc_marks_finish: not empty (%d). retry.\n", (int)mark_stack_size(&objspace->mark_stack));
5496  return FALSE;
5497  }
5498 
5499 #if RGENGC_CHECK_MODE >= 2
5500  if (gc_verify_heap_pages(objspace) != 0) {
5501  rb_bug("gc_marks_finish (incremental): there are remembered old objects.");
5502  }
5503 #endif
5504 
5506  /* check children of all marked wb-unprotected objects */
5507  gc_marks_wb_unprotected_objects(objspace);
5508  }
5509 #endif /* GC_ENABLE_INCREMENTAL_MARK */
5510 
5511 #if RGENGC_CHECK_MODE >= 2
5512  gc_verify_internal_consistency(Qnil);
5513 #endif
5514 
5515 #if USE_RGENGC
5516  if (is_full_marking(objspace)) {
5517  /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
5518  const double r = gc_params.oldobject_limit_factor;
5520  objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
5521  }
5522 #endif
5523 
5524 #if RGENGC_CHECK_MODE >= 4
5525  gc_marks_check(objspace, gc_check_after_marks_i, "after_marks");
5526 #endif
5527 
5528  {
5529  /* decide full GC is needed or not */
5530  rb_heap_t *heap = heap_eden;
5531  size_t total_slots = heap_allocatable_pages * HEAP_PAGE_OBJ_LIMIT + heap->total_slots;
5532  size_t sweep_slots = total_slots - objspace->marked_slots; /* will be swept slots */
5533  size_t max_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_max_ratio);
5534  size_t min_free_slots = (size_t)(total_slots * gc_params.heap_free_slots_min_ratio);
5535  int full_marking = is_full_marking(objspace);
5536 
5537  GC_ASSERT(heap->total_slots >= objspace->marked_slots);
5538 
5539  /* setup free-able page counts */
5540  if (max_free_slots < gc_params.heap_init_slots) max_free_slots = gc_params.heap_init_slots;
5541 
5542  if (sweep_slots > max_free_slots) {
5543  heap_pages_freeable_pages = (sweep_slots - max_free_slots) / HEAP_PAGE_OBJ_LIMIT;
5544  }
5545  else {
5547  }
5548 
5549  /* check free_min */
5550  if (min_free_slots < gc_params.heap_free_slots) min_free_slots = gc_params.heap_free_slots;
5551 
5552 #if USE_RGENGC
5553  if (sweep_slots < min_free_slots) {
5554  if (!full_marking) {
5555  if (objspace->profile.count - objspace->rgengc.last_major_gc < RVALUE_OLD_AGE) {
5556  full_marking = TRUE;
5557  /* do not update last_major_gc, because full marking is not done. */
5558  goto increment;
5559  }
5560  else {
5561  gc_report(1, objspace, "gc_marks_finish: next is full GC!!)\n");
5563  }
5564  }
5565  else {
5566  increment:
5567  gc_report(1, objspace, "gc_marks_finish: heap_set_increment!!\n");
5568  heap_set_increment(objspace, heap_extend_pages(objspace, sweep_slots, total_slots));
5569  heap_increment(objspace, heap);
5570  }
5571  }
5572 
5573  if (full_marking) {
5574  /* See the comment about RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR */
5575  const double r = gc_params.oldobject_limit_factor;
5577  objspace->rgengc.old_objects_limit = (size_t)(objspace->rgengc.old_objects * r);
5578  }
5579 
5582  }
5583  if (objspace->rgengc.old_objects > objspace->rgengc.old_objects_limit) {
5585  }
5586  if (RGENGC_FORCE_MAJOR_GC) {
5588  }
5589 
5590  gc_report(1, objspace, "gc_marks_finish (marks %d objects, old %d objects, total %d slots, sweep %d slots, increment: %d, next GC: %s)\n",
5591  (int)objspace->marked_slots, (int)objspace->rgengc.old_objects, (int)heap->total_slots, (int)sweep_slots, (int)heap_allocatable_pages,
5592  objspace->rgengc.need_major_gc ? "major" : "minor");
5593 #else /* USE_RGENGC */
5594  if (sweep_slots < min_free_slots) {
5595  gc_report(1, objspace, "gc_marks_finish: heap_set_increment!!\n");
5596  heap_set_increment(objspace, heap_extend_pages(objspace, sweep_slot, total_slot));
5597  heap_increment(objspace, heap);
5598  }
5599 #endif
5600  }
5601 
5603 
5604  return TRUE;
5605 }
5606 
5607 #if GC_ENABLE_INCREMENTAL_MARK
5608 static void
5609 gc_marks_step(rb_objspace_t *objspace, int slots)
5610 {
5611  GC_ASSERT(is_marking(objspace));
5612 
5613  if (gc_mark_stacked_objects_incremental(objspace, slots)) {
5614  if (gc_marks_finish(objspace)) {
5615  /* finish */
5616  gc_sweep(objspace);
5617  }
5618  }
5619  if (0) fprintf(stderr, "objspace->marked_slots: %d\n", (int)objspace->marked_slots);
5620 }
5621 #endif
5622 
5623 static void
5624 gc_marks_rest(rb_objspace_t *objspace)
5625 {
5626  gc_report(1, objspace, "gc_marks_rest\n");
5627 
5628 #if GC_ENABLE_INCREMENTAL_MARK
5629  heap_eden->pooled_pages = NULL;
5630 #endif
5631 
5632  if (is_incremental_marking(objspace)) {
5633  do {
5634  while (gc_mark_stacked_objects_incremental(objspace, INT_MAX) == FALSE);
5635  } while (gc_marks_finish(objspace) == FALSE);
5636  }
5637  else {
5638  gc_mark_stacked_objects_all(objspace);
5639  gc_marks_finish(objspace);
5640  }
5641 
5642  /* move to sweep */
5643  gc_sweep(objspace);
5644 }
5645 
5646 #if GC_ENABLE_INCREMENTAL_MARK
5647 static void
5648 gc_marks_continue(rb_objspace_t *objspace, rb_heap_t *heap)
5649 {
5650  int slots = 0;
5651  const char *from;
5652 
5653  GC_ASSERT(dont_gc == FALSE);
5654 
5655  gc_enter(objspace, "marks_continue");
5656 
5658  {
5659  if (heap->pooled_pages) {
5660  while (heap->pooled_pages && slots < HEAP_PAGE_OBJ_LIMIT) {
5661  struct heap_page *page = heap_move_pooled_pages_to_free_pages(heap);
5662  slots += page->free_slots;
5663  }
5664  from = "pooled-pages";
5665  }
5666  else if (heap_increment(objspace, heap)) {
5667  slots = heap->free_pages->free_slots;
5668  from = "incremented-pages";
5669  }
5670 
5671  if (slots > 0) {
5672  gc_report(2, objspace, "gc_marks_continue: provide %d slots from %s.\n", slots, from);
5673  gc_marks_step(objspace, (int)objspace->rincgc.step_slots);
5674  }
5675  else {
5676  gc_report(2, objspace, "gc_marks_continue: no more pooled pages (stack depth: %d).\n", (int)mark_stack_size(&objspace->mark_stack));
5677  gc_marks_rest(objspace);
5678  }
5679  }
5681 
5682  gc_exit(objspace, "marks_continue");
5683 }
5684 #endif
5685 
5686 static void
5687 gc_marks(rb_objspace_t *objspace, int full_mark)
5688 {
5689  gc_prof_mark_timer_start(objspace);
5690 
5692  {
5693  /* setup marking */
5694 
5695 #if USE_RGENGC
5696  gc_marks_start(objspace, full_mark);
5697  if (!is_incremental_marking(objspace)) {
5698  gc_marks_rest(objspace);
5699  }
5700 
5701 #if RGENGC_PROFILE > 0
5702  if (gc_prof_record(objspace)) {
5703  gc_profile_record *record = gc_prof_record(objspace);
5704  record->old_objects = objspace->rgengc.old_objects;
5705  }
5706 #endif
5707 
5708 #else /* USE_RGENGC */
5709  gc_marks_start(objspace, TRUE);
5710  gc_marks_rest(objspace);
5711 #endif
5712  }
5714  gc_prof_mark_timer_stop(objspace);
5715 }
5716 
5717 /* RGENGC */
5718 
5719 static void
5720 gc_report_body(int level, rb_objspace_t *objspace, const char *fmt, ...)
5721 {
5722  if (level <= RGENGC_DEBUG) {
5723  char buf[1024];
5724  FILE *out = stderr;
5725  va_list args;
5726  const char *status = " ";
5727 
5728 #if USE_RGENGC
5729  if (during_gc) {
5730  status = is_full_marking(objspace) ? "+" : "-";
5731  }
5732  else {
5733  if (is_lazy_sweeping(heap_eden)) {
5734  status = "S";
5735  }
5736  if (is_incremental_marking(objspace)) {
5737  status = "M";
5738  }
5739  }
5740 #endif
5741 
5742  va_start(args, fmt);
5743  vsnprintf(buf, 1024, fmt, args);
5744  va_end(args);
5745 
5746  fprintf(out, "%s|", status);
5747  fputs(buf, out);
5748  }
5749 }
5750 
5751 #if USE_RGENGC
5752 
5753 /* bit operations */
5754 
5755 static int
5756 rgengc_remembersetbits_get(rb_objspace_t *objspace, VALUE obj)
5757 {
5758  return RVALUE_REMEMBERED(obj);
5759 }
5760 
5761 static int
5762 rgengc_remembersetbits_set(rb_objspace_t *objspace, VALUE obj)
5763 {
5764  struct heap_page *page = GET_HEAP_PAGE(obj);
5765  bits_t *bits = &page->marking_bits[0];
5766 
5767  GC_ASSERT(!is_incremental_marking(objspace));
5768 
5769  if (MARKED_IN_BITMAP(bits, obj)) {
5770  return FALSE;
5771  }
5772  else {
5774  MARK_IN_BITMAP(bits, obj);
5775  return TRUE;
5776  }
5777 }
5778 
5779 /* wb, etc */
5780 
5781 /* return FALSE if already remembered */
5782 static int
5783 rgengc_remember(rb_objspace_t *objspace, VALUE obj)
5784 {
5785  gc_report(6, objspace, "rgengc_remember: %s %s\n", obj_info(obj),
5786  rgengc_remembersetbits_get(objspace, obj) ? "was already remembered" : "is remembered now");
5787 
5788  check_rvalue_consistency(obj);
5789 
5790  if (RGENGC_CHECK_MODE) {
5791  if (RVALUE_WB_UNPROTECTED(obj)) rb_bug("rgengc_remember: %s is not wb protected.", obj_info(obj));
5792  }
5793 
5794 #if RGENGC_PROFILE > 0
5795  if (!rgengc_remembered(objspace, obj)) {
5796  if (RVALUE_WB_UNPROTECTED(obj) == 0) {
5797  objspace->profile.total_remembered_normal_object_count++;
5798 #if RGENGC_PROFILE >= 2
5799  objspace->profile.remembered_normal_object_count_types[BUILTIN_TYPE(obj)]++;
5800 #endif
5801  }
5802  }
5803 #endif /* RGENGC_PROFILE > 0 */
5804 
5805  return rgengc_remembersetbits_set(objspace, obj);
5806 }
5807 
5808 static int
5809 rgengc_remembered(rb_objspace_t *objspace, VALUE obj)
5810 {
5811  int result = rgengc_remembersetbits_get(objspace, obj);
5812  check_rvalue_consistency(obj);
5813  gc_report(6, objspace, "rgengc_remembered: %s\n", obj_info(obj));
5814  return result;
5815 }
5816 
5817 #ifndef PROFILE_REMEMBERSET_MARK
5818 #define PROFILE_REMEMBERSET_MARK 0
5819 #endif
5820 
5821 static void
5822 rgengc_rememberset_mark(rb_objspace_t *objspace, rb_heap_t *heap)
5823 {
5824  size_t j;
5825  struct heap_page *page = heap->pages;
5826 #if PROFILE_REMEMBERSET_MARK
5827  int has_old = 0, has_shady = 0, has_both = 0, skip = 0;
5828 #endif
5829  gc_report(1, objspace, "rgengc_rememberset_mark: start\n");
5830 
5831  while (page) {
5833  RVALUE *p = page->start;
5834  RVALUE *offset = p - NUM_IN_PAGE(p);
5835  bits_t bitset, bits[HEAP_PAGE_BITMAP_LIMIT];
5836  bits_t *marking_bits = page->marking_bits;
5839 #if PROFILE_REMEMBERSET_MARK
5840  if (page->flags.has_remembered_objects && page->flags.has_uncollectible_shady_objects) has_both++;
5841  else if (page->flags.has_remembered_objects) has_old++;
5842  else if (page->flags.has_uncollectible_shady_objects) has_shady++;
5843 #endif
5844  for (j=0; j<HEAP_PAGE_BITMAP_LIMIT; j++) {
5845  bits[j] = marking_bits[j] | (uncollectible_bits[j] & wb_unprotected_bits[j]);
5846  marking_bits[j] = 0;
5847  }
5849 
5850  for (j=0; j < HEAP_PAGE_BITMAP_LIMIT; j++) {
5851  bitset = bits[j];
5852 
5853  if (bitset) {
5854  p = offset + j * BITS_BITLENGTH;
5855 
5856  do {
5857  if (bitset & 1) {
5858  VALUE obj = (VALUE)p;
5859  gc_report(2, objspace, "rgengc_rememberset_mark: mark %s\n", obj_info(obj));
5860  GC_ASSERT(RVALUE_UNCOLLECTIBLE(obj));
5861  GC_ASSERT(RVALUE_OLD_P(obj) || RVALUE_WB_UNPROTECTED(obj));
5862 
5863  gc_mark_children(objspace, obj);
5864  }
5865  p++;
5866  bitset >>= 1;
5867  } while (bitset);
5868  }
5869  }
5870  }
5871 #if PROFILE_REMEMBERSET_MARK
5872  else {
5873  skip++;
5874  }
5875 #endif
5876 
5877  page = page->next;
5878  }
5879 
5880 #if PROFILE_REMEMBERSET_MARK
5881  fprintf(stderr, "%d\t%d\t%d\t%d\n", has_both, has_old, has_shady, skip);
5882 #endif
5883  gc_report(1, objspace, "rgengc_rememberset_mark: finished\n");
5884 }
5885 
5886 static void
5887 rgengc_mark_and_rememberset_clear(rb_objspace_t *objspace, rb_heap_t *heap)
5888 {
5889  struct heap_page *page = heap->pages;
5890 
5891  while (page) {
5892  memset(&page->mark_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5893  memset(&page->marking_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5894  memset(&page->uncollectible_bits[0], 0, HEAP_PAGE_BITMAP_SIZE);
5897  page = page->next;
5898  }
5899 }
5900 
5901 /* RGENGC: APIs */
5902 
5903 NOINLINE(static void gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace));
5904 
5905 static void
5906 gc_writebarrier_generational(VALUE a, VALUE b, rb_objspace_t *objspace)
5907 {
5908  if (RGENGC_CHECK_MODE) {
5909  if (!RVALUE_OLD_P(a)) rb_bug("gc_writebarrier_generational: %s is not an old object.", obj_info(a));
5910  if ( RVALUE_OLD_P(b)) rb_bug("gc_writebarrier_generational: %s is an old object.", obj_info(b));
5911  if (is_incremental_marking(objspace)) rb_bug("gc_writebarrier_generational: called while incremental marking: %s -> %s", obj_info(a), obj_info(b));
5912  }
5913 
5914 #if 1
5915  /* mark `a' and remember (default behavior) */
5916  if (!rgengc_remembered(objspace, a)) {
5917  rgengc_remember(objspace, a);
5918  gc_report(1, objspace, "gc_writebarrier_generational: %s (remembered) -> %s\n", obj_info(a), obj_info(b));
5919  }
5920 #else
5921  /* mark `b' and remember */
5923  if (RVALUE_WB_UNPROTECTED(b)) {
5924  gc_remember_unprotected(objspace, b);
5925  }
5926  else {
5927  RVALUE_AGE_SET_OLD(objspace, b);
5928  rgengc_remember(objspace, b);
5929  }
5930 
5931  gc_report(1, objspace, "gc_writebarrier_generational: %s -> %s (remembered)\n", obj_info(a), obj_info(b));
5932 #endif
5933 
5934  check_rvalue_consistency(a);
5935  check_rvalue_consistency(b);
5936 }
5937 
5938 #if GC_ENABLE_INCREMENTAL_MARK
5939 static void
5940 gc_mark_from(rb_objspace_t *objspace, VALUE obj, VALUE parent)
5941 {
5942  gc_mark_set_parent(objspace, parent);
5943  rgengc_check_relation(objspace, obj);
5944  if (gc_mark_set(objspace, obj) == FALSE) return;
5945  gc_aging(objspace, obj);
5946  gc_grey(objspace, obj);
5947 }
5948 
5949 NOINLINE(static void gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace));
5950 
5951 static void
5952 gc_writebarrier_incremental(VALUE a, VALUE b, rb_objspace_t *objspace)
5953 {
5954  gc_report(2, objspace, "gc_writebarrier_incremental: [LG] %s -> %s\n", obj_info(a), obj_info(b));
5955 
5956  if (RVALUE_BLACK_P(a)) {
5957  if (RVALUE_WHITE_P(b)) {
5958  if (!RVALUE_WB_UNPROTECTED(a)) {
5959  gc_report(2, objspace, "gc_writebarrier_incremental: [IN] %s -> %s\n", obj_info(a), obj_info(b));
5960  gc_mark_from(objspace, b, a);
5961  }
5962  }
5963  else if (RVALUE_OLD_P(a) && !RVALUE_OLD_P(b)) {
5964  if (!RVALUE_WB_UNPROTECTED(b)) {
5965  gc_report(1, objspace, "gc_writebarrier_incremental: [GN] %s -> %s\n", obj_info(a), obj_info(b));
5966  RVALUE_AGE_SET_OLD(objspace, b);
5967 
5968  if (RVALUE_BLACK_P(b)) {
5969  gc_grey(objspace, b);
5970  }
5971  }
5972  else {
5973  gc_report(1, objspace, "gc_writebarrier_incremental: [LL] %s -> %s\n", obj_info(a), obj_info(b));
5974  gc_remember_unprotected(objspace, b);
5975  }
5976  }
5977  }
5978 }
5979 #else
5980 #define gc_writebarrier_incremental(a, b, objspace)
5981 #endif
5982 
5983 void
5985 {
5986  rb_objspace_t *objspace = &rb_objspace;
5987 
5988  if (RGENGC_CHECK_MODE && SPECIAL_CONST_P(a)) rb_bug("rb_gc_writebarrier: a is special const");
5989  if (RGENGC_CHECK_MODE && SPECIAL_CONST_P(b)) rb_bug("rb_gc_writebarrier: b is special const");
5990 
5991  if (!is_incremental_marking(objspace)) {
5992  if (!RVALUE_OLD_P(a) || RVALUE_OLD_P(b)) {
5993  return;
5994  }
5995  else {
5996  gc_writebarrier_generational(a, b, objspace);
5997  }
5998  }
5999  else { /* slow path */
6000  gc_writebarrier_incremental(a, b, objspace);
6001  }
6002 }
6003 
6004 void
6006 {
6007  if (RVALUE_WB_UNPROTECTED(obj)) {
6008  return;
6009  }
6010  else {
6011  rb_objspace_t *objspace = &rb_objspace;
6012 
6013  gc_report(2, objspace, "rb_gc_writebarrier_unprotect: %s %s\n", obj_info(obj),
6014  rgengc_remembered(objspace, obj) ? " (already remembered)" : "");
6015 
6016  if (RVALUE_OLD_P(obj)) {
6017  gc_report(1, objspace, "rb_gc_writebarrier_unprotect: %s\n", obj_info(obj));
6018  RVALUE_DEMOTE(objspace, obj);
6019  gc_mark_set(objspace, obj);
6020  gc_remember_unprotected(objspace, obj);
6021 
6022 #if RGENGC_PROFILE
6023  objspace->profile.total_shade_operation_count++;
6024 #if RGENGC_PROFILE >= 2
6025  objspace->profile.shade_operation_count_types[BUILTIN_TYPE(obj)]++;
6026 #endif /* RGENGC_PROFILE >= 2 */
6027 #endif /* RGENGC_PROFILE */
6028  }
6029  else {
6030  RVALUE_AGE_RESET(obj);
6031  }
6032 
6034  }
6035 }
6036 
6037 /*
6038  * remember `obj' if needed.
6039  */
6040 void
6042 {
6043  rb_objspace_t *objspace = &rb_objspace;
6044 
6045  gc_report(1, objspace, "rb_gc_writebarrier_remember: %s\n", obj_info(obj));
6046 
6047  if (is_incremental_marking(objspace)) {
6048  if (RVALUE_BLACK_P(obj)) {
6049  gc_grey(objspace, obj);
6050  }
6051  }
6052  else {
6053  if (RVALUE_OLD_P(obj)) {
6054  rgengc_remember(objspace, obj);
6055  }
6056  }
6057 }
6058 
6059 static st_table *rgengc_unprotect_logging_table;
6060 
6061 static int
6062 rgengc_unprotect_logging_exit_func_i(st_data_t key, st_data_t val, st_data_t arg)
6063 {
6064  fprintf(stderr, "%s\t%d\n", (char *)key, (int)val);
6065  return ST_CONTINUE;
6066 }
6067 
6068 static void
6069 rgengc_unprotect_logging_exit_func(void)
6070 {
6071  st_foreach(rgengc_unprotect_logging_table, rgengc_unprotect_logging_exit_func_i, 0);
6072 }
6073 
6074 void
6075 rb_gc_unprotect_logging(void *objptr, const char *filename, int line)
6076 {
6077  VALUE obj = (VALUE)objptr;
6078 
6079  if (rgengc_unprotect_logging_table == 0) {
6080  rgengc_unprotect_logging_table = st_init_strtable();
6081  atexit(rgengc_unprotect_logging_exit_func);
6082  }
6083 
6084  if (RVALUE_WB_UNPROTECTED(obj) == 0) {
6085  char buff[0x100];
6086  st_data_t cnt = 1;
6087  char *ptr = buff;
6088 
6089  snprintf(ptr, 0x100 - 1, "%s|%s:%d", obj_info(obj), filename, line);
6090 
6091  if (st_lookup(rgengc_unprotect_logging_table, (st_data_t)ptr, &cnt)) {
6092  cnt++;
6093  }
6094  else {
6095  ptr = (strdup)(buff);
6096  if (!ptr) rb_memerror();
6097  }
6098  st_insert(rgengc_unprotect_logging_table, (st_data_t)ptr, cnt);
6099  }
6100 }
6101 #endif /* USE_RGENGC */
6102 
6103 void
6105 {
6106 #if USE_RGENGC
6107  rb_objspace_t *objspace = &rb_objspace;
6108 
6109  if (RVALUE_WB_UNPROTECTED(obj) && !RVALUE_WB_UNPROTECTED(dest)) {
6110  if (!RVALUE_OLD_P(dest)) {
6112  RVALUE_AGE_RESET_RAW(dest);
6113  }
6114  else {
6115  RVALUE_DEMOTE(objspace, dest);
6116  }
6117  }
6118 
6119  check_rvalue_consistency(dest);
6120 #endif
6121 }
6122 
6123 /* RGENGC analysis information */
6124 
6125 VALUE
6127 {
6128 #if USE_RGENGC
6129  return RVALUE_WB_UNPROTECTED(obj) ? Qfalse : Qtrue;
6130 #else
6131  return Qfalse;
6132 #endif
6133 }
6134 
6135 VALUE
6137 {
6138  return OBJ_PROMOTED(obj) ? Qtrue : Qfalse;
6139 }
6140 
6141 size_t
6142 rb_obj_gc_flags(VALUE obj, ID* flags, size_t max)
6143 {
6144  size_t n = 0;
6145  static ID ID_marked;
6146 #if USE_RGENGC
6147  static ID ID_wb_protected, ID_old, ID_marking, ID_uncollectible;
6148 #endif
6149 
6150  if (!ID_marked) {
6151 #define I(s) ID_##s = rb_intern(#s);
6152  I(marked);
6153 #if USE_RGENGC
6154  I(wb_protected);
6155  I(old);
6156  I(marking);
6157  I(uncollectible);
6158 #endif
6159 #undef I
6160  }
6161 
6162 #if USE_RGENGC
6163  if (RVALUE_WB_UNPROTECTED(obj) == 0 && n<max) flags[n++] = ID_wb_protected;
6164  if (RVALUE_OLD_P(obj) && n<max) flags[n++] = ID_old;
6165  if (RVALUE_UNCOLLECTIBLE(obj) && n<max) flags[n++] = ID_uncollectible;
6166  if (MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj) && n<max) flags[n++] = ID_marking;
6167 #endif
6168  if (MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj) && n<max) flags[n++] = ID_marked;
6169  return n;
6170 }
6171 
6172 /* GC */
6173 
6174 void
6176 {
6177  rb_objspace_t *objspace = &rb_objspace;
6178 
6179 #if USE_RGENGC
6180  int is_old = RVALUE_OLD_P(obj);
6181 
6182  gc_report(2, objspace, "rb_gc_force_recycle: %s\n", obj_info(obj));
6183 
6184  if (is_old) {
6185  if (RVALUE_MARKED(obj)) {
6186  objspace->rgengc.old_objects--;
6187  }
6188  }
6191 
6192 #if GC_ENABLE_INCREMENTAL_MARK
6193  if (is_incremental_marking(objspace)) {
6194  if (MARKED_IN_BITMAP(GET_HEAP_MARKING_BITS(obj), obj)) {
6195  invalidate_mark_stack(&objspace->mark_stack, obj);
6197  }
6199  }
6200  else {
6201 #endif
6202  if (is_old || !GET_HEAP_PAGE(obj)->flags.before_sweep) {
6204  }
6206 #if GC_ENABLE_INCREMENTAL_MARK
6207  }
6208 #endif
6209 #endif
6210 
6211  objspace->profile.total_freed_objects++;
6212 
6213  heap_page_add_freeobj(objspace, GET_HEAP_PAGE(obj), obj);
6214 
6215  /* Disable counting swept_slots because there are no meaning.
6216  * if (!MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(p), p)) {
6217  * objspace->heap.swept_slots++;
6218  * }
6219  */
6220 }
6221 
6222 #ifndef MARK_OBJECT_ARY_BUCKET_SIZE
6223 #define MARK_OBJECT_ARY_BUCKET_SIZE 1024
6224 #endif
6225 
6226 void
6228 {
6229  VALUE ary_ary = GET_THREAD()->vm->mark_object_ary;
6230  VALUE ary = rb_ary_last(0, 0, ary_ary);
6231 
6232  if (ary == Qnil || RARRAY_LEN(ary) >= MARK_OBJECT_ARY_BUCKET_SIZE) {
6234  rb_ary_push(ary_ary, ary);
6235  }
6236 
6237  rb_ary_push(ary, obj);
6238 }
6239 
6240 void
6242 {
6243  rb_objspace_t *objspace = &rb_objspace;
6244  struct gc_list *tmp;
6245 
6246  tmp = ALLOC(struct gc_list);
6247  tmp->next = global_list;
6248  tmp->varptr = addr;
6249  global_list = tmp;
6250 }
6251 
6252 void
6254 {
6255  rb_objspace_t *objspace = &rb_objspace;
6256  struct gc_list *tmp = global_list;
6257 
6258  if (tmp->varptr == addr) {
6259  global_list = tmp->next;
6260  xfree(tmp);
6261  return;
6262  }
6263  while (tmp->next) {
6264  if (tmp->next->varptr == addr) {
6265  struct gc_list *t = tmp->next;
6266 
6267  tmp->next = tmp->next->next;
6268  xfree(t);
6269  break;
6270  }
6271  tmp = tmp->next;
6272  }
6273 }
6274 
6275 void
6277 {
6279 }
6280 
6281 #define GC_NOTIFY 0
6282 
6283 enum {
6288 };
6289 
6290 #define gc_stress_full_mark_after_malloc_p() \
6291  (FIXNUM_P(ruby_gc_stress_mode) && (FIX2LONG(ruby_gc_stress_mode) & (1<<gc_stress_full_mark_after_malloc)))
6292 
6293 static void
6294 heap_ready_to_gc(rb_objspace_t *objspace, rb_heap_t *heap)
6295 {
6296  if (!heap->freelist && !heap->free_pages) {
6297  if (!heap_increment(objspace, heap)) {
6298  heap_set_increment(objspace, 1);
6299  heap_increment(objspace, heap);
6300  }
6301  }
6302 }
6303 
6304 static int
6305 ready_to_gc(rb_objspace_t *objspace)
6306 {
6307  if (dont_gc || during_gc || ruby_disable_gc) {
6308  heap_ready_to_gc(objspace, heap_eden);
6309  return FALSE;
6310  }
6311  else {
6312  return TRUE;
6313  }
6314 }
6315 
6316 static void
6317 gc_reset_malloc_info(rb_objspace_t *objspace)
6318 {
6319  gc_prof_set_malloc_info(objspace);
6320  {
6321  size_t inc = ATOMIC_SIZE_EXCHANGE(malloc_increase, 0);
6322  size_t old_limit = malloc_limit;
6323 
6324  if (inc > malloc_limit) {
6325  malloc_limit = (size_t)(inc * gc_params.malloc_limit_growth_factor);
6326  if (gc_params.malloc_limit_max > 0 && /* ignore max-check if 0 */
6327  malloc_limit > gc_params.malloc_limit_max) {
6328  malloc_limit = gc_params.malloc_limit_max;
6329  }
6330  }
6331  else {
6332  malloc_limit = (size_t)(malloc_limit * 0.98); /* magic number */
6333  if (malloc_limit < gc_params.malloc_limit_min) {
6334  malloc_limit = gc_params.malloc_limit_min;
6335  }
6336  }
6337 
6338  if (0) {
6339  if (old_limit != malloc_limit) {
6340  fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: %"PRIuSIZE" -> %"PRIuSIZE"\n",
6341  rb_gc_count(), old_limit, malloc_limit);
6342  }
6343  else {
6344  fprintf(stderr, "[%"PRIuSIZE"] malloc_limit: not changed (%"PRIuSIZE")\n",
6346  }
6347  }
6348  }
6349 
6350  /* reset oldmalloc info */
6351 #if RGENGC_ESTIMATE_OLDMALLOC
6352  if (!is_full_marking(objspace)) {
6353  if (objspace->rgengc.oldmalloc_increase > objspace->rgengc.oldmalloc_increase_limit) {
6355  objspace->rgengc.oldmalloc_increase_limit =
6356  (size_t)(objspace->rgengc.oldmalloc_increase_limit * gc_params.oldmalloc_limit_growth_factor);
6357 
6358  if (objspace->rgengc.oldmalloc_increase_limit > gc_params.oldmalloc_limit_max) {
6359  objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_max;
6360  }
6361  }
6362 
6363  if (0) fprintf(stderr, "%d\t%d\t%u\t%u\t%d\n",
6364  (int)rb_gc_count(),
6365  (int)objspace->rgengc.need_major_gc,
6366  (unsigned int)objspace->rgengc.oldmalloc_increase,
6367  (unsigned int)objspace->rgengc.oldmalloc_increase_limit,
6368  (unsigned int)gc_params.oldmalloc_limit_max);
6369  }
6370  else {
6371  /* major GC */
6372  objspace->rgengc.oldmalloc_increase = 0;
6373 
6374  if ((objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_BY_OLDMALLOC) == 0) {
6375  objspace->rgengc.oldmalloc_increase_limit =
6376  (size_t)(objspace->rgengc.oldmalloc_increase_limit / ((gc_params.oldmalloc_limit_growth_factor - 1)/10 + 1));
6377  if (objspace->rgengc.oldmalloc_increase_limit < gc_params.oldmalloc_limit_min) {
6378  objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
6379  }
6380  }
6381  }
6382 #endif
6383 }
6384 
6385 static int
6386 garbage_collect(rb_objspace_t *objspace, int full_mark, int immediate_mark, int immediate_sweep, int reason)
6387 {
6388 #if GC_PROFILE_MORE_DETAIL
6389  objspace->profile.prepare_time = getrusage_time();
6390 #endif
6391 
6392  gc_rest(objspace);
6393 
6394 #if GC_PROFILE_MORE_DETAIL
6395  objspace->profile.prepare_time = getrusage_time() - objspace->profile.prepare_time;
6396 #endif
6397 
6398  return gc_start(objspace, full_mark, immediate_mark, immediate_sweep, reason);
6399 }
6400 
6401 static int
6402 gc_start(rb_objspace_t *objspace, const int full_mark, const int immediate_mark, const unsigned int immediate_sweep, int reason)
6403 {
6404  int do_full_mark = full_mark;
6405  objspace->flags.immediate_sweep = immediate_sweep;
6406 
6407  if (!heap_allocated_pages) return FALSE; /* heap is not ready */
6408  if (reason != GPR_FLAG_METHOD && !ready_to_gc(objspace)) return TRUE; /* GC is not allowed */
6409 
6410  GC_ASSERT(gc_mode(objspace) == gc_mode_none);
6412  GC_ASSERT(!is_incremental_marking(objspace));
6413 #if RGENGC_CHECK_MODE >= 2
6414  gc_verify_internal_consistency(Qnil);
6415 #endif
6416 
6417  gc_enter(objspace, "gc_start");
6418 
6419  if (ruby_gc_stressful) {
6421 
6422  if ((flag & (1<<gc_stress_no_major)) == 0) {
6423  do_full_mark = TRUE;
6424  }
6425 
6426  objspace->flags.immediate_sweep = !(flag & (1<<gc_stress_no_immediate_sweep));
6427  }
6428  else {
6429 #if USE_RGENGC
6430  if (objspace->rgengc.need_major_gc) {
6431  reason |= objspace->rgengc.need_major_gc;
6432  do_full_mark = TRUE;
6433  }
6434  else if (RGENGC_FORCE_MAJOR_GC) {
6435  reason = GPR_FLAG_MAJOR_BY_FORCE;
6436  do_full_mark = TRUE;
6437  }
6438 
6439  objspace->rgengc.need_major_gc = GPR_FLAG_NONE;
6440 #endif
6441  }
6442 
6443  if (do_full_mark && (reason & GPR_FLAG_MAJOR_MASK) == 0) {
6444  reason |= GPR_FLAG_MAJOR_BY_FORCE; /* GC by CAPI, METHOD, and so on. */
6445  }
6446 
6447 #if GC_ENABLE_INCREMENTAL_MARK
6448  if (!GC_ENABLE_INCREMENTAL_MARK || objspace->flags.dont_incremental || immediate_mark) {
6450  }
6451  else {
6452  objspace->flags.during_incremental_marking = do_full_mark;
6453  }
6454 #endif
6455 
6456  if (!GC_ENABLE_LAZY_SWEEP || objspace->flags.dont_incremental) {
6457  objspace->flags.immediate_sweep = TRUE;
6458  }
6459 
6460  if (objspace->flags.immediate_sweep) reason |= GPR_FLAG_IMMEDIATE_SWEEP;
6461 
6462  gc_report(1, objspace, "gc_start(%d, %d, %d, reason: %d) => %d, %d, %d\n",
6463  full_mark, immediate_mark, immediate_sweep, reason,
6464  do_full_mark, !is_incremental_marking(objspace), objspace->flags.immediate_sweep);
6465 
6466  objspace->profile.count++;
6467  objspace->profile.latest_gc_info = reason;
6470  gc_prof_setup_new_record(objspace, reason);
6471  gc_reset_malloc_info(objspace);
6472 
6473  gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_START, 0 /* TODO: pass minor/immediate flag? */);
6475 
6476  gc_prof_timer_start(objspace);
6477  {
6478  gc_marks(objspace, do_full_mark);
6479  }
6480  gc_prof_timer_stop(objspace);
6481 
6482  gc_exit(objspace, "gc_start");
6483  return TRUE;
6484 }
6485 
6486 static void
6487 gc_rest(rb_objspace_t *objspace)
6488 {
6489  int marking = is_incremental_marking(objspace);
6490  int sweeping = is_lazy_sweeping(heap_eden);
6491 
6492  if (marking || sweeping) {
6493  gc_enter(objspace, "gc_rest");
6494 
6495  if (RGENGC_CHECK_MODE >= 2) gc_verify_internal_consistency(Qnil);
6496 
6497  if (is_incremental_marking(objspace)) {
6499  gc_marks_rest(objspace);
6501  }
6502  if (is_lazy_sweeping(heap_eden)) {
6503  gc_sweep_rest(objspace);
6504  }
6505  gc_exit(objspace, "gc_rest");
6506  }
6507 }
6508 
6511  int reason;
6515 };
6516 
6517 static void
6518 gc_current_status_fill(rb_objspace_t *objspace, char *buff)
6519 {
6520  int i = 0;
6521  if (is_marking(objspace)) {
6522  buff[i++] = 'M';
6523 #if USE_RGENGC
6524  if (is_full_marking(objspace)) buff[i++] = 'F';
6525 #if GC_ENABLE_INCREMENTAL_MARK
6526  if (is_incremental_marking(objspace)) buff[i++] = 'I';
6527 #endif
6528 #endif
6529  }
6530  else if (is_sweeping(objspace)) {
6531  buff[i++] = 'S';
6532  if (is_lazy_sweeping(heap_eden)) buff[i++] = 'L';
6533  }
6534  else {
6535  buff[i++] = 'N';
6536  }
6537  buff[i] = '\0';
6538 }
6539 
6540 static const char *
6541 gc_current_status(rb_objspace_t *objspace)
6542 {
6543  static char buff[0x10];
6544  gc_current_status_fill(objspace, buff);
6545  return buff;
6546 }
6547 
6548 #if PRINT_ENTER_EXIT_TICK
6549 
6550 static tick_t last_exit_tick;
6551 static tick_t enter_tick;
6552 static int enter_count = 0;
6553 static char last_gc_status[0x10];
6554 
6555 static inline void
6556 gc_record(rb_objspace_t *objspace, int direction, const char *event)
6557 {
6558  if (direction == 0) { /* enter */
6559  enter_count++;
6560  enter_tick = tick();
6561  gc_current_status_fill(objspace, last_gc_status);
6562  }
6563  else { /* exit */
6564  tick_t exit_tick = tick();
6565  char current_gc_status[0x10];
6566  gc_current_status_fill(objspace, current_gc_status);
6567 #if 1
6568  /* [last mutator time] [gc time] [event] */
6569  fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
6570  enter_tick - last_exit_tick,
6571  exit_tick - enter_tick,
6572  event,
6573  last_gc_status, current_gc_status,
6574  (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
6575  last_exit_tick = exit_tick;
6576 #else
6577  /* [enter_tick] [gc time] [event] */
6578  fprintf(stderr, "%"PRItick"\t%"PRItick"\t%s\t[%s->%s|%c]\n",
6579  enter_tick,
6580  exit_tick - enter_tick,
6581  event,
6582  last_gc_status, current_gc_status,
6583  (objspace->profile.latest_gc_info & GPR_FLAG_MAJOR_MASK) ? '+' : '-');
6584 #endif
6585  }
6586 }
6587 #else /* PRINT_ENTER_EXIT_TICK */
6588 static inline void
6589 gc_record(rb_objspace_t *objspace, int direction, const char *event)
6590 {
6591  /* null */
6592 }
6593 #endif /* PRINT_ENTER_EXIT_TICK */
6594 
6595 static inline void
6596 gc_enter(rb_objspace_t *objspace, const char *event)
6597 {
6598  GC_ASSERT(during_gc == 0);
6599  if (RGENGC_CHECK_MODE >= 3) gc_verify_internal_consistency(Qnil);
6600 
6601  during_gc = TRUE;
6602  gc_report(1, objspace, "gc_entr: %s [%s]\n", event, gc_current_status(objspace));
6603  gc_record(objspace, 0, event);
6604  gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_ENTER, 0); /* TODO: which parameter should be passed? */
6605 }
6606 
6607 static inline void
6608 gc_exit(rb_objspace_t *objspace, const char *event)
6609 {
6610  GC_ASSERT(during_gc != 0);
6611 
6612  gc_event_hook(objspace, RUBY_INTERNAL_EVENT_GC_EXIT, 0); /* TODO: which parameter should be passsed? */
6613  gc_record(objspace, 1, event);
6614  gc_report(1, objspace, "gc_exit: %s [%s]\n", event, gc_current_status(objspace));
6615  during_gc = FALSE;
6616 }
6617 
6618 static void *
6619 gc_with_gvl(void *ptr)
6620 {
6621  struct objspace_and_reason *oar = (struct objspace_and_reason *)ptr;
6622  return (void *)(VALUE)garbage_collect(oar->objspace, oar->full_mark, oar->immediate_mark, oar->immediate_sweep, oar->reason);
6623 }
6624 
6625 static int
6626 garbage_collect_with_gvl(rb_objspace_t *objspace, int full_mark, int immediate_mark, int immediate_sweep, int reason)
6627 {
6628  if (dont_gc) return TRUE;
6629  if (ruby_thread_has_gvl_p()) {
6630  return garbage_collect(objspace, full_mark, immediate_mark, immediate_sweep, reason);
6631  }
6632  else {
6633  if (ruby_native_thread_p()) {
6634  struct objspace_and_reason oar;
6635  oar.objspace = objspace;
6636  oar.reason = reason;
6637  oar.full_mark = full_mark;
6640  return (int)(VALUE)rb_thread_call_with_gvl(gc_with_gvl, (void *)&oar);
6641  }
6642  else {
6643  /* no ruby thread */
6644  fprintf(stderr, "[FATAL] failed to allocate memory\n");
6645  exit(EXIT_FAILURE);
6646  }
6647  }
6648 }
6649 
6650 int
6652 {
6653  return garbage_collect(&rb_objspace, TRUE, TRUE, TRUE, GPR_FLAG_CAPI);
6654 }
6655 
6656 #undef Init_stack
6657 
6658 void
6659 Init_stack(volatile VALUE *addr)
6660 {
6661  ruby_init_stack(addr);
6662 }
6663 
6664 /*
6665  * call-seq:
6666  * GC.start -> nil
6667  * ObjectSpace.garbage_collect -> nil
6668  * include GC; garbage_collect -> nil
6669  * GC.start(full_mark: true, immediate_sweep: true) -> nil
6670  * ObjectSpace.garbage_collect(full_mark: true, immediate_sweep: true) -> nil
6671  * include GC; garbage_collect(full_mark: true, immediate_sweep: true) -> nil
6672  *
6673  * Initiates garbage collection, unless manually disabled.
6674  *
6675  * This method is defined with keyword arguments that default to true:
6676  *
6677  * def GC.start(full_mark: true, immediate_sweep: true); end
6678  *
6679  * Use full_mark: false to perform a minor GC.
6680  * Use immediate_sweep: false to defer sweeping (use lazy sweep).
6681  *
6682  * Note: These keyword arguments are implementation and version dependent. They
6683  * are not guaranteed to be future-compatible, and may be ignored if the
6684  * underlying implementation does not support them.
6685  */
6686 
6687 static VALUE
6688 gc_start_internal(int argc, VALUE *argv, VALUE self)
6689 {
6690  rb_objspace_t *objspace = &rb_objspace;
6691  int full_mark = TRUE, immediate_mark = TRUE, immediate_sweep = TRUE;
6692  VALUE opt = Qnil;
6693  static ID keyword_ids[3];
6694 
6695  rb_scan_args(argc, argv, "0:", &opt);
6696 
6697  if (!NIL_P(opt)) {
6698  VALUE kwvals[3];
6699 
6700  if (!keyword_ids[0]) {
6701  keyword_ids[0] = rb_intern("full_mark");
6702  keyword_ids[1] = rb_intern("immediate_mark");
6703  keyword_ids[2] = rb_intern("immediate_sweep");
6704  }
6705 
6706  rb_get_kwargs(opt, keyword_ids, 0, 3, kwvals);
6707 
6708  if (kwvals[0] != Qundef) full_mark = RTEST(kwvals[0]);
6709  if (kwvals[1] != Qundef) immediate_mark = RTEST(kwvals[1]);
6710  if (kwvals[2] != Qundef) immediate_sweep = RTEST(kwvals[2]);
6711  }
6712 
6713  garbage_collect(objspace, full_mark, immediate_mark, immediate_sweep, GPR_FLAG_METHOD);
6714  gc_finalize_deferred(objspace);
6715 
6716  return Qnil;
6717 }
6718 
6719 VALUE
6721 {
6722  rb_gc();
6723  return Qnil;
6724 }
6725 
6726 void
6727 rb_gc(void)
6728 {
6729  rb_objspace_t *objspace = &rb_objspace;
6730  garbage_collect(objspace, TRUE, TRUE, TRUE, GPR_FLAG_CAPI);
6731  gc_finalize_deferred(objspace);
6732 }
6733 
6734 int
6736 {
6737  rb_objspace_t *objspace = &rb_objspace;
6738  return during_gc;
6739 }
6740 
6741 int
6743 {
6744  rb_objspace_t *objspace = rb_objspace_of(th->vm);
6745  return during_gc;
6746 }
6747 
6748 #if RGENGC_PROFILE >= 2
6749 
6750 static const char *type_name(int type, VALUE obj);
6751 
6752 static void
6753 gc_count_add_each_types(VALUE hash, const char *name, const size_t *types)
6754 {
6756  int i;
6757  for (i=0; i<T_MASK; i++) {
6758  const char *type = type_name(i, 0);
6759  rb_hash_aset(result, ID2SYM(rb_intern(type)), SIZET2NUM(types[i]));
6760  }
6761  rb_hash_aset(hash, ID2SYM(rb_intern(name)), result);
6762 }
6763 #endif
6764 
6765 size_t
6767 {
6768  return rb_objspace.profile.count;
6769 }
6770 
6771 /*
6772  * call-seq:
6773  * GC.count -> Integer
6774  *
6775  * The number of times GC occurred.
6776  *
6777  * It returns the number of times GC occurred since the process started.
6778  *
6779  */
6780 
6781 static VALUE
6782 gc_count(VALUE self)
6783 {
6784  return SIZET2NUM(rb_gc_count());
6785 }
6786 
6787 static VALUE
6788 gc_info_decode(rb_objspace_t *objspace, const VALUE hash_or_key, const int orig_flags)
6789 {
6790  static VALUE sym_major_by = Qnil, sym_gc_by, sym_immediate_sweep, sym_have_finalizer, sym_state;
6791  static VALUE sym_nofree, sym_oldgen, sym_shady, sym_force, sym_stress;
6792 #if RGENGC_ESTIMATE_OLDMALLOC
6793  static VALUE sym_oldmalloc;
6794 #endif
6795  static VALUE sym_newobj, sym_malloc, sym_method, sym_capi;
6796  static VALUE sym_none, sym_marking, sym_sweeping;
6797  VALUE hash = Qnil, key = Qnil;
6798  VALUE major_by;
6799  VALUE flags = orig_flags ? orig_flags : objspace->profile.latest_gc_info;
6800 
6801  if (SYMBOL_P(hash_or_key)) {
6802  key = hash_or_key;
6803  }
6804  else if (RB_TYPE_P(hash_or_key, T_HASH)) {
6805  hash = hash_or_key;
6806  }
6807  else {
6808  rb_raise(rb_eTypeError, "non-hash or symbol given");
6809  }
6810 
6811  if (sym_major_by == Qnil) {
6812 #define S(s) sym_##s = ID2SYM(rb_intern_const(#s))
6813  S(major_by);
6814  S(gc_by);
6815  S(immediate_sweep);
6816  S(have_finalizer);
6817  S(state);
6818 
6819  S(stress);
6820  S(nofree);
6821  S(oldgen);
6822  S(shady);
6823  S(force);
6824 #if RGENGC_ESTIMATE_OLDMALLOC
6825  S(oldmalloc);
6826 #endif
6827  S(newobj);
6828  S(malloc);
6829  S(method);
6830  S(capi);
6831 
6832  S(none);
6833  S(marking);
6834  S(sweeping);
6835 #undef S
6836  }
6837 
6838 #define SET(name, attr) \
6839  if (key == sym_##name) \
6840  return (attr); \
6841  else if (hash != Qnil) \
6842  rb_hash_aset(hash, sym_##name, (attr));
6843 
6844  major_by =
6845  (flags & GPR_FLAG_MAJOR_BY_NOFREE) ? sym_nofree :
6846  (flags & GPR_FLAG_MAJOR_BY_OLDGEN) ? sym_oldgen :
6847  (flags & GPR_FLAG_MAJOR_BY_SHADY) ? sym_shady :
6848  (flags & GPR_FLAG_MAJOR_BY_FORCE) ? sym_force :
6849 #if RGENGC_ESTIMATE_OLDMALLOC
6850  (flags & GPR_FLAG_MAJOR_BY_OLDMALLOC) ? sym_oldmalloc :
6851 #endif
6852  Qnil;
6853  SET(major_by, major_by);
6854 
6855  SET(gc_by,
6856  (flags & GPR_FLAG_NEWOBJ) ? sym_newobj :
6857  (flags & GPR_FLAG_MALLOC) ? sym_malloc :
6858  (flags & GPR_FLAG_METHOD) ? sym_method :
6859  (flags & GPR_FLAG_CAPI) ? sym_capi :
6860  (flags & GPR_FLAG_STRESS) ? sym_stress :
6861  Qnil
6862  );
6863 
6864  SET(have_finalizer, (flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
6865  SET(immediate_sweep, (flags & GPR_FLAG_IMMEDIATE_SWEEP) ? Qtrue : Qfalse);
6866 
6867  if (orig_flags == 0) {
6868  SET(state, gc_mode(objspace) == gc_mode_none ? sym_none :
6869  gc_mode(objspace) == gc_mode_marking ? sym_marking : sym_sweeping);
6870  }
6871 #undef SET
6872 
6873  if (!NIL_P(key)) {/* matched key should return above */
6874  rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key));
6875  }
6876 
6877  return hash;
6878 }
6879 
6880 VALUE
6882 {
6883  rb_objspace_t *objspace = &rb_objspace;
6884  return gc_info_decode(objspace, key, 0);
6885 }
6886 
6887 /*
6888  * call-seq:
6889  * GC.latest_gc_info -> {:gc_by=>:newobj}
6890  * GC.latest_gc_info(hash) -> hash
6891  * GC.latest_gc_info(:major_by) -> :malloc
6892  *
6893  * Returns information about the most recent garbage collection.
6894  */
6895 
6896 static VALUE
6897 gc_latest_gc_info(int argc, VALUE *argv, VALUE self)
6898 {
6899  rb_objspace_t *objspace = &rb_objspace;
6900  VALUE arg = Qnil;
6901 
6902  if (rb_scan_args(argc, argv, "01", &arg) == 1) {
6903  if (!SYMBOL_P(arg) && !RB_TYPE_P(arg, T_HASH)) {
6904  rb_raise(rb_eTypeError, "non-hash or symbol given");
6905  }
6906  }
6907 
6908  if (arg == Qnil) {
6909  arg = rb_hash_new();
6910  }
6911 
6912  return gc_info_decode(objspace, arg, 0);
6913 }
6914 
6933 #if USE_RGENGC
6940 #if RGENGC_ESTIMATE_OLDMALLOC
6943 #endif
6944 #if RGENGC_PROFILE
6945  gc_stat_sym_total_generated_normal_object_count,
6946  gc_stat_sym_total_generated_shady_object_count,
6947  gc_stat_sym_total_shade_operation_count,
6948  gc_stat_sym_total_promoted_count,
6949  gc_stat_sym_total_remembered_normal_object_count,
6950  gc_stat_sym_total_remembered_shady_object_count,
6951 #endif
6952 #endif
6954 };
6955 
6966 #if USE_RGENGC
6971 #endif
6976 #if RGENGC_ESTIMATE_OLDMALLOC
6979 #endif
6981 };
6982 
6983 static VALUE gc_stat_symbols[gc_stat_sym_last];
6984 static VALUE gc_stat_compat_symbols[gc_stat_compat_sym_last];
6985 static VALUE gc_stat_compat_table;
6986 
6987 static void
6988 setup_gc_stat_symbols(void)
6989 {
6990  if (gc_stat_symbols[0] == 0) {
6991 #define S(s) gc_stat_symbols[gc_stat_sym_##s] = ID2SYM(rb_intern_const(#s))
6992  S(count);
6994  S(heap_sorted_length);
6996  S(heap_available_slots);
6997  S(heap_live_slots);
6998  S(heap_free_slots);
6999  S(heap_final_slots);
7000  S(heap_marked_slots);
7001  S(heap_eden_pages);
7002  S(heap_tomb_pages);
7003  S(total_allocated_pages);
7004  S(total_freed_pages);
7005  S(total_allocated_objects);
7006  S(total_freed_objects);
7007  S(malloc_increase_bytes);
7008  S(malloc_increase_bytes_limit);
7009 #if USE_RGENGC
7010  S(minor_gc_count);
7011  S(major_gc_count);
7012  S(remembered_wb_unprotected_objects);
7013  S(remembered_wb_unprotected_objects_limit);
7014  S(old_objects);
7015  S(old_objects_limit);
7016 #if RGENGC_ESTIMATE_OLDMALLOC
7017  S(oldmalloc_increase_bytes);
7018  S(oldmalloc_increase_bytes_limit);
7019 #endif
7020 #if RGENGC_PROFILE
7021  S(total_generated_normal_object_count);
7022  S(total_generated_shady_object_count);
7023  S(total_shade_operation_count);
7024  S(total_promoted_count);
7025  S(total_remembered_normal_object_count);
7026  S(total_remembered_shady_object_count);
7027 #endif /* RGENGC_PROFILE */
7028 #endif /* USE_RGENGC */
7029 #undef S
7030 #define S(s) gc_stat_compat_symbols[gc_stat_compat_sym_##s] = ID2SYM(rb_intern_const(#s))
7031  S(gc_stat_heap_used);
7032  S(heap_eden_page_length);
7033  S(heap_tomb_page_length);
7034  S(heap_increment);
7035  S(heap_length);
7036  S(heap_live_slot);
7037  S(heap_free_slot);
7038  S(heap_final_slot);
7039  S(heap_swept_slot);
7040 #if USE_RGEGC
7041  S(remembered_shady_object);
7042  S(remembered_shady_object_limit);
7043  S(old_object);
7044  S(old_object_limit);
7045 #endif
7046  S(total_allocated_object);
7047  S(total_freed_object);
7048  S(malloc_increase);
7049  S(malloc_limit);
7050 #if RGENGC_ESTIMATE_OLDMALLOC
7051  S(oldmalloc_increase);
7052  S(oldmalloc_limit);
7053 #endif
7054 #undef S
7055 
7056  {
7057  VALUE table = gc_stat_compat_table = rb_hash_new();
7058  rb_obj_hide(table);
7060 
7061  /* compatibility layer for Ruby 2.1 */
7062 #define OLD_SYM(s) gc_stat_compat_symbols[gc_stat_compat_sym_##s]
7063 #define NEW_SYM(s) gc_stat_symbols[gc_stat_sym_##s]
7064  rb_hash_aset(table, OLD_SYM(gc_stat_heap_used), NEW_SYM(heap_allocated_pages));
7065  rb_hash_aset(table, OLD_SYM(heap_eden_page_length), NEW_SYM(heap_eden_pages));
7066  rb_hash_aset(table, OLD_SYM(heap_tomb_page_length), NEW_SYM(heap_tomb_pages));
7067  rb_hash_aset(table, OLD_SYM(heap_increment), NEW_SYM(heap_allocatable_pages));
7068  rb_hash_aset(table, OLD_SYM(heap_length), NEW_SYM(heap_sorted_length));
7069  rb_hash_aset(table, OLD_SYM(heap_live_slot), NEW_SYM(heap_live_slots));
7070  rb_hash_aset(table, OLD_SYM(heap_free_slot), NEW_SYM(heap_free_slots));
7071  rb_hash_aset(table, OLD_SYM(heap_final_slot), NEW_SYM(heap_final_slots));
7072 #if USE_RGEGC
7073  rb_hash_aset(table, OLD_SYM(remembered_shady_object), NEW_SYM(remembered_wb_unprotected_objects));
7074  rb_hash_aset(table, OLD_SYM(remembered_shady_object_limit), NEW_SYM(remembered_wb_unprotected_objects_limit));
7075  rb_hash_aset(table, OLD_SYM(old_object), NEW_SYM(old_objects));
7076  rb_hash_aset(table, OLD_SYM(old_object_limit), NEW_SYM(old_objects_limit));
7077 #endif
7078  rb_hash_aset(table, OLD_SYM(total_allocated_object), NEW_SYM(total_allocated_objects));
7079  rb_hash_aset(table, OLD_SYM(total_freed_object), NEW_SYM(total_freed_objects));
7080  rb_hash_aset(table, OLD_SYM(malloc_increase), NEW_SYM(malloc_increase_bytes));
7081  rb_hash_aset(table, OLD_SYM(malloc_limit), NEW_SYM(malloc_increase_bytes_limit));
7082 #if RGENGC_ESTIMATE_OLDMALLOC
7083  rb_hash_aset(table, OLD_SYM(oldmalloc_increase), NEW_SYM(oldmalloc_increase_bytes));
7084  rb_hash_aset(table, OLD_SYM(oldmalloc_limit), NEW_SYM(oldmalloc_increase_bytes_limit));
7085 #endif
7086 #undef OLD_SYM
7087 #undef NEW_SYM
7088  rb_obj_freeze(table);
7089  }
7090  }
7091 }
7092 
7093 static VALUE
7094 compat_key(VALUE key)
7095 {
7096  VALUE new_key = rb_hash_lookup(gc_stat_compat_table, key);
7097 
7098  if (!NIL_P(new_key)) {
7099  static int warned = 0;
7100  if (warned == 0) {
7101  rb_warn("GC.stat keys were changed from Ruby 2.1. "
7102  "In this case, you refer to obsolete `%"PRIsVALUE"' (new key is `%"PRIsVALUE"'). "
7103  "Please check <https://bugs.ruby-lang.org/issues/9924> for more information.",
7104  key, new_key);
7105  warned = 1;
7106  }
7107  }
7108 
7109  return new_key;
7110 }
7111 
7112 static VALUE
7113 default_proc_for_compat_func(VALUE hash, VALUE dmy, int argc, VALUE *argv)
7114 {
7115  VALUE key, new_key;
7116 
7117  Check_Type(hash, T_HASH);
7118  rb_check_arity(argc, 2, 2);
7119  key = argv[1];
7120 
7121  if ((new_key = compat_key(key)) != Qnil) {
7122  return rb_hash_lookup(hash, new_key);
7123  }
7124 
7125  return Qnil;
7126 }
7127 
7128 static size_t
7129 gc_stat_internal(VALUE hash_or_sym)
7130 {
7131  rb_objspace_t *objspace = &rb_objspace;
7132  VALUE hash = Qnil, key = Qnil;
7133 
7134  setup_gc_stat_symbols();
7135 
7136  if (RB_TYPE_P(hash_or_sym, T_HASH)) {
7137  hash = hash_or_sym;
7138 
7139  if (NIL_P(RHASH_IFNONE(hash))) {
7140  static VALUE default_proc_for_compat = 0;
7141  if (default_proc_for_compat == 0) { /* TODO: it should be */
7142  default_proc_for_compat = rb_proc_new(default_proc_for_compat_func, Qnil);
7143  rb_gc_register_mark_object(default_proc_for_compat);
7144  }
7145  rb_hash_set_default_proc(hash, default_proc_for_compat);
7146  }
7147  }
7148  else if (SYMBOL_P(hash_or_sym)) {
7149  key = hash_or_sym;
7150  }
7151  else {
7152  rb_raise(rb_eTypeError, "non-hash or symbol argument");
7153  }
7154 
7155 #define SET(name, attr) \
7156  if (key == gc_stat_symbols[gc_stat_sym_##name]) \
7157  return attr; \
7158  else if (hash != Qnil) \
7159  rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
7160 
7161  again:
7162  SET(count, objspace->profile.count);
7163 
7164  /* implementation dependent counters */
7166  SET(heap_sorted_length, heap_pages_sorted_length);
7168  SET(heap_available_slots, objspace_available_slots(objspace));
7169  SET(heap_live_slots, objspace_live_slots(objspace));
7170  SET(heap_free_slots, objspace_free_slots(objspace));
7171  SET(heap_final_slots, heap_pages_final_slots);
7172  SET(heap_marked_slots, objspace->marked_slots);
7173  SET(heap_eden_pages, heap_eden->total_pages);
7174  SET(heap_tomb_pages, heap_tomb->total_pages);
7175  SET(total_allocated_pages, objspace->profile.total_allocated_pages);
7176  SET(total_freed_pages, objspace->profile.total_freed_pages);
7177  SET(total_allocated_objects, objspace->total_allocated_objects);
7178  SET(total_freed_objects, objspace->profile.total_freed_objects);
7179  SET(malloc_increase_bytes, malloc_increase);
7180  SET(malloc_increase_bytes_limit, malloc_limit);
7181 #if USE_RGENGC
7182  SET(minor_gc_count, objspace->profile.minor_gc_count);
7183  SET(major_gc_count, objspace->profile.major_gc_count);
7184  SET(remembered_wb_unprotected_objects, objspace->rgengc.uncollectible_wb_unprotected_objects);
7185  SET(remembered_wb_unprotected_objects_limit, objspace->rgengc.uncollectible_wb_unprotected_objects_limit);
7186  SET(old_objects, objspace->rgengc.old_objects);
7187  SET(old_objects_limit, objspace->rgengc.old_objects_limit);
7188 #if RGENGC_ESTIMATE_OLDMALLOC
7189  SET(oldmalloc_increase_bytes, objspace->rgengc.oldmalloc_increase);
7190  SET(oldmalloc_increase_bytes_limit, objspace->rgengc.oldmalloc_increase_limit);
7191 #endif
7192 
7193 #if RGENGC_PROFILE
7194  SET(total_generated_normal_object_count, objspace->profile.total_generated_normal_object_count);
7195  SET(total_generated_shady_object_count, objspace->profile.total_generated_shady_object_count);
7196  SET(total_shade_operation_count, objspace->profile.total_shade_operation_count);
7197  SET(total_promoted_count, objspace->profile.total_promoted_count);
7198  SET(total_remembered_normal_object_count, objspace->profile.total_remembered_normal_object_count);
7199  SET(total_remembered_shady_object_count, objspace->profile.total_remembered_shady_object_count);
7200 #endif /* RGENGC_PROFILE */
7201 #endif /* USE_RGENGC */
7202 #undef SET
7203 
7204  if (!NIL_P(key)) { /* matched key should return above */
7205  VALUE new_key;
7206  if ((new_key = compat_key(key)) != Qnil) {
7207  key = new_key;
7208  goto again;
7209  }
7210  rb_raise(rb_eArgError, "unknown key: %"PRIsVALUE, rb_sym2str(key));
7211  }
7212 
7213 #if defined(RGENGC_PROFILE) && RGENGC_PROFILE >= 2
7214  if (hash != Qnil) {
7215  gc_count_add_each_types(hash, "generated_normal_object_count_types", objspace->profile.generated_normal_object_count_types);
7216  gc_count_add_each_types(hash, "generated_shady_object_count_types", objspace->profile.generated_shady_object_count_types);
7217  gc_count_add_each_types(hash, "shade_operation_count_types", objspace->profile.shade_operation_count_types);
7218  gc_count_add_each_types(hash, "promoted_types", objspace->profile.promoted_types);
7219  gc_count_add_each_types(hash, "remembered_normal_object_count_types", objspace->profile.remembered_normal_object_count_types);
7220  gc_count_add_each_types(hash, "remembered_shady_object_count_types", objspace->profile.remembered_shady_object_count_types);
7221  }
7222 #endif
7223 
7224  return 0;
7225 }
7226 
7227 /*
7228  * call-seq:
7229  * GC.stat -> Hash
7230  * GC.stat(hash) -> hash
7231  * GC.stat(:key) -> Numeric
7232  *
7233  * Returns a Hash containing information about the GC.
7234  *
7235  * The hash includes information about internal statistics about GC such as:
7236  *
7237  * {
7238  * :count=>0,
7239  * :heap_allocated_pages=>24,
7240  * :heap_sorted_length=>24,
7241  * :heap_allocatable_pages=>0,
7242  * :heap_available_slots=>9783,
7243  * :heap_live_slots=>7713,
7244  * :heap_free_slots=>2070,
7245  * :heap_final_slots=>0,
7246  * :heap_marked_slots=>0,
7247  * :heap_eden_pages=>24,
7248  * :heap_tomb_pages=>0,
7249  * :total_allocated_pages=>24,
7250  * :total_freed_pages=>0,
7251  * :total_allocated_objects=>7796,
7252  * :total_freed_objects=>83,
7253  * :malloc_increase_bytes=>2389312,
7254  * :malloc_increase_bytes_limit=>16777216,
7255  * :minor_gc_count=>0,
7256  * :major_gc_count=>0,
7257  * :remembered_wb_unprotected_objects=>0,
7258  * :remembered_wb_unprotected_objects_limit=>0,
7259  * :old_objects=>0,
7260  * :old_objects_limit=>0,
7261  * :oldmalloc_increase_bytes=>2389760,
7262  * :oldmalloc_increase_bytes_limit=>16777216
7263  * }
7264  *
7265  * The contents of the hash are implementation specific and may be changed in
7266  * the future.
7267  *
7268  * This method is only expected to work on C Ruby.
7269  *
7270  */
7271 
7272 static VALUE
7273 gc_stat(int argc, VALUE *argv, VALUE self)
7274 {
7275  VALUE arg = Qnil;
7276 
7277  if (rb_scan_args(argc, argv, "01", &arg) == 1) {
7278  if (SYMBOL_P(arg)) {
7279  size_t value = gc_stat_internal(arg);
7280  return SIZET2NUM(value);
7281  }
7282  else if (!RB_TYPE_P(arg, T_HASH)) {
7283  rb_raise(rb_eTypeError, "non-hash or symbol given");
7284  }
7285  }
7286 
7287  if (arg == Qnil) {
7288  arg = rb_hash_new();
7289  }
7290  gc_stat_internal(arg);
7291  return arg;
7292 }
7293 
7294 size_t
7296 {
7297  if (SYMBOL_P(key)) {
7298  size_t value = gc_stat_internal(key);
7299  return value;
7300  }
7301  else {
7302  gc_stat_internal(key);
7303  return 0;
7304  }
7305 }
7306 
7307 /*
7308  * call-seq:
7309  * GC.stress -> integer, true or false
7310  *
7311  * Returns current status of GC stress mode.
7312  */
7313 
7314 static VALUE
7315 gc_stress_get(VALUE self)
7316 {
7317  rb_objspace_t *objspace = &rb_objspace;
7318  return ruby_gc_stress_mode;
7319 }
7320 
7321 static void
7322 gc_stress_set(rb_objspace_t *objspace, VALUE flag)
7323 {
7324  objspace->flags.gc_stressful = RTEST(flag);
7325  objspace->gc_stress_mode = flag;
7326 }
7327 
7328 /*
7329  * call-seq:
7330  * GC.stress = flag -> flag
7331  *
7332  * Updates the GC stress mode.
7333  *
7334  * When stress mode is enabled, the GC is invoked at every GC opportunity:
7335  * all memory and object allocations.
7336  *
7337  * Enabling stress mode will degrade performance, it is only for debugging.
7338  *
7339  * flag can be true, false, or an integer bit-ORed following flags.
7340  * 0x01:: no major GC
7341  * 0x02:: no immediate sweep
7342  * 0x04:: full mark after malloc/calloc/realloc
7343  */
7344 
7345 static VALUE
7346 gc_stress_set_m(VALUE self, VALUE flag)
7347 {
7348  rb_objspace_t *objspace = &rb_objspace;
7349  gc_stress_set(objspace, flag);
7350  return flag;
7351 }
7352 
7353 /*
7354  * call-seq:
7355  * GC.enable -> true or false
7356  *
7357  * Enables garbage collection, returning +true+ if garbage
7358  * collection was previously disabled.
7359  *
7360  * GC.disable #=> false
7361  * GC.enable #=> true
7362  * GC.enable #=> false
7363  *
7364  */
7365 
7366 VALUE
7368 {
7369  rb_objspace_t *objspace = &rb_objspace;
7370  int old = dont_gc;
7371 
7372  dont_gc = FALSE;
7373  return old ? Qtrue : Qfalse;
7374 }
7375 
7376 /*
7377  * call-seq:
7378  * GC.disable -> true or false
7379  *
7380  * Disables garbage collection, returning +true+ if garbage
7381  * collection was already disabled.
7382  *
7383  * GC.disable #=> false
7384  * GC.disable #=> true
7385  *
7386  */
7387 
7388 VALUE
7390 {
7391  rb_objspace_t *objspace = &rb_objspace;
7392  int old = dont_gc;
7393 
7394  gc_rest(objspace);
7395 
7396  dont_gc = TRUE;
7397  return old ? Qtrue : Qfalse;
7398 }
7399 
7400 static int
7401 get_envparam_size(const char *name, size_t *default_value, size_t lower_bound)
7402 {
7403  char *ptr = getenv(name);
7404  ssize_t val;
7405 
7406  if (ptr != NULL && *ptr) {
7407  size_t unit = 0;
7408  char *end;
7409 #if SIZEOF_SIZE_T == SIZEOF_LONG_LONG
7410  val = strtoll(ptr, &end, 0);
7411 #else
7412  val = strtol(ptr, &end, 0);
7413 #endif
7414  switch (*end) {
7415  case 'k': case 'K':
7416  unit = 1024;
7417  ++end;
7418  break;
7419  case 'm': case 'M':
7420  unit = 1024*1024;
7421  ++end;
7422  break;
7423  case 'g': case 'G':
7424  unit = 1024*1024*1024;
7425  ++end;
7426  break;
7427  }
7428  while (*end && isspace((unsigned char)*end)) end++;
7429  if (*end) {
7430  if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
7431  return 0;
7432  }
7433  if (unit > 0) {
7434  if (val < -(ssize_t)(SIZE_MAX / 2 / unit) || (ssize_t)(SIZE_MAX / 2 / unit) < val) {
7435  if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%s is ignored because it overflows\n", name, ptr);
7436  return 0;
7437  }
7438  val *= unit;
7439  }
7440  if (val > 0 && (size_t)val > lower_bound) {
7441  if (RTEST(ruby_verbose)) {
7442  fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE")\n", name, val, *default_value);
7443  }
7444  *default_value = (size_t)val;
7445  return 1;
7446  }
7447  else {
7448  if (RTEST(ruby_verbose)) {
7449  fprintf(stderr, "%s=%"PRIdSIZE" (default value: %"PRIuSIZE") is ignored because it must be greater than %"PRIuSIZE".\n",
7450  name, val, *default_value, lower_bound);
7451  }
7452  return 0;
7453  }
7454  }
7455  return 0;
7456 }
7457 
7458 static int
7459 get_envparam_double(const char *name, double *default_value, double lower_bound, double upper_bound, int accept_zero)
7460 {
7461  char *ptr = getenv(name);
7462  double val;
7463 
7464  if (ptr != NULL && *ptr) {
7465  char *end;
7466  val = strtod(ptr, &end);
7467  if (!*ptr || *end) {
7468  if (RTEST(ruby_verbose)) fprintf(stderr, "invalid string for %s: %s\n", name, ptr);
7469  return 0;
7470  }
7471 
7472  if (accept_zero && val == 0.0) {
7473  goto accept;
7474  }
7475  else if (val <= lower_bound) {
7476  if (RTEST(ruby_verbose)) {
7477  fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be greater than %f.\n",
7478  name, val, *default_value, lower_bound);
7479  }
7480  }
7481  else if (upper_bound != 0.0 && /* ignore upper_bound if it is 0.0 */
7482  val > upper_bound) {
7483  if (RTEST(ruby_verbose)) {
7484  fprintf(stderr, "%s=%f (default value: %f) is ignored because it must be lower than %f.\n",
7485  name, val, *default_value, upper_bound);
7486  }
7487  }
7488  else {
7489  accept:
7490  if (RTEST(ruby_verbose)) fprintf(stderr, "%s=%f (default value: %f)\n", name, val, *default_value);
7491  *default_value = val;
7492  return 1;
7493  }
7494  }
7495  return 0;
7496 }
7497 
7498 static void
7499 gc_set_initial_pages(void)
7500 {
7501  size_t min_pages;
7502  rb_objspace_t *objspace = &rb_objspace;
7503 
7504  min_pages = gc_params.heap_init_slots / HEAP_PAGE_OBJ_LIMIT;
7505  if (min_pages > heap_eden->total_pages) {
7506  heap_add_pages(objspace, heap_eden, min_pages - heap_eden->total_pages);
7507  }
7508 }
7509 
7510 /*
7511  * GC tuning environment variables
7512  *
7513  * * RUBY_GC_HEAP_INIT_SLOTS
7514  * - Initial allocation slots.
7515  * * RUBY_GC_HEAP_FREE_SLOTS
7516  * - Prepare at least this amount of slots after GC.
7517  * - Allocate slots if there are not enough slots.
7518  * * RUBY_GC_HEAP_GROWTH_FACTOR (new from 2.1)
7519  * - Allocate slots by this factor.
7520  * - (next slots number) = (current slots number) * (this factor)
7521  * * RUBY_GC_HEAP_GROWTH_MAX_SLOTS (new from 2.1)
7522  * - Allocation rate is limited to this number of slots.
7523  * * RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO (new from 2.4)
7524  * - Allocate additional pages when the number of free slots is
7525  * lower than the value (total_slots * (this ratio)).
7526  * * RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO (new from 2.4)
7527  * - Allocate slots to satisfy this formula:
7528  * free_slots = total_slots * goal_ratio
7529  * - In other words, prepare (total_slots * goal_ratio) free slots.
7530  * - if this value is 0.0, then use RUBY_GC_HEAP_GROWTH_FACTOR directly.
7531  * * RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO (new from 2.4)
7532  * - Allow to free pages when the number of free slots is
7533  * greater than the value (total_slots * (this ratio)).
7534  * * RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR (new from 2.1.1)
7535  * - Do full GC when the number of old objects is more than R * N
7536  * where R is this factor and
7537  * N is the number of old objects just after last full GC.
7538  *
7539  * * obsolete
7540  * * RUBY_FREE_MIN -> RUBY_GC_HEAP_FREE_SLOTS (from 2.1)
7541  * * RUBY_HEAP_MIN_SLOTS -> RUBY_GC_HEAP_INIT_SLOTS (from 2.1)
7542  *
7543  * * RUBY_GC_MALLOC_LIMIT
7544  * * RUBY_GC_MALLOC_LIMIT_MAX (new from 2.1)
7545  * * RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
7546  *
7547  * * RUBY_GC_OLDMALLOC_LIMIT (new from 2.1)
7548  * * RUBY_GC_OLDMALLOC_LIMIT_MAX (new from 2.1)
7549  * * RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR (new from 2.1)
7550  */
7551 
7552 void
7553 ruby_gc_set_params(int safe_level)
7554 {
7555  if (safe_level > 0) return;
7556 
7557  /* RUBY_GC_HEAP_FREE_SLOTS */
7558  if (get_envparam_size("RUBY_GC_HEAP_FREE_SLOTS", &gc_params.heap_free_slots, 0)) {
7559  /* ok */
7560  }
7561  else if (get_envparam_size("RUBY_FREE_MIN", &gc_params.heap_free_slots, 0)) {
7562  rb_warn("RUBY_FREE_MIN is obsolete. Use RUBY_GC_HEAP_FREE_SLOTS instead.");
7563  }
7564 
7565  /* RUBY_GC_HEAP_INIT_SLOTS */
7566  if (get_envparam_size("RUBY_GC_HEAP_INIT_SLOTS", &gc_params.heap_init_slots, 0)) {
7567  gc_set_initial_pages();
7568  }
7569  else if (get_envparam_size("RUBY_HEAP_MIN_SLOTS", &gc_params.heap_init_slots, 0)) {
7570  rb_warn("RUBY_HEAP_MIN_SLOTS is obsolete. Use RUBY_GC_HEAP_INIT_SLOTS instead.");
7571  gc_set_initial_pages();
7572  }
7573 
7574  get_envparam_double("RUBY_GC_HEAP_GROWTH_FACTOR", &gc_params.growth_factor, 1.0, 0.0, FALSE);
7575  get_envparam_size ("RUBY_GC_HEAP_GROWTH_MAX_SLOTS", &gc_params.growth_max_slots, 0);
7576  get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MIN_RATIO", &gc_params.heap_free_slots_min_ratio,
7577  0.0, 1.0, FALSE);
7578  get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_MAX_RATIO", &gc_params.heap_free_slots_max_ratio,
7579  gc_params.heap_free_slots_min_ratio, 1.0, FALSE);
7580  get_envparam_double("RUBY_GC_HEAP_FREE_SLOTS_GOAL_RATIO", &gc_params.heap_free_slots_goal_ratio,
7582  get_envparam_double("RUBY_GC_HEAP_OLDOBJECT_LIMIT_FACTOR", &gc_params.oldobject_limit_factor, 0.0, 0.0, TRUE);
7583 
7584  get_envparam_size ("RUBY_GC_MALLOC_LIMIT", &gc_params.malloc_limit_min, 0);
7585  get_envparam_size ("RUBY_GC_MALLOC_LIMIT_MAX", &gc_params.malloc_limit_max, 0);
7586  get_envparam_double("RUBY_GC_MALLOC_LIMIT_GROWTH_FACTOR", &gc_params.malloc_limit_growth_factor, 1.0, 0.0, FALSE);
7587 
7588 #if RGENGC_ESTIMATE_OLDMALLOC
7589  if (get_envparam_size("RUBY_GC_OLDMALLOC_LIMIT", &gc_params.oldmalloc_limit_min, 0)) {
7590  rb_objspace_t *objspace = &rb_objspace;
7591  objspace->rgengc.oldmalloc_increase_limit = gc_params.oldmalloc_limit_min;
7592  }
7593  get_envparam_size ("RUBY_GC_OLDMALLOC_LIMIT_MAX", &gc_params.oldmalloc_limit_max, 0);
7594  get_envparam_double("RUBY_GC_OLDMALLOC_LIMIT_GROWTH_FACTOR", &gc_params.oldmalloc_limit_growth_factor, 1.0, 0.0, FALSE);
7595 #endif
7596 }
7597 
7598 void
7599 rb_objspace_reachable_objects_from(VALUE obj, void (func)(VALUE, void *), void *data)
7600 {
7601  rb_objspace_t *objspace = &rb_objspace;
7602 
7603  if (is_markable_object(objspace, obj)) {
7604  struct mark_func_data_struct mfd;
7605  mfd.mark_func = func;
7606  mfd.data = data;
7607  PUSH_MARK_FUNC_DATA(&mfd);
7608  gc_mark_children(objspace, obj);
7610  }
7611 }
7612 
7614  const char *category;
7615  void (*func)(const char *category, VALUE, void *);
7616  void *data;
7617 };
7618 
7619 static void
7620 root_objects_from(VALUE obj, void *ptr)
7621 {
7622  const struct root_objects_data *data = (struct root_objects_data *)ptr;
7623  (*data->func)(data->category, obj, data->data);
7624 }
7625 
7626 void
7627 rb_objspace_reachable_objects_from_root(void (func)(const char *category, VALUE, void *), void *passing_data)
7628 {
7629  rb_objspace_t *objspace = &rb_objspace;
7630  struct root_objects_data data;
7631  struct mark_func_data_struct mfd;
7632 
7633  data.func = func;
7634  data.data = passing_data;
7635 
7636  mfd.mark_func = root_objects_from;
7637  mfd.data = &data;
7638 
7639  PUSH_MARK_FUNC_DATA(&mfd);
7640  gc_mark_roots(objspace, &data.category);
7642 }
7643 
7644 /*
7645  ------------------------ Extended allocator ------------------------
7646 */
7647 
7648 static void objspace_xfree(rb_objspace_t *objspace, void *ptr, size_t size);
7649 
7650 static void *
7651 negative_size_allocation_error_with_gvl(void *ptr)
7652 {
7653  rb_raise(rb_eNoMemError, "%s", (const char *)ptr);
7654  return 0; /* should not be reached */
7655 }
7656 
7657 static void
7658 negative_size_allocation_error(const char *msg)
7659 {
7660  if (ruby_thread_has_gvl_p()) {
7661  rb_raise(rb_eNoMemError, "%s", msg);
7662  }
7663  else {
7664  if (ruby_native_thread_p()) {
7665  rb_thread_call_with_gvl(negative_size_allocation_error_with_gvl, (void *)msg);
7666  }
7667  else {
7668  fprintf(stderr, "[FATAL] %s\n", msg);
7669  exit(EXIT_FAILURE);
7670  }
7671  }
7672 }
7673 
7674 static void *
7675 ruby_memerror_body(void *dummy)
7676 {
7677  rb_memerror();
7678  return 0;
7679 }
7680 
7681 static void
7682 ruby_memerror(void)
7683 {
7684  if (ruby_thread_has_gvl_p()) {
7685  rb_memerror();
7686  }
7687  else {
7688  if (ruby_native_thread_p()) {
7689  rb_thread_call_with_gvl(ruby_memerror_body, 0);
7690  }
7691  else {
7692  /* no ruby thread */
7693  fprintf(stderr, "[FATAL] failed to allocate memory\n");
7694  exit(EXIT_FAILURE);
7695  }
7696  }
7697 }
7698 
7699 void
7701 {
7702  rb_thread_t *th = GET_THREAD();
7703  rb_objspace_t *objspace = rb_objspace_of(th->vm);
7704  VALUE exc;
7705 
7706  if (during_gc) gc_exit(objspace, "rb_memerror");
7707 
7708  exc = nomem_error;
7709  if (!exc ||
7711  fprintf(stderr, "[FATAL] failed to allocate memory\n");
7712  exit(EXIT_FAILURE);
7713  }
7716  }
7717  else {
7719  exc = ruby_vm_special_exception_copy(exc);
7720  }
7721  th->ec.errinfo = exc;
7722  TH_JUMP_TAG(th, TAG_RAISE);
7723 }
7724 
7725 static void *
7726 aligned_malloc(size_t alignment, size_t size)
7727 {
7728  void *res;
7729 
7730 #if defined __MINGW32__
7731  res = __mingw_aligned_malloc(size, alignment);
7732 #elif defined _WIN32
7733  void *_aligned_malloc(size_t, size_t);
7734  res = _aligned_malloc(size, alignment);
7735 #elif defined(HAVE_POSIX_MEMALIGN)
7736  if (posix_memalign(&res, alignment, size) == 0) {
7737  return res;
7738  }
7739  else {
7740  return NULL;
7741  }
7742 #elif defined(HAVE_MEMALIGN)
7743  res = memalign(alignment, size);
7744 #else
7745  char* aligned;
7746  res = malloc(alignment + size + sizeof(void*));
7747  aligned = (char*)res + alignment + sizeof(void*);
7748  aligned -= ((VALUE)aligned & (alignment - 1));
7749  ((void**)aligned)[-1] = res;
7750  res = (void*)aligned;
7751 #endif
7752 
7753  /* alignment must be a power of 2 */
7754  GC_ASSERT(((alignment - 1) & alignment) == 0);
7755  GC_ASSERT(alignment % sizeof(void*) == 0);
7756  return res;
7757 }
7758 
7759 static void
7760 aligned_free(void *ptr)
7761 {
7762 #if defined __MINGW32__
7763  __mingw_aligned_free(ptr);
7764 #elif defined _WIN32
7765  _aligned_free(ptr);
7766 #elif defined(HAVE_MEMALIGN) || defined(HAVE_POSIX_MEMALIGN)
7767  free(ptr);
7768 #else
7769  free(((void**)ptr)[-1]);
7770 #endif
7771 }
7772 
7773 static inline size_t
7774 objspace_malloc_size(rb_objspace_t *objspace, void *ptr, size_t hint)
7775 {
7776 #ifdef HAVE_MALLOC_USABLE_SIZE
7777  return malloc_usable_size(ptr);
7778 #else
7779  return hint;
7780 #endif
7781 }
7782 
7787 };
7788 
7789 static inline void
7790 atomic_sub_nounderflow(size_t *var, size_t sub)
7791 {
7792  if (sub == 0) return;
7793 
7794  while (1) {
7795  size_t val = *var;
7796  if (val < sub) sub = val;
7797  if (ATOMIC_SIZE_CAS(*var, val, val-sub) == val) break;
7798  }
7799 }
7800 
7801 static void
7802 objspace_malloc_gc_stress(rb_objspace_t *objspace)
7803 {
7805  garbage_collect_with_gvl(objspace, gc_stress_full_mark_after_malloc_p(), TRUE, TRUE, GPR_FLAG_STRESS | GPR_FLAG_MALLOC);
7806  }
7807 }
7808 
7809 static void
7810 objspace_malloc_increase(rb_objspace_t *objspace, void *mem, size_t new_size, size_t old_size, enum memop_type type)
7811 {
7812  if (new_size > old_size) {
7813  ATOMIC_SIZE_ADD(malloc_increase, new_size - old_size);
7814 #if RGENGC_ESTIMATE_OLDMALLOC
7815  ATOMIC_SIZE_ADD(objspace->rgengc.oldmalloc_increase, new_size - old_size);
7816 #endif
7817  }
7818  else {
7819  atomic_sub_nounderflow(&malloc_increase, old_size - new_size);
7820 #if RGENGC_ESTIMATE_OLDMALLOC
7821  atomic_sub_nounderflow(&objspace->rgengc.oldmalloc_increase, old_size - new_size);
7822 #endif
7823  }
7824 
7825  if (type == MEMOP_TYPE_MALLOC) {
7826  retry:
7829  gc_rest(objspace); /* gc_rest can reduce malloc_increase */
7830  goto retry;
7831  }
7832  garbage_collect_with_gvl(objspace, FALSE, FALSE, FALSE, GPR_FLAG_MALLOC);
7833  }
7834  }
7835 
7836 #if MALLOC_ALLOCATED_SIZE
7837  if (new_size >= old_size) {
7838  ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, new_size - old_size);
7839  }
7840  else {
7841  size_t dec_size = old_size - new_size;
7842  size_t allocated_size = objspace->malloc_params.allocated_size;
7843 
7844 #if MALLOC_ALLOCATED_SIZE_CHECK
7845  if (allocated_size < dec_size) {
7846  rb_bug("objspace_malloc_increase: underflow malloc_params.allocated_size.");
7847  }
7848 #endif
7849  atomic_sub_nounderflow(&objspace->malloc_params.allocated_size, dec_size);
7850  }
7851 
7852  if (0) fprintf(stderr, "increase - ptr: %p, type: %s, new_size: %d, old_size: %d\n",
7853  mem,
7854  type == MEMOP_TYPE_MALLOC ? "malloc" :
7855  type == MEMOP_TYPE_FREE ? "free " :
7856  type == MEMOP_TYPE_REALLOC ? "realloc": "error",
7857  (int)new_size, (int)old_size);
7858 
7859  switch (type) {
7860  case MEMOP_TYPE_MALLOC:
7861  ATOMIC_SIZE_INC(objspace->malloc_params.allocations);
7862  break;
7863  case MEMOP_TYPE_FREE:
7864  {
7865  size_t allocations = objspace->malloc_params.allocations;
7866  if (allocations > 0) {
7867  atomic_sub_nounderflow(&objspace->malloc_params.allocations, 1);
7868  }
7869 #if MALLOC_ALLOCATED_SIZE_CHECK
7870  else {
7871  GC_ASSERT(objspace->malloc_params.allocations > 0);
7872  }
7873 #endif
7874  }
7875  break;
7876  case MEMOP_TYPE_REALLOC: /* ignore */ break;
7877  }
7878 #endif
7879 }
7880 
7881 static inline size_t
7882 objspace_malloc_prepare(rb_objspace_t *objspace, size_t size)
7883 {
7884  if (size == 0) size = 1;
7885 
7886 #if CALC_EXACT_MALLOC_SIZE
7887  size += sizeof(size_t);
7888 #endif
7889 
7890  return size;
7891 }
7892 
7893 static inline void *
7894 objspace_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size)
7895 {
7896  size = objspace_malloc_size(objspace, mem, size);
7897  objspace_malloc_increase(objspace, mem, size, 0, MEMOP_TYPE_MALLOC);
7898 
7899 #if CALC_EXACT_MALLOC_SIZE
7900  ((size_t *)mem)[0] = size;
7901  mem = (size_t *)mem + 1;
7902 #endif
7903 
7904  return mem;
7905 }
7906 
7907 #define TRY_WITH_GC(alloc) do { \
7908  objspace_malloc_gc_stress(objspace); \
7909  if (!(alloc) && \
7910  (!garbage_collect_with_gvl(objspace, TRUE, TRUE, TRUE, GPR_FLAG_MALLOC) || /* full/immediate mark && immediate sweep */ \
7911  !(alloc))) { \
7912  ruby_memerror(); \
7913  } \
7914  } while (0)
7915 
7916 /* these shouldn't be called directly.
7917  * objspace_* functinos do not check allocation size.
7918  */
7919 static void *
7920 objspace_xmalloc0(rb_objspace_t *objspace, size_t size)
7921 {
7922  void *mem;
7923 
7924  size = objspace_malloc_prepare(objspace, size);
7925  TRY_WITH_GC(mem = malloc(size));
7926  return objspace_malloc_fixup(objspace, mem, size);
7927 }
7928 
7929 static inline size_t
7930 xmalloc2_size(const size_t count, const size_t elsize)
7931 {
7932  size_t ret;
7933  if (rb_mul_size_overflow(count, elsize, SSIZE_MAX, &ret)) {
7934  ruby_malloc_size_overflow(count, elsize);
7935  }
7936  return ret;
7937 }
7938 
7939 static void *
7940 objspace_xrealloc(rb_objspace_t *objspace, void *ptr, size_t new_size, size_t old_size)
7941 {
7942  void *mem;
7943 
7944  if (!ptr) return objspace_xmalloc0(objspace, new_size);
7945 
7946  /*
7947  * The behavior of realloc(ptr, 0) is implementation defined.
7948  * Therefore we don't use realloc(ptr, 0) for portability reason.
7949  * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm
7950  */
7951  if (new_size == 0) {
7952  objspace_xfree(objspace, ptr, old_size);
7953  return 0;
7954  }
7955 
7956 #if CALC_EXACT_MALLOC_SIZE
7957  new_size += sizeof(size_t);
7958  ptr = (size_t *)ptr - 1;
7959  old_size = ((size_t *)ptr)[0];
7960 #endif
7961 
7962  old_size = objspace_malloc_size(objspace, ptr, old_size);
7963  TRY_WITH_GC(mem = realloc(ptr, new_size));
7964  new_size = objspace_malloc_size(objspace, mem, new_size);
7965 
7966 #if CALC_EXACT_MALLOC_SIZE
7967  ((size_t *)mem)[0] = new_size;
7968  mem = (size_t *)mem + 1;
7969 #endif
7970 
7971  objspace_malloc_increase(objspace, mem, new_size, old_size, MEMOP_TYPE_REALLOC);
7972 
7973  return mem;
7974 }
7975 
7976 static void
7977 objspace_xfree(rb_objspace_t *objspace, void *ptr, size_t old_size)
7978 {
7979 #if CALC_EXACT_MALLOC_SIZE
7980  ptr = ((size_t *)ptr) - 1;
7981  old_size = ((size_t*)ptr)[0];
7982 #endif
7983  old_size = objspace_malloc_size(objspace, ptr, old_size);
7984 
7985  free(ptr);
7986 
7987  objspace_malloc_increase(objspace, ptr, 0, old_size, MEMOP_TYPE_FREE);
7988 }
7989 
7990 static void *
7991 ruby_xmalloc0(size_t size)
7992 {
7993  return objspace_xmalloc0(&rb_objspace, size);
7994 }
7995 
7996 void *
7997 ruby_xmalloc(size_t size)
7998 {
7999  if ((ssize_t)size < 0) {
8000  negative_size_allocation_error("too large allocation size");
8001  }
8002  return ruby_xmalloc0(size);
8003 }
8004 
8005 void
8006 ruby_malloc_size_overflow(size_t count, size_t elsize)
8007 {
8009  "malloc: possible integer overflow (%"PRIuSIZE"*%"PRIuSIZE")",
8010  count, elsize);
8011 }
8012 
8013 void *
8014 ruby_xmalloc2(size_t n, size_t size)
8015 {
8016  return objspace_xmalloc0(&rb_objspace, xmalloc2_size(n, size));
8017 }
8018 
8019 static void *
8020 objspace_xcalloc(rb_objspace_t *objspace, size_t size)
8021 {
8022  void *mem;
8023 
8024  size = objspace_malloc_prepare(objspace, size);
8025  TRY_WITH_GC(mem = calloc(1, size));
8026  return objspace_malloc_fixup(objspace, mem, size);
8027 }
8028 
8029 void *
8030 ruby_xcalloc(size_t n, size_t size)
8031 {
8032  return objspace_xcalloc(&rb_objspace, xmalloc2_size(n, size));
8033 }
8034 
8035 #ifdef ruby_sized_xrealloc
8036 #undef ruby_sized_xrealloc
8037 #endif
8038 void *
8039 ruby_sized_xrealloc(void *ptr, size_t new_size, size_t old_size)
8040 {
8041  if ((ssize_t)new_size < 0) {
8042  negative_size_allocation_error("too large allocation size");
8043  }
8044 
8045  return objspace_xrealloc(&rb_objspace, ptr, new_size, old_size);
8046 }
8047 
8048 void *
8049 ruby_xrealloc(void *ptr, size_t new_size)
8050 {
8051  return ruby_sized_xrealloc(ptr, new_size, 0);
8052 }
8053 
8054 #ifdef ruby_sized_xrealloc2
8055 #undef ruby_sized_xrealloc2
8056 #endif
8057 void *
8058 ruby_sized_xrealloc2(void *ptr, size_t n, size_t size, size_t old_n)
8059 {
8060  size_t len = size * n;
8061  if (n != 0 && size != len / n) {
8062  rb_raise(rb_eArgError, "realloc: possible integer overflow");
8063  }
8064  return objspace_xrealloc(&rb_objspace, ptr, len, old_n * size);
8065 }
8066 
8067 void *
8068 ruby_xrealloc2(void *ptr, size_t n, size_t size)
8069 {
8070  return ruby_sized_xrealloc2(ptr, n, size, 0);
8071 }
8072 
8073 #ifdef ruby_sized_xfree
8074 #undef ruby_sized_xfree
8075 #endif
8076 void
8077 ruby_sized_xfree(void *x, size_t size)
8078 {
8079  if (x) {
8080  objspace_xfree(&rb_objspace, x, size);
8081  }
8082 }
8083 
8084 void
8085 ruby_xfree(void *x)
8086 {
8087  ruby_sized_xfree(x, 0);
8088 }
8089 
8090 /* Mimic ruby_xmalloc, but need not rb_objspace.
8091  * should return pointer suitable for ruby_xfree
8092  */
8093 void *
8094 ruby_mimmalloc(size_t size)
8095 {
8096  void *mem;
8097 #if CALC_EXACT_MALLOC_SIZE
8098  size += sizeof(size_t);
8099 #endif
8100  mem = malloc(size);
8101 #if CALC_EXACT_MALLOC_SIZE
8102  /* set 0 for consistency of allocated_size/allocations */
8103  ((size_t *)mem)[0] = 0;
8104  mem = (size_t *)mem + 1;
8105 #endif
8106  return mem;
8107 }
8108 
8109 void
8110 ruby_mimfree(void *ptr)
8111 {
8112  size_t *mem = (size_t *)ptr;
8113 #if CALC_EXACT_MALLOC_SIZE
8114  mem = mem - 1;
8115 #endif
8116  free(mem);
8117 }
8118 
8119 void *
8120 rb_alloc_tmp_buffer_with_count(volatile VALUE *store, size_t size, size_t cnt)
8121 {
8122  VALUE s;
8123  rb_imemo_alloc_t *a;
8124  void *ptr;
8125 
8126  s = rb_imemo_new(imemo_alloc, 0, 0, 0, 0);
8127  ptr = ruby_xmalloc0(size);
8128  a = (rb_imemo_alloc_t*)s;
8129  a->ptr = (VALUE*)ptr;
8130  a->cnt = cnt;
8131  *store = s;
8132  return ptr;
8133 }
8134 
8135 void *
8136 rb_alloc_tmp_buffer(volatile VALUE *store, long len)
8137 {
8138  long cnt;
8139 
8140  if (len < 0 || (cnt = (long)roomof(len, sizeof(VALUE))) < 0) {
8141  rb_raise(rb_eArgError, "negative buffer size (or size too big)");
8142  }
8143 
8144  return rb_alloc_tmp_buffer_with_count(store, len, cnt);
8145 }
8146 
8147 void
8148 rb_free_tmp_buffer(volatile VALUE *store)
8149 {
8150  VALUE s = ATOMIC_VALUE_EXCHANGE(*store, 0);
8151  if (s) {
8152  void *ptr = ATOMIC_PTR_EXCHANGE(RNODE(s)->u1.node, 0);
8153  RNODE(s)->u3.cnt = 0;
8154  ruby_xfree(ptr);
8155  }
8156 }
8157 
8158 #if MALLOC_ALLOCATED_SIZE
8159 /*
8160  * call-seq:
8161  * GC.malloc_allocated_size -> Integer
8162  *
8163  * Returns the size of memory allocated by malloc().
8164  *
8165  * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
8166  */
8167 
8168 static VALUE
8169 gc_malloc_allocated_size(VALUE self)
8170 {
8171  return UINT2NUM(rb_objspace.malloc_params.allocated_size);
8172 }
8173 
8174 /*
8175  * call-seq:
8176  * GC.malloc_allocations -> Integer
8177  *
8178  * Returns the number of malloc() allocations.
8179  *
8180  * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+.
8181  */
8182 
8183 static VALUE
8184 gc_malloc_allocations(VALUE self)
8185 {
8186  return UINT2NUM(rb_objspace.malloc_params.allocations);
8187 }
8188 #endif
8189 
8190 void
8192 {
8193  rb_objspace_t *objspace = &rb_objspace;
8194  if (diff > 0) {
8195  objspace_malloc_increase(objspace, 0, diff, 0, MEMOP_TYPE_REALLOC);
8196  }
8197  else if (diff < 0) {
8198  objspace_malloc_increase(objspace, 0, 0, -diff, MEMOP_TYPE_REALLOC);
8199  }
8200 }
8201 
8202 /*
8203  ------------------------------ WeakMap ------------------------------
8204 */
8205 
8206 struct weakmap {
8207  st_table *obj2wmap; /* obj -> [ref,...] */
8208  st_table *wmap2obj; /* ref -> obj */
8209  VALUE final;
8210 };
8211 
8212 #define WMAP_DELETE_DEAD_OBJECT_IN_MARK 0
8213 
8214 #if WMAP_DELETE_DEAD_OBJECT_IN_MARK
8215 static int
8216 wmap_mark_map(st_data_t key, st_data_t val, st_data_t arg)
8217 {
8218  rb_objspace_t *objspace = (rb_objspace_t *)arg;
8219  VALUE obj = (VALUE)val;
8220  if (!is_live_object(objspace, obj)) return ST_DELETE;
8221  return ST_CONTINUE;
8222 }
8223 #endif
8224 
8225 static void
8226 wmap_mark(void *ptr)
8227 {
8228  struct weakmap *w = ptr;
8229 #if WMAP_DELETE_DEAD_OBJECT_IN_MARK
8230  if (w->obj2wmap) st_foreach(w->obj2wmap, wmap_mark_map, (st_data_t)&rb_objspace);
8231 #endif
8232  rb_gc_mark(w->final);
8233 }
8234 
8235 static int
8236 wmap_free_map(st_data_t key, st_data_t val, st_data_t arg)
8237 {
8238  VALUE *ptr = (VALUE *)val;
8239  ruby_sized_xfree(ptr, (ptr[0] + 1) * sizeof(VALUE));
8240  return ST_CONTINUE;
8241 }
8242 
8243 static void
8244 wmap_free(void *ptr)
8245 {
8246  struct weakmap *w = ptr;
8247  st_foreach(w->obj2wmap, wmap_free_map, 0);
8248  st_free_table(w->obj2wmap);
8249  st_free_table(w->wmap2obj);
8250 }
8251 
8252 static int
8253 wmap_memsize_map(st_data_t key, st_data_t val, st_data_t arg)
8254 {
8255  VALUE *ptr = (VALUE *)val;
8256  *(size_t *)arg += (ptr[0] + 1) * sizeof(VALUE);
8257  return ST_CONTINUE;
8258 }
8259 
8260 static size_t
8261 wmap_memsize(const void *ptr)
8262 {
8263  size_t size;
8264  const struct weakmap *w = ptr;
8265  size = sizeof(*w);
8266  size += st_memsize(w->obj2wmap);
8267  size += st_memsize(w->wmap2obj);
8268  st_foreach(w->obj2wmap, wmap_memsize_map, (st_data_t)&size);
8269  return size;
8270 }
8271 
8272 static const rb_data_type_t weakmap_type = {
8273  "weakmap",
8274  {
8275  wmap_mark,
8276  wmap_free,
8277  wmap_memsize,
8278  },
8280 };
8281 
8282 static VALUE
8283 wmap_allocate(VALUE klass)
8284 {
8285  struct weakmap *w;
8286  VALUE obj = TypedData_Make_Struct(klass, struct weakmap, &weakmap_type, w);
8287  w->obj2wmap = st_init_numtable();
8288  w->wmap2obj = st_init_numtable();
8289  w->final = rb_obj_method(obj, ID2SYM(rb_intern("finalize")));
8290  return obj;
8291 }
8292 
8293 static int
8294 wmap_final_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing)
8295 {
8296  VALUE wmap, *ptr, size, i, j;
8297  if (!existing) return ST_STOP;
8298  wmap = (VALUE)arg, ptr = (VALUE *)*value;
8299  for (i = j = 1, size = ptr[0]; i <= size; ++i) {
8300  if (ptr[i] != wmap) {
8301  ptr[j++] = ptr[i];
8302  }
8303  }
8304  if (j == 1) {
8305  ruby_sized_xfree(ptr, i * sizeof(VALUE));
8306  return ST_DELETE;
8307  }
8308  if (j < i) {
8309  ptr = ruby_sized_xrealloc2(ptr, j + 1, sizeof(VALUE), i);
8310  ptr[0] = j;
8311  *value = (st_data_t)ptr;
8312  }
8313  return ST_CONTINUE;
8314 }
8315 
8316 static VALUE
8317 wmap_finalize(VALUE self, VALUE objid)
8318 {
8319  st_data_t orig, wmap, data;
8320  VALUE obj, *rids, i, size;
8321  struct weakmap *w;
8322 
8323  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8324  /* Get reference from object id. */
8325  obj = obj_id_to_ref(objid);
8326 
8327  /* obj is original referenced object and/or weak reference. */
8328  orig = (st_data_t)obj;
8329  if (st_delete(w->obj2wmap, &orig, &data)) {
8330  rids = (VALUE *)data;
8331  size = *rids++;
8332  for (i = 0; i < size; ++i) {
8333  wmap = (st_data_t)rids[i];
8334  st_delete(w->wmap2obj, &wmap, NULL);
8335  }
8336  ruby_sized_xfree((VALUE *)data, (size + 1) * sizeof(VALUE));
8337  }
8338 
8339  wmap = (st_data_t)obj;
8340  if (st_delete(w->wmap2obj, &wmap, &orig)) {
8341  wmap = (st_data_t)obj;
8342  st_update(w->obj2wmap, orig, wmap_final_func, wmap);
8343  }
8344  return self;
8345 }
8346 
8350 };
8351 
8352 static int
8353 wmap_inspect_i(st_data_t key, st_data_t val, st_data_t arg)
8354 {
8355  VALUE str = (VALUE)arg;
8356  VALUE k = (VALUE)key, v = (VALUE)val;
8357 
8358  if (RSTRING_PTR(str)[0] == '#') {
8359  rb_str_cat2(str, ", ");
8360  }
8361  else {
8362  rb_str_cat2(str, ": ");
8363  RSTRING_PTR(str)[0] = '#';
8364  }
8365  k = SPECIAL_CONST_P(k) ? rb_inspect(k) : rb_any_to_s(k);
8366  rb_str_append(str, k);
8367  rb_str_cat2(str, " => ");
8368  v = SPECIAL_CONST_P(v) ? rb_inspect(v) : rb_any_to_s(v);
8369  rb_str_append(str, v);
8370  OBJ_INFECT(str, k);
8371  OBJ_INFECT(str, v);
8372 
8373  return ST_CONTINUE;
8374 }
8375 
8376 static VALUE
8377 wmap_inspect(VALUE self)
8378 {
8379  VALUE str;
8380  VALUE c = rb_class_name(CLASS_OF(self));
8381  struct weakmap *w;
8382 
8383  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8384  str = rb_sprintf("-<%"PRIsVALUE":%p", c, (void *)self);
8385  if (w->wmap2obj) {
8386  st_foreach(w->wmap2obj, wmap_inspect_i, str);
8387  }
8388  RSTRING_PTR(str)[0] = '#';
8389  rb_str_cat2(str, ">");
8390  return str;
8391 }
8392 
8393 static int
8394 wmap_each_i(st_data_t key, st_data_t val, st_data_t arg)
8395 {
8396  rb_objspace_t *objspace = (rb_objspace_t *)arg;
8397  VALUE obj = (VALUE)val;
8398  if (is_id_value(objspace, obj) && is_live_object(objspace, obj)) {
8399  rb_yield_values(2, (VALUE)key, obj);
8400  }
8401  return ST_CONTINUE;
8402 }
8403 
8404 /* Iterates over keys and objects in a weakly referenced object */
8405 static VALUE
8406 wmap_each(VALUE self)
8407 {
8408  struct weakmap *w;
8409  rb_objspace_t *objspace = &rb_objspace;
8410 
8411  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8412  st_foreach(w->wmap2obj, wmap_each_i, (st_data_t)objspace);
8413  return self;
8414 }
8415 
8416 static int
8417 wmap_each_key_i(st_data_t key, st_data_t val, st_data_t arg)
8418 {
8419  rb_objspace_t *objspace = (rb_objspace_t *)arg;
8420  VALUE obj = (VALUE)val;
8421  if (is_id_value(objspace, obj) && is_live_object(objspace, obj)) {
8422  rb_yield((VALUE)key);
8423  }
8424  return ST_CONTINUE;
8425 }
8426 
8427 /* Iterates over keys and objects in a weakly referenced object */
8428 static VALUE
8429 wmap_each_key(VALUE self)
8430 {
8431  struct weakmap *w;
8432  rb_objspace_t *objspace = &rb_objspace;
8433 
8434  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8435  st_foreach(w->wmap2obj, wmap_each_key_i, (st_data_t)objspace);
8436  return self;
8437 }
8438 
8439 static int
8440 wmap_each_value_i(st_data_t key, st_data_t val, st_data_t arg)
8441 {
8442  rb_objspace_t *objspace = (rb_objspace_t *)arg;
8443  VALUE obj = (VALUE)val;
8444  if (is_id_value(objspace, obj) && is_live_object(objspace, obj)) {
8445  rb_yield(obj);
8446  }
8447  return ST_CONTINUE;
8448 }
8449 
8450 /* Iterates over keys and objects in a weakly referenced object */
8451 static VALUE
8452 wmap_each_value(VALUE self)
8453 {
8454  struct weakmap *w;
8455  rb_objspace_t *objspace = &rb_objspace;
8456 
8457  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8458  st_foreach(w->wmap2obj, wmap_each_value_i, (st_data_t)objspace);
8459  return self;
8460 }
8461 
8462 static int
8463 wmap_keys_i(st_data_t key, st_data_t val, st_data_t arg)
8464 {
8465  struct wmap_iter_arg *argp = (struct wmap_iter_arg *)arg;
8466  rb_objspace_t *objspace = argp->objspace;
8467  VALUE ary = argp->value;
8468  VALUE obj = (VALUE)val;
8469  if (is_id_value(objspace, obj) && is_live_object(objspace, obj)) {
8470  rb_ary_push(ary, (VALUE)key);
8471  }
8472  return ST_CONTINUE;
8473 }
8474 
8475 /* Iterates over keys and objects in a weakly referenced object */
8476 static VALUE
8477 wmap_keys(VALUE self)
8478 {
8479  struct weakmap *w;
8480  struct wmap_iter_arg args;
8481 
8482  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8483  args.objspace = &rb_objspace;
8484  args.value = rb_ary_new();
8485  st_foreach(w->wmap2obj, wmap_keys_i, (st_data_t)&args);
8486  return args.value;
8487 }
8488 
8489 static int
8490 wmap_values_i(st_data_t key, st_data_t val, st_data_t arg)
8491 {
8492  struct wmap_iter_arg *argp = (struct wmap_iter_arg *)arg;
8493  rb_objspace_t *objspace = argp->objspace;
8494  VALUE ary = argp->value;
8495  VALUE obj = (VALUE)val;
8496  if (is_id_value(objspace, obj) && is_live_object(objspace, obj)) {
8497  rb_ary_push(ary, obj);
8498  }
8499  return ST_CONTINUE;
8500 }
8501 
8502 /* Iterates over values and objects in a weakly referenced object */
8503 static VALUE
8504 wmap_values(VALUE self)
8505 {
8506  struct weakmap *w;
8507  struct wmap_iter_arg args;
8508 
8509  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8510  args.objspace = &rb_objspace;
8511  args.value = rb_ary_new();
8512  st_foreach(w->wmap2obj, wmap_values_i, (st_data_t)&args);
8513  return args.value;
8514 }
8515 
8516 static int
8517 wmap_aset_update(st_data_t *key, st_data_t *val, st_data_t arg, int existing)
8518 {
8519  VALUE size, *ptr, *optr;
8520  if (existing) {
8521  size = (ptr = optr = (VALUE *)*val)[0];
8522  ++size;
8523  ptr = ruby_sized_xrealloc2(ptr, size + 1, sizeof(VALUE), size);
8524  }
8525  else {
8526  optr = 0;
8527  size = 1;
8528  ptr = ruby_xmalloc0(2 * sizeof(VALUE));
8529  }
8530  ptr[0] = size;
8531  ptr[size] = (VALUE)arg;
8532  if (ptr == optr) return ST_STOP;
8533  *val = (st_data_t)ptr;
8534  return ST_CONTINUE;
8535 }
8536 
8537 /* Creates a weak reference from the given key to the given value */
8538 static VALUE
8539 wmap_aset(VALUE self, VALUE wmap, VALUE orig)
8540 {
8541  struct weakmap *w;
8542 
8543  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8544  should_be_finalizable(orig);
8545  should_be_finalizable(wmap);
8546  define_final0(orig, w->final);
8547  define_final0(wmap, w->final);
8548  st_update(w->obj2wmap, (st_data_t)orig, wmap_aset_update, wmap);
8549  st_insert(w->wmap2obj, (st_data_t)wmap, (st_data_t)orig);
8550  return nonspecial_obj_id(orig);
8551 }
8552 
8553 /* Retrieves a weakly referenced object with the given key */
8554 static VALUE
8555 wmap_aref(VALUE self, VALUE wmap)
8556 {
8557  st_data_t data;
8558  VALUE obj;
8559  struct weakmap *w;
8560  rb_objspace_t *objspace = &rb_objspace;
8561 
8562  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8563  if (!st_lookup(w->wmap2obj, (st_data_t)wmap, &data)) return Qnil;
8564  obj = (VALUE)data;
8565  if (!is_id_value(objspace, obj)) return Qnil;
8566  if (!is_live_object(objspace, obj)) return Qnil;
8567  return obj;
8568 }
8569 
8570 /* Returns +true+ if +key+ is registered */
8571 static VALUE
8572 wmap_has_key(VALUE self, VALUE key)
8573 {
8574  return NIL_P(wmap_aref(self, key)) ? Qfalse : Qtrue;
8575 }
8576 
8577 static VALUE
8578 wmap_size(VALUE self)
8579 {
8580  struct weakmap *w;
8581  st_index_t n;
8582 
8583  TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w);
8584  n = w->wmap2obj->num_entries;
8585 #if SIZEOF_ST_INDEX_T <= SIZEOF_LONG
8586  return ULONG2NUM(n);
8587 #else
8588  return ULL2NUM(n);
8589 #endif
8590 }
8591 
8592 /*
8593  ------------------------------ GC profiler ------------------------------
8594 */
8595 
8596 #define GC_PROFILE_RECORD_DEFAULT_SIZE 100
8597 
8598 /* return sec in user time */
8599 static double
8600 getrusage_time(void)
8601 {
8602 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID)
8603  {
8604  static int try_clock_gettime = 1;
8605  struct timespec ts;
8606  if (try_clock_gettime && clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == 0) {
8607  return ts.tv_sec + ts.tv_nsec * 1e-9;
8608  }
8609  else {
8610  try_clock_gettime = 0;
8611  }
8612  }
8613 #endif
8614 
8615 #ifdef RUSAGE_SELF
8616  {
8617  struct rusage usage;
8618  struct timeval time;
8619  if (getrusage(RUSAGE_SELF, &usage) == 0) {
8620  time = usage.ru_utime;
8621  return time.tv_sec + time.tv_usec * 1e-6;
8622  }
8623  }
8624 #endif
8625 
8626 #ifdef _WIN32
8627  {
8628  FILETIME creation_time, exit_time, kernel_time, user_time;
8629  ULARGE_INTEGER ui;
8630  LONG_LONG q;
8631  double t;
8632 
8633  if (GetProcessTimes(GetCurrentProcess(),
8634  &creation_time, &exit_time, &kernel_time, &user_time) != 0) {
8635  memcpy(&ui, &user_time, sizeof(FILETIME));
8636  q = ui.QuadPart / 10L;
8637  t = (DWORD)(q % 1000000L) * 1e-6;
8638  q /= 1000000L;
8639 #ifdef __GNUC__
8640  t += q;
8641 #else
8642  t += (double)(DWORD)(q >> 16) * (1 << 16);
8643  t += (DWORD)q & ~(~0 << 16);
8644 #endif
8645  return t;
8646  }
8647  }
8648 #endif
8649 
8650  return 0.0;
8651 }
8652 
8653 static inline void
8654 gc_prof_setup_new_record(rb_objspace_t *objspace, int reason)
8655 {
8656  if (objspace->profile.run) {
8657  size_t index = objspace->profile.next_index;
8658  gc_profile_record *record;
8659 
8660  /* create new record */
8661  objspace->profile.next_index++;
8662 
8663  if (!objspace->profile.records) {
8665  objspace->profile.records = malloc(sizeof(gc_profile_record) * objspace->profile.size);
8666  }
8667  if (index >= objspace->profile.size) {
8668  void *ptr;
8669  objspace->profile.size += 1000;
8670  ptr = realloc(objspace->profile.records, sizeof(gc_profile_record) * objspace->profile.size);
8671  if (!ptr) rb_memerror();
8672  objspace->profile.records = ptr;
8673  }
8674  if (!objspace->profile.records) {
8675  rb_bug("gc_profile malloc or realloc miss");
8676  }
8677  record = objspace->profile.current_record = &objspace->profile.records[objspace->profile.next_index - 1];
8678  MEMZERO(record, gc_profile_record, 1);
8679 
8680  /* setup before-GC parameter */
8681  record->flags = reason | (ruby_gc_stressful ? GPR_FLAG_STRESS : 0);
8682 #if MALLOC_ALLOCATED_SIZE
8683  record->allocated_size = malloc_allocated_size;
8684 #endif
8685 #if GC_PROFILE_MORE_DETAIL && GC_PROFILE_DETAIL_MEMORY
8686 #ifdef RUSAGE_SELF
8687  {
8688  struct rusage usage;
8689  if (getrusage(RUSAGE_SELF, &usage) == 0) {
8690  record->maxrss = usage.ru_maxrss;
8691  record->minflt = usage.ru_minflt;
8692  record->majflt = usage.ru_majflt;
8693  }
8694  }
8695 #endif
8696 #endif
8697  }
8698 }
8699 
8700 static inline void
8701 gc_prof_timer_start(rb_objspace_t *objspace)
8702 {
8703  if (gc_prof_enabled(objspace)) {
8704  gc_profile_record *record = gc_prof_record(objspace);
8705 #if GC_PROFILE_MORE_DETAIL
8706  record->prepare_time = objspace->profile.prepare_time;
8707 #endif
8708  record->gc_time = 0;
8709  record->gc_invoke_time = getrusage_time();
8710  }
8711 }
8712 
8713 static double
8714 elapsed_time_from(double time)
8715 {
8716  double now = getrusage_time();
8717  if (now > time) {
8718  return now - time;
8719  }
8720  else {
8721  return 0;
8722  }
8723 }
8724 
8725 static inline void
8726 gc_prof_timer_stop(rb_objspace_t *objspace)
8727 {
8728  if (gc_prof_enabled(objspace)) {
8729  gc_profile_record *record = gc_prof_record(objspace);
8730  record->gc_time = elapsed_time_from(record->gc_invoke_time);
8731  record->gc_invoke_time -= objspace->profile.invoke_time;
8732  }
8733 }
8734 
8735 #define RUBY_DTRACE_GC_HOOK(name) \
8736  do {if (RUBY_DTRACE_GC_##name##_ENABLED()) RUBY_DTRACE_GC_##name();} while (0)
8737 static inline void
8738 gc_prof_mark_timer_start(rb_objspace_t *objspace)
8739 {
8740  RUBY_DTRACE_GC_HOOK(MARK_BEGIN);
8741 #if GC_PROFILE_MORE_DETAIL
8742  if (gc_prof_enabled(objspace)) {
8743  gc_prof_record(objspace)->gc_mark_time = getrusage_time();
8744  }
8745 #endif
8746 }
8747 
8748 static inline void
8749 gc_prof_mark_timer_stop(rb_objspace_t *objspace)
8750 {
8751  RUBY_DTRACE_GC_HOOK(MARK_END);
8752 #if GC_PROFILE_MORE_DETAIL
8753  if (gc_prof_enabled(objspace)) {
8754  gc_profile_record *record = gc_prof_record(objspace);
8755  record->gc_mark_time = elapsed_time_from(record->gc_mark_time);
8756  }
8757 #endif
8758 }
8759 
8760 static inline void
8761 gc_prof_sweep_timer_start(rb_objspace_t *objspace)
8762 {
8763  RUBY_DTRACE_GC_HOOK(SWEEP_BEGIN);
8764  if (gc_prof_enabled(objspace)) {
8765  gc_profile_record *record = gc_prof_record(objspace);
8766 
8767  if (record->gc_time > 0 || GC_PROFILE_MORE_DETAIL) {
8768  objspace->profile.gc_sweep_start_time = getrusage_time();
8769  }
8770  }
8771 }
8772 
8773 static inline void
8774 gc_prof_sweep_timer_stop(rb_objspace_t *objspace)
8775 {
8776  RUBY_DTRACE_GC_HOOK(SWEEP_END);
8777 
8778  if (gc_prof_enabled(objspace)) {
8779  double sweep_time;
8780  gc_profile_record *record = gc_prof_record(objspace);
8781 
8782  if (record->gc_time > 0) {
8783  sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
8784  /* need to accumulate GC time for lazy sweep after gc() */
8785  record->gc_time += sweep_time;
8786  }
8787  else if (GC_PROFILE_MORE_DETAIL) {
8788  sweep_time = elapsed_time_from(objspace->profile.gc_sweep_start_time);
8789  }
8790 
8791 #if GC_PROFILE_MORE_DETAIL
8792  record->gc_sweep_time += sweep_time;
8794 #endif
8796  }
8797 }
8798 
8799 static inline void
8800 gc_prof_set_malloc_info(rb_objspace_t *objspace)
8801 {
8802 #if GC_PROFILE_MORE_DETAIL
8803  if (gc_prof_enabled(objspace)) {
8804  gc_profile_record *record = gc_prof_record(objspace);
8805  record->allocate_increase = malloc_increase;
8806  record->allocate_limit = malloc_limit;
8807  }
8808 #endif
8809 }
8810 
8811 static inline void
8812 gc_prof_set_heap_info(rb_objspace_t *objspace)
8813 {
8814  if (gc_prof_enabled(objspace)) {
8815  gc_profile_record *record = gc_prof_record(objspace);
8816  size_t live = objspace->profile.total_allocated_objects_at_gc_start - objspace->profile.total_freed_objects;
8817  size_t total = objspace->profile.heap_used_at_gc_start * HEAP_PAGE_OBJ_LIMIT;
8818 
8819 #if GC_PROFILE_MORE_DETAIL
8820  record->heap_use_pages = objspace->profile.heap_used_at_gc_start;
8821  record->heap_live_objects = live;
8822  record->heap_free_objects = total - live;
8823 #endif
8824 
8825  record->heap_total_objects = total;
8826  record->heap_use_size = live * sizeof(RVALUE);
8827  record->heap_total_size = total * sizeof(RVALUE);
8828  }
8829 }
8830 
8831 /*
8832  * call-seq:
8833  * GC::Profiler.clear -> nil
8834  *
8835  * Clears the GC profiler data.
8836  *
8837  */
8838 
8839 static VALUE
8840 gc_profile_clear(void)
8841 {
8842  rb_objspace_t *objspace = &rb_objspace;
8843  if (GC_PROFILE_RECORD_DEFAULT_SIZE * 2 < objspace->profile.size) {
8845  objspace->profile.records = realloc(objspace->profile.records, sizeof(gc_profile_record) * objspace->profile.size);
8846  if (!objspace->profile.records) {
8847  rb_memerror();
8848  }
8849  }
8850  MEMZERO(objspace->profile.records, gc_profile_record, objspace->profile.size);
8851  objspace->profile.next_index = 0;
8852  objspace->profile.current_record = 0;
8853  return Qnil;
8854 }
8855 
8856 /*
8857  * call-seq:
8858  * GC::Profiler.raw_data -> [Hash, ...]
8859  *
8860  * Returns an Array of individual raw profile data Hashes ordered
8861  * from earliest to latest by +:GC_INVOKE_TIME+.
8862  *
8863  * For example:
8864  *
8865  * [
8866  * {
8867  * :GC_TIME=>1.3000000000000858e-05,
8868  * :GC_INVOKE_TIME=>0.010634999999999999,
8869  * :HEAP_USE_SIZE=>289640,
8870  * :HEAP_TOTAL_SIZE=>588960,
8871  * :HEAP_TOTAL_OBJECTS=>14724,
8872  * :GC_IS_MARKED=>false
8873  * },
8874  * # ...
8875  * ]
8876  *
8877  * The keys mean:
8878  *
8879  * +:GC_TIME+::
8880  * Time elapsed in seconds for this GC run
8881  * +:GC_INVOKE_TIME+::
8882  * Time elapsed in seconds from startup to when the GC was invoked
8883  * +:HEAP_USE_SIZE+::
8884  * Total bytes of heap used
8885  * +:HEAP_TOTAL_SIZE+::
8886  * Total size of heap in bytes
8887  * +:HEAP_TOTAL_OBJECTS+::
8888  * Total number of objects
8889  * +:GC_IS_MARKED+::
8890  * Returns +true+ if the GC is in mark phase
8891  *
8892  * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access
8893  * to the following hash keys:
8894  *
8895  * +:GC_MARK_TIME+::
8896  * +:GC_SWEEP_TIME+::
8897  * +:ALLOCATE_INCREASE+::
8898  * +:ALLOCATE_LIMIT+::
8899  * +:HEAP_USE_PAGES+::
8900  * +:HEAP_LIVE_OBJECTS+::
8901  * +:HEAP_FREE_OBJECTS+::
8902  * +:HAVE_FINALIZE+::
8903  *
8904  */
8905 
8906 static VALUE
8907 gc_profile_record_get(void)
8908 {
8909  VALUE prof;
8910  VALUE gc_profile = rb_ary_new();
8911  size_t i;
8912  rb_objspace_t *objspace = (&rb_objspace);
8913 
8914  if (!objspace->profile.run) {
8915  return Qnil;
8916  }
8917 
8918  for (i =0; i < objspace->profile.next_index; i++) {
8919  gc_profile_record *record = &objspace->profile.records[i];
8920 
8921  prof = rb_hash_new();
8922  rb_hash_aset(prof, ID2SYM(rb_intern("GC_FLAGS")), gc_info_decode(0, rb_hash_new(), record->flags));
8923  rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(record->gc_time));
8924  rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(record->gc_invoke_time));
8925  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(record->heap_use_size));
8926  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(record->heap_total_size));
8927  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(record->heap_total_objects));
8928  rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), Qtrue);
8929 #if GC_PROFILE_MORE_DETAIL
8930  rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(record->gc_mark_time));
8931  rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(record->gc_sweep_time));
8932  rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(record->allocate_increase));
8933  rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(record->allocate_limit));
8934  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_PAGES")), SIZET2NUM(record->heap_use_pages));
8935  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(record->heap_live_objects));
8936  rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(record->heap_free_objects));
8937 
8938  rb_hash_aset(prof, ID2SYM(rb_intern("REMOVING_OBJECTS")), SIZET2NUM(record->removing_objects));
8939  rb_hash_aset(prof, ID2SYM(rb_intern("EMPTY_OBJECTS")), SIZET2NUM(record->empty_objects));
8940 
8941  rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), (record->flags & GPR_FLAG_HAVE_FINALIZE) ? Qtrue : Qfalse);
8942 #endif
8943 
8944 #if RGENGC_PROFILE > 0
8945  rb_hash_aset(prof, ID2SYM(rb_intern("OLD_OBJECTS")), SIZET2NUM(record->old_objects));
8946  rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_NORMAL_OBJECTS")), SIZET2NUM(record->remembered_normal_objects));
8947  rb_hash_aset(prof, ID2SYM(rb_intern("REMEMBERED_SHADY_OBJECTS")), SIZET2NUM(record->remembered_shady_objects));
8948 #endif
8949  rb_ary_push(gc_profile, prof);
8950  }
8951 
8952  return gc_profile;
8953 }
8954 
8955 #if GC_PROFILE_MORE_DETAIL
8956 #define MAJOR_REASON_MAX 0x10
8957 
8958 static char *
8959 gc_profile_dump_major_reason(int flags, char *buff)
8960 {
8961  int reason = flags & GPR_FLAG_MAJOR_MASK;
8962  int i = 0;
8963 
8964  if (reason == GPR_FLAG_NONE) {
8965  buff[0] = '-';
8966  buff[1] = 0;
8967  }
8968  else {
8969 #define C(x, s) \
8970  if (reason & GPR_FLAG_MAJOR_BY_##x) { \
8971  buff[i++] = #x[0]; \
8972  if (i >= MAJOR_REASON_MAX) rb_bug("gc_profile_dump_major_reason: overflow"); \
8973  buff[i] = 0; \
8974  }
8975  C(NOFREE, N);
8976  C(OLDGEN, O);
8977  C(SHADY, S);
8978 #if RGENGC_ESTIMATE_OLDMALLOC
8979  C(OLDMALLOC, M);
8980 #endif
8981 #undef C
8982  }
8983  return buff;
8984 }
8985 #endif
8986 
8987 static void
8988 gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE))
8989 {
8990  rb_objspace_t *objspace = &rb_objspace;
8991  size_t count = objspace->profile.next_index;
8992 #ifdef MAJOR_REASON_MAX
8993  char reason_str[MAJOR_REASON_MAX];
8994 #endif
8995 
8996  if (objspace->profile.run && count /* > 1 */) {
8997  size_t i;
8998  const gc_profile_record *record;
8999 
9000  append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->profile.count));
9001  append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n"));
9002 
9003  for (i = 0; i < count; i++) {
9004  record = &objspace->profile.records[i];
9005  append(out, rb_sprintf("%5"PRIuSIZE" %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n",
9006  i+1, record->gc_invoke_time, record->heap_use_size,
9007  record->heap_total_size, record->heap_total_objects, record->gc_time*1000));
9008  }
9009 
9010 #if GC_PROFILE_MORE_DETAIL
9011  append(out, rb_str_new_cstr("\n\n" \
9012  "More detail.\n" \
9013  "Prepare Time = Previously GC's rest sweep time\n"
9014  "Index Flags Allocate Inc. Allocate Limit"
9016  " Allocated Size"
9017 #endif
9018  " Use Page Mark Time(ms) Sweep Time(ms) Prepare Time(ms) LivingObj FreeObj RemovedObj EmptyObj"
9019 #if RGENGC_PROFILE
9020  " OldgenObj RemNormObj RemShadObj"
9021 #endif
9023  " MaxRSS(KB) MinorFLT MajorFLT"
9024 #endif
9025  "\n"));
9026 
9027  for (i = 0; i < count; i++) {
9028  record = &objspace->profile.records[i];
9029  append(out, rb_sprintf("%5"PRIuSIZE" %4s/%c/%6s%c %13"PRIuSIZE" %15"PRIuSIZE
9031  " %15"PRIuSIZE
9032 #endif
9033  " %9"PRIuSIZE" %17.12f %17.12f %17.12f %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
9034 #if RGENGC_PROFILE
9035  "%10"PRIuSIZE" %10"PRIuSIZE" %10"PRIuSIZE
9036 #endif
9038  "%11ld %8ld %8ld"
9039 #endif
9040 
9041  "\n",
9042  i+1,
9043  gc_profile_dump_major_reason(record->flags, reason_str),
9044  (record->flags & GPR_FLAG_HAVE_FINALIZE) ? 'F' : '.',
9045  (record->flags & GPR_FLAG_NEWOBJ) ? "NEWOBJ" :
9046  (record->flags & GPR_FLAG_MALLOC) ? "MALLOC" :
9047  (record->flags & GPR_FLAG_METHOD) ? "METHOD" :
9048  (record->flags & GPR_FLAG_CAPI) ? "CAPI__" : "??????",
9049  (record->flags & GPR_FLAG_STRESS) ? '!' : ' ',
9050  record->allocate_increase, record->allocate_limit,
9052  record->allocated_size,
9053 #endif
9054  record->heap_use_pages,
9055  record->gc_mark_time*1000,
9056  record->gc_sweep_time*1000,
9057  record->prepare_time*1000,
9058 
9059  record->heap_live_objects,
9060  record->heap_free_objects,
9061  record->removing_objects,
9062  record->empty_objects
9063 #if RGENGC_PROFILE
9064  ,
9065  record->old_objects,
9066  record->remembered_normal_objects,
9067  record->remembered_shady_objects
9068 #endif
9070  ,
9071  record->maxrss / 1024,
9072  record->minflt,
9073  record->majflt
9074 #endif
9075 
9076  ));
9077  }
9078 #endif
9079  }
9080 }
9081 
9082 /*
9083  * call-seq:
9084  * GC::Profiler.result -> String
9085  *
9086  * Returns a profile data report such as:
9087  *
9088  * GC 1 invokes.
9089  * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms)
9090  * 1 0.012 159240 212940 10647 0.00000000000001530000
9091  */
9092 
9093 static VALUE
9094 gc_profile_result(void)
9095 {
9096  VALUE str = rb_str_buf_new(0);
9097  gc_profile_dump_on(str, rb_str_buf_append);
9098  return str;
9099 }
9100 
9101 /*
9102  * call-seq:
9103  * GC::Profiler.report
9104  * GC::Profiler.report(io)
9105  *
9106  * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object.
9107  *
9108  */
9109 
9110 static VALUE
9111 gc_profile_report(int argc, VALUE *argv, VALUE self)
9112 {
9113  VALUE out;
9114 
9115  if (argc == 0) {
9116  out = rb_stdout;
9117  }
9118  else {
9119  rb_scan_args(argc, argv, "01", &out);
9120  }
9121  gc_profile_dump_on(out, rb_io_write);
9122 
9123  return Qnil;
9124 }
9125 
9126 /*
9127  * call-seq:
9128  * GC::Profiler.total_time -> float
9129  *
9130  * The total time used for garbage collection in seconds
9131  */
9132 
9133 static VALUE
9134 gc_profile_total_time(VALUE self)
9135 {
9136  double time = 0;
9137  rb_objspace_t *objspace = &rb_objspace;
9138 
9139  if (objspace->profile.run && objspace->profile.next_index > 0) {
9140  size_t i;
9141  size_t count = objspace->profile.next_index;
9142 
9143  for (i = 0; i < count; i++) {
9144  time += objspace->profile.records[i].gc_time;
9145  }
9146  }
9147  return DBL2NUM(time);
9148 }
9149 
9150 /*
9151  * call-seq:
9152  * GC::Profiler.enabled? -> true or false
9153  *
9154  * The current status of GC profile mode.
9155  */
9156 
9157 static VALUE
9158 gc_profile_enable_get(VALUE self)
9159 {
9160  rb_objspace_t *objspace = &rb_objspace;
9161  return objspace->profile.run ? Qtrue : Qfalse;
9162 }
9163 
9164 /*
9165  * call-seq:
9166  * GC::Profiler.enable -> nil
9167  *
9168  * Starts the GC profiler.
9169  *
9170  */
9171 
9172 static VALUE
9173 gc_profile_enable(void)
9174 {
9175  rb_objspace_t *objspace = &rb_objspace;
9176  objspace->profile.run = TRUE;
9177  objspace->profile.current_record = 0;
9178  return Qnil;
9179 }
9180 
9181 /*
9182  * call-seq:
9183  * GC::Profiler.disable -> nil
9184  *
9185  * Stops the GC profiler.
9186  *
9187  */
9188 
9189 static VALUE
9190 gc_profile_disable(void)
9191 {
9192  rb_objspace_t *objspace = &rb_objspace;
9193 
9194  objspace->profile.run = FALSE;
9195  objspace->profile.current_record = 0;
9196  return Qnil;
9197 }
9198 
9199 /*
9200  ------------------------------ DEBUG ------------------------------
9201 */
9202 
9203 static const char *
9204 type_name(int type, VALUE obj)
9205 {
9206  switch (type) {
9207 #define TYPE_NAME(t) case (t): return #t;
9208  TYPE_NAME(T_NONE);
9210  TYPE_NAME(T_CLASS);
9212  TYPE_NAME(T_FLOAT);
9215  TYPE_NAME(T_ARRAY);
9216  TYPE_NAME(T_HASH);
9219  TYPE_NAME(T_FILE);
9220  TYPE_NAME(T_MATCH);
9223  TYPE_NAME(T_NIL);
9224  TYPE_NAME(T_TRUE);
9225  TYPE_NAME(T_FALSE);
9228  TYPE_NAME(T_UNDEF);
9229  TYPE_NAME(T_IMEMO);
9230  TYPE_NAME(T_NODE);
9233  case T_DATA:
9234  if (obj && rb_objspace_data_type_name(obj)) {
9235  return rb_objspace_data_type_name(obj);
9236  }
9237  return "T_DATA";
9238 #undef TYPE_NAME
9239  }
9240  return "unknown";
9241 }
9242 
9243 static const char *
9244 obj_type_name(VALUE obj)
9245 {
9246  return type_name(TYPE(obj), obj);
9247 }
9248 
9249 static const char *
9250 method_type_name(rb_method_type_t type)
9251 {
9252  switch (type) {
9253  case VM_METHOD_TYPE_ISEQ: return "iseq";
9254  case VM_METHOD_TYPE_ATTRSET: return "attrest";
9255  case VM_METHOD_TYPE_IVAR: return "ivar";
9256  case VM_METHOD_TYPE_BMETHOD: return "bmethod";
9257  case VM_METHOD_TYPE_ALIAS: return "alias";
9258  case VM_METHOD_TYPE_REFINED: return "refined";
9259  case VM_METHOD_TYPE_CFUNC: return "cfunc";
9260  case VM_METHOD_TYPE_ZSUPER: return "zsuper";
9261  case VM_METHOD_TYPE_MISSING: return "missing";
9262  case VM_METHOD_TYPE_OPTIMIZED: return "optimized";
9263  case VM_METHOD_TYPE_UNDEF: return "undef";
9264  case VM_METHOD_TYPE_NOTIMPLEMENTED: return "notimplemented";
9265  }
9266  rb_bug("method_type_name: unreachable (type: %d)", type);
9267 }
9268 
9269 /* from array.c */
9270 # define ARY_SHARED_P(ary) \
9271  (GC_ASSERT(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
9272  FL_TEST((ary),ELTS_SHARED)!=0)
9273 # define ARY_EMBED_P(ary) \
9274  (GC_ASSERT(!FL_TEST((ary), ELTS_SHARED) || !FL_TEST((ary), RARRAY_EMBED_FLAG)), \
9275  FL_TEST((ary), RARRAY_EMBED_FLAG)!=0)
9276 
9277 static void
9278 rb_raw_iseq_info(char *buff, const int buff_size, const rb_iseq_t *iseq)
9279 {
9280  if (iseq->body->location.label) {
9281  VALUE path = rb_iseq_path(iseq);
9282  snprintf(buff, buff_size, "%s %s@%s:%d", buff,
9283  RSTRING_PTR(iseq->body->location.label),
9284  RSTRING_PTR(path),
9285  FIX2INT(iseq->body->location.first_lineno));
9286  }
9287 }
9288 
9289 const char *
9290 rb_raw_obj_info(char *buff, const int buff_size, VALUE obj)
9291 {
9292  if (SPECIAL_CONST_P(obj)) {
9293  snprintf(buff, buff_size, "%s", obj_type_name(obj));
9294  }
9295  else {
9296 #define TF(c) ((c) != 0 ? "true" : "false")
9297 #define C(c, s) ((c) != 0 ? (s) : " ")
9298  const int type = BUILTIN_TYPE(obj);
9299 #if USE_RGENGC
9300  const int age = RVALUE_FLAGS_AGE(RBASIC(obj)->flags);
9301 
9302  snprintf(buff, buff_size, "%p [%d%s%s%s%s] %s",
9303  (void *)obj, age,
9304  C(RVALUE_UNCOLLECTIBLE_BITMAP(obj), "L"),
9305  C(RVALUE_MARK_BITMAP(obj), "M"),
9306  C(RVALUE_MARKING_BITMAP(obj), "R"),
9307  C(RVALUE_WB_UNPROTECTED_BITMAP(obj), "U"),
9308  obj_type_name(obj));
9309 #else
9310  snprintf(buff, buff_size, "%p [%s] %s",
9311  (void *)obj,
9312  C(RVALUE_MARK_BITMAP(obj), "M"),
9313  obj_type_name(obj));
9314 #endif
9315 
9316  if (internal_object_p(obj)) {
9317  /* ignore */
9318  }
9319  else if (RBASIC(obj)->klass == 0) {
9320  snprintf(buff, buff_size, "%s (temporary internal)", buff);
9321  }
9322  else {
9323  VALUE class_path = rb_class_path_cached(RBASIC(obj)->klass);
9324  if (!NIL_P(class_path)) {
9325  snprintf(buff, buff_size, "%s (%s)", buff, RSTRING_PTR(class_path));
9326  }
9327  }
9328 
9329 #if GC_DEBUG
9330  snprintf(buff, buff_size, "%s @%s:%d", buff, RANY(obj)->file, RANY(obj)->line);
9331 #endif
9332 
9333  switch (type) {
9334  case T_NODE:
9335  snprintf(buff, buff_size, "%s (%s)", buff,
9336  ruby_node_name(nd_type(obj)));
9337  break;
9338  case T_ARRAY:
9339  snprintf(buff, buff_size, "%s [%s%s] len: %d", buff,
9340  C(ARY_EMBED_P(obj), "E"),
9341  C(ARY_SHARED_P(obj), "S"),
9342  (int)RARRAY_LEN(obj));
9343  break;
9344  case T_STRING: {
9345  snprintf(buff, buff_size, "%s %s", buff, RSTRING_PTR(obj));
9346  break;
9347  }
9348  case T_CLASS: {
9349  VALUE class_path = rb_class_path_cached(obj);
9350  if (!NIL_P(class_path)) {
9351  snprintf(buff, buff_size, "%s %s", buff, RSTRING_PTR(class_path));
9352  }
9353  break;
9354  }
9355  case T_DATA: {
9356  const rb_iseq_t *iseq;
9357  if (rb_obj_is_proc(obj) && (iseq = vm_proc_iseq(obj)) != NULL) {
9358  rb_raw_iseq_info(buff, buff_size, iseq);
9359  }
9360  else {
9361  const char * const type_name = rb_objspace_data_type_name(obj);
9362  if (type_name) {
9363  snprintf(buff, buff_size, "%s %s", buff, type_name);
9364  }
9365  }
9366  break;
9367  }
9368  case T_IMEMO: {
9369  const char *imemo_name;
9370  switch (imemo_type(obj)) {
9371 #define IMEMO_NAME(x) case imemo_##x: imemo_name = #x; break;
9372  IMEMO_NAME(env);
9373  IMEMO_NAME(cref);
9374  IMEMO_NAME(svar);
9375  IMEMO_NAME(throw_data);
9376  IMEMO_NAME(ifunc);
9377  IMEMO_NAME(memo);
9378  IMEMO_NAME(ment);
9379  IMEMO_NAME(iseq);
9380  IMEMO_NAME(alloc);
9381 #undef IMEMO_NAME
9382  default: UNREACHABLE;
9383  }
9384  snprintf(buff, buff_size, "%s %s", buff, imemo_name);
9385 
9386  switch (imemo_type(obj)) {
9387  case imemo_ment: {
9388  const rb_method_entry_t *me = &RANY(obj)->as.imemo.ment;
9389  snprintf(buff, buff_size, "%s (called_id: %s, type: %s, alias: %d, owner: %s, defined_class: %s)", buff,
9390  rb_id2name(me->called_id),
9391  method_type_name(me->def->type),
9392  me->def->alias_count,
9393  obj_info(me->owner),
9394  obj_info(me->defined_class));
9395  break;
9396  }
9397  case imemo_iseq: {
9398  const rb_iseq_t *iseq = (const rb_iseq_t *)obj;
9399  rb_raw_iseq_info(buff, buff_size, iseq);
9400  break;
9401  }
9402  default:
9403  break;
9404  }
9405  }
9406  default:
9407  break;
9408  }
9409 #undef TF
9410 #undef C
9411  }
9412  return buff;
9413 }
9414 
9415 #if RGENGC_OBJ_INFO
9416 #define OBJ_INFO_BUFFERS_NUM 10
9417 #define OBJ_INFO_BUFFERS_SIZE 0x100
9418 static int obj_info_buffers_index = 0;
9419 static char obj_info_buffers[OBJ_INFO_BUFFERS_NUM][OBJ_INFO_BUFFERS_SIZE];
9420 
9421 static const char *
9422 obj_info(VALUE obj)
9423 {
9424  const int index = obj_info_buffers_index++;
9425  char *const buff = &obj_info_buffers[index][0];
9426 
9427  if (obj_info_buffers_index >= OBJ_INFO_BUFFERS_NUM) {
9428  obj_info_buffers_index = 0;
9429  }
9430 
9431  return rb_raw_obj_info(buff, OBJ_INFO_BUFFERS_SIZE, obj);
9432 }
9433 #else
9434 static const char *
9435 obj_info(VALUE obj)
9436 {
9437  return obj_type_name(obj);
9438 }
9439 #endif
9440 
9441 const char *
9443 {
9444  if (!rb_special_const_p(obj)) {
9445  return obj_info(obj);
9446  }
9447  else {
9448  return obj_type_name(obj);
9449  }
9450 }
9451 
9452 void
9454 {
9455  char buff[0x100];
9456  fprintf(stderr, "rb_obj_info_dump: %s\n", rb_raw_obj_info(buff, 0x100, obj));
9457 }
9458 
9459 #if GC_DEBUG
9460 
9461 void
9463 {
9464  rb_objspace_t *objspace = &rb_objspace;
9465 
9466  fprintf(stderr, "created at: %s:%d\n", RANY(obj)->file, RANY(obj)->line);
9467 
9468  if (is_pointer_to_heap(objspace, (void *)obj)) {
9469  fprintf(stderr, "pointer to heap?: true\n");
9470  }
9471  else {
9472  fprintf(stderr, "pointer to heap?: false\n");
9473  return;
9474  }
9475 
9476  fprintf(stderr, "marked? : %s\n", MARKED_IN_BITMAP(GET_HEAP_MARK_BITS(obj), obj) ? "true" : "false");
9477 #if USE_RGENGC
9478  fprintf(stderr, "age? : %d\n", RVALUE_AGE(obj));
9479  fprintf(stderr, "old? : %s\n", RVALUE_OLD_P(obj) ? "true" : "false");
9480  fprintf(stderr, "WB-protected?: %s\n", RVALUE_WB_UNPROTECTED(obj) ? "false" : "true");
9481  fprintf(stderr, "remembered? : %s\n", RVALUE_REMEMBERED(obj) ? "true" : "false");
9482 #endif
9483 
9484  if (is_lazy_sweeping(heap_eden)) {
9485  fprintf(stderr, "lazy sweeping?: true\n");
9486  fprintf(stderr, "swept?: %s\n", is_swept_object(objspace, obj) ? "done" : "not yet");
9487  }
9488  else {
9489  fprintf(stderr, "lazy sweeping?: false\n");
9490  }
9491 }
9492 
9493 static VALUE
9494 gcdebug_sentinel(VALUE obj, VALUE name)
9495 {
9496  fprintf(stderr, "WARNING: object %s(%p) is inadvertently collected\n", (char *)name, (void *)obj);
9497  return Qnil;
9498 }
9499 
9500 void
9501 rb_gcdebug_sentinel(VALUE obj, const char *name)
9502 {
9503  rb_define_finalizer(obj, rb_proc_new(gcdebug_sentinel, (VALUE)name));
9504 }
9505 
9506 #endif /* GC_DEBUG */
9507 
9508 #if GC_DEBUG_STRESS_TO_CLASS
9509 static VALUE
9510 rb_gcdebug_add_stress_to_class(int argc, VALUE *argv, VALUE self)
9511 {
9512  rb_objspace_t *objspace = &rb_objspace;
9513 
9514  if (!stress_to_class) {
9516  }
9517  rb_ary_cat(stress_to_class, argv, argc);
9518  return self;
9519 }
9520 
9521 static VALUE
9522 rb_gcdebug_remove_stress_to_class(int argc, VALUE *argv, VALUE self)
9523 {
9524  rb_objspace_t *objspace = &rb_objspace;
9525  int i;
9526 
9527  if (stress_to_class) {
9528  for (i = 0; i < argc; ++i) {
9530  }
9531  if (RARRAY_LEN(stress_to_class) == 0) {
9532  stress_to_class = 0;
9533  }
9534  }
9535  return Qnil;
9536 }
9537 #endif
9538 
9539 /*
9540  * Document-module: ObjectSpace
9541  *
9542  * The ObjectSpace module contains a number of routines
9543  * that interact with the garbage collection facility and allow you to
9544  * traverse all living objects with an iterator.
9545  *
9546  * ObjectSpace also provides support for object finalizers, procs that will be
9547  * called when a specific object is about to be destroyed by garbage
9548  * collection.
9549  *
9550  * require 'objspace'
9551  *
9552  * a = "A"
9553  * b = "B"
9554  *
9555  * ObjectSpace.define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" })
9556  * ObjectSpace.define_finalizer(b, proc {|id| puts "Finalizer two on #{id}" })
9557  *
9558  * _produces:_
9559  *
9560  * Finalizer two on 537763470
9561  * Finalizer one on 537763480
9562  */
9563 
9564 /*
9565  * Document-class: ObjectSpace::WeakMap
9566  *
9567  * An ObjectSpace::WeakMap object holds references to
9568  * any objects, but those objects can get garbage collected.
9569  *
9570  * This class is mostly used internally by WeakRef, please use
9571  * +lib/weakref.rb+ for the public interface.
9572  */
9573 
9574 /* Document-class: GC::Profiler
9575  *
9576  * The GC profiler provides access to information on GC runs including time,
9577  * length and object space size.
9578  *
9579  * Example:
9580  *
9581  * GC::Profiler.enable
9582  *
9583  * require 'rdoc/rdoc'
9584  *
9585  * GC::Profiler.report
9586  *
9587  * GC::Profiler.disable
9588  *
9589  * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations
9590  */
9591 
9592 /*
9593  * The GC module provides an interface to Ruby's mark and
9594  * sweep garbage collection mechanism.
9595  *
9596  * Some of the underlying methods are also available via the ObjectSpace
9597  * module.
9598  *
9599  * You may obtain information about the operation of the GC through
9600  * GC::Profiler.
9601  */
9602 
9603 void
9604 Init_GC(void)
9605 {
9606 #undef rb_intern
9607  VALUE rb_mObjSpace;
9608  VALUE rb_mProfiler;
9609  VALUE gc_constants;
9610 
9611  rb_mGC = rb_define_module("GC");
9612  rb_define_singleton_method(rb_mGC, "start", gc_start_internal, -1);
9613  rb_define_singleton_method(rb_mGC, "enable", rb_gc_enable, 0);
9614  rb_define_singleton_method(rb_mGC, "disable", rb_gc_disable, 0);
9615  rb_define_singleton_method(rb_mGC, "stress", gc_stress_get, 0);
9616  rb_define_singleton_method(rb_mGC, "stress=", gc_stress_set_m, 1);
9617  rb_define_singleton_method(rb_mGC, "count", gc_count, 0);
9618  rb_define_singleton_method(rb_mGC, "stat", gc_stat, -1);
9619  rb_define_singleton_method(rb_mGC, "latest_gc_info", gc_latest_gc_info, -1);
9620  rb_define_method(rb_mGC, "garbage_collect", gc_start_internal, -1);
9621 
9622  gc_constants = rb_hash_new();
9623  rb_hash_aset(gc_constants, ID2SYM(rb_intern("RVALUE_SIZE")), SIZET2NUM(sizeof(RVALUE)));
9624  rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_OBJ_LIMIT")), SIZET2NUM(HEAP_PAGE_OBJ_LIMIT));
9625  rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_SIZE")), SIZET2NUM(HEAP_PAGE_BITMAP_SIZE));
9626  rb_hash_aset(gc_constants, ID2SYM(rb_intern("HEAP_PAGE_BITMAP_PLANES")), SIZET2NUM(HEAP_PAGE_BITMAP_PLANES));
9627  OBJ_FREEZE(gc_constants);
9628  rb_define_const(rb_mGC, "INTERNAL_CONSTANTS", gc_constants);
9629 
9630  rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler");
9631  rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0);
9632  rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0);
9633  rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, 0);
9634  rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0);
9635  rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0);
9636  rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0);
9637  rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1);
9638  rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0);
9639 
9640  rb_mObjSpace = rb_define_module("ObjectSpace");
9641  rb_define_module_function(rb_mObjSpace, "each_object", os_each_obj, -1);
9642  rb_define_module_function(rb_mObjSpace, "garbage_collect", gc_start_internal, -1);
9643 
9644  rb_define_module_function(rb_mObjSpace, "define_finalizer", define_final, -1);
9645  rb_define_module_function(rb_mObjSpace, "undefine_finalizer", undefine_final, 1);
9646 
9647  rb_define_module_function(rb_mObjSpace, "_id2ref", id2ref, 1);
9648 
9650 
9652  rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0);
9653 
9654  rb_define_module_function(rb_mObjSpace, "count_objects", count_objects, -1);
9655 
9656  {
9657  VALUE rb_cWeakMap = rb_define_class_under(rb_mObjSpace, "WeakMap", rb_cObject);
9658  rb_define_alloc_func(rb_cWeakMap, wmap_allocate);
9659  rb_define_method(rb_cWeakMap, "[]=", wmap_aset, 2);
9660  rb_define_method(rb_cWeakMap, "[]", wmap_aref, 1);
9661  rb_define_method(rb_cWeakMap, "include?", wmap_has_key, 1);
9662  rb_define_method(rb_cWeakMap, "member?", wmap_has_key, 1);
9663  rb_define_method(rb_cWeakMap, "key?", wmap_has_key, 1);
9664  rb_define_method(rb_cWeakMap, "inspect", wmap_inspect, 0);
9665  rb_define_method(rb_cWeakMap, "each", wmap_each, 0);
9666  rb_define_method(rb_cWeakMap, "each_pair", wmap_each, 0);
9667  rb_define_method(rb_cWeakMap, "each_key", wmap_each_key, 0);
9668  rb_define_method(rb_cWeakMap, "each_value", wmap_each_value, 0);
9669  rb_define_method(rb_cWeakMap, "keys", wmap_keys, 0);
9670  rb_define_method(rb_cWeakMap, "values", wmap_values, 0);
9671  rb_define_method(rb_cWeakMap, "size", wmap_size, 0);
9672  rb_define_method(rb_cWeakMap, "length", wmap_size, 0);
9673  rb_define_private_method(rb_cWeakMap, "finalize", wmap_finalize, 1);
9674  rb_include_module(rb_cWeakMap, rb_mEnumerable);
9675  }
9676 
9677  /* internal methods */
9678  rb_define_singleton_method(rb_mGC, "verify_internal_consistency", gc_verify_internal_consistency, 0);
9679 #if MALLOC_ALLOCATED_SIZE
9680  rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0);
9681  rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0);
9682 #endif
9683 
9684 #if GC_DEBUG_STRESS_TO_CLASS
9685  rb_define_singleton_method(rb_mGC, "add_stress_to_class", rb_gcdebug_add_stress_to_class, -1);
9686  rb_define_singleton_method(rb_mGC, "remove_stress_to_class", rb_gcdebug_remove_stress_to_class, -1);
9687 #endif
9688 
9689  /* ::GC::OPTS, which shows GC build options */
9690  {
9691  VALUE opts;
9692  rb_define_const(rb_mGC, "OPTS", opts = rb_ary_new());
9693 #define OPT(o) if (o) rb_ary_push(opts, rb_fstring_lit(#o))
9694  OPT(GC_DEBUG);
9695  OPT(USE_RGENGC);
9696  OPT(RGENGC_DEBUG);
9706 #undef OPT
9707  OBJ_FREEZE(opts);
9708  }
9709 }
struct RString::@67::@68 heap
#define ELTS_SHARED
Definition: ruby.h:937
VALUE of
Definition: gc.c:2521
rb_event_flag_t hook_events
Definition: gc.c:544
#define rb_objspace
Definition: gc.c:729
#define RBASIC_CLEAR_CLASS(obj)
Definition: internal.h:1469
VALUE value
Definition: gc.c:8349
int rb_objspace_marked_object_p(VALUE obj)
Definition: gc.c:4474
void rb_gc(void)
Definition: gc.c:6727
void rb_gc_finalize_deferred(void)
Definition: gc.c:2876
void rb_class_remove_from_super_subclasses(VALUE klass)
Definition: class.c:76
struct RNode node
Definition: gc.c:429
#define T_SYMBOL
Definition: ruby.h:508
size_t heap_total_objects
Definition: gc.c:371
#define T_OBJECT
Definition: ruby.h:491
size_t step_slots
Definition: gc.c:650
size_t marked_slots
Definition: gc.c:560
void(* RUBY_DATA_FUNC)(void *)
Definition: ruby.h:1115
wrapper for method_missing(id)
Definition: method.h:112
const VALUE num
Definition: internal.h:626
Definition: re.h:44
Definition: st.h:99
VALUE rb_ary_last(int argc, const VALUE *argv, VALUE ary)
Definition: array.c:1380
rb_vm_t * vm
Definition: vm_core.h:788
void rb_class_detach_subclasses(VALUE klass)
Definition: class.c:133
void rb_free_const_table(struct rb_id_table *tbl)
Definition: gc.c:2140
void * data
Definition: gc.c:823
void rb_warn(const char *fmt,...)
Definition: error.c:246
#define FL_EXIVAR
Definition: ruby.h:1215
VALUE regexp
Definition: re.h:48
void rb_bug(const char *fmt,...)
Definition: error.c:521
struct heap_page * pooled_pages
Definition: gc.c:506
void rb_gc_writebarrier(VALUE a, VALUE b)
Definition: gc.c:5984
#define RARRAY_LEN(a)
Definition: ruby.h:1019
#define heap_pages_final_slots
Definition: gc.c:750
#define FALSE
Definition: nkf.h:174
ruby_tag_type
Definition: vm_core.h:151
#define RUBY_TYPED_FREE_IMMEDIATELY
Definition: ruby.h:1138
#define GC_PROFILE_MORE_DETAIL
Definition: gc.c:308
double heap_free_slots_min_ratio
Definition: gc.c:170
VALUE deferred_final
Definition: gc.c:572
#define STACK_START
Definition: gc.c:3982
VALUE rb_obj_id(VALUE obj)
Definition: gc.c:3158
#define SSIZE_MAX
Definition: ruby.h:292
size_t strlen(const char *)
gc_profile_record_flag
Definition: gc.c:341
#define roomof(x, y)
Definition: internal.h:965
#define INT2NUM(x)
Definition: ruby.h:1538
#define has_sweeping_pages(heap)
Definition: gc.c:803
RVALUE * start
Definition: gc.c:690
void rb_objspace_free(rb_objspace_t *objspace)
Definition: gc.c:1343
int need_major_gc
Definition: gc.c:630
iterator function
Definition: internal.h:843
#define RCLASS_CONST_TBL(c)
Definition: internal.h:790
Definition: constant.h:31
#define is_marking(objspace)
Definition: gc.c:786
size_t uncollectible_wb_unprotected_objects_limit
Definition: gc.c:633
#define T_FIXNUM
Definition: ruby.h:503
Definition: st.h:79
#define RUBY_DEFAULT_FREE
Definition: ruby.h:1132
void rb_gc_free_dsymbol(VALUE)
Definition: symbol.c:629
#define IMEMO_NAME(x)
size_t num
Definition: gc.c:2520
Definition: st.h:99
size_t total_pages
Definition: gc.c:508
#define BIGNUM_DIGITS(b)
Definition: internal.h:616
#define T_MATCH
Definition: ruby.h:507
double gc_sweep_start_time
Definition: gc.c:613
size_t unused_cache_size
Definition: gc.c:495
#define RSTRUCT_CONST_PTR(st)
Definition: internal.h:710
struct heap_page::@63 flags
VALUE rb_yield_values(int n,...)
Definition: vm_eval.c:985
struct RBasic basic
Definition: gc.c:820
int count
Definition: encoding.c:56
struct RFile file
Definition: gc.c:428
rb_control_frame_t * cfp
Definition: vm_core.h:744
short final_slots
Definition: gc.c:681
void rb_define_singleton_method(VALUE obj, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a singleton method for obj.
Definition: class.c:1716
#define FIXNUM_FLAG
Definition: ruby.h:441
int rb_threadptr_stack_check(rb_thread_t *th)
Definition: gc.c:4047
void * ruby_sized_xrealloc2(void *ptr, size_t n, size_t size, size_t old_n)
Definition: gc.c:8058
#define TAG_NONE
Definition: vm_core.h:164
size_t size
Definition: gc.c:583
#define GC_HEAP_GROWTH_FACTOR
Definition: gc.c:112
#define FL_USHIFT
Definition: ruby.h:1218
#define RVALUE_AGE_SHIFT
Definition: gc.c:1047
int run
Definition: gc.c:578
int immediate_sweep
Definition: gc.c:6514
VALUE rb_data_typed_object_wrap(VALUE klass, void *datap, const rb_data_type_t *type)
Definition: gc.c:2058
size_t ruby_stack_length(VALUE **p)
Definition: gc.c:4008
#define FLUSH_REGISTER_WINDOWS
Definition: defines.h:296
size_t old_objects_limit
Definition: gc.c:635
#define malloc_allocated_size
Definition: gc.c:742
#define CLASS_OF(v)
Definition: ruby.h:453
void rb_gc_free_node(VALUE obj)
Definition: node.c:1062
#define GC_HEAP_OLDOBJECT_LIMIT_FACTOR
Definition: gc.c:118
void rb_raise(VALUE exc, const char *fmt,...)
Definition: error.c:2284
#define T_MODULE
Definition: ruby.h:494
const VALUE file
Definition: constant.h:35
#define RCLASS_EXT(c)
Definition: classext.h:15
#define N
Definition: lgamma_r.c:20
void rb_class_remove_from_module_subclasses(VALUE klass)
Definition: class.c:94
#define st_foreach
Definition: regint.h:186
#define ATOMIC_EXCHANGE(var, val)
Definition: ruby_atomic.h:131
int rb_get_kwargs(VALUE keyword_hash, const ID *table, int required, int optional, VALUE *values)
Definition: class.c:1847
VALUE rb_obj_is_thread(VALUE obj)
Definition: vm.c:2506
const VALUE * env
Definition: vm_core.h:921
#define Qtrue
Definition: ruby.h:437
struct rb_method_definition_struct rb_method_definition_t
Definition: method.h:173
#define rb_data_typed_object_alloc
Definition: gc.c:15
unsigned int during_minor_gc
Definition: gc.c:537
size_t onig_memsize(const regex_t *reg)
Definition: regcomp.c:5651
VALUE ecopts
Definition: io.h:85
size_t oldmalloc_limit_max
Definition: gc.c:180
#define BIGNUM_LEN(b)
Definition: internal.h:610
Definition: io.h:62
VALUE rb_imemo_new(enum imemo_type type, VALUE v1, VALUE v2, VALUE v3, VALUE v0)
Definition: gc.c:2020
VALUE rb_wb_protected_newobj_of(VALUE klass, VALUE flags)
Definition: gc.c:1989
struct rb_io_t * fptr
Definition: ruby.h:1065
#define rb_id2str(id)
Definition: vm_backtrace.c:29
void rb_iseq_free(const rb_iseq_t *iseq)
Definition: iseq.c:70
Definition: st.h:99
#define GC_HEAP_FREE_SLOTS_MAX_RATIO
Definition: gc.c:128
#define TypedData_Get_Struct(obj, type, data_type, sval)
Definition: ruby.h:1183
#define OBJ_FREEZE(x)
Definition: ruby.h:1306
#define RGENGC_FORCE_MAJOR_GC
Definition: gc.c:288
node_type
Definition: node.h:22
#define GET_HEAP_UNCOLLECTIBLE_BITS(x)
Definition: gc.c:722
void rb_copy_wb_protected_attribute(VALUE dest, VALUE obj)
Definition: gc.c:6104
void * ruby_xmalloc2(size_t n, size_t size)
Definition: gc.c:8014
#define heap_pages_sorted_length
Definition: gc.c:745
void rb_define_private_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1527
void rb_iseq_mark(const rb_iseq_t *iseq)
Definition: iseq.c:106
void ruby_mimfree(void *ptr)
Definition: gc.c:8110
#define dont_gc
Definition: gc.c:754
void rb_gcdebug_print_obj_condition(VALUE obj)
#define GC_ENABLE_LAZY_SWEEP
Definition: gc.c:317
Ruby method.
Definition: method.h:102
#define rb_vm_register_special_exception(sp, e, m)
Definition: vm_core.h:1543
void rb_id_table_free(struct rb_id_table *tbl)
Definition: id_table.c:102
void(* dfree)(void *)
Definition: gc.c:822
size_t increase
Definition: gc.c:521
#define TH_JUMP_TAG(th, st)
Definition: eval_intern.h:204
#define finalizer_table
Definition: gc.c:757
#define T_RATIONAL
Definition: ruby.h:509
VALUE rb_newobj(void)
Definition: gc.c:1998
#define rb_check_arity
Definition: intern.h:298
RUBY_ALIAS_FUNCTION(rb_data_object_alloc(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree), rb_data_object_wrap,(klass, datap, dmark, dfree))
Definition: gc.c:2044
#define UNREACHABLE
Definition: ruby.h:46
#define ULONG2NUM(x)
Definition: ruby.h:1574
const rb_iseq_t * iseq
Definition: vm_core.h:919
VALUE rb_ary_push(VALUE ary, VALUE item)
Definition: array.c:924
#define SIZED_REALLOC_N(var, type, n, old_n)
Definition: internal.h:1244
#define RREGEXP_PTR(r)
Definition: ruby.h:1049
#define heap_pages_freeable_pages
Definition: gc.c:749
rb_objspace_t * objspace
Definition: gc.c:5110
if(len<=MAX_WORD_LENGTH &&len >=MIN_WORD_LENGTH)
Definition: zonetab.h:883
#define GET_PAGE_BODY(x)
Definition: gc.c:705
#define RGENGC_DEBUG
Definition: gc.c:227
#define SYM2ID(x)
Definition: ruby.h:384
size_t oldmalloc_increase
Definition: gc.c:638
#define ARY_SHARED_P(ary)
Definition: gc.c:9270
const VALUE owner
Definition: method.h:56
ONIG_EXTERN void onig_region_free(OnigRegion *region, int free_self)
Definition: regexec.c:341
VALUE rb_ary_tmp_new(long capa)
Definition: array.c:544
#define RGENGC_ESTIMATE_OLDMALLOC
Definition: gc.c:281
void * ruby_xrealloc2(void *ptr, size_t n, size_t size)
Definition: gc.c:8068
struct rb_iseq_constant_body * body
Definition: vm_core.h:423
#define RGENGC_PROFILE
Definition: gc.c:271
#define OBJ_PROMOTED(x)
Definition: ruby.h:1423
#define RGENGC_CHECK_MODE
Definition: gc.c:246
void ruby_sized_xfree(void *x, size_t size)
Definition: gc.c:8077
void rb_objspace_reachable_objects_from_root(void(func)(const char *category, VALUE, void *), void *passing_data)
Definition: gc.c:7627
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:774
size_t next_index
Definition: gc.c:582
#define MARK_OBJECT_ARY_BUCKET_SIZE
Definition: gc.c:6223
#define GC_ASSERT(expr)
Definition: gc.c:252
#define global_list
Definition: gc.c:758
struct gc_list * next
Definition: gc.c:479
#define STACK_UPPER(x, a, b)
Definition: gc.h:77
VALUE rb_eNoMemError
Definition: error.c:812
#define gc_mode_set(objspace, mode)
Definition: gc.c:784
#define PRIxVALUE
Definition: ruby.h:133
#define GC_HEAP_FREE_SLOTS_MIN_RATIO
Definition: gc.c:122
const VALUE * ep
Definition: vm_core.h:920
#define GC_MALLOC_LIMIT_MAX
Definition: gc.c:135
VALUE rb_define_class_under(VALUE outer, const char *name, VALUE super)
Defines a class under the namespace of outer.
Definition: class.c:693
#define Check_Type(v, t)
Definition: ruby.h:562
int rb_io_fptr_finalize(rb_io_t *)
Definition: io.c:4424
struct re_registers regs
Definition: re.h:37
#define heap_allocated_pages
Definition: gc.c:744
rb_env_t env
Definition: gc.c:441
ID called_id
Definition: method.h:55
int rb_objspace_garbage_object_p(VALUE obj)
Definition: gc.c:3072
int ruby_get_stack_grow_direction(volatile VALUE *addr)
Definition: gc.c:3997
#define GC_PROFILE_DETAIL_MEMORY
Definition: gc.c:311
void * rb_alloc_tmp_buffer(volatile VALUE *store, long len)
Definition: gc.c:8136
#define TH_EXEC_TAG()
Definition: eval_intern.h:198
void rb_define_alloc_func(VALUE, rb_alloc_func_t)
#define T_HASH
Definition: ruby.h:499
void Init_heap(void)
Definition: gc.c:2381
ONIG_EXTERN void onig_free(OnigRegex)
#define ruby_gc_stress_mode
Definition: gc.c:760
size_t rb_io_memsize(const rb_io_t *)
Definition: io.c:4439
const VALUE value
Definition: constant.h:34
#define ruby_gc_stressful
Definition: gc.c:759
#define ARY_EMBED_P(ary)
Definition: gc.c:9273
double oldobject_limit_factor
Definition: gc.c:173
#define nd_set_type(n, t)
Definition: node.h:273
#define DATA_PTR(dta)
Definition: ruby.h:1106
void rb_objspace_each_objects(each_obj_callback *callback, void *data)
Definition: gc.c:2489
unsigned int mode
Definition: gc.c:529
void rb_include_module(VALUE klass, VALUE module)
Definition: class.c:864
#define GC_PROFILE_RECORD_DEFAULT_SIZE
Definition: gc.c:8596
void rb_gc_mark(VALUE ptr)
Definition: gc.c:4464
int ruby_disable_gc
Definition: gc.c:832
special variable
Definition: internal.h:841
size_t rb_gc_count(void)
Definition: gc.c:6766
VALUE rb_hash_lookup(VALUE hash, VALUE key)
Definition: hash.c:853
int rb_objspace_markable_object_p(VALUE obj)
Definition: gc.c:3065
size_t sorted_length
Definition: gc.c:566
#define FL_UNSET(x, f)
Definition: ruby.h:1290
#define T_ARRAY
Definition: ruby.h:498
st_data_t st_index_t
Definition: st.h:50
#define ATOMIC_PTR_EXCHANGE(var, val)
Definition: ruby_atomic.h:177
#define RUBY_INTERNAL_EVENT_GC_START
Definition: ruby.h:2108
#define BITMAP_BIT(p)
Definition: gc.c:712
#define st_delete
Definition: regint.h:182
#define st_lookup
Definition: regint.h:185
void rb_gc_register_address(VALUE *addr)
Definition: gc.c:6241
#define heap_pages_himem
Definition: gc.c:747
int st_update(st_table *table, st_data_t key, st_update_callback_func *func, st_data_t arg)
Definition: st.c:1393
VALUE rb_io_write(VALUE, VALUE)
Definition: io.c:1510
#define VALGRIND_MAKE_MEM_UNDEFINED(p, n)
Definition: zlib.c:25
#define RFILE(obj)
Definition: ruby.h:1206
#define ROBJECT_NUMIV(o)
Definition: ruby.h:900
memop_type
Definition: gc.c:7783
#define S(s)
int index
Definition: gc.c:492
#define rb_setjmp(env)
Definition: gc.c:90
time_t tv_sec
Definition: missing.h:54
Definition: gc.c:477
const rb_iseq_t iseq
Definition: gc.c:440
VALUE rb_ensure(VALUE(*b_proc)(ANYARGS), VALUE data1, VALUE(*e_proc)(ANYARGS), VALUE data2)
An equivalent to ensure clause.
Definition: eval.c:1035
size_t heap_used_at_gc_start
Definition: gc.c:615
void rb_gc_force_recycle(VALUE obj)
Definition: gc.c:6175
VALUE writeconv_pre_ecopts
Definition: io.h:95
size_t malloc_limit_min
Definition: gc.c:175
int char_offset_num_allocated
Definition: re.h:40
void rb_obj_info_dump(VALUE obj)
Definition: gc.c:9453
struct RNode * node
Definition: node.h:237
#define gc_event_hook(objspace, event, data)
Definition: gc.c:1827
#define FIXNUM_P(f)
Definition: ruby.h:365
VALUE rb_inspect(VALUE)
Convenient wrapper of Object::inspect.
Definition: object.c:656
VALUE rb_hash_new_with_size(st_index_t size)
Definition: hash.c:430
#define ATOMIC_VALUE_EXCHANGE(var, val)
Definition: ruby_atomic.h:206
const char * rb_source_loc(int *pline)
Definition: vm.c:1313
#define st_init_strtable
Definition: regint.h:180
#define FL_TEST(x, f)
Definition: ruby.h:1282
int ruby_native_thread_p(void)
Definition: thread.c:4913
#define T_UNDEF
Definition: ruby.h:512
#define nd_type(n)
Definition: node.h:272
VALUE rb_ary_cat(VALUE ary, const VALUE *argv, long len)
Definition: array.c:936
#define RDATA(obj)
Definition: ruby.h:1204
VALUE rb_str_buf_append(VALUE, VALUE)
Definition: string.c:2884
int limit
Definition: gc.c:493
size_t total_allocated_objects_at_gc_start
Definition: gc.c:614
#define SET(name, attr)
Definition: ruby.h:1071
void rb_gc_mark_locations(const VALUE *start, const VALUE *end)
Definition: gc.c:4081
#define RSTRUCT(obj)
Definition: internal.h:714
#define is_incremental_marking(objspace)
Definition: gc.c:794
bits_t wb_unprotected_bits[HEAP_PAGE_BITMAP_LIMIT]
Definition: gc.c:695
VALUE gc_stress_mode
Definition: gc.c:625
int ruby_stack_grow_direction
Definition: gc.c:3995
gc_stat_sym
Definition: gc.c:6915
int ruby_stack_check(void)
Definition: gc.c:4053
size_t oldmalloc_limit_min
Definition: gc.c:179
struct heap_page_header header
Definition: gc.c:472
refinement
Definition: method.h:113
#define RHASH_IFNONE(h)
Definition: ruby.h:1058
const char * rb_obj_classname(VALUE)
Definition: variable.c:459
struct rb_objspace::mark_func_data_struct * mark_func_data
#define MARK_CHECKPOINT(category)
stack_chunk_t * chunk
Definition: gc.c:490
#define ATOMIC_SIZE_ADD(var, val)
Definition: ruby_atomic.h:134
unsigned int has_hook
Definition: gc.c:535
#define ATOMIC_SIZE_CAS(var, oldval, val)
Definition: ruby_atomic.h:156
gc_profile_record * current_record
Definition: gc.c:581
#define ruby_initial_gc_stress
Definition: gc.c:736
#define RVALUE_MARKING_BITMAP(obj)
Definition: gc.c:1040
#define GET_THREAD()
Definition: vm_core.h:1583
rb_heap_t tomb_heap
Definition: gc.c:548
VALUE rb_eArgError
Definition: error.c:802
struct rb_objspace::@60 profile
time_t tv_sec
Definition: missing.h:61
RUBY_SYMBOL_EXPORT_BEGIN typedef unsigned long st_data_t
Definition: st.h:22
#define heap_pages_deferred_final
Definition: gc.c:751
Definition: node.h:233
unsigned int immediate_sweep
Definition: gc.c:530
#define obj_id_to_ref(objid)
Definition: gc.c:808
union RString::@67 as
#define RVALUE_PAGE_WB_UNPROTECTED(page, obj)
Definition: gc.c:1042
void rb_global_variable(VALUE *var)
Definition: gc.c:6276
#define GC_OLDMALLOC_LIMIT_GROWTH_FACTOR
Definition: gc.c:145
void rb_gc_unprotect_logging(void *objptr, const char *filename, int line)
Definition: gc.c:6075
void rb_objspace_each_objects_without_setup(each_obj_callback *callback, void *data)
Definition: gc.c:2510
VALUE data[STACK_CHUNK_SIZE]
Definition: gc.c:485
unsigned int gc_stressful
Definition: gc.c:534
void rb_gc_mark_values(long n, const VALUE *values)
Definition: gc.c:4097
#define RVALUE_OLD_AGE
Definition: gc.c:1046
void rb_objspace_set_event_hook(const rb_event_flag_t event)
Definition: gc.c:1811
size_t limit
Definition: gc.c:520
const VALUE den
Definition: internal.h:627
#define malloc_increase
Definition: gc.c:741
SVAR (Special VARiable)
Definition: internal.h:883
#define FL_SINGLETON
Definition: ruby.h:1208
struct RVALUE RVALUE
#define RHASH(obj)
Definition: internal.h:663
VALUE rb_define_finalizer(VALUE obj, VALUE block)
Definition: gc.c:2748
size_t total_freed_objects
Definition: gc.c:619
gc_mode
Definition: gc.c:512
#define strtod(s, e)
Definition: util.h:77
#define RBASIC_SET_CLASS_RAW(obj, cls)
Definition: internal.h:1470
size_t rb_obj_memsize_of(VALUE obj)
Definition: gc.c:3327
VALUE rb_obj_class(VALUE)
call-seq: obj.class -> class
Definition: object.c:277
#define RB_TYPE_P(obj, type)
Definition: ruby.h:527
void * ruby_xcalloc(size_t n, size_t size)
Definition: gc.c:8030
#define GET_STACK_BOUNDS(start, end, appendix)
Definition: gc.c:4241
VALUE rb_obj_is_kind_of(VALUE, VALUE)
call-seq: obj.is_a?(class) -> true or false obj.kind_of?(class) -> true or false
Definition: object.c:842
Definition: gc.c:8206
struct heap_page * next
Definition: gc.c:692
size_t uncollectible_wb_unprotected_objects
Definition: gc.c:632
#define ATOMIC_SET(var, val)
Definition: ruby_atomic.h:127
void Init_GC(void)
Definition: gc.c:9604
#define TH_POP_TAG()
Definition: eval_intern.h:138
#define will_be_incremental_marking(objspace)
Definition: gc.c:799
#define MEMZERO(p, type, n)
Definition: ruby.h:1660
VALUE rb_obj_method(VALUE, VALUE)
Definition: proc.c:1716
Definition: ruby.h:954
const VALUE src
Definition: ruby.h:1046
#define is_sweeping(objspace)
Definition: gc.c:787
size_t oldmalloc_increase_limit
Definition: gc.c:639
void rb_gc_adjust_memory_usage(ssize_t diff)
Definition: gc.c:8191
#define UNLIKELY(x)
Definition: internal.h:43
#define RUBY_INTERNAL_EVENT_GC_ENTER
Definition: ruby.h:2111
size_t total_allocated_objects
Definition: gc.c:545
void rb_free_generic_ivar(VALUE)
Definition: variable.c:1133
#define during_gc
Definition: gc.c:755
struct rb_objspace::@62 rincgc
VALUE rb_eRangeError
Definition: error.c:805
int rb_postponed_job_register_one(unsigned int flags, rb_postponed_job_func_t func, void *data)
Definition: vm_trace.c:1567
int latest_gc_info
Definition: gc.c:579
void rb_gc_mark_machine_stack(const rb_execution_context_t *ec)
Definition: gc.c:4274
PUREFUNC(static inline int is_id_value(rb_objspace_t *objspace, VALUE ptr))
void * rb_alloc_tmp_buffer_with_count(volatile VALUE *store, size_t size, size_t cnt)
Definition: gc.c:8120
void rb_ary_free(VALUE ary)
Definition: array.c:559
void rb_mark_end_proc(void)
Definition: eval_jump.c:80
#define STACK_CHUNK_SIZE
Definition: gc.c:482
#define ROBJECT_IVPTR(o)
Definition: ruby.h:904
#define GC_HEAP_GROWTH_MAX_SLOTS
Definition: gc.c:115
VALUE rb_class_name(VALUE)
Definition: variable.c:444
VALUE rb_undefine_finalizer(VALUE obj)
Definition: gc.c:2653
#define RGENGC_OLD_NEWOBJ_CHECK
Definition: gc.c:262
#define RUBY_SAFE_LEVEL_MAX
Definition: ruby.h:599
#define ALLOC_N(type, n)
Definition: ruby.h:1587
void rb_vm_mark(void *ptr)
Definition: vm.c:2124
VALUE rb_hash_aset(VALUE hash, VALUE key, VALUE val)
Definition: hash.c:1616
double gc_invoke_time
Definition: gc.c:369
size_t rb_generic_ivar_memsize(VALUE)
Definition: variable.c:1150
NOINLINE(static VALUE newobj_slowpath_wb_protected(VALUE klass, VALUE flags, VALUE v1, VALUE v2, VALUE v3, rb_objspace_t *objspace))
const rb_env_t * rb_vm_env_prev_env(const rb_env_t *env)
Definition: vm.c:741
void rb_gc_copy_finalizer(VALUE dest, VALUE obj)
Definition: gc.c:2756
#define nomem_error
Definition: gc.c:828
VALUE final
Definition: gc.c:8209
#define val
size_t allocated_pages
Definition: gc.c:564
short total_slots
Definition: gc.c:679
long tv_usec
Definition: missing.h:55
RUBY_EXTERN VALUE rb_cObject
Definition: ruby.h:1893
IUnknown DWORD
Definition: win32ole.c:32
void rb_gc_unregister_address(VALUE *addr)
Definition: gc.c:6253
size_t pooled_slots
Definition: gc.c:649
size_t st_memsize(const st_table *tab)
Definition: st.c:676
void rb_free_tmp_buffer(volatile VALUE *store)
Definition: gc.c:8148
#define VALGRIND_MAKE_MEM_DEFINED(p, n)
Definition: zlib.c:24
void rb_str_free(VALUE)
Definition: string.c:1316
size_t malloc_limit_max
Definition: gc.c:176
#define I(s)
#define GET_HEAP_MARKING_BITS(x)
Definition: gc.c:724
#define T_NIL
Definition: ruby.h:490
VALUE * varptr
Definition: gc.c:478
#define NUM2PTR(x)
const VALUE imag
Definition: internal.h:644
rb_atomic_t finalizing
Definition: gc.c:551
VALUE rb_str_cat2(VALUE, const char *)
struct rb_data_type_struct::@73 function
RUBY_EXTERN VALUE rb_cBasicObject
Definition: ruby.h:1892
#define FL_SET(x, f)
Definition: ruby.h:1288
VALUE rb_ary_new(void)
Definition: array.c:499
#define O(member)
Definition: eventids2.c:130
#define T_TRUE
Definition: ruby.h:504
struct gc_profile_record gc_profile_record
#define UINT2NUM(x)
Definition: ruby.h:1539
mark_stack_t mark_stack
Definition: gc.c:559
Definition: ruby.h:854
VALUE rb_any_to_s(VALUE)
call-seq: obj.to_s -> string
Definition: object.c:631
RUBY_EXTERN VALUE rb_mKernel
Definition: ruby.h:1881
#define RSTRUCT_LEN(st)
Definition: ruby.h:1186
#define M(n)
#define snprintf
Definition: subst.h:6
unsigned int before_sweep
Definition: gc.c:683
Definition: ruby.h:1002
Definition: gc.c:410
struct rb_objspace::@61 rgengc
#define nonspecial_obj_id(obj)
Definition: gc.c:807
#define NIL_P(v)
Definition: ruby.h:451
st_table * obj2wmap
Definition: gc.c:8207
long tv_nsec
Definition: missing.h:62
const VALUE real
Definition: internal.h:643
VALUE rb_gc_latest_gc_info(VALUE key)
Definition: gc.c:6881
#define add(x, y)
Definition: date_strftime.c:23
#define CEILDIV(i, mod)
Definition: gc.c:665
unsigned int dont_incremental
Definition: gc.c:532
#define calloc
Definition: ripper.c:360
struct rb_imemo_alloc_struct * next
Definition: internal.h:937
struct rb_method_definition_struct *const def
Definition: method.h:54
void rb_free_method_entry(const rb_method_entry_t *me)
Definition: vm_method.c:168
double gc_time
Definition: gc.c:368
#define RCLASS_IV_TBL(c)
Definition: internal.h:789
#define RUBY_DTRACE_GC_HOOK(name)
Definition: gc.c:8735
void rb_define_const(VALUE, const char *, VALUE)
Definition: variable.c:2691
VALUE rb_obj_is_mutex(VALUE obj)
Definition: thread_sync.c:127
#define MALLOC_ALLOCATED_SIZE
Definition: gc.c:327
THROW_DATA.
Definition: internal.h:895
MEMO.
Definition: internal.h:945
rb_atomic_t cnt[RUBY_NSIG]
Definition: signal.c:525
#define FLONUM_P(x)
Definition: ruby.h:399
struct rb_io_t::rb_io_enc_t encs
#define T_FLOAT
Definition: ruby.h:495
VALUE rb_mGC
Definition: gc.c:831
#define rb_data_object_alloc
Definition: gc.c:14
#define TYPE(x)
Definition: ruby.h:521
int argc
Definition: ruby.c:187
VALUE writeconv_asciicompat
Definition: io.h:92
size_t total_freed_pages
Definition: gc.c:621
struct heap_page * pages
Definition: gc.c:503
#define Qfalse
Definition: ruby.h:436
#define RVALUE_UNCOLLECTIBLE_BITMAP(obj)
Definition: gc.c:1039
#define realloc
Definition: ripper.c:359
size_t onig_region_memsize(const OnigRegion *regs)
Definition: regcomp.c:5666
unsigned int dont_gc
Definition: gc.c:531
Definition: method.h:51
struct force_finalize_list * next
Definition: gc.c:2892
VALUE rb_gc_mark_node(NODE *obj)
Definition: node.c:1098
#define T_BIGNUM
Definition: ruby.h:501
#define range(low, item, hi)
Definition: date_strftime.c:21
#define heap_eden
Definition: gc.c:752
void rb_gc_register_mark_object(VALUE obj)
Definition: gc.c:6227
#define ATOMIC_SIZE_EXCHANGE(var, val)
Definition: ruby_atomic.h:136
#define T_NODE
Definition: ruby.h:513
#define GC_MALLOC_LIMIT_GROWTH_FACTOR
Definition: gc.c:138
size_t(* dsize)(const void *)
Definition: ruby.h:1085
#define RNODE(obj)
Definition: node.h:260
#define STACK_END
Definition: gc.c:3983
#define EXIT_FAILURE
Definition: eval_intern.h:33
#define is_lazy_sweeping(heap)
Definition: gc.c:804
#define STR_SHARED_P(s)
Definition: internal.h:1653
#define T_COMPLEX
Definition: ruby.h:510
#define RVALUE_MARK_BITMAP(obj)
Definition: gc.c:1034
size_t rb_objspace_data_type_memsize(VALUE obj)
Definition: gc.c:2078
#define is_full_marking(objspace)
Definition: gc.c:789
NODE * rb_node_newnode(enum node_type type, VALUE a0, VALUE a1, VALUE a2)
Definition: gc.c:2010
double heap_free_slots_goal_ratio
Definition: gc.c:171
#define numberof(array)
Definition: etc.c:618
#define ALLOC(type)
Definition: ruby.h:1588
rb_method_type_t
Definition: method.h:101
void * ruby_mimmalloc(size_t size)
Definition: gc.c:8094
#define PRIuVALUE
Definition: ruby.h:132
size_t heap_total_size
Definition: gc.c:373
struct st_table * ntbl
Definition: internal.h:658
st_table * finalizer_table
Definition: gc.c:575
#define rb_thread_raised_clear(th)
Definition: eval_intern.h:288
#define RUBY_INTERNAL_EVENT_GC_END_MARK
Definition: ruby.h:2109
#define stress_to_class
Definition: gc.c:764
#define sub(x, y)
Definition: date_strftime.c:24
attr_writer or attr_accessor
Definition: method.h:104
class reference
Definition: internal.h:840
#define FL_FINALIZE
Definition: ruby.h:1212
#define FL_PROMOTED1
Definition: ruby.h:1211
#define COUNT_TYPE(t)
size_t total_slots
Definition: gc.c:509
void rb_define_module_function(VALUE module, const char *name, VALUE(*func)(ANYARGS), int argc)
Defines a module function for module.
Definition: class.c:1731
VALUE rb_yield(VALUE)
Definition: vm_eval.c:973
volatile VALUE * rb_gc_guarded_ptr_val(volatile VALUE *ptr, VALUE val)
Definition: gc.c:97
#define RCLASS_M_TBL(c)
Definition: internal.h:791
#define heap_tomb
Definition: gc.c:753
#define RARRAY_CONST_PTR(a)
Definition: ruby.h:1021
#define FL_PROMOTED0
Definition: ruby.h:1210
struct RRational rational
Definition: gc.c:431
int rb_during_gc(void)
Definition: gc.c:6735
void rb_id_table_foreach_values(struct rb_id_table *tbl, rb_id_table_foreach_values_func_t *func, void *data)
Definition: id_table.c:289
#define lo
Definition: siphash.c:21
#define TRUE
Definition: nkf.h:175
VALUE * ruby_initial_gc_stress_ptr
Definition: gc.c:738
#define T_DATA
Definition: ruby.h:506
VALUE rb_obj_freeze(VALUE)
call-seq: obj.freeze -> obj
Definition: object.c:1331
double malloc_limit_growth_factor
Definition: gc.c:177
VALUE rb_obj_is_proc(VALUE)
Definition: proc.c:116
void ruby_malloc_size_overflow(size_t count, size_t elsize)
Definition: gc.c:8006
size_t cache_size
Definition: gc.c:494
VALUE rb_mEnumerable
Definition: enum.c:19
VALUE rb_sprintf(const char *format,...)
Definition: sprintf.c:1452
int rb_objspace_internal_object_p(VALUE obj)
Definition: gc.c:2552
#define GET_HEAP_MARK_BITS(x)
Definition: gc.c:720
#define STACKFRAME_FOR_CALL_CFUNC
Definition: gc.c:4044
VALUE parent_object
Definition: gc.c:629
#define RICLASS_IS_ORIGIN
Definition: internal.h:798
int rb_obj_respond_to(VALUE, ID, int)
Definition: vm_method.c:1984
#define GC_DEBUG
Definition: gc.c:212
#define RESTORE_FINALIZER()
PRINTF_ARGS(static void gc_report_body(int level, rb_objspace_t *objspace, const char *fmt,...), 3, 4)
unsigned int has_remembered_objects
Definition: gc.c:684
const VALUE klass
Definition: ruby.h:856
size_t rb_obj_gc_flags(VALUE obj, ID *flags, size_t max)
Definition: gc.c:6142
#define MARKED_IN_BITMAP(bits, p)
Definition: gc.c:715
#define MEMMOVE(p1, p2, type, n)
Definition: ruby.h:1662
#define malloc
Definition: ripper.c:358
union RArray::@70 as
#define RZOMBIE(o)
Definition: gc.c:826
struct RHash hash
Definition: gc.c:423
VALUE rb_hash_new(void)
Definition: hash.c:424
void ruby_xfree(void *x)
Definition: gc.c:8085
#define STACK_LENGTH
Definition: gc.c:3991
size_t rb_str_memsize(VALUE)
Definition: string.c:1338
#define strdup(s)
Definition: util.h:70
int rb_scan_args(int argc, const VALUE *argv, const char *fmt,...)
Definition: class.c:1908
RVALUE * freelist
Definition: gc.c:499
const char * category
Definition: gc.c:7614
#define RUBY_INTERNAL_EVENT_GC_EXIT
Definition: ruby.h:2112
#define rb_thread_raised_set(th, f)
Definition: eval_intern.h:285
Definition: ruby.h:1063
unsigned char buf[MIME_BUF_SIZE]
Definition: nkf.c:4309
#define T_IMEMO
Definition: ruby.h:511
#define PRIsVALUE
Definition: ruby.h:135
void Init_stack(volatile VALUE *addr)
Definition: gc.c:6659
unsigned long ID
Definition: ruby.h:86
size_t final_slots
Definition: gc.c:571
VALUE tied_io_for_writing
Definition: io.h:73
VALUE v2
Definition: gc.c:447
unsigned int env_size
Definition: vm_core.h:922
#define FL_ABLE(x)
Definition: ruby.h:1280
#define ATOMIC_SIZE_INC(var)
Definition: ruby_atomic.h:147
#define MALLOC_ALLOCATED_SIZE_CHECK
Definition: gc.c:330
#define Qnil
Definition: ruby.h:438
#define T_STRUCT
Definition: ruby.h:500
unsigned int uintptr_t
Definition: win32.h:106
VALUE next
Definition: gc.c:821
size_t major_gc_count
Definition: gc.c:592
#define BITMAP_INDEX(p)
Definition: gc.c:710
IFUNC (Internal FUNCtion)
Definition: internal.h:917
VALUE rb_obj_rgengc_writebarrier_protected_p(VALUE obj)
Definition: gc.c:6126
#define BUILTIN_TYPE(x)
Definition: ruby.h:518
unsigned long VALUE
Definition: ruby.h:85
#define NUM_IN_PAGE(p)
Definition: gc.c:709
#define OBJ_TAINTED(x)
Definition: ruby.h:1296
int rb_threadptr_during_gc(rb_thread_t *th)
Definition: gc.c:6742
#define EXEC_EVENT_HOOK(th_, flag_, self_, id_, called_id_, klass_, data_)
Definition: vm_core.h:1686
short free_slots
Definition: gc.c:680
#define gc_prof_record(objspace)
Definition: gc.c:910
#define RBASIC(obj)
Definition: ruby.h:1197
const char * rb_objspace_data_type_name(VALUE obj)
Definition: gc.c:2091
const VALUE defined_class
Definition: method.h:53
#define GET_HEAP_WB_UNPROTECTED_BITS(x)
Definition: gc.c:723
double heap_free_slots_max_ratio
Definition: gc.c:172
#define USE_RGENGC
Definition: ruby.h:760
VALUE rb_eTypeError
Definition: error.c:801
#define STATIC_SYM_P(x)
Definition: ruby.h:380
#define FIX2INT(x)
Definition: ruby.h:686
void rb_mark_tbl(st_table *tbl)
Definition: gc.c:4302
Definition: gc.c:677
rb_cref_t cref
Definition: gc.c:434
size_t heap_use_size
Definition: gc.c:372
void(* dmark)(void *)
Definition: ruby.h:1073
RUBY_FUNC_EXPORTED size_t rb_ary_memsize(VALUE ary)
Definition: array.c:571
#define heap_pages_lomem
Definition: gc.c:746
#define rb_ary_new3
Definition: intern.h:91
#define TH_PUSH_TAG(th)
Definition: eval_intern.h:131
VALUE rb_gc_disable(void)
Definition: gc.c:7389
#define OPT(o)
VALUE rb_check_funcall(VALUE, ID, int, const VALUE *)
Definition: vm_eval.c:389
int clock_gettime(clockid_t, struct timespec *)
Definition: win32.c:4608
#define SET_MACHINE_STACK_END(p)
Definition: gc.h:11
void ruby_init_stack(volatile VALUE *)
const char * rb_id2name(ID)
Definition: symbol.c:751
VALUE flags
Definition: ruby.h:855
CREF (Class REFerence)
Definition: method.h:41
VALUE rb_str_new_cstr(const char *)
Definition: string.c:771
struct heap_page * free_next
Definition: gc.c:689
int rb_sigaltstack_size(void)
void * ruby_xrealloc(void *ptr, size_t new_size)
Definition: gc.c:8049
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition: object.c:72
size_t growth_max_slots
Definition: gc.c:168
struct heap_page * page
Definition: gc.c:468
struct RVALUE::@52::@53 free
void ruby_gc_set_params(int safe_level)
Definition: gc.c:7553
void rb_class_detach_module_subclasses(VALUE klass)
Definition: class.c:145
int rb_garbage_collect(void)
Definition: gc.c:6651
void * data
Definition: gc.c:7616
#define rb_objspace_of(vm)
Definition: gc.c:730
#define CHAR_BIT
Definition: ruby.h:196
Definition: re.h:36
#define RANY(o)
Definition: gc.c:817
Kernel::send, Proc::call, etc.
Definition: method.h:111
#define RTYPEDDATA_P(v)
Definition: ruby.h:1108
rb_objspace_t * objspace
Definition: gc.c:6510
#define ROBJECT(obj)
Definition: ruby.h:1198
#define LONG2NUM(x)
Definition: ruby.h:1573
struct rb_execution_context_struct::@143 machine
void rb_memerror(void)
Definition: gc.c:7700
unsigned int uint32_t
Definition: sha2.h:101
register unsigned int len
Definition: zonetab.h:51
VALUE rb_define_module_under(VALUE outer, const char *name)
Definition: class.c:790
VALUE rb_data_typed_object_zalloc(VALUE klass, size_t size, const rb_data_type_t *type)
#define C(c, s)
void rb_set_safe_level_force(int)
Definition: safe.c:41
#define getenv(name)
Definition: win32.c:71
VALUE str
Definition: re.h:46
void * ruby_xmalloc(size_t size)
Definition: gc.c:7997
size_t rb_node_memsize(VALUE obj)
Definition: node.c:1079
#define RSTRING_PTR(str)
Definition: ruby.h:975
#define MARK_IN_BITMAP(bits, p)
Definition: gc.c:716
size_t count
Definition: gc.c:618
#define GC_HEAP_FREE_SLOTS_GOAL_RATIO
Definition: gc.c:125
VALUE write_lock
Definition: io.h:97
#define RVALUE_WB_UNPROTECTED_BITMAP(obj)
Definition: gc.c:1038
struct heap_page * prev
Definition: gc.c:678
#define finalizing
Definition: gc.c:756
bits_t mark_bits[HEAP_PAGE_BITMAP_LIMIT]
Definition: gc.c:698
Definition: gc.c:463
#define STACK_LEVEL_MAX
Definition: gc.c:3984
void * ruby_sized_xrealloc(void *ptr, size_t new_size, size_t old_size)
Definition: gc.c:8039
struct RMatch match
Definition: gc.c:430
#define GC_HEAP_FREE_SLOTS
Definition: gc.c:109
int size
Definition: encoding.c:57
#define PUSH_MARK_FUNC_DATA(v)
Definition: gc.c:922
void rb_mark_generic_ivar(VALUE)
Definition: variable.c:1123
#define f
#define INT2FIX(i)
Definition: ruby.h:232
void * data
Definition: gc.c:2412
VALUE rb_data_object_wrap(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree)
Definition: gc.c:2037
#define RCLASS_SUPER(c)
Definition: classext.h:16
int rb_safe_level(void)
Definition: safe.c:35
VALUE v1
Definition: gc.c:446
#define RARRAY_AREF(a, i)
Definition: ruby.h:1033
#define GC_ENABLE_INCREMENTAL_MARK
Definition: gc.c:314
double invoke_time
Definition: gc.c:588
#define RVALUE_PAGE_UNCOLLECTIBLE(page, obj)
Definition: gc.c:1043
VALUE rb_block_proc(void)
Definition: proc.c:780
#define xmalloc
Definition: defines.h:183
#define SIZE_MAX
Definition: ruby.h:276
void rb_objspace_reachable_objects_from(VALUE obj, void(func)(VALUE, void *), void *data)
Definition: gc.c:7599
int ruby_thread_has_gvl_p(void)
Definition: thread.c:1543
#define RUBY_INTERNAL_EVENT_NEWOBJ
Definition: ruby.h:2106
#define heap_allocatable_pages
Definition: gc.c:748
#define RUBY_INTERNAL_EVENT_FREEOBJ
Definition: ruby.h:2107
#define st_init_numtable
Definition: regint.h:178
VALUE rb_gc_start(void)
Definition: gc.c:6720
size_t allocatable_pages
Definition: gc.c:565
#define ANYARGS
Definition: defines.h:173
int getrusage(int who, struct rusage *usage)
VALUE rb_wb_unprotected_newobj_of(VALUE klass, VALUE flags)
Definition: gc.c:1982
size_t rb_gc_stat(VALUE key)
Definition: gc.c:7295
void rb_mark_set(st_table *tbl)
Definition: gc.c:4134
struct RVALUE * next
Definition: gc.c:414
#define gc_stress_full_mark_after_malloc_p()
Definition: gc.c:6290
RUBY_SYMBOL_EXPORT_BEGIN void * rb_thread_call_with_gvl(void *(*func)(void *), void *data1)
Definition: thread.c:1501
struct RRegexp regexp
Definition: gc.c:422
st_table * wmap2obj
Definition: gc.c:8208
size_t minor_gc_count
Definition: gc.c:591
const char * ruby_node_name(int node)
Definition: iseq.c:1767
VALUE rb_newobj_of(VALUE klass, VALUE flags)
Definition: gc.c:2004
#define RCLASS_IV_INDEX_TBL(c)
Definition: internal.h:793
#define RHASH_TBL_RAW(h)
Definition: internal.h:1268
int ruby_rgengc_debug
Definition: gc.c:235
VALUE rb_class_path_cached(VALUE)
Definition: variable.c:319
#define FL_WB_PROTECTED
Definition: ruby.h:1209
struct gc_list * global_list
Definition: gc.c:623
struct RArray::@70::@71 heap
VALUE rb_obj_is_fiber(VALUE obj)
Definition: cont.c:425
int ruby_gc_debug_indent
Definition: gc.c:830
VALUE rb_data_object_zalloc(VALUE, size_t, RUBY_DATA_FUNC, RUBY_DATA_FUNC)
VALUE pathv
Definition: io.h:68
#define RCLASS_CALLABLE_M_TBL(c)
Definition: internal.h:792
gc_profile_record * records
Definition: gc.c:580
#define RTEST(v)
Definition: ruby.h:450
VALUE rb_proc_new(VALUE(*)(ANYARGS), VALUE)
Definition: proc.c:2649
#define HEAP_PAGE_ALIGN_LOG
Definition: gc.c:663
#define T_STRING
Definition: ruby.h:496
#define POP_MARK_FUNC_DATA()
Definition: gc.c:926
#define PRIuSIZE
Definition: ruby.h:177
unsigned int in_tomb
Definition: gc.c:686
VALUE rb_obj_rgengc_promoted_p(VALUE obj)
Definition: gc.c:6136
struct rb_encoding_entry * list
Definition: encoding.c:55
#define OBJ_INFECT(x, s)
Definition: ruby.h:1302
#define st_add_direct
Definition: regint.h:187
size_t last_major_gc
Definition: gc.c:631
int each_obj_callback(void *, void *, size_t, void *)
Definition: gc.c:2408
#define T_FALSE
Definition: ruby.h:505
#define T_FILE
Definition: ruby.h:502
struct rb_heap_struct rb_heap_t
int rb_singleton_class_internal_p(VALUE sklass)
Definition: class.c:450
rb_objspace_t * rb_objspace_alloc(void)
Definition: gc.c:1327
size_t heap_free_slots
Definition: gc.c:166
size_t heap_init_slots
Definition: gc.c:165
#define VM_UNREACHABLE(func)
Definition: vm_core.h:54
VALUE rb_errinfo(void)
The current exception in the current thread.
Definition: eval.c:1777
double growth_factor
Definition: gc.c:167
#define TypedData_Make_Struct(klass, type, data_type, sval)
Definition: ruby.h:1175
const char * rb_obj_info(VALUE obj)
Definition: gc.c:9442
#define CHECK(sub)
Definition: compile.c:442
VALUE rb_iseq_path(const rb_iseq_t *iseq)
Definition: iseq.c:692
RVALUE * freelist
Definition: gc.c:691
#define NEW_SYM(s)
struct mark_stack mark_stack_t
#define rb_thread_raised_p(th, f)
Definition: eval_intern.h:287
void rb_gc_writebarrier_remember(VALUE obj)
Definition: gc.c:6041
rb_heap_t eden_heap
Definition: gc.c:547
#define RETURN_ENUMERATOR(obj, argc, argv)
Definition: intern.h:238
unsigned int during_incremental_marking
Definition: gc.c:540
#define st_insert
Definition: regint.h:184
int rb_atomic_t
Definition: ruby_atomic.h:120
#define heap_pages_sorted
Definition: gc.c:743
#define T_CLASS
Definition: ruby.h:492
size_t total_allocated_pages
Definition: gc.c:620
const VALUE ifnone
Definition: internal.h:660
struct rmatch_offset * char_offset
Definition: re.h:41
#define SET_STACK_END
Definition: gc.c:3979
VALUE rb_hash_set_default_proc(VALUE hash, VALUE proc)
Definition: hash.c:1025
int immediate_mark
Definition: gc.c:6513
#define RB_DEBUG_COUNTER_INC(type)
volatile VALUE rb_gc_guarded_val
Definition: gc.c:95
#define PRIdSIZE
Definition: ruby.h:174
void rb_gc_mark_maybe(VALUE obj)
Definition: gc.c:4320
VALUE self
Definition: vm_core.h:515
rb_execution_context_t ec
Definition: vm_core.h:790
VALUE gc_stress
Definition: gc.c:183
const char * name
Definition: nkf.c:208
struct RData data
Definition: gc.c:424
struct rb_objspace::@56 malloc_params
#define ID2SYM(x)
Definition: ruby.h:383
#define GC_HEAP_INIT_SLOTS
Definition: gc.c:106
#define gc_event_hook_available_p(objspace)
Definition: gc.c:1824
void rb_gc_mark_global_tbl(void)
Definition: variable.c:594
union RVALUE::@52 as
Definition: ruby.h:889
#define GC_OLDMALLOC_LIMIT_MIN
Definition: gc.c:142
imemo_type
Definition: internal.h:838
#define st_free_table
Definition: regint.h:188
gc_stat_compat_sym
Definition: gc.c:6956
const char * rb_raw_obj_info(char *buff, const int buff_size, VALUE obj)
Definition: gc.c:9290
uint32_t rb_event_flag_t
Definition: ruby.h:2116
#define hi
Definition: siphash.c:22
#define ATTRIBUTE_NO_ADDRESS_SAFETY_ANALYSIS
Definition: gc.c:66
#define RMATCH(obj)
Definition: re.h:51
void(* func)(const char *category, VALUE, void *)
Definition: gc.c:7615
const rb_data_type_t * type
Definition: ruby.h:1101
uintptr_t bits_t
Definition: gc.c:461
#define gc_mode(objspace)
Definition: gc.c:783
#define RTYPEDDATA_DATA(v)
Definition: ruby.h:1110
void rb_gc_writebarrier_unprotect(VALUE obj)
Definition: gc.c:6005
void(* mark_func)(VALUE v, void *data)
Definition: gc.c:556
C method.
Definition: method.h:103
struct heap_page * using_page
Definition: gc.c:502
void(* dmark)(void *)
Definition: ruby.h:1083
#define rb_check_frozen(obj)
Definition: intern.h:271
#define RVALUE_PAGE_MARKING(page, obj)
Definition: gc.c:1044
struct RTypedData typeddata
Definition: gc.c:425
rb_id_table_iterator_result
Definition: id_table.h:8
RUBY_EXTERN VALUE rb_stdout
Definition: ruby.h:1971
void rb_gc_call_finalizer_at_exit(void)
Definition: gc.c:2908
VALUE rb_gc_enable(void)
Definition: gc.c:7367
Definition: gc.c:819
#define vsnprintf
Definition: subst.h:7
#define SPECIAL_CONST_P(x)
Definition: ruby.h:1242
struct RArray array
Definition: gc.c:421
struct rb_objspace rb_objspace_t
#define RUBY_INTERNAL_EVENT_OBJSPACE_MASK
Definition: ruby.h:2113
#define TYPE_NAME(t)
void void xfree(void *)
#define RUBY_INTERNAL_EVENT_GC_END_SWEEP
Definition: ruby.h:2110
struct RBasic basic
Definition: gc.c:416
VALUE ruby_vm_special_exception_copy(VALUE)
Definition: vm_insnhelper.c:26
#define RHASH_EMPTY_P(h)
Definition: ruby.h:1060
VALUE rb_define_module(const char *name)
Definition: class.c:768
#define gc_prof_enabled(objspace)
Definition: gc.c:911
bits_t uncollectible_bits[HEAP_PAGE_BITMAP_LIMIT]
Definition: gc.c:700
size_t rb_id_table_memsize(const struct rb_id_table *tbl)
Definition: id_table.c:123
void rb_mark_hash(st_table *tbl)
Definition: gc.c:4157
VALUE v3
Definition: gc.c:448
#define GC_MALLOC_LIMIT_MIN
Definition: gc.c:132
Definition: id.h:94
#define rb_intern(str)
each_obj_callback * callback
Definition: gc.c:2411
void * data
Definition: ruby.h:1075
VALUE rb_str_buf_new(long)
Definition: string.c:1282
#define gc_report
Definition: gc.c:917
#define T_ZOMBIE
Definition: ruby.h:514
void rb_gc_mark_encodings(void)
Definition: encoding.c:263
#define SYMBOL_P(x)
Definition: ruby.h:382
size_t old_objects
Definition: gc.c:634
#define RCLASS(obj)
Definition: ruby.h:1199
#define T_NONE
Definition: ruby.h:489
struct RString string
Definition: gc.c:420
#define TAG_RAISE
Definition: vm_core.h:170
#define env
#define NULL
Definition: _sdbm.c:102
stack_chunk_t * cache
Definition: gc.c:491
#define OLD_SYM(s)
#define RTYPEDDATA_TYPE(v)
Definition: ruby.h:1109
unsigned int during_gc
Definition: gc.c:533
struct rb_objspace::@57 flags
struct rb_classext_struct rb_classext_t
Definition: internal.h:774
#define Qundef
Definition: ruby.h:439
size_t freeable_pages
Definition: gc.c:568
#define T_ICLASS
Definition: ruby.h:493
#define GC_OLDMALLOC_LIMIT_MAX
Definition: gc.c:148
VALUE flags
Definition: gc.c:413
attr_reader or attr_accessor
Definition: method.h:105
void rb_gc_verify_internal_consistency(void)
Definition: gc.c:5379
#define GET_HEAP_PAGE(x)
Definition: gc.c:707
st_index_t num_entries
Definition: st.h:86
#define malloc_limit
Definition: gc.c:740
void rb_define_method(VALUE klass, const char *name, VALUE(*func)(ANYARGS), int argc)
Definition: class.c:1515
#define ruby_verbose
Definition: ruby.h:1813
VALUE rb_str_append(VALUE, VALUE)
Definition: string.c:2900
#define CALC_EXACT_MALLOC_SIZE
Definition: gc.c:320
struct heap_page ** sorted
Definition: gc.c:563
double oldmalloc_limit_growth_factor
Definition: gc.c:181
struct RComplex complex
Definition: gc.c:432
void rb_ary_delete_same(VALUE ary, VALUE item)
Definition: array.c:3036
struct stack_chunk stack_chunk_t
free(psz)
#define SIZET2NUM(v)
Definition: ruby.h:264
#define T_REGEXP
Definition: ruby.h:497
#define CLEAR_IN_BITMAP(bits, p)
Definition: gc.c:717
#define T_MASK
Definition: md5.c:131
rb_objspace_t * objspace
Definition: gc.c:8348
#define rb_jmp_buf
Definition: gc.c:91
#define BDIGIT
Definition: bigdecimal.h:48
#define BIGNUM_EMBED_FLAG
Definition: internal.h:607
unsigned int has_uncollectible_shady_objects
Definition: gc.c:685
bits_t marking_bits[HEAP_PAGE_BITMAP_LIMIT]
Definition: gc.c:701
char ** argv
Definition: ruby.c:188
Definition: ruby.h:1043
struct heap_page * free_pages
Definition: gc.c:501
#define DBL2NUM(dbl)
Definition: ruby.h:934
#define __asm__
rb_iseq_location_t location
Definition: vm_core.h:386
#define rb_sym2str(sym)
Definition: console.c:107
#define TRY_WITH_GC(alloc)
Definition: gc.c:7907
#define SIGNED_VALUE
Definition: ruby.h:87
#define LIKELY(x)
Definition: internal.h:42
#define xcalloc
Definition: defines.h:185
struct stack_chunk * next
Definition: gc.c:486
Definition: gc.c:489
struct heap_page * sweep_pages
Definition: gc.c:504