Ruby
2.0.0p247(2013-06-27revision41674)
|
00001 /********************************************************************** 00002 00003 gc.c - 00004 00005 $Author: nagachika $ 00006 created at: Tue Oct 5 09:44:46 JST 1993 00007 00008 Copyright (C) 1993-2007 Yukihiro Matsumoto 00009 Copyright (C) 2000 Network Applied Communication Laboratory, Inc. 00010 Copyright (C) 2000 Information-technology Promotion Agency, Japan 00011 00012 **********************************************************************/ 00013 00014 #include "ruby/ruby.h" 00015 #include "ruby/st.h" 00016 #include "ruby/re.h" 00017 #include "ruby/io.h" 00018 #include "ruby/thread.h" 00019 #include "ruby/util.h" 00020 #include "eval_intern.h" 00021 #include "vm_core.h" 00022 #include "internal.h" 00023 #include "gc.h" 00024 #include "constant.h" 00025 #include "ruby_atomic.h" 00026 #include "probes.h" 00027 #include <stdio.h> 00028 #include <setjmp.h> 00029 #include <sys/types.h> 00030 #include <assert.h> 00031 00032 #ifdef HAVE_SYS_TIME_H 00033 #include <sys/time.h> 00034 #endif 00035 00036 #ifdef HAVE_SYS_RESOURCE_H 00037 #include <sys/resource.h> 00038 #endif 00039 #if defined(__native_client__) && defined(NACL_NEWLIB) 00040 # include "nacl/resource.h" 00041 # undef HAVE_POSIX_MEMALIGN 00042 # undef HAVE_MEMALIGN 00043 00044 #endif 00045 00046 #if defined _WIN32 || defined __CYGWIN__ 00047 #include <windows.h> 00048 #elif defined(HAVE_POSIX_MEMALIGN) 00049 #elif defined(HAVE_MEMALIGN) 00050 #include <malloc.h> 00051 #endif 00052 00053 #ifdef HAVE_VALGRIND_MEMCHECK_H 00054 # include <valgrind/memcheck.h> 00055 # ifndef VALGRIND_MAKE_MEM_DEFINED 00056 # define VALGRIND_MAKE_MEM_DEFINED(p, n) VALGRIND_MAKE_READABLE((p), (n)) 00057 # endif 00058 # ifndef VALGRIND_MAKE_MEM_UNDEFINED 00059 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) VALGRIND_MAKE_WRITABLE((p), (n)) 00060 # endif 00061 #else 00062 # define VALGRIND_MAKE_MEM_DEFINED(p, n) 0 00063 # define VALGRIND_MAKE_MEM_UNDEFINED(p, n) 0 00064 #endif 00065 00066 #define rb_setjmp(env) RUBY_SETJMP(env) 00067 #define rb_jmp_buf rb_jmpbuf_t 00068 00069 #ifndef GC_MALLOC_LIMIT 00070 #define GC_MALLOC_LIMIT 8000000 00071 #endif 00072 #define HEAP_MIN_SLOTS 10000 00073 #define FREE_MIN 4096 00074 00075 typedef struct { 00076 unsigned int initial_malloc_limit; 00077 unsigned int initial_heap_min_slots; 00078 unsigned int initial_free_min; 00079 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE 00080 int gc_stress; 00081 #endif 00082 } ruby_gc_params_t; 00083 00084 static ruby_gc_params_t initial_params = { 00085 GC_MALLOC_LIMIT, 00086 HEAP_MIN_SLOTS, 00087 FREE_MIN, 00088 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE 00089 FALSE, 00090 #endif 00091 }; 00092 00093 #define nomem_error GET_VM()->special_exceptions[ruby_error_nomemory] 00094 00095 #ifndef GC_PROFILE_MORE_DETAIL 00096 #define GC_PROFILE_MORE_DETAIL 0 00097 #endif 00098 00099 typedef struct gc_profile_record { 00100 double gc_time; 00101 double gc_invoke_time; 00102 00103 size_t heap_total_objects; 00104 size_t heap_use_size; 00105 size_t heap_total_size; 00106 00107 int is_marked; 00108 00109 #if GC_PROFILE_MORE_DETAIL 00110 double gc_mark_time; 00111 double gc_sweep_time; 00112 00113 size_t heap_use_slots; 00114 size_t heap_live_objects; 00115 size_t heap_free_objects; 00116 00117 int have_finalize; 00118 00119 size_t allocate_increase; 00120 size_t allocate_limit; 00121 #endif 00122 } gc_profile_record; 00123 00124 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__) 00125 #pragma pack(push, 1) /* magic for reducing sizeof(RVALUE): 24 -> 20 */ 00126 #endif 00127 00128 typedef struct RVALUE { 00129 union { 00130 struct { 00131 VALUE flags; /* always 0 for freed obj */ 00132 struct RVALUE *next; 00133 } free; 00134 struct RBasic basic; 00135 struct RObject object; 00136 struct RClass klass; 00137 struct RFloat flonum; 00138 struct RString string; 00139 struct RArray array; 00140 struct RRegexp regexp; 00141 struct RHash hash; 00142 struct RData data; 00143 struct RTypedData typeddata; 00144 struct RStruct rstruct; 00145 struct RBignum bignum; 00146 struct RFile file; 00147 struct RNode node; 00148 struct RMatch match; 00149 struct RRational rational; 00150 struct RComplex complex; 00151 } as; 00152 #ifdef GC_DEBUG 00153 const char *file; 00154 int line; 00155 #endif 00156 } RVALUE; 00157 00158 #if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__CYGWIN__) 00159 #pragma pack(pop) 00160 #endif 00161 00162 struct heaps_slot { 00163 struct heaps_header *header; 00164 uintptr_t *bits; 00165 RVALUE *freelist; 00166 struct heaps_slot *next; 00167 struct heaps_slot *prev; 00168 struct heaps_slot *free_next; 00169 }; 00170 00171 struct heaps_header { 00172 struct heaps_slot *base; 00173 uintptr_t *bits; 00174 RVALUE *start; 00175 RVALUE *end; 00176 size_t limit; 00177 }; 00178 00179 struct heaps_free_bitmap { 00180 struct heaps_free_bitmap *next; 00181 }; 00182 00183 struct gc_list { 00184 VALUE *varptr; 00185 struct gc_list *next; 00186 }; 00187 00188 #define STACK_CHUNK_SIZE 500 00189 00190 typedef struct stack_chunk { 00191 VALUE data[STACK_CHUNK_SIZE]; 00192 struct stack_chunk *next; 00193 } stack_chunk_t; 00194 00195 typedef struct mark_stack { 00196 stack_chunk_t *chunk; 00197 stack_chunk_t *cache; 00198 size_t index; 00199 size_t limit; 00200 size_t cache_size; 00201 size_t unused_cache_size; 00202 } mark_stack_t; 00203 00204 #ifndef CALC_EXACT_MALLOC_SIZE 00205 #define CALC_EXACT_MALLOC_SIZE 0 00206 #endif 00207 00208 typedef struct rb_objspace { 00209 struct { 00210 size_t limit; 00211 size_t increase; 00212 #if CALC_EXACT_MALLOC_SIZE 00213 size_t allocated_size; 00214 size_t allocations; 00215 #endif 00216 } malloc_params; 00217 struct { 00218 size_t increment; 00219 struct heaps_slot *ptr; 00220 struct heaps_slot *sweep_slots; 00221 struct heaps_slot *free_slots; 00222 struct heaps_header **sorted; 00223 size_t length; 00224 size_t used; 00225 struct heaps_free_bitmap *free_bitmap; 00226 RVALUE *range[2]; 00227 struct heaps_header *freed; 00228 size_t marked_num; 00229 size_t free_num; 00230 size_t free_min; 00231 size_t final_num; 00232 size_t do_heap_free; 00233 } heap; 00234 struct { 00235 int dont_gc; 00236 int dont_lazy_sweep; 00237 int during_gc; 00238 rb_atomic_t finalizing; 00239 } flags; 00240 struct { 00241 st_table *table; 00242 RVALUE *deferred; 00243 } final; 00244 mark_stack_t mark_stack; 00245 struct { 00246 int run; 00247 gc_profile_record *record; 00248 size_t count; 00249 size_t size; 00250 double invoke_time; 00251 } profile; 00252 struct gc_list *global_list; 00253 size_t count; 00254 size_t total_allocated_object_num; 00255 size_t total_freed_object_num; 00256 int gc_stress; 00257 00258 struct mark_func_data_struct { 00259 void *data; 00260 void (*mark_func)(VALUE v, void *data); 00261 } *mark_func_data; 00262 } rb_objspace_t; 00263 00264 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE 00265 #define rb_objspace (*GET_VM()->objspace) 00266 #define ruby_initial_gc_stress initial_params.gc_stress 00267 int *ruby_initial_gc_stress_ptr = &ruby_initial_gc_stress; 00268 #else 00269 static rb_objspace_t rb_objspace = {{GC_MALLOC_LIMIT}}; 00270 int *ruby_initial_gc_stress_ptr = &rb_objspace.gc_stress; 00271 #endif 00272 #define malloc_limit objspace->malloc_params.limit 00273 #define malloc_increase objspace->malloc_params.increase 00274 #define heaps objspace->heap.ptr 00275 #define heaps_length objspace->heap.length 00276 #define heaps_used objspace->heap.used 00277 #define lomem objspace->heap.range[0] 00278 #define himem objspace->heap.range[1] 00279 #define heaps_inc objspace->heap.increment 00280 #define heaps_freed objspace->heap.freed 00281 #define dont_gc objspace->flags.dont_gc 00282 #define during_gc objspace->flags.during_gc 00283 #define finalizing objspace->flags.finalizing 00284 #define finalizer_table objspace->final.table 00285 #define deferred_final_list objspace->final.deferred 00286 #define global_List objspace->global_list 00287 #define ruby_gc_stress objspace->gc_stress 00288 #define initial_malloc_limit initial_params.initial_malloc_limit 00289 #define initial_heap_min_slots initial_params.initial_heap_min_slots 00290 #define initial_free_min initial_params.initial_free_min 00291 00292 #define is_lazy_sweeping(objspace) ((objspace)->heap.sweep_slots != 0) 00293 00294 #if SIZEOF_LONG == SIZEOF_VOIDP 00295 # define nonspecial_obj_id(obj) (VALUE)((SIGNED_VALUE)(obj)|FIXNUM_FLAG) 00296 # define obj_id_to_ref(objid) ((objid) ^ FIXNUM_FLAG) /* unset FIXNUM_FLAG */ 00297 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP 00298 # define nonspecial_obj_id(obj) LL2NUM((SIGNED_VALUE)(obj) / 2) 00299 # define obj_id_to_ref(objid) (FIXNUM_P(objid) ? \ 00300 ((objid) ^ FIXNUM_FLAG) : (NUM2PTR(objid) << 1)) 00301 #else 00302 # error not supported 00303 #endif 00304 00305 #define RANY(o) ((RVALUE*)(o)) 00306 #define has_free_object (objspace->heap.free_slots && objspace->heap.free_slots->freelist) 00307 00308 #define HEAP_HEADER(p) ((struct heaps_header *)(p)) 00309 #define GET_HEAP_HEADER(x) (HEAP_HEADER((uintptr_t)(x) & ~(HEAP_ALIGN_MASK))) 00310 #define GET_HEAP_SLOT(x) (GET_HEAP_HEADER(x)->base) 00311 #define GET_HEAP_BITMAP(x) (GET_HEAP_HEADER(x)->bits) 00312 #define NUM_IN_SLOT(p) (((uintptr_t)(p) & HEAP_ALIGN_MASK)/sizeof(RVALUE)) 00313 #define BITMAP_INDEX(p) (NUM_IN_SLOT(p) / (sizeof(uintptr_t) * CHAR_BIT)) 00314 #define BITMAP_OFFSET(p) (NUM_IN_SLOT(p) & ((sizeof(uintptr_t) * CHAR_BIT)-1)) 00315 #define MARKED_IN_BITMAP(bits, p) (bits[BITMAP_INDEX(p)] & ((uintptr_t)1 << BITMAP_OFFSET(p))) 00316 00317 #ifndef HEAP_ALIGN_LOG 00318 /* default tiny heap size: 16KB */ 00319 #define HEAP_ALIGN_LOG 14 00320 #endif 00321 00322 #define CEILDIV(i, mod) (((i) + (mod) - 1)/(mod)) 00323 00324 enum { 00325 HEAP_ALIGN = (1UL << HEAP_ALIGN_LOG), 00326 HEAP_ALIGN_MASK = (~(~0UL << HEAP_ALIGN_LOG)), 00327 REQUIRED_SIZE_BY_MALLOC = (sizeof(size_t) * 5), 00328 HEAP_SIZE = (HEAP_ALIGN - REQUIRED_SIZE_BY_MALLOC), 00329 HEAP_OBJ_LIMIT = (unsigned int)((HEAP_SIZE - sizeof(struct heaps_header))/sizeof(struct RVALUE)), 00330 HEAP_BITMAP_LIMIT = CEILDIV(CEILDIV(HEAP_SIZE, sizeof(struct RVALUE)), sizeof(uintptr_t) * CHAR_BIT) 00331 }; 00332 00333 int ruby_gc_debug_indent = 0; 00334 VALUE rb_mGC; 00335 extern st_table *rb_class_tbl; 00336 int ruby_disable_gc_stress = 0; 00337 00338 static void rb_objspace_call_finalizer(rb_objspace_t *objspace); 00339 static VALUE define_final0(VALUE obj, VALUE block); 00340 VALUE rb_define_final(VALUE obj, VALUE block); 00341 VALUE rb_undefine_final(VALUE obj); 00342 static void run_final(rb_objspace_t *objspace, VALUE obj); 00343 static void initial_expand_heap(rb_objspace_t *objspace); 00344 00345 static void negative_size_allocation_error(const char *); 00346 static void *aligned_malloc(size_t, size_t); 00347 static void aligned_free(void *); 00348 00349 static void init_mark_stack(mark_stack_t *stack); 00350 00351 static VALUE lazy_sweep_enable(void); 00352 static int garbage_collect(rb_objspace_t *); 00353 static int gc_prepare_free_objects(rb_objspace_t *); 00354 static void mark_tbl(rb_objspace_t *, st_table *); 00355 static void rest_sweep(rb_objspace_t *); 00356 static void gc_mark_stacked_objects(rb_objspace_t *); 00357 00358 static double getrusage_time(void); 00359 static inline void gc_prof_timer_start(rb_objspace_t *); 00360 static inline void gc_prof_timer_stop(rb_objspace_t *, int); 00361 static inline void gc_prof_mark_timer_start(rb_objspace_t *); 00362 static inline void gc_prof_mark_timer_stop(rb_objspace_t *); 00363 static inline void gc_prof_sweep_timer_start(rb_objspace_t *); 00364 static inline void gc_prof_sweep_timer_stop(rb_objspace_t *); 00365 static inline void gc_prof_set_malloc_info(rb_objspace_t *); 00366 00367 00368 /* 00369 --------------------------- ObjectSpace ----------------------------- 00370 */ 00371 00372 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE 00373 rb_objspace_t * 00374 rb_objspace_alloc(void) 00375 { 00376 rb_objspace_t *objspace = malloc(sizeof(rb_objspace_t)); 00377 memset(objspace, 0, sizeof(*objspace)); 00378 malloc_limit = initial_malloc_limit; 00379 ruby_gc_stress = ruby_initial_gc_stress; 00380 00381 return objspace; 00382 } 00383 #endif 00384 00385 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE 00386 static void free_stack_chunks(mark_stack_t *); 00387 00388 void 00389 rb_objspace_free(rb_objspace_t *objspace) 00390 { 00391 rest_sweep(objspace); 00392 if (objspace->profile.record) { 00393 free(objspace->profile.record); 00394 objspace->profile.record = 0; 00395 } 00396 if (global_List) { 00397 struct gc_list *list, *next; 00398 for (list = global_List; list; list = next) { 00399 next = list->next; 00400 xfree(list); 00401 } 00402 } 00403 if (objspace->heap.free_bitmap) { 00404 struct heaps_free_bitmap *list, *next; 00405 for (list = objspace->heap.free_bitmap; list; list = next) { 00406 next = list->next; 00407 free(list); 00408 } 00409 } 00410 if (objspace->heap.sorted) { 00411 size_t i; 00412 for (i = 0; i < heaps_used; ++i) { 00413 free(objspace->heap.sorted[i]->bits); 00414 aligned_free(objspace->heap.sorted[i]); 00415 } 00416 free(objspace->heap.sorted); 00417 heaps_used = 0; 00418 heaps = 0; 00419 } 00420 free_stack_chunks(&objspace->mark_stack); 00421 free(objspace); 00422 } 00423 #endif 00424 00425 void 00426 rb_global_variable(VALUE *var) 00427 { 00428 rb_gc_register_address(var); 00429 } 00430 00431 static void 00432 allocate_sorted_heaps(rb_objspace_t *objspace, size_t next_heaps_length) 00433 { 00434 struct heaps_header **p; 00435 struct heaps_free_bitmap *bits; 00436 size_t size, add, i; 00437 00438 size = next_heaps_length*sizeof(struct heaps_header *); 00439 add = next_heaps_length - heaps_used; 00440 00441 if (heaps_used > 0) { 00442 p = (struct heaps_header **)realloc(objspace->heap.sorted, size); 00443 if (p) objspace->heap.sorted = p; 00444 } 00445 else { 00446 p = objspace->heap.sorted = (struct heaps_header **)malloc(size); 00447 } 00448 00449 if (p == 0) { 00450 during_gc = 0; 00451 rb_memerror(); 00452 } 00453 00454 for (i = 0; i < add; i++) { 00455 bits = (struct heaps_free_bitmap *)malloc(HEAP_BITMAP_LIMIT * sizeof(uintptr_t)); 00456 if (bits == 0) { 00457 during_gc = 0; 00458 rb_memerror(); 00459 return; 00460 } 00461 bits->next = objspace->heap.free_bitmap; 00462 objspace->heap.free_bitmap = bits; 00463 } 00464 } 00465 00466 static void 00467 link_free_heap_slot(rb_objspace_t *objspace, struct heaps_slot *slot) 00468 { 00469 slot->free_next = objspace->heap.free_slots; 00470 objspace->heap.free_slots = slot; 00471 } 00472 00473 static void 00474 unlink_free_heap_slot(rb_objspace_t *objspace, struct heaps_slot *slot) 00475 { 00476 objspace->heap.free_slots = slot->free_next; 00477 slot->free_next = NULL; 00478 } 00479 00480 static void 00481 assign_heap_slot(rb_objspace_t *objspace) 00482 { 00483 RVALUE *p, *pend, *membase; 00484 struct heaps_slot *slot; 00485 size_t hi, lo, mid; 00486 size_t objs; 00487 00488 objs = HEAP_OBJ_LIMIT; 00489 p = (RVALUE*)aligned_malloc(HEAP_ALIGN, HEAP_SIZE); 00490 if (p == 0) { 00491 during_gc = 0; 00492 rb_memerror(); 00493 } 00494 slot = (struct heaps_slot *)malloc(sizeof(struct heaps_slot)); 00495 if (slot == 0) { 00496 aligned_free(p); 00497 during_gc = 0; 00498 rb_memerror(); 00499 } 00500 MEMZERO((void*)slot, struct heaps_slot, 1); 00501 00502 slot->next = heaps; 00503 if (heaps) heaps->prev = slot; 00504 heaps = slot; 00505 00506 membase = p; 00507 p = (RVALUE*)((VALUE)p + sizeof(struct heaps_header)); 00508 if ((VALUE)p % sizeof(RVALUE) != 0) { 00509 p = (RVALUE*)((VALUE)p + sizeof(RVALUE) - ((VALUE)p % sizeof(RVALUE))); 00510 objs = (HEAP_SIZE - (size_t)((VALUE)p - (VALUE)membase))/sizeof(RVALUE); 00511 } 00512 00513 lo = 0; 00514 hi = heaps_used; 00515 while (lo < hi) { 00516 register RVALUE *mid_membase; 00517 mid = (lo + hi) / 2; 00518 mid_membase = (RVALUE *)objspace->heap.sorted[mid]; 00519 if (mid_membase < membase) { 00520 lo = mid + 1; 00521 } 00522 else if (mid_membase > membase) { 00523 hi = mid; 00524 } 00525 else { 00526 rb_bug("same heap slot is allocated: %p at %"PRIuVALUE, (void *)membase, (VALUE)mid); 00527 } 00528 } 00529 if (hi < heaps_used) { 00530 MEMMOVE(&objspace->heap.sorted[hi+1], &objspace->heap.sorted[hi], struct heaps_header*, heaps_used - hi); 00531 } 00532 heaps->header = (struct heaps_header *)membase; 00533 objspace->heap.sorted[hi] = heaps->header; 00534 objspace->heap.sorted[hi]->start = p; 00535 objspace->heap.sorted[hi]->end = (p + objs); 00536 objspace->heap.sorted[hi]->base = heaps; 00537 objspace->heap.sorted[hi]->limit = objs; 00538 assert(objspace->heap.free_bitmap != NULL); 00539 heaps->bits = (uintptr_t *)objspace->heap.free_bitmap; 00540 objspace->heap.sorted[hi]->bits = (uintptr_t *)objspace->heap.free_bitmap; 00541 objspace->heap.free_bitmap = objspace->heap.free_bitmap->next; 00542 memset(heaps->bits, 0, HEAP_BITMAP_LIMIT * sizeof(uintptr_t)); 00543 pend = p + objs; 00544 if (lomem == 0 || lomem > p) lomem = p; 00545 if (himem < pend) himem = pend; 00546 heaps_used++; 00547 00548 while (p < pend) { 00549 p->as.free.flags = 0; 00550 p->as.free.next = heaps->freelist; 00551 heaps->freelist = p; 00552 p++; 00553 } 00554 link_free_heap_slot(objspace, heaps); 00555 } 00556 00557 static void 00558 add_heap_slots(rb_objspace_t *objspace, size_t add) 00559 { 00560 size_t i; 00561 size_t next_heaps_length; 00562 00563 next_heaps_length = heaps_used + add; 00564 00565 if (next_heaps_length > heaps_length) { 00566 allocate_sorted_heaps(objspace, next_heaps_length); 00567 heaps_length = next_heaps_length; 00568 } 00569 00570 for (i = 0; i < add; i++) { 00571 assign_heap_slot(objspace); 00572 } 00573 heaps_inc = 0; 00574 } 00575 00576 static void 00577 init_heap(rb_objspace_t *objspace) 00578 { 00579 add_heap_slots(objspace, HEAP_MIN_SLOTS / HEAP_OBJ_LIMIT); 00580 init_mark_stack(&objspace->mark_stack); 00581 00582 #ifdef USE_SIGALTSTACK 00583 { 00584 /* altstack of another threads are allocated in another place */ 00585 rb_thread_t *th = GET_THREAD(); 00586 void *tmp = th->altstack; 00587 th->altstack = malloc(rb_sigaltstack_size()); 00588 free(tmp); /* free previously allocated area */ 00589 } 00590 #endif 00591 00592 objspace->profile.invoke_time = getrusage_time(); 00593 finalizer_table = st_init_numtable(); 00594 } 00595 00596 static void 00597 initial_expand_heap(rb_objspace_t *objspace) 00598 { 00599 size_t min_size = initial_heap_min_slots / HEAP_OBJ_LIMIT; 00600 00601 if (min_size > heaps_used) { 00602 add_heap_slots(objspace, min_size - heaps_used); 00603 } 00604 } 00605 00606 static void 00607 set_heaps_increment(rb_objspace_t *objspace) 00608 { 00609 size_t next_heaps_length = (size_t)(heaps_used * 1.8); 00610 00611 if (next_heaps_length == heaps_used) { 00612 next_heaps_length++; 00613 } 00614 00615 heaps_inc = next_heaps_length - heaps_used; 00616 00617 if (next_heaps_length > heaps_length) { 00618 allocate_sorted_heaps(objspace, next_heaps_length); 00619 heaps_length = next_heaps_length; 00620 } 00621 } 00622 00623 static int 00624 heaps_increment(rb_objspace_t *objspace) 00625 { 00626 if (heaps_inc > 0) { 00627 assign_heap_slot(objspace); 00628 heaps_inc--; 00629 return TRUE; 00630 } 00631 return FALSE; 00632 } 00633 00634 static VALUE 00635 newobj(VALUE klass, VALUE flags) 00636 { 00637 rb_objspace_t *objspace = &rb_objspace; 00638 VALUE obj; 00639 00640 if (UNLIKELY(during_gc)) { 00641 dont_gc = 1; 00642 during_gc = 0; 00643 rb_bug("object allocation during garbage collection phase"); 00644 } 00645 00646 if (UNLIKELY(ruby_gc_stress && !ruby_disable_gc_stress)) { 00647 if (!garbage_collect(objspace)) { 00648 during_gc = 0; 00649 rb_memerror(); 00650 } 00651 } 00652 00653 if (UNLIKELY(!has_free_object)) { 00654 if (!gc_prepare_free_objects(objspace)) { 00655 during_gc = 0; 00656 rb_memerror(); 00657 } 00658 } 00659 00660 obj = (VALUE)objspace->heap.free_slots->freelist; 00661 objspace->heap.free_slots->freelist = RANY(obj)->as.free.next; 00662 if (objspace->heap.free_slots->freelist == NULL) { 00663 unlink_free_heap_slot(objspace, objspace->heap.free_slots); 00664 } 00665 00666 MEMZERO((void*)obj, RVALUE, 1); 00667 #ifdef GC_DEBUG 00668 RANY(obj)->file = rb_sourcefile(); 00669 RANY(obj)->line = rb_sourceline(); 00670 #endif 00671 objspace->total_allocated_object_num++; 00672 00673 return obj; 00674 } 00675 00676 VALUE 00677 rb_newobj(void) 00678 { 00679 return newobj(0, T_NONE); 00680 } 00681 00682 VALUE 00683 rb_newobj_of(VALUE klass, VALUE flags) 00684 { 00685 VALUE obj; 00686 00687 obj = newobj(klass, flags); 00688 OBJSETUP(obj, klass, flags); 00689 00690 return obj; 00691 } 00692 00693 NODE* 00694 rb_node_newnode(enum node_type type, VALUE a0, VALUE a1, VALUE a2) 00695 { 00696 NODE *n = (NODE*)rb_newobj(); 00697 00698 n->flags |= T_NODE; 00699 nd_set_type(n, type); 00700 00701 n->u1.value = a0; 00702 n->u2.value = a1; 00703 n->u3.value = a2; 00704 00705 return n; 00706 } 00707 00708 VALUE 00709 rb_data_object_alloc(VALUE klass, void *datap, RUBY_DATA_FUNC dmark, RUBY_DATA_FUNC dfree) 00710 { 00711 NEWOBJ(data, struct RData); 00712 if (klass) Check_Type(klass, T_CLASS); 00713 OBJSETUP(data, klass, T_DATA); 00714 data->data = datap; 00715 data->dfree = dfree; 00716 data->dmark = dmark; 00717 00718 return (VALUE)data; 00719 } 00720 00721 VALUE 00722 rb_data_typed_object_alloc(VALUE klass, void *datap, const rb_data_type_t *type) 00723 { 00724 NEWOBJ(data, struct RTypedData); 00725 00726 if (klass) Check_Type(klass, T_CLASS); 00727 00728 OBJSETUP(data, klass, T_DATA); 00729 00730 data->data = datap; 00731 data->typed_flag = 1; 00732 data->type = type; 00733 00734 return (VALUE)data; 00735 } 00736 00737 size_t 00738 rb_objspace_data_type_memsize(VALUE obj) 00739 { 00740 if (RTYPEDDATA_P(obj) && RTYPEDDATA_TYPE(obj)->function.dsize) { 00741 return RTYPEDDATA_TYPE(obj)->function.dsize(RTYPEDDATA_DATA(obj)); 00742 } 00743 else { 00744 return 0; 00745 } 00746 } 00747 00748 const char * 00749 rb_objspace_data_type_name(VALUE obj) 00750 { 00751 if (RTYPEDDATA_P(obj)) { 00752 return RTYPEDDATA_TYPE(obj)->wrap_struct_name; 00753 } 00754 else { 00755 return 0; 00756 } 00757 } 00758 00759 static void gc_mark(rb_objspace_t *objspace, VALUE ptr); 00760 static void gc_mark_children(rb_objspace_t *objspace, VALUE ptr); 00761 00762 static inline int 00763 is_pointer_to_heap(rb_objspace_t *objspace, void *ptr) 00764 { 00765 register RVALUE *p = RANY(ptr); 00766 register struct heaps_header *heap; 00767 register size_t hi, lo, mid; 00768 00769 if (p < lomem || p > himem) return FALSE; 00770 if ((VALUE)p % sizeof(RVALUE) != 0) return FALSE; 00771 00772 /* check if p looks like a pointer using bsearch*/ 00773 lo = 0; 00774 hi = heaps_used; 00775 while (lo < hi) { 00776 mid = (lo + hi) / 2; 00777 heap = objspace->heap.sorted[mid]; 00778 if (heap->start <= p) { 00779 if (p < heap->end) 00780 return TRUE; 00781 lo = mid + 1; 00782 } 00783 else { 00784 hi = mid; 00785 } 00786 } 00787 return FALSE; 00788 } 00789 00790 static int 00791 free_method_entry_i(ID key, rb_method_entry_t *me, st_data_t data) 00792 { 00793 if (!me->mark) { 00794 rb_free_method_entry(me); 00795 } 00796 return ST_CONTINUE; 00797 } 00798 00799 void 00800 rb_free_m_table(st_table *tbl) 00801 { 00802 st_foreach(tbl, free_method_entry_i, 0); 00803 st_free_table(tbl); 00804 } 00805 00806 static int 00807 free_const_entry_i(ID key, rb_const_entry_t *ce, st_data_t data) 00808 { 00809 xfree(ce); 00810 return ST_CONTINUE; 00811 } 00812 00813 void 00814 rb_free_const_table(st_table *tbl) 00815 { 00816 st_foreach(tbl, free_const_entry_i, 0); 00817 st_free_table(tbl); 00818 } 00819 00820 static int obj_free(rb_objspace_t *, VALUE); 00821 00822 static inline struct heaps_slot * 00823 add_slot_local_freelist(rb_objspace_t *objspace, RVALUE *p) 00824 { 00825 struct heaps_slot *slot; 00826 00827 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE)); 00828 p->as.free.flags = 0; 00829 slot = GET_HEAP_SLOT(p); 00830 p->as.free.next = slot->freelist; 00831 slot->freelist = p; 00832 00833 return slot; 00834 } 00835 00836 static void 00837 unlink_heap_slot(rb_objspace_t *objspace, struct heaps_slot *slot) 00838 { 00839 if (slot->prev) 00840 slot->prev->next = slot->next; 00841 if (slot->next) 00842 slot->next->prev = slot->prev; 00843 if (heaps == slot) 00844 heaps = slot->next; 00845 if (objspace->heap.sweep_slots == slot) 00846 objspace->heap.sweep_slots = slot->next; 00847 slot->prev = NULL; 00848 slot->next = NULL; 00849 } 00850 00851 static void 00852 free_unused_heaps(rb_objspace_t *objspace) 00853 { 00854 size_t i, j; 00855 struct heaps_header *last = 0; 00856 00857 for (i = j = 1; j < heaps_used; i++) { 00858 if (objspace->heap.sorted[i]->limit == 0) { 00859 struct heaps_header* h = objspace->heap.sorted[i]; 00860 ((struct heaps_free_bitmap *)(h->bits))->next = 00861 objspace->heap.free_bitmap; 00862 objspace->heap.free_bitmap = (struct heaps_free_bitmap *)h->bits; 00863 if (!last) { 00864 last = objspace->heap.sorted[i]; 00865 } 00866 else { 00867 aligned_free(objspace->heap.sorted[i]); 00868 } 00869 heaps_used--; 00870 } 00871 else { 00872 if (i != j) { 00873 objspace->heap.sorted[j] = objspace->heap.sorted[i]; 00874 } 00875 j++; 00876 } 00877 } 00878 if (last) { 00879 if (last < heaps_freed) { 00880 aligned_free(heaps_freed); 00881 heaps_freed = last; 00882 } 00883 else { 00884 aligned_free(last); 00885 } 00886 } 00887 } 00888 static inline void 00889 make_deferred(RVALUE *p) 00890 { 00891 p->as.basic.flags = (p->as.basic.flags & ~T_MASK) | T_ZOMBIE; 00892 } 00893 00894 static inline void 00895 make_io_deferred(RVALUE *p) 00896 { 00897 rb_io_t *fptr = p->as.file.fptr; 00898 make_deferred(p); 00899 p->as.data.dfree = (void (*)(void*))rb_io_fptr_finalize; 00900 p->as.data.data = fptr; 00901 } 00902 00903 static int 00904 obj_free(rb_objspace_t *objspace, VALUE obj) 00905 { 00906 switch (BUILTIN_TYPE(obj)) { 00907 case T_NIL: 00908 case T_FIXNUM: 00909 case T_TRUE: 00910 case T_FALSE: 00911 rb_bug("obj_free() called for broken object"); 00912 break; 00913 } 00914 00915 if (FL_TEST(obj, FL_EXIVAR)) { 00916 rb_free_generic_ivar((VALUE)obj); 00917 FL_UNSET(obj, FL_EXIVAR); 00918 } 00919 00920 switch (BUILTIN_TYPE(obj)) { 00921 case T_OBJECT: 00922 if (!(RANY(obj)->as.basic.flags & ROBJECT_EMBED) && 00923 RANY(obj)->as.object.as.heap.ivptr) { 00924 xfree(RANY(obj)->as.object.as.heap.ivptr); 00925 } 00926 break; 00927 case T_MODULE: 00928 case T_CLASS: 00929 rb_clear_cache_by_class((VALUE)obj); 00930 if (RCLASS_M_TBL(obj)) { 00931 rb_free_m_table(RCLASS_M_TBL(obj)); 00932 } 00933 if (RCLASS_IV_TBL(obj)) { 00934 st_free_table(RCLASS_IV_TBL(obj)); 00935 } 00936 if (RCLASS_CONST_TBL(obj)) { 00937 rb_free_const_table(RCLASS_CONST_TBL(obj)); 00938 } 00939 if (RCLASS_IV_INDEX_TBL(obj)) { 00940 st_free_table(RCLASS_IV_INDEX_TBL(obj)); 00941 } 00942 xfree(RANY(obj)->as.klass.ptr); 00943 break; 00944 case T_STRING: 00945 rb_str_free(obj); 00946 break; 00947 case T_ARRAY: 00948 rb_ary_free(obj); 00949 break; 00950 case T_HASH: 00951 if (RANY(obj)->as.hash.ntbl) { 00952 st_free_table(RANY(obj)->as.hash.ntbl); 00953 } 00954 break; 00955 case T_REGEXP: 00956 if (RANY(obj)->as.regexp.ptr) { 00957 onig_free(RANY(obj)->as.regexp.ptr); 00958 } 00959 break; 00960 case T_DATA: 00961 if (DATA_PTR(obj)) { 00962 if (RTYPEDDATA_P(obj)) { 00963 RDATA(obj)->dfree = RANY(obj)->as.typeddata.type->function.dfree; 00964 } 00965 if (RANY(obj)->as.data.dfree == (RUBY_DATA_FUNC)-1) { 00966 xfree(DATA_PTR(obj)); 00967 } 00968 else if (RANY(obj)->as.data.dfree) { 00969 make_deferred(RANY(obj)); 00970 return 1; 00971 } 00972 } 00973 break; 00974 case T_MATCH: 00975 if (RANY(obj)->as.match.rmatch) { 00976 struct rmatch *rm = RANY(obj)->as.match.rmatch; 00977 onig_region_free(&rm->regs, 0); 00978 if (rm->char_offset) 00979 xfree(rm->char_offset); 00980 xfree(rm); 00981 } 00982 break; 00983 case T_FILE: 00984 if (RANY(obj)->as.file.fptr) { 00985 make_io_deferred(RANY(obj)); 00986 return 1; 00987 } 00988 break; 00989 case T_RATIONAL: 00990 case T_COMPLEX: 00991 break; 00992 case T_ICLASS: 00993 /* iClass shares table with the module */ 00994 xfree(RANY(obj)->as.klass.ptr); 00995 break; 00996 00997 case T_FLOAT: 00998 break; 00999 01000 case T_BIGNUM: 01001 if (!(RBASIC(obj)->flags & RBIGNUM_EMBED_FLAG) && RBIGNUM_DIGITS(obj)) { 01002 xfree(RBIGNUM_DIGITS(obj)); 01003 } 01004 break; 01005 case T_NODE: 01006 switch (nd_type(obj)) { 01007 case NODE_SCOPE: 01008 if (RANY(obj)->as.node.u1.tbl) { 01009 xfree(RANY(obj)->as.node.u1.tbl); 01010 } 01011 break; 01012 case NODE_ARGS: 01013 if (RANY(obj)->as.node.u3.args) { 01014 xfree(RANY(obj)->as.node.u3.args); 01015 } 01016 break; 01017 case NODE_ALLOCA: 01018 xfree(RANY(obj)->as.node.u1.node); 01019 break; 01020 } 01021 break; /* no need to free iv_tbl */ 01022 01023 case T_STRUCT: 01024 if ((RBASIC(obj)->flags & RSTRUCT_EMBED_LEN_MASK) == 0 && 01025 RANY(obj)->as.rstruct.as.heap.ptr) { 01026 xfree(RANY(obj)->as.rstruct.as.heap.ptr); 01027 } 01028 break; 01029 01030 default: 01031 rb_bug("gc_sweep(): unknown data type 0x%x(%p) 0x%"PRIxVALUE, 01032 BUILTIN_TYPE(obj), (void*)obj, RBASIC(obj)->flags); 01033 } 01034 01035 return 0; 01036 } 01037 01038 void 01039 Init_heap(void) 01040 { 01041 init_heap(&rb_objspace); 01042 } 01043 01044 typedef int each_obj_callback(void *, void *, size_t, void *); 01045 01046 struct each_obj_args { 01047 each_obj_callback *callback; 01048 void *data; 01049 }; 01050 01051 static VALUE 01052 objspace_each_objects(VALUE arg) 01053 { 01054 size_t i; 01055 RVALUE *membase = 0; 01056 RVALUE *pstart, *pend; 01057 rb_objspace_t *objspace = &rb_objspace; 01058 struct each_obj_args *args = (struct each_obj_args *)arg; 01059 volatile VALUE v; 01060 01061 i = 0; 01062 while (i < heaps_used) { 01063 while (0 < i && (uintptr_t)membase < (uintptr_t)objspace->heap.sorted[i-1]) 01064 i--; 01065 while (i < heaps_used && (uintptr_t)objspace->heap.sorted[i] <= (uintptr_t)membase) 01066 i++; 01067 if (heaps_used <= i) 01068 break; 01069 membase = (RVALUE *)objspace->heap.sorted[i]; 01070 01071 pstart = objspace->heap.sorted[i]->start; 01072 pend = pstart + objspace->heap.sorted[i]->limit; 01073 01074 for (; pstart != pend; pstart++) { 01075 if (pstart->as.basic.flags) { 01076 v = (VALUE)pstart; /* acquire to save this object */ 01077 break; 01078 } 01079 } 01080 if (pstart != pend) { 01081 if ((*args->callback)(pstart, pend, sizeof(RVALUE), args->data)) { 01082 break; 01083 } 01084 } 01085 } 01086 RB_GC_GUARD(v); 01087 01088 return Qnil; 01089 } 01090 01091 /* 01092 * rb_objspace_each_objects() is special C API to walk through 01093 * Ruby object space. This C API is too difficult to use it. 01094 * To be frank, you should not use it. Or you need to read the 01095 * source code of this function and understand what this function does. 01096 * 01097 * 'callback' will be called several times (the number of heap slot, 01098 * at current implementation) with: 01099 * vstart: a pointer to the first living object of the heap_slot. 01100 * vend: a pointer to next to the valid heap_slot area. 01101 * stride: a distance to next VALUE. 01102 * 01103 * If callback() returns non-zero, the iteration will be stopped. 01104 * 01105 * This is a sample callback code to iterate liveness objects: 01106 * 01107 * int 01108 * sample_callback(void *vstart, void *vend, int stride, void *data) { 01109 * VALUE v = (VALUE)vstart; 01110 * for (; v != (VALUE)vend; v += stride) { 01111 * if (RBASIC(v)->flags) { // liveness check 01112 * // do something with live object 'v' 01113 * } 01114 * return 0; // continue to iteration 01115 * } 01116 * 01117 * Note: 'vstart' is not a top of heap_slot. This point the first 01118 * living object to grasp at least one object to avoid GC issue. 01119 * This means that you can not walk through all Ruby object slot 01120 * including freed object slot. 01121 * 01122 * Note: On this implementation, 'stride' is same as sizeof(RVALUE). 01123 * However, there are possibilities to pass variable values with 01124 * 'stride' with some reasons. You must use stride instead of 01125 * use some constant value in the iteration. 01126 */ 01127 void 01128 rb_objspace_each_objects(each_obj_callback *callback, void *data) 01129 { 01130 struct each_obj_args args; 01131 rb_objspace_t *objspace = &rb_objspace; 01132 01133 rest_sweep(objspace); 01134 objspace->flags.dont_lazy_sweep = TRUE; 01135 01136 args.callback = callback; 01137 args.data = data; 01138 rb_ensure(objspace_each_objects, (VALUE)&args, lazy_sweep_enable, Qnil); 01139 } 01140 01141 struct os_each_struct { 01142 size_t num; 01143 VALUE of; 01144 }; 01145 01146 static int 01147 internal_object_p(VALUE obj) 01148 { 01149 RVALUE *p = (RVALUE *)obj; 01150 01151 if (p->as.basic.flags) { 01152 switch (BUILTIN_TYPE(p)) { 01153 case T_NONE: 01154 case T_ICLASS: 01155 case T_NODE: 01156 case T_ZOMBIE: 01157 break; 01158 case T_CLASS: 01159 if (FL_TEST(p, FL_SINGLETON)) 01160 break; 01161 default: 01162 if (!p->as.basic.klass) break; 01163 return 0; 01164 } 01165 } 01166 return 1; 01167 } 01168 01169 int 01170 rb_objspace_internal_object_p(VALUE obj) 01171 { 01172 return internal_object_p(obj); 01173 } 01174 01175 static int 01176 os_obj_of_i(void *vstart, void *vend, size_t stride, void *data) 01177 { 01178 struct os_each_struct *oes = (struct os_each_struct *)data; 01179 RVALUE *p = (RVALUE *)vstart, *pend = (RVALUE *)vend; 01180 01181 for (; p != pend; p++) { 01182 volatile VALUE v = (VALUE)p; 01183 if (!internal_object_p(v)) { 01184 if (!oes->of || rb_obj_is_kind_of(v, oes->of)) { 01185 rb_yield(v); 01186 oes->num++; 01187 } 01188 } 01189 } 01190 01191 return 0; 01192 } 01193 01194 static VALUE 01195 os_obj_of(VALUE of) 01196 { 01197 struct os_each_struct oes; 01198 01199 oes.num = 0; 01200 oes.of = of; 01201 rb_objspace_each_objects(os_obj_of_i, &oes); 01202 return SIZET2NUM(oes.num); 01203 } 01204 01205 /* 01206 * call-seq: 01207 * ObjectSpace.each_object([module]) {|obj| ... } -> fixnum 01208 * ObjectSpace.each_object([module]) -> an_enumerator 01209 * 01210 * Calls the block once for each living, nonimmediate object in this 01211 * Ruby process. If <i>module</i> is specified, calls the block 01212 * for only those classes or modules that match (or are a subclass of) 01213 * <i>module</i>. Returns the number of objects found. Immediate 01214 * objects (<code>Fixnum</code>s, <code>Symbol</code>s 01215 * <code>true</code>, <code>false</code>, and <code>nil</code>) are 01216 * never returned. In the example below, <code>each_object</code> 01217 * returns both the numbers we defined and several constants defined in 01218 * the <code>Math</code> module. 01219 * 01220 * If no block is given, an enumerator is returned instead. 01221 * 01222 * a = 102.7 01223 * b = 95 # Won't be returned 01224 * c = 12345678987654321 01225 * count = ObjectSpace.each_object(Numeric) {|x| p x } 01226 * puts "Total count: #{count}" 01227 * 01228 * <em>produces:</em> 01229 * 01230 * 12345678987654321 01231 * 102.7 01232 * 2.71828182845905 01233 * 3.14159265358979 01234 * 2.22044604925031e-16 01235 * 1.7976931348623157e+308 01236 * 2.2250738585072e-308 01237 * Total count: 7 01238 * 01239 */ 01240 01241 static VALUE 01242 os_each_obj(int argc, VALUE *argv, VALUE os) 01243 { 01244 VALUE of; 01245 01246 rb_secure(4); 01247 if (argc == 0) { 01248 of = 0; 01249 } 01250 else { 01251 rb_scan_args(argc, argv, "01", &of); 01252 } 01253 RETURN_ENUMERATOR(os, 1, &of); 01254 return os_obj_of(of); 01255 } 01256 01257 /* 01258 * call-seq: 01259 * ObjectSpace.undefine_finalizer(obj) 01260 * 01261 * Removes all finalizers for <i>obj</i>. 01262 * 01263 */ 01264 01265 static VALUE 01266 undefine_final(VALUE os, VALUE obj) 01267 { 01268 return rb_undefine_final(obj); 01269 } 01270 01271 VALUE 01272 rb_undefine_final(VALUE obj) 01273 { 01274 rb_objspace_t *objspace = &rb_objspace; 01275 st_data_t data = obj; 01276 rb_check_frozen(obj); 01277 st_delete(finalizer_table, &data, 0); 01278 FL_UNSET(obj, FL_FINALIZE); 01279 return obj; 01280 } 01281 01282 /* 01283 * call-seq: 01284 * ObjectSpace.define_finalizer(obj, aProc=proc()) 01285 * 01286 * Adds <i>aProc</i> as a finalizer, to be called after <i>obj</i> 01287 * was destroyed. 01288 * 01289 */ 01290 01291 static VALUE 01292 define_final(int argc, VALUE *argv, VALUE os) 01293 { 01294 VALUE obj, block; 01295 01296 rb_scan_args(argc, argv, "11", &obj, &block); 01297 rb_check_frozen(obj); 01298 if (argc == 1) { 01299 block = rb_block_proc(); 01300 } 01301 else if (!rb_respond_to(block, rb_intern("call"))) { 01302 rb_raise(rb_eArgError, "wrong type argument %s (should be callable)", 01303 rb_obj_classname(block)); 01304 } 01305 01306 return define_final0(obj, block); 01307 } 01308 01309 static VALUE 01310 define_final0(VALUE obj, VALUE block) 01311 { 01312 rb_objspace_t *objspace = &rb_objspace; 01313 VALUE table; 01314 st_data_t data; 01315 01316 if (!FL_ABLE(obj)) { 01317 rb_raise(rb_eArgError, "cannot define finalizer for %s", 01318 rb_obj_classname(obj)); 01319 } 01320 RBASIC(obj)->flags |= FL_FINALIZE; 01321 01322 block = rb_ary_new3(2, INT2FIX(rb_safe_level()), block); 01323 OBJ_FREEZE(block); 01324 01325 if (st_lookup(finalizer_table, obj, &data)) { 01326 table = (VALUE)data; 01327 rb_ary_push(table, block); 01328 } 01329 else { 01330 table = rb_ary_new3(1, block); 01331 RBASIC(table)->klass = 0; 01332 st_add_direct(finalizer_table, obj, table); 01333 } 01334 return block; 01335 } 01336 01337 VALUE 01338 rb_define_final(VALUE obj, VALUE block) 01339 { 01340 rb_check_frozen(obj); 01341 if (!rb_respond_to(block, rb_intern("call"))) { 01342 rb_raise(rb_eArgError, "wrong type argument %s (should be callable)", 01343 rb_obj_classname(block)); 01344 } 01345 return define_final0(obj, block); 01346 } 01347 01348 void 01349 rb_gc_copy_finalizer(VALUE dest, VALUE obj) 01350 { 01351 rb_objspace_t *objspace = &rb_objspace; 01352 VALUE table; 01353 st_data_t data; 01354 01355 if (!FL_TEST(obj, FL_FINALIZE)) return; 01356 if (st_lookup(finalizer_table, obj, &data)) { 01357 table = (VALUE)data; 01358 st_insert(finalizer_table, dest, table); 01359 } 01360 FL_SET(dest, FL_FINALIZE); 01361 } 01362 01363 static VALUE 01364 run_single_final(VALUE arg) 01365 { 01366 VALUE *args = (VALUE *)arg; 01367 rb_eval_cmd(args[0], args[1], (int)args[2]); 01368 return Qnil; 01369 } 01370 01371 static void 01372 run_finalizer(rb_objspace_t *objspace, VALUE obj, VALUE table) 01373 { 01374 long i; 01375 int status; 01376 VALUE args[3]; 01377 VALUE objid = nonspecial_obj_id(obj); 01378 01379 if (RARRAY_LEN(table) > 0) { 01380 args[1] = rb_obj_freeze(rb_ary_new3(1, objid)); 01381 } 01382 else { 01383 args[1] = 0; 01384 } 01385 01386 args[2] = (VALUE)rb_safe_level(); 01387 for (i=0; i<RARRAY_LEN(table); i++) { 01388 VALUE final = RARRAY_PTR(table)[i]; 01389 args[0] = RARRAY_PTR(final)[1]; 01390 args[2] = FIX2INT(RARRAY_PTR(final)[0]); 01391 status = 0; 01392 rb_protect(run_single_final, (VALUE)args, &status); 01393 if (status) 01394 rb_set_errinfo(Qnil); 01395 } 01396 } 01397 01398 static void 01399 run_final(rb_objspace_t *objspace, VALUE obj) 01400 { 01401 RUBY_DATA_FUNC free_func = 0; 01402 st_data_t key, table; 01403 01404 objspace->heap.final_num--; 01405 01406 RBASIC(obj)->klass = 0; 01407 01408 if (RTYPEDDATA_P(obj)) { 01409 free_func = RTYPEDDATA_TYPE(obj)->function.dfree; 01410 } 01411 else { 01412 free_func = RDATA(obj)->dfree; 01413 } 01414 if (free_func) { 01415 (*free_func)(DATA_PTR(obj)); 01416 } 01417 01418 key = (st_data_t)obj; 01419 if (st_delete(finalizer_table, &key, &table)) { 01420 run_finalizer(objspace, obj, (VALUE)table); 01421 } 01422 } 01423 01424 static void 01425 finalize_list(rb_objspace_t *objspace, RVALUE *p) 01426 { 01427 while (p) { 01428 RVALUE *tmp = p->as.free.next; 01429 run_final(objspace, (VALUE)p); 01430 objspace->total_freed_object_num++; 01431 if (!FL_TEST(p, FL_SINGLETON)) { /* not freeing page */ 01432 add_slot_local_freelist(objspace, p); 01433 objspace->heap.free_num++; 01434 } 01435 else { 01436 struct heaps_slot *slot = (struct heaps_slot *)(VALUE)RDATA(p)->dmark; 01437 slot->header->limit--; 01438 } 01439 p = tmp; 01440 } 01441 } 01442 01443 static void 01444 finalize_deferred(rb_objspace_t *objspace) 01445 { 01446 RVALUE *p = deferred_final_list; 01447 deferred_final_list = 0; 01448 01449 if (p) { 01450 finalize_list(objspace, p); 01451 } 01452 } 01453 01454 void 01455 rb_gc_finalize_deferred(void) 01456 { 01457 rb_objspace_t *objspace = &rb_objspace; 01458 if (ATOMIC_EXCHANGE(finalizing, 1)) return; 01459 finalize_deferred(objspace); 01460 ATOMIC_SET(finalizing, 0); 01461 } 01462 01463 struct force_finalize_list { 01464 VALUE obj; 01465 VALUE table; 01466 struct force_finalize_list *next; 01467 }; 01468 01469 static int 01470 force_chain_object(st_data_t key, st_data_t val, st_data_t arg) 01471 { 01472 struct force_finalize_list **prev = (struct force_finalize_list **)arg; 01473 struct force_finalize_list *curr = ALLOC(struct force_finalize_list); 01474 curr->obj = key; 01475 curr->table = val; 01476 curr->next = *prev; 01477 *prev = curr; 01478 return ST_CONTINUE; 01479 } 01480 01481 void 01482 rb_gc_call_finalizer_at_exit(void) 01483 { 01484 rb_objspace_call_finalizer(&rb_objspace); 01485 } 01486 01487 static void 01488 rb_objspace_call_finalizer(rb_objspace_t *objspace) 01489 { 01490 RVALUE *p, *pend; 01491 RVALUE *final_list = 0; 01492 size_t i; 01493 01494 rest_sweep(objspace); 01495 01496 if (ATOMIC_EXCHANGE(finalizing, 1)) return; 01497 01498 /* run finalizers */ 01499 finalize_deferred(objspace); 01500 assert(deferred_final_list == 0); 01501 01502 /* force to run finalizer */ 01503 while (finalizer_table->num_entries) { 01504 struct force_finalize_list *list = 0; 01505 st_foreach(finalizer_table, force_chain_object, (st_data_t)&list); 01506 while (list) { 01507 struct force_finalize_list *curr = list; 01508 st_data_t obj = (st_data_t)curr->obj; 01509 run_finalizer(objspace, curr->obj, curr->table); 01510 st_delete(finalizer_table, &obj, 0); 01511 list = curr->next; 01512 xfree(curr); 01513 } 01514 } 01515 01516 /* finalizers are part of garbage collection */ 01517 during_gc++; 01518 01519 /* run data object's finalizers */ 01520 for (i = 0; i < heaps_used; i++) { 01521 p = objspace->heap.sorted[i]->start; pend = p + objspace->heap.sorted[i]->limit; 01522 while (p < pend) { 01523 if (BUILTIN_TYPE(p) == T_DATA && 01524 DATA_PTR(p) && RANY(p)->as.data.dfree && 01525 !rb_obj_is_thread((VALUE)p) && !rb_obj_is_mutex((VALUE)p) && 01526 !rb_obj_is_fiber((VALUE)p)) { 01527 p->as.free.flags = 0; 01528 if (RTYPEDDATA_P(p)) { 01529 RDATA(p)->dfree = RANY(p)->as.typeddata.type->function.dfree; 01530 } 01531 if (RANY(p)->as.data.dfree == (RUBY_DATA_FUNC)-1) { 01532 xfree(DATA_PTR(p)); 01533 } 01534 else if (RANY(p)->as.data.dfree) { 01535 make_deferred(RANY(p)); 01536 RANY(p)->as.free.next = final_list; 01537 final_list = p; 01538 } 01539 } 01540 else if (BUILTIN_TYPE(p) == T_FILE) { 01541 if (RANY(p)->as.file.fptr) { 01542 make_io_deferred(RANY(p)); 01543 RANY(p)->as.free.next = final_list; 01544 final_list = p; 01545 } 01546 } 01547 p++; 01548 } 01549 } 01550 during_gc = 0; 01551 if (final_list) { 01552 finalize_list(objspace, final_list); 01553 } 01554 01555 st_free_table(finalizer_table); 01556 finalizer_table = 0; 01557 ATOMIC_SET(finalizing, 0); 01558 } 01559 01560 static inline int 01561 is_id_value(rb_objspace_t *objspace, VALUE ptr) 01562 { 01563 if (!is_pointer_to_heap(objspace, (void *)ptr)) return FALSE; 01564 if (BUILTIN_TYPE(ptr) > T_FIXNUM) return FALSE; 01565 if (BUILTIN_TYPE(ptr) == T_ICLASS) return FALSE; 01566 return TRUE; 01567 } 01568 01569 static inline int 01570 is_swept_object(rb_objspace_t *objspace, VALUE ptr) 01571 { 01572 struct heaps_slot *slot = objspace->heap.sweep_slots; 01573 01574 while (slot) { 01575 if ((VALUE)slot->header->start <= ptr && ptr < (VALUE)(slot->header->end)) 01576 return FALSE; 01577 slot = slot->next; 01578 } 01579 return TRUE; 01580 } 01581 01582 static inline int 01583 is_dead_object(rb_objspace_t *objspace, VALUE ptr) 01584 { 01585 if (!is_lazy_sweeping(objspace) || MARKED_IN_BITMAP(GET_HEAP_BITMAP(ptr), ptr)) 01586 return FALSE; 01587 if (!is_swept_object(objspace, ptr)) 01588 return TRUE; 01589 return FALSE; 01590 } 01591 01592 static inline int 01593 is_live_object(rb_objspace_t *objspace, VALUE ptr) 01594 { 01595 if (BUILTIN_TYPE(ptr) == 0) return FALSE; 01596 if (RBASIC(ptr)->klass == 0) return FALSE; 01597 if (is_dead_object(objspace, ptr)) return FALSE; 01598 return TRUE; 01599 } 01600 01601 /* 01602 * call-seq: 01603 * ObjectSpace._id2ref(object_id) -> an_object 01604 * 01605 * Converts an object id to a reference to the object. May not be 01606 * called on an object id passed as a parameter to a finalizer. 01607 * 01608 * s = "I am a string" #=> "I am a string" 01609 * r = ObjectSpace._id2ref(s.object_id) #=> "I am a string" 01610 * r == s #=> true 01611 * 01612 */ 01613 01614 static VALUE 01615 id2ref(VALUE obj, VALUE objid) 01616 { 01617 #if SIZEOF_LONG == SIZEOF_VOIDP 01618 #define NUM2PTR(x) NUM2ULONG(x) 01619 #elif SIZEOF_LONG_LONG == SIZEOF_VOIDP 01620 #define NUM2PTR(x) NUM2ULL(x) 01621 #endif 01622 rb_objspace_t *objspace = &rb_objspace; 01623 VALUE ptr; 01624 void *p0; 01625 01626 rb_secure(4); 01627 ptr = NUM2PTR(objid); 01628 p0 = (void *)ptr; 01629 01630 if (ptr == Qtrue) return Qtrue; 01631 if (ptr == Qfalse) return Qfalse; 01632 if (ptr == Qnil) return Qnil; 01633 if (FIXNUM_P(ptr)) return (VALUE)ptr; 01634 if (FLONUM_P(ptr)) return (VALUE)ptr; 01635 ptr = obj_id_to_ref(objid); 01636 01637 if ((ptr % sizeof(RVALUE)) == (4 << 2)) { 01638 ID symid = ptr / sizeof(RVALUE); 01639 if (rb_id2name(symid) == 0) 01640 rb_raise(rb_eRangeError, "%p is not symbol id value", p0); 01641 return ID2SYM(symid); 01642 } 01643 01644 if (!is_id_value(objspace, ptr)) { 01645 rb_raise(rb_eRangeError, "%p is not id value", p0); 01646 } 01647 if (!is_live_object(objspace, ptr)) { 01648 rb_raise(rb_eRangeError, "%p is recycled object", p0); 01649 } 01650 return (VALUE)ptr; 01651 } 01652 01653 /* 01654 * Document-method: __id__ 01655 * Document-method: object_id 01656 * 01657 * call-seq: 01658 * obj.__id__ -> integer 01659 * obj.object_id -> integer 01660 * 01661 * Returns an integer identifier for +obj+. 01662 * 01663 * The same number will be returned on all calls to +id+ for a given object, 01664 * and no two active objects will share an id. 01665 * 01666 * Object#object_id is a different concept from the +:name+ notation, which 01667 * returns the symbol id of +name+. 01668 * 01669 * Replaces the deprecated Object#id. 01670 */ 01671 01672 /* 01673 * call-seq: 01674 * obj.hash -> fixnum 01675 * 01676 * Generates a Fixnum hash value for this object. 01677 * 01678 * This function must have the property that <code>a.eql?(b)</code> implies 01679 * <code>a.hash == b.hash</code>. 01680 * 01681 * The hash value is used by Hash class. 01682 * 01683 * Any hash value that exceeds the capacity of a Fixnum will be truncated 01684 * before being used. 01685 */ 01686 01687 VALUE 01688 rb_obj_id(VALUE obj) 01689 { 01690 /* 01691 * 32-bit VALUE space 01692 * MSB ------------------------ LSB 01693 * false 00000000000000000000000000000000 01694 * true 00000000000000000000000000000010 01695 * nil 00000000000000000000000000000100 01696 * undef 00000000000000000000000000000110 01697 * symbol ssssssssssssssssssssssss00001110 01698 * object oooooooooooooooooooooooooooooo00 = 0 (mod sizeof(RVALUE)) 01699 * fixnum fffffffffffffffffffffffffffffff1 01700 * 01701 * object_id space 01702 * LSB 01703 * false 00000000000000000000000000000000 01704 * true 00000000000000000000000000000010 01705 * nil 00000000000000000000000000000100 01706 * undef 00000000000000000000000000000110 01707 * symbol 000SSSSSSSSSSSSSSSSSSSSSSSSSSS0 S...S % A = 4 (S...S = s...s * A + 4) 01708 * object oooooooooooooooooooooooooooooo0 o...o % A = 0 01709 * fixnum fffffffffffffffffffffffffffffff1 bignum if required 01710 * 01711 * where A = sizeof(RVALUE)/4 01712 * 01713 * sizeof(RVALUE) is 01714 * 20 if 32-bit, double is 4-byte aligned 01715 * 24 if 32-bit, double is 8-byte aligned 01716 * 40 if 64-bit 01717 */ 01718 if (SYMBOL_P(obj)) { 01719 return (SYM2ID(obj) * sizeof(RVALUE) + (4 << 2)) | FIXNUM_FLAG; 01720 } 01721 else if (FLONUM_P(obj)) { 01722 #if SIZEOF_LONG == SIZEOF_VOIDP 01723 return LONG2NUM((SIGNED_VALUE)obj); 01724 #else 01725 return LL2NUM((SIGNED_VALUE)obj); 01726 #endif 01727 } 01728 else if (SPECIAL_CONST_P(obj)) { 01729 return LONG2NUM((SIGNED_VALUE)obj); 01730 } 01731 return nonspecial_obj_id(obj); 01732 } 01733 01734 static int 01735 set_zero(st_data_t key, st_data_t val, st_data_t arg) 01736 { 01737 VALUE k = (VALUE)key; 01738 VALUE hash = (VALUE)arg; 01739 rb_hash_aset(hash, k, INT2FIX(0)); 01740 return ST_CONTINUE; 01741 } 01742 01743 /* 01744 * call-seq: 01745 * ObjectSpace.count_objects([result_hash]) -> hash 01746 * 01747 * Counts objects for each type. 01748 * 01749 * It returns a hash, such as: 01750 * { 01751 * :TOTAL=>10000, 01752 * :FREE=>3011, 01753 * :T_OBJECT=>6, 01754 * :T_CLASS=>404, 01755 * # ... 01756 * } 01757 * 01758 * The contents of the returned hash are implementation specific. 01759 * It may be changed in future. 01760 * 01761 * If the optional argument +result_hash+ is given, 01762 * it is overwritten and returned. This is intended to avoid probe effect. 01763 * 01764 * This method is only expected to work on C Ruby. 01765 * 01766 */ 01767 01768 static VALUE 01769 count_objects(int argc, VALUE *argv, VALUE os) 01770 { 01771 rb_objspace_t *objspace = &rb_objspace; 01772 size_t counts[T_MASK+1]; 01773 size_t freed = 0; 01774 size_t total = 0; 01775 size_t i; 01776 VALUE hash; 01777 01778 if (rb_scan_args(argc, argv, "01", &hash) == 1) { 01779 if (!RB_TYPE_P(hash, T_HASH)) 01780 rb_raise(rb_eTypeError, "non-hash given"); 01781 } 01782 01783 for (i = 0; i <= T_MASK; i++) { 01784 counts[i] = 0; 01785 } 01786 01787 for (i = 0; i < heaps_used; i++) { 01788 RVALUE *p, *pend; 01789 01790 p = objspace->heap.sorted[i]->start; pend = p + objspace->heap.sorted[i]->limit; 01791 for (;p < pend; p++) { 01792 if (p->as.basic.flags) { 01793 counts[BUILTIN_TYPE(p)]++; 01794 } 01795 else { 01796 freed++; 01797 } 01798 } 01799 total += objspace->heap.sorted[i]->limit; 01800 } 01801 01802 if (hash == Qnil) { 01803 hash = rb_hash_new(); 01804 } 01805 else if (!RHASH_EMPTY_P(hash)) { 01806 st_foreach(RHASH_TBL(hash), set_zero, hash); 01807 } 01808 rb_hash_aset(hash, ID2SYM(rb_intern("TOTAL")), SIZET2NUM(total)); 01809 rb_hash_aset(hash, ID2SYM(rb_intern("FREE")), SIZET2NUM(freed)); 01810 01811 for (i = 0; i <= T_MASK; i++) { 01812 VALUE type; 01813 switch (i) { 01814 #define COUNT_TYPE(t) case (t): type = ID2SYM(rb_intern(#t)); break; 01815 COUNT_TYPE(T_NONE); 01816 COUNT_TYPE(T_OBJECT); 01817 COUNT_TYPE(T_CLASS); 01818 COUNT_TYPE(T_MODULE); 01819 COUNT_TYPE(T_FLOAT); 01820 COUNT_TYPE(T_STRING); 01821 COUNT_TYPE(T_REGEXP); 01822 COUNT_TYPE(T_ARRAY); 01823 COUNT_TYPE(T_HASH); 01824 COUNT_TYPE(T_STRUCT); 01825 COUNT_TYPE(T_BIGNUM); 01826 COUNT_TYPE(T_FILE); 01827 COUNT_TYPE(T_DATA); 01828 COUNT_TYPE(T_MATCH); 01829 COUNT_TYPE(T_COMPLEX); 01830 COUNT_TYPE(T_RATIONAL); 01831 COUNT_TYPE(T_NIL); 01832 COUNT_TYPE(T_TRUE); 01833 COUNT_TYPE(T_FALSE); 01834 COUNT_TYPE(T_SYMBOL); 01835 COUNT_TYPE(T_FIXNUM); 01836 COUNT_TYPE(T_UNDEF); 01837 COUNT_TYPE(T_NODE); 01838 COUNT_TYPE(T_ICLASS); 01839 COUNT_TYPE(T_ZOMBIE); 01840 #undef COUNT_TYPE 01841 default: type = INT2NUM(i); break; 01842 } 01843 if (counts[i]) 01844 rb_hash_aset(hash, type, SIZET2NUM(counts[i])); 01845 } 01846 01847 return hash; 01848 } 01849 01850 01851 01852 /* 01853 ------------------------ Garbage Collection ------------------------ 01854 */ 01855 01856 /* Sweeping */ 01857 01858 static VALUE 01859 lazy_sweep_enable(void) 01860 { 01861 rb_objspace_t *objspace = &rb_objspace; 01862 01863 objspace->flags.dont_lazy_sweep = FALSE; 01864 return Qnil; 01865 } 01866 01867 static void 01868 gc_clear_slot_bits(struct heaps_slot *slot) 01869 { 01870 memset(slot->bits, 0, HEAP_BITMAP_LIMIT * sizeof(uintptr_t)); 01871 } 01872 01873 static size_t 01874 objspace_live_num(rb_objspace_t *objspace) 01875 { 01876 return objspace->total_allocated_object_num - objspace->total_freed_object_num; 01877 } 01878 01879 static void 01880 slot_sweep(rb_objspace_t *objspace, struct heaps_slot *sweep_slot) 01881 { 01882 size_t empty_num = 0, freed_num = 0, final_num = 0; 01883 RVALUE *p, *pend; 01884 RVALUE *final = deferred_final_list; 01885 int deferred; 01886 uintptr_t *bits; 01887 01888 p = sweep_slot->header->start; pend = p + sweep_slot->header->limit; 01889 bits = GET_HEAP_BITMAP(p); 01890 while (p < pend) { 01891 if ((!(MARKED_IN_BITMAP(bits, p))) && BUILTIN_TYPE(p) != T_ZOMBIE) { 01892 if (p->as.basic.flags) { 01893 if ((deferred = obj_free(objspace, (VALUE)p)) || 01894 (FL_TEST(p, FL_FINALIZE))) { 01895 if (!deferred) { 01896 p->as.free.flags = T_ZOMBIE; 01897 RDATA(p)->dfree = 0; 01898 } 01899 p->as.free.next = deferred_final_list; 01900 deferred_final_list = p; 01901 assert(BUILTIN_TYPE(p) == T_ZOMBIE); 01902 final_num++; 01903 } 01904 else { 01905 (void)VALGRIND_MAKE_MEM_UNDEFINED((void*)p, sizeof(RVALUE)); 01906 p->as.free.flags = 0; 01907 p->as.free.next = sweep_slot->freelist; 01908 sweep_slot->freelist = p; 01909 freed_num++; 01910 } 01911 } 01912 else { 01913 empty_num++; 01914 } 01915 } 01916 p++; 01917 } 01918 gc_clear_slot_bits(sweep_slot); 01919 if (final_num + freed_num + empty_num == sweep_slot->header->limit && 01920 objspace->heap.free_num > objspace->heap.do_heap_free) { 01921 RVALUE *pp; 01922 01923 for (pp = deferred_final_list; pp != final; pp = pp->as.free.next) { 01924 RDATA(pp)->dmark = (void (*)(void *))(VALUE)sweep_slot; 01925 pp->as.free.flags |= FL_SINGLETON; /* freeing page mark */ 01926 } 01927 sweep_slot->header->limit = final_num; 01928 unlink_heap_slot(objspace, sweep_slot); 01929 } 01930 else { 01931 if (freed_num + empty_num > 0) { 01932 link_free_heap_slot(objspace, sweep_slot); 01933 } 01934 else { 01935 sweep_slot->free_next = NULL; 01936 } 01937 objspace->heap.free_num += freed_num + empty_num; 01938 } 01939 objspace->total_freed_object_num += freed_num; 01940 objspace->heap.final_num += final_num; 01941 01942 if (deferred_final_list && !finalizing) { 01943 rb_thread_t *th = GET_THREAD(); 01944 if (th) { 01945 RUBY_VM_SET_FINALIZER_INTERRUPT(th); 01946 } 01947 } 01948 } 01949 01950 static int 01951 ready_to_gc(rb_objspace_t *objspace) 01952 { 01953 if (dont_gc || during_gc) { 01954 if (!has_free_object) { 01955 if (!heaps_increment(objspace)) { 01956 set_heaps_increment(objspace); 01957 heaps_increment(objspace); 01958 } 01959 } 01960 return FALSE; 01961 } 01962 return TRUE; 01963 } 01964 01965 static void 01966 before_gc_sweep(rb_objspace_t *objspace) 01967 { 01968 objspace->heap.do_heap_free = (size_t)((heaps_used * HEAP_OBJ_LIMIT) * 0.65); 01969 objspace->heap.free_min = (size_t)((heaps_used * HEAP_OBJ_LIMIT) * 0.2); 01970 if (objspace->heap.free_min < initial_free_min) { 01971 objspace->heap.free_min = initial_free_min; 01972 if (objspace->heap.do_heap_free < initial_free_min) 01973 objspace->heap.do_heap_free = initial_free_min; 01974 } 01975 objspace->heap.sweep_slots = heaps; 01976 objspace->heap.free_num = 0; 01977 objspace->heap.free_slots = NULL; 01978 01979 /* sweep unlinked method entries */ 01980 if (GET_VM()->unlinked_method_entry_list) { 01981 rb_sweep_method_entry(GET_VM()); 01982 } 01983 } 01984 01985 static void 01986 after_gc_sweep(rb_objspace_t *objspace) 01987 { 01988 size_t inc; 01989 01990 gc_prof_set_malloc_info(objspace); 01991 if (objspace->heap.free_num < objspace->heap.free_min) { 01992 set_heaps_increment(objspace); 01993 heaps_increment(objspace); 01994 } 01995 01996 inc = ATOMIC_SIZE_EXCHANGE(malloc_increase, 0); 01997 if (inc > malloc_limit) { 01998 malloc_limit += 01999 (size_t)((inc - malloc_limit) * (double)objspace->heap.marked_num / (heaps_used * HEAP_OBJ_LIMIT)); 02000 if (malloc_limit < initial_malloc_limit) malloc_limit = initial_malloc_limit; 02001 } 02002 02003 free_unused_heaps(objspace); 02004 } 02005 02006 static int 02007 lazy_sweep(rb_objspace_t *objspace) 02008 { 02009 struct heaps_slot *next; 02010 02011 heaps_increment(objspace); 02012 while (objspace->heap.sweep_slots) { 02013 next = objspace->heap.sweep_slots->next; 02014 slot_sweep(objspace, objspace->heap.sweep_slots); 02015 objspace->heap.sweep_slots = next; 02016 if (has_free_object) { 02017 during_gc = 0; 02018 return TRUE; 02019 } 02020 } 02021 return FALSE; 02022 } 02023 02024 static void 02025 rest_sweep(rb_objspace_t *objspace) 02026 { 02027 if (objspace->heap.sweep_slots) { 02028 while (objspace->heap.sweep_slots) { 02029 lazy_sweep(objspace); 02030 } 02031 after_gc_sweep(objspace); 02032 } 02033 } 02034 02035 static void gc_marks(rb_objspace_t *objspace); 02036 02037 static int 02038 gc_prepare_free_objects(rb_objspace_t *objspace) 02039 { 02040 int res; 02041 02042 if (objspace->flags.dont_lazy_sweep) 02043 return garbage_collect(objspace); 02044 02045 02046 if (!ready_to_gc(objspace)) return TRUE; 02047 02048 during_gc++; 02049 gc_prof_timer_start(objspace); 02050 gc_prof_sweep_timer_start(objspace); 02051 02052 if (objspace->heap.sweep_slots) { 02053 res = lazy_sweep(objspace); 02054 if (res) { 02055 gc_prof_sweep_timer_stop(objspace); 02056 gc_prof_set_malloc_info(objspace); 02057 gc_prof_timer_stop(objspace, Qfalse); 02058 return res; 02059 } 02060 after_gc_sweep(objspace); 02061 } 02062 else { 02063 if (heaps_increment(objspace)) { 02064 during_gc = 0; 02065 return TRUE; 02066 } 02067 } 02068 02069 gc_marks(objspace); 02070 02071 before_gc_sweep(objspace); 02072 if (objspace->heap.free_min > (heaps_used * HEAP_OBJ_LIMIT - objspace->heap.marked_num)) { 02073 set_heaps_increment(objspace); 02074 } 02075 02076 gc_prof_sweep_timer_start(objspace); 02077 if (!(res = lazy_sweep(objspace))) { 02078 after_gc_sweep(objspace); 02079 if (has_free_object) { 02080 res = TRUE; 02081 during_gc = 0; 02082 } 02083 } 02084 gc_prof_sweep_timer_stop(objspace); 02085 02086 gc_prof_timer_stop(objspace, Qtrue); 02087 return res; 02088 } 02089 02090 static void 02091 gc_sweep(rb_objspace_t *objspace) 02092 { 02093 struct heaps_slot *next; 02094 02095 before_gc_sweep(objspace); 02096 02097 while (objspace->heap.sweep_slots) { 02098 next = objspace->heap.sweep_slots->next; 02099 slot_sweep(objspace, objspace->heap.sweep_slots); 02100 objspace->heap.sweep_slots = next; 02101 } 02102 02103 after_gc_sweep(objspace); 02104 02105 during_gc = 0; 02106 } 02107 02108 /* Marking stack */ 02109 02110 static void push_mark_stack(mark_stack_t *, VALUE); 02111 static int pop_mark_stack(mark_stack_t *, VALUE *); 02112 static void shrink_stack_chunk_cache(mark_stack_t *stack); 02113 02114 static stack_chunk_t * 02115 stack_chunk_alloc(void) 02116 { 02117 stack_chunk_t *res; 02118 02119 res = malloc(sizeof(stack_chunk_t)); 02120 if (!res) 02121 rb_memerror(); 02122 02123 return res; 02124 } 02125 02126 static inline int 02127 is_mark_stask_empty(mark_stack_t *stack) 02128 { 02129 return stack->chunk == NULL; 02130 } 02131 02132 static void 02133 add_stack_chunk_cache(mark_stack_t *stack, stack_chunk_t *chunk) 02134 { 02135 chunk->next = stack->cache; 02136 stack->cache = chunk; 02137 stack->cache_size++; 02138 } 02139 02140 static void 02141 shrink_stack_chunk_cache(mark_stack_t *stack) 02142 { 02143 stack_chunk_t *chunk; 02144 02145 if (stack->unused_cache_size > (stack->cache_size/2)) { 02146 chunk = stack->cache; 02147 stack->cache = stack->cache->next; 02148 stack->cache_size--; 02149 free(chunk); 02150 } 02151 stack->unused_cache_size = stack->cache_size; 02152 } 02153 02154 static void 02155 push_mark_stack_chunk(mark_stack_t *stack) 02156 { 02157 stack_chunk_t *next; 02158 02159 assert(stack->index == stack->limit); 02160 if (stack->cache_size > 0) { 02161 next = stack->cache; 02162 stack->cache = stack->cache->next; 02163 stack->cache_size--; 02164 if (stack->unused_cache_size > stack->cache_size) 02165 stack->unused_cache_size = stack->cache_size; 02166 } 02167 else { 02168 next = stack_chunk_alloc(); 02169 } 02170 next->next = stack->chunk; 02171 stack->chunk = next; 02172 stack->index = 0; 02173 } 02174 02175 static void 02176 pop_mark_stack_chunk(mark_stack_t *stack) 02177 { 02178 stack_chunk_t *prev; 02179 02180 prev = stack->chunk->next; 02181 assert(stack->index == 0); 02182 add_stack_chunk_cache(stack, stack->chunk); 02183 stack->chunk = prev; 02184 stack->index = stack->limit; 02185 } 02186 02187 #if defined(ENABLE_VM_OBJSPACE) && ENABLE_VM_OBJSPACE 02188 static void 02189 free_stack_chunks(mark_stack_t *stack) 02190 { 02191 stack_chunk_t *chunk = stack->chunk; 02192 stack_chunk_t *next = NULL; 02193 02194 while (chunk != NULL) { 02195 next = chunk->next; 02196 free(chunk); 02197 chunk = next; 02198 } 02199 } 02200 #endif 02201 02202 static void 02203 push_mark_stack(mark_stack_t *stack, VALUE data) 02204 { 02205 if (stack->index == stack->limit) { 02206 push_mark_stack_chunk(stack); 02207 } 02208 stack->chunk->data[stack->index++] = data; 02209 } 02210 02211 static int 02212 pop_mark_stack(mark_stack_t *stack, VALUE *data) 02213 { 02214 if (is_mark_stask_empty(stack)) { 02215 return FALSE; 02216 } 02217 if (stack->index == 1) { 02218 *data = stack->chunk->data[--stack->index]; 02219 pop_mark_stack_chunk(stack); 02220 return TRUE; 02221 } 02222 *data = stack->chunk->data[--stack->index]; 02223 return TRUE; 02224 } 02225 02226 static void 02227 init_mark_stack(mark_stack_t *stack) 02228 { 02229 int i; 02230 02231 push_mark_stack_chunk(stack); 02232 stack->limit = STACK_CHUNK_SIZE; 02233 02234 for (i=0; i < 4; i++) { 02235 add_stack_chunk_cache(stack, stack_chunk_alloc()); 02236 } 02237 stack->unused_cache_size = stack->cache_size; 02238 } 02239 02240 02241 /* Marking */ 02242 02243 #define MARK_IN_BITMAP(bits, p) (bits[BITMAP_INDEX(p)] = bits[BITMAP_INDEX(p)] | ((uintptr_t)1 << BITMAP_OFFSET(p))) 02244 02245 02246 #ifdef __ia64 02247 #define SET_STACK_END (SET_MACHINE_STACK_END(&th->machine_stack_end), th->machine_register_stack_end = rb_ia64_bsp()) 02248 #else 02249 #define SET_STACK_END SET_MACHINE_STACK_END(&th->machine_stack_end) 02250 #endif 02251 02252 #define STACK_START (th->machine_stack_start) 02253 #define STACK_END (th->machine_stack_end) 02254 #define STACK_LEVEL_MAX (th->machine_stack_maxsize/sizeof(VALUE)) 02255 02256 #if STACK_GROW_DIRECTION < 0 02257 # define STACK_LENGTH (size_t)(STACK_START - STACK_END) 02258 #elif STACK_GROW_DIRECTION > 0 02259 # define STACK_LENGTH (size_t)(STACK_END - STACK_START + 1) 02260 #else 02261 # define STACK_LENGTH ((STACK_END < STACK_START) ? (size_t)(STACK_START - STACK_END) \ 02262 : (size_t)(STACK_END - STACK_START + 1)) 02263 #endif 02264 #if !STACK_GROW_DIRECTION 02265 int ruby_stack_grow_direction; 02266 int 02267 ruby_get_stack_grow_direction(volatile VALUE *addr) 02268 { 02269 VALUE *end; 02270 SET_MACHINE_STACK_END(&end); 02271 02272 if (end > addr) return ruby_stack_grow_direction = 1; 02273 return ruby_stack_grow_direction = -1; 02274 } 02275 #endif 02276 02277 size_t 02278 ruby_stack_length(VALUE **p) 02279 { 02280 rb_thread_t *th = GET_THREAD(); 02281 SET_STACK_END; 02282 if (p) *p = STACK_UPPER(STACK_END, STACK_START, STACK_END); 02283 return STACK_LENGTH; 02284 } 02285 02286 #if !(defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK)) 02287 static int 02288 stack_check(int water_mark) 02289 { 02290 int ret; 02291 rb_thread_t *th = GET_THREAD(); 02292 SET_STACK_END; 02293 ret = STACK_LENGTH > STACK_LEVEL_MAX - water_mark; 02294 #ifdef __ia64 02295 if (!ret) { 02296 ret = (VALUE*)rb_ia64_bsp() - th->machine_register_stack_start > 02297 th->machine_register_stack_maxsize/sizeof(VALUE) - water_mark; 02298 } 02299 #endif 02300 return ret; 02301 } 02302 #endif 02303 02304 #define STACKFRAME_FOR_CALL_CFUNC 512 02305 02306 int 02307 ruby_stack_check(void) 02308 { 02309 #if defined(POSIX_SIGNAL) && defined(SIGSEGV) && defined(HAVE_SIGALTSTACK) 02310 return 0; 02311 #else 02312 return stack_check(STACKFRAME_FOR_CALL_CFUNC); 02313 #endif 02314 } 02315 02316 static void 02317 mark_locations_array(rb_objspace_t *objspace, register VALUE *x, register long n) 02318 { 02319 VALUE v; 02320 while (n--) { 02321 v = *x; 02322 (void)VALGRIND_MAKE_MEM_DEFINED(&v, sizeof(v)); 02323 if (is_pointer_to_heap(objspace, (void *)v)) { 02324 gc_mark(objspace, v); 02325 } 02326 x++; 02327 } 02328 } 02329 02330 static void 02331 gc_mark_locations(rb_objspace_t *objspace, VALUE *start, VALUE *end) 02332 { 02333 long n; 02334 02335 if (end <= start) return; 02336 n = end - start; 02337 mark_locations_array(objspace, start, n); 02338 } 02339 02340 void 02341 rb_gc_mark_locations(VALUE *start, VALUE *end) 02342 { 02343 gc_mark_locations(&rb_objspace, start, end); 02344 } 02345 02346 #define rb_gc_mark_locations(start, end) gc_mark_locations(objspace, (start), (end)) 02347 02348 struct mark_tbl_arg { 02349 rb_objspace_t *objspace; 02350 }; 02351 02352 static int 02353 mark_entry(st_data_t key, st_data_t value, st_data_t data) 02354 { 02355 struct mark_tbl_arg *arg = (void*)data; 02356 gc_mark(arg->objspace, (VALUE)value); 02357 return ST_CONTINUE; 02358 } 02359 02360 static void 02361 mark_tbl(rb_objspace_t *objspace, st_table *tbl) 02362 { 02363 struct mark_tbl_arg arg; 02364 if (!tbl || tbl->num_entries == 0) return; 02365 arg.objspace = objspace; 02366 st_foreach(tbl, mark_entry, (st_data_t)&arg); 02367 } 02368 02369 static int 02370 mark_key(st_data_t key, st_data_t value, st_data_t data) 02371 { 02372 struct mark_tbl_arg *arg = (void*)data; 02373 gc_mark(arg->objspace, (VALUE)key); 02374 return ST_CONTINUE; 02375 } 02376 02377 static void 02378 mark_set(rb_objspace_t *objspace, st_table *tbl) 02379 { 02380 struct mark_tbl_arg arg; 02381 if (!tbl) return; 02382 arg.objspace = objspace; 02383 st_foreach(tbl, mark_key, (st_data_t)&arg); 02384 } 02385 02386 void 02387 rb_mark_set(st_table *tbl) 02388 { 02389 mark_set(&rb_objspace, tbl); 02390 } 02391 02392 static int 02393 mark_keyvalue(st_data_t key, st_data_t value, st_data_t data) 02394 { 02395 struct mark_tbl_arg *arg = (void*)data; 02396 gc_mark(arg->objspace, (VALUE)key); 02397 gc_mark(arg->objspace, (VALUE)value); 02398 return ST_CONTINUE; 02399 } 02400 02401 static void 02402 mark_hash(rb_objspace_t *objspace, st_table *tbl) 02403 { 02404 struct mark_tbl_arg arg; 02405 if (!tbl) return; 02406 arg.objspace = objspace; 02407 st_foreach(tbl, mark_keyvalue, (st_data_t)&arg); 02408 } 02409 02410 void 02411 rb_mark_hash(st_table *tbl) 02412 { 02413 mark_hash(&rb_objspace, tbl); 02414 } 02415 02416 static void 02417 mark_method_entry(rb_objspace_t *objspace, const rb_method_entry_t *me) 02418 { 02419 const rb_method_definition_t *def = me->def; 02420 02421 gc_mark(objspace, me->klass); 02422 again: 02423 if (!def) return; 02424 switch (def->type) { 02425 case VM_METHOD_TYPE_ISEQ: 02426 gc_mark(objspace, def->body.iseq->self); 02427 break; 02428 case VM_METHOD_TYPE_BMETHOD: 02429 gc_mark(objspace, def->body.proc); 02430 break; 02431 case VM_METHOD_TYPE_ATTRSET: 02432 case VM_METHOD_TYPE_IVAR: 02433 gc_mark(objspace, def->body.attr.location); 02434 break; 02435 case VM_METHOD_TYPE_REFINED: 02436 if (def->body.orig_me) { 02437 def = def->body.orig_me->def; 02438 goto again; 02439 } 02440 break; 02441 default: 02442 break; /* ignore */ 02443 } 02444 } 02445 02446 void 02447 rb_mark_method_entry(const rb_method_entry_t *me) 02448 { 02449 mark_method_entry(&rb_objspace, me); 02450 } 02451 02452 static int 02453 mark_method_entry_i(ID key, const rb_method_entry_t *me, st_data_t data) 02454 { 02455 struct mark_tbl_arg *arg = (void*)data; 02456 mark_method_entry(arg->objspace, me); 02457 return ST_CONTINUE; 02458 } 02459 02460 static void 02461 mark_m_tbl(rb_objspace_t *objspace, st_table *tbl) 02462 { 02463 struct mark_tbl_arg arg; 02464 if (!tbl) return; 02465 arg.objspace = objspace; 02466 st_foreach(tbl, mark_method_entry_i, (st_data_t)&arg); 02467 } 02468 02469 static int 02470 mark_const_entry_i(ID key, const rb_const_entry_t *ce, st_data_t data) 02471 { 02472 struct mark_tbl_arg *arg = (void*)data; 02473 gc_mark(arg->objspace, ce->value); 02474 gc_mark(arg->objspace, ce->file); 02475 return ST_CONTINUE; 02476 } 02477 02478 static void 02479 mark_const_tbl(rb_objspace_t *objspace, st_table *tbl) 02480 { 02481 struct mark_tbl_arg arg; 02482 if (!tbl) return; 02483 arg.objspace = objspace; 02484 st_foreach(tbl, mark_const_entry_i, (st_data_t)&arg); 02485 } 02486 02487 #if STACK_GROW_DIRECTION < 0 02488 #define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_END, (end) = STACK_START) 02489 #elif STACK_GROW_DIRECTION > 0 02490 #define GET_STACK_BOUNDS(start, end, appendix) ((start) = STACK_START, (end) = STACK_END+(appendix)) 02491 #else 02492 #define GET_STACK_BOUNDS(start, end, appendix) \ 02493 ((STACK_END < STACK_START) ? \ 02494 ((start) = STACK_END, (end) = STACK_START) : ((start) = STACK_START, (end) = STACK_END+(appendix))) 02495 #endif 02496 02497 #define numberof(array) (int)(sizeof(array) / sizeof((array)[0])) 02498 02499 static void 02500 mark_current_machine_context(rb_objspace_t *objspace, rb_thread_t *th) 02501 { 02502 union { 02503 rb_jmp_buf j; 02504 VALUE v[sizeof(rb_jmp_buf) / sizeof(VALUE)]; 02505 } save_regs_gc_mark; 02506 VALUE *stack_start, *stack_end; 02507 02508 FLUSH_REGISTER_WINDOWS; 02509 /* This assumes that all registers are saved into the jmp_buf (and stack) */ 02510 rb_setjmp(save_regs_gc_mark.j); 02511 02512 SET_STACK_END; 02513 GET_STACK_BOUNDS(stack_start, stack_end, 1); 02514 02515 mark_locations_array(objspace, save_regs_gc_mark.v, numberof(save_regs_gc_mark.v)); 02516 02517 rb_gc_mark_locations(stack_start, stack_end); 02518 #ifdef __ia64 02519 rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end); 02520 #endif 02521 #if defined(__mc68000__) 02522 mark_locations_array(objspace, (VALUE*)((char*)STACK_END + 2), 02523 (STACK_START - STACK_END)); 02524 #endif 02525 } 02526 02527 void 02528 rb_gc_mark_machine_stack(rb_thread_t *th) 02529 { 02530 rb_objspace_t *objspace = &rb_objspace; 02531 VALUE *stack_start, *stack_end; 02532 02533 GET_STACK_BOUNDS(stack_start, stack_end, 0); 02534 rb_gc_mark_locations(stack_start, stack_end); 02535 #ifdef __ia64 02536 rb_gc_mark_locations(th->machine_register_stack_start, th->machine_register_stack_end); 02537 #endif 02538 } 02539 02540 void 02541 rb_mark_tbl(st_table *tbl) 02542 { 02543 mark_tbl(&rb_objspace, tbl); 02544 } 02545 02546 void 02547 rb_gc_mark_maybe(VALUE obj) 02548 { 02549 if (is_pointer_to_heap(&rb_objspace, (void *)obj)) { 02550 gc_mark(&rb_objspace, obj); 02551 } 02552 } 02553 02554 static int 02555 gc_mark_ptr(rb_objspace_t *objspace, VALUE ptr) 02556 { 02557 register uintptr_t *bits = GET_HEAP_BITMAP(ptr); 02558 if (MARKED_IN_BITMAP(bits, ptr)) return 0; 02559 MARK_IN_BITMAP(bits, ptr); 02560 objspace->heap.marked_num++; 02561 return 1; 02562 } 02563 02564 static int 02565 markable_object_p(rb_objspace_t *objspace, VALUE ptr) 02566 { 02567 register RVALUE *obj = RANY(ptr); 02568 02569 if (rb_special_const_p(ptr)) return 0; /* special const not marked */ 02570 if (obj->as.basic.flags == 0) return 0 ; /* free cell */ 02571 02572 return 1; 02573 } 02574 02575 int 02576 rb_objspace_markable_object_p(VALUE obj) 02577 { 02578 return markable_object_p(/* now it doesn't use &rb_objspace */ 0, obj); 02579 } 02580 02581 static void 02582 gc_mark(rb_objspace_t *objspace, VALUE ptr) 02583 { 02584 if (!markable_object_p(objspace, ptr)) { 02585 return; 02586 } 02587 02588 if (LIKELY(objspace->mark_func_data == 0)) { 02589 if (!gc_mark_ptr(objspace, ptr)) return; /* already marked */ 02590 push_mark_stack(&objspace->mark_stack, ptr); 02591 } 02592 else { 02593 objspace->mark_func_data->mark_func(ptr, objspace->mark_func_data->data); 02594 } 02595 } 02596 02597 void 02598 rb_gc_mark(VALUE ptr) 02599 { 02600 gc_mark(&rb_objspace, ptr); 02601 } 02602 02603 static void 02604 gc_mark_children(rb_objspace_t *objspace, VALUE ptr) 02605 { 02606 register RVALUE *obj = RANY(ptr); 02607 02608 goto marking; /* skip */ 02609 02610 again: 02611 if (LIKELY(objspace->mark_func_data == 0)) { 02612 obj = RANY(ptr); 02613 if (!markable_object_p(objspace, ptr)) return; 02614 if (!gc_mark_ptr(objspace, ptr)) return; /* already marked */ 02615 } 02616 else { 02617 gc_mark(objspace, ptr); 02618 return; 02619 } 02620 02621 marking: 02622 if (FL_TEST(obj, FL_EXIVAR)) { 02623 rb_mark_generic_ivar(ptr); 02624 } 02625 02626 switch (BUILTIN_TYPE(obj)) { 02627 case T_NIL: 02628 case T_FIXNUM: 02629 rb_bug("rb_gc_mark() called for broken object"); 02630 break; 02631 02632 case T_NODE: 02633 switch (nd_type(obj)) { 02634 case NODE_IF: /* 1,2,3 */ 02635 case NODE_FOR: 02636 case NODE_ITER: 02637 case NODE_WHEN: 02638 case NODE_MASGN: 02639 case NODE_RESCUE: 02640 case NODE_RESBODY: 02641 case NODE_CLASS: 02642 case NODE_BLOCK_PASS: 02643 gc_mark(objspace, (VALUE)obj->as.node.u2.node); 02644 /* fall through */ 02645 case NODE_BLOCK: /* 1,3 */ 02646 case NODE_ARRAY: 02647 case NODE_DSTR: 02648 case NODE_DXSTR: 02649 case NODE_DREGX: 02650 case NODE_DREGX_ONCE: 02651 case NODE_ENSURE: 02652 case NODE_CALL: 02653 case NODE_DEFS: 02654 case NODE_OP_ASGN1: 02655 gc_mark(objspace, (VALUE)obj->as.node.u1.node); 02656 /* fall through */ 02657 case NODE_SUPER: /* 3 */ 02658 case NODE_FCALL: 02659 case NODE_DEFN: 02660 case NODE_ARGS_AUX: 02661 ptr = (VALUE)obj->as.node.u3.node; 02662 goto again; 02663 02664 case NODE_WHILE: /* 1,2 */ 02665 case NODE_UNTIL: 02666 case NODE_AND: 02667 case NODE_OR: 02668 case NODE_CASE: 02669 case NODE_SCLASS: 02670 case NODE_DOT2: 02671 case NODE_DOT3: 02672 case NODE_FLIP2: 02673 case NODE_FLIP3: 02674 case NODE_MATCH2: 02675 case NODE_MATCH3: 02676 case NODE_OP_ASGN_OR: 02677 case NODE_OP_ASGN_AND: 02678 case NODE_MODULE: 02679 case NODE_ALIAS: 02680 case NODE_VALIAS: 02681 case NODE_ARGSCAT: 02682 gc_mark(objspace, (VALUE)obj->as.node.u1.node); 02683 /* fall through */ 02684 case NODE_GASGN: /* 2 */ 02685 case NODE_LASGN: 02686 case NODE_DASGN: 02687 case NODE_DASGN_CURR: 02688 case NODE_IASGN: 02689 case NODE_IASGN2: 02690 case NODE_CVASGN: 02691 case NODE_COLON3: 02692 case NODE_OPT_N: 02693 case NODE_EVSTR: 02694 case NODE_UNDEF: 02695 case NODE_POSTEXE: 02696 ptr = (VALUE)obj->as.node.u2.node; 02697 goto again; 02698 02699 case NODE_HASH: /* 1 */ 02700 case NODE_LIT: 02701 case NODE_STR: 02702 case NODE_XSTR: 02703 case NODE_DEFINED: 02704 case NODE_MATCH: 02705 case NODE_RETURN: 02706 case NODE_BREAK: 02707 case NODE_NEXT: 02708 case NODE_YIELD: 02709 case NODE_COLON2: 02710 case NODE_SPLAT: 02711 case NODE_TO_ARY: 02712 ptr = (VALUE)obj->as.node.u1.node; 02713 goto again; 02714 02715 case NODE_SCOPE: /* 2,3 */ 02716 case NODE_CDECL: 02717 case NODE_OPT_ARG: 02718 gc_mark(objspace, (VALUE)obj->as.node.u3.node); 02719 ptr = (VALUE)obj->as.node.u2.node; 02720 goto again; 02721 02722 case NODE_ARGS: /* custom */ 02723 { 02724 struct rb_args_info *args = obj->as.node.u3.args; 02725 if (args) { 02726 if (args->pre_init) gc_mark(objspace, (VALUE)args->pre_init); 02727 if (args->post_init) gc_mark(objspace, (VALUE)args->post_init); 02728 if (args->opt_args) gc_mark(objspace, (VALUE)args->opt_args); 02729 if (args->kw_args) gc_mark(objspace, (VALUE)args->kw_args); 02730 if (args->kw_rest_arg) gc_mark(objspace, (VALUE)args->kw_rest_arg); 02731 } 02732 } 02733 ptr = (VALUE)obj->as.node.u2.node; 02734 goto again; 02735 02736 case NODE_ZARRAY: /* - */ 02737 case NODE_ZSUPER: 02738 case NODE_VCALL: 02739 case NODE_GVAR: 02740 case NODE_LVAR: 02741 case NODE_DVAR: 02742 case NODE_IVAR: 02743 case NODE_CVAR: 02744 case NODE_NTH_REF: 02745 case NODE_BACK_REF: 02746 case NODE_REDO: 02747 case NODE_RETRY: 02748 case NODE_SELF: 02749 case NODE_NIL: 02750 case NODE_TRUE: 02751 case NODE_FALSE: 02752 case NODE_ERRINFO: 02753 case NODE_BLOCK_ARG: 02754 break; 02755 case NODE_ALLOCA: 02756 mark_locations_array(objspace, 02757 (VALUE*)obj->as.node.u1.value, 02758 obj->as.node.u3.cnt); 02759 gc_mark(objspace, (VALUE)obj->as.node.u2.node); 02760 break; 02761 02762 case NODE_CREF: 02763 gc_mark(objspace, obj->as.node.nd_refinements); 02764 gc_mark(objspace, (VALUE)obj->as.node.u1.node); 02765 ptr = (VALUE)obj->as.node.u3.node; 02766 goto again; 02767 02768 default: /* unlisted NODE */ 02769 if (is_pointer_to_heap(objspace, obj->as.node.u1.node)) { 02770 gc_mark(objspace, (VALUE)obj->as.node.u1.node); 02771 } 02772 if (is_pointer_to_heap(objspace, obj->as.node.u2.node)) { 02773 gc_mark(objspace, (VALUE)obj->as.node.u2.node); 02774 } 02775 if (is_pointer_to_heap(objspace, obj->as.node.u3.node)) { 02776 gc_mark(objspace, (VALUE)obj->as.node.u3.node); 02777 } 02778 } 02779 return; /* no need to mark class. */ 02780 } 02781 02782 gc_mark(objspace, obj->as.basic.klass); 02783 switch (BUILTIN_TYPE(obj)) { 02784 case T_ICLASS: 02785 case T_CLASS: 02786 case T_MODULE: 02787 mark_m_tbl(objspace, RCLASS_M_TBL(obj)); 02788 if (!RCLASS_EXT(obj)) break; 02789 mark_tbl(objspace, RCLASS_IV_TBL(obj)); 02790 mark_const_tbl(objspace, RCLASS_CONST_TBL(obj)); 02791 ptr = RCLASS_SUPER(obj); 02792 goto again; 02793 02794 case T_ARRAY: 02795 if (FL_TEST(obj, ELTS_SHARED)) { 02796 ptr = obj->as.array.as.heap.aux.shared; 02797 goto again; 02798 } 02799 else { 02800 long i, len = RARRAY_LEN(obj); 02801 VALUE *ptr = RARRAY_PTR(obj); 02802 for (i=0; i < len; i++) { 02803 gc_mark(objspace, *ptr++); 02804 } 02805 } 02806 break; 02807 02808 case T_HASH: 02809 mark_hash(objspace, obj->as.hash.ntbl); 02810 ptr = obj->as.hash.ifnone; 02811 goto again; 02812 02813 case T_STRING: 02814 #define STR_ASSOC FL_USER3 /* copied from string.c */ 02815 if (FL_TEST(obj, RSTRING_NOEMBED) && FL_ANY(obj, ELTS_SHARED|STR_ASSOC)) { 02816 ptr = obj->as.string.as.heap.aux.shared; 02817 goto again; 02818 } 02819 break; 02820 02821 case T_DATA: 02822 if (RTYPEDDATA_P(obj)) { 02823 RUBY_DATA_FUNC mark_func = obj->as.typeddata.type->function.dmark; 02824 if (mark_func) (*mark_func)(DATA_PTR(obj)); 02825 } 02826 else { 02827 if (obj->as.data.dmark) (*obj->as.data.dmark)(DATA_PTR(obj)); 02828 } 02829 break; 02830 02831 case T_OBJECT: 02832 { 02833 long i, len = ROBJECT_NUMIV(obj); 02834 VALUE *ptr = ROBJECT_IVPTR(obj); 02835 for (i = 0; i < len; i++) { 02836 gc_mark(objspace, *ptr++); 02837 } 02838 } 02839 break; 02840 02841 case T_FILE: 02842 if (obj->as.file.fptr) { 02843 gc_mark(objspace, obj->as.file.fptr->pathv); 02844 gc_mark(objspace, obj->as.file.fptr->tied_io_for_writing); 02845 gc_mark(objspace, obj->as.file.fptr->writeconv_asciicompat); 02846 gc_mark(objspace, obj->as.file.fptr->writeconv_pre_ecopts); 02847 gc_mark(objspace, obj->as.file.fptr->encs.ecopts); 02848 gc_mark(objspace, obj->as.file.fptr->write_lock); 02849 } 02850 break; 02851 02852 case T_REGEXP: 02853 ptr = obj->as.regexp.src; 02854 goto again; 02855 02856 case T_FLOAT: 02857 case T_BIGNUM: 02858 case T_ZOMBIE: 02859 break; 02860 02861 case T_MATCH: 02862 gc_mark(objspace, obj->as.match.regexp); 02863 if (obj->as.match.str) { 02864 ptr = obj->as.match.str; 02865 goto again; 02866 } 02867 break; 02868 02869 case T_RATIONAL: 02870 gc_mark(objspace, obj->as.rational.num); 02871 ptr = obj->as.rational.den; 02872 goto again; 02873 02874 case T_COMPLEX: 02875 gc_mark(objspace, obj->as.complex.real); 02876 ptr = obj->as.complex.imag; 02877 goto again; 02878 02879 case T_STRUCT: 02880 { 02881 long len = RSTRUCT_LEN(obj); 02882 VALUE *ptr = RSTRUCT_PTR(obj); 02883 02884 while (len--) { 02885 gc_mark(objspace, *ptr++); 02886 } 02887 } 02888 break; 02889 02890 default: 02891 rb_bug("rb_gc_mark(): unknown data type 0x%x(%p) %s", 02892 BUILTIN_TYPE(obj), (void *)obj, 02893 is_pointer_to_heap(objspace, obj) ? "corrupted object" : "non object"); 02894 } 02895 } 02896 02897 static void 02898 gc_mark_stacked_objects(rb_objspace_t *objspace) 02899 { 02900 mark_stack_t *mstack = &objspace->mark_stack; 02901 VALUE obj = 0; 02902 02903 if (!mstack->index) return; 02904 while (pop_mark_stack(mstack, &obj)) { 02905 gc_mark_children(objspace, obj); 02906 } 02907 shrink_stack_chunk_cache(mstack); 02908 } 02909 02910 static void 02911 gc_marks(rb_objspace_t *objspace) 02912 { 02913 struct gc_list *list; 02914 rb_thread_t *th = GET_THREAD(); 02915 struct mark_func_data_struct *prev_mark_func_data; 02916 02917 prev_mark_func_data = objspace->mark_func_data; 02918 objspace->mark_func_data = 0; 02919 02920 gc_prof_mark_timer_start(objspace); 02921 objspace->heap.marked_num = 0; 02922 objspace->count++; 02923 02924 SET_STACK_END; 02925 02926 th->vm->self ? rb_gc_mark(th->vm->self) : rb_vm_mark(th->vm); 02927 02928 mark_tbl(objspace, finalizer_table); 02929 mark_current_machine_context(objspace, th); 02930 02931 rb_gc_mark_symbols(); 02932 rb_gc_mark_encodings(); 02933 02934 /* mark protected global variables */ 02935 for (list = global_List; list; list = list->next) { 02936 rb_gc_mark_maybe(*list->varptr); 02937 } 02938 rb_mark_end_proc(); 02939 rb_gc_mark_global_tbl(); 02940 02941 mark_tbl(objspace, rb_class_tbl); 02942 02943 /* mark generic instance variables for special constants */ 02944 rb_mark_generic_ivar_tbl(); 02945 02946 rb_gc_mark_parser(); 02947 02948 rb_gc_mark_unlinked_live_method_entries(th->vm); 02949 02950 /* marking-loop */ 02951 gc_mark_stacked_objects(objspace); 02952 02953 gc_prof_mark_timer_stop(objspace); 02954 02955 objspace->mark_func_data = prev_mark_func_data; 02956 } 02957 02958 /* GC */ 02959 02960 void 02961 rb_gc_force_recycle(VALUE p) 02962 { 02963 rb_objspace_t *objspace = &rb_objspace; 02964 struct heaps_slot *slot; 02965 02966 objspace->total_freed_object_num++; 02967 if (MARKED_IN_BITMAP(GET_HEAP_BITMAP(p), p)) { 02968 add_slot_local_freelist(objspace, (RVALUE *)p); 02969 } 02970 else { 02971 objspace->heap.free_num++; 02972 slot = add_slot_local_freelist(objspace, (RVALUE *)p); 02973 if (slot->free_next == NULL) { 02974 link_free_heap_slot(objspace, slot); 02975 } 02976 } 02977 } 02978 02979 void 02980 rb_gc_register_mark_object(VALUE obj) 02981 { 02982 VALUE ary = GET_THREAD()->vm->mark_object_ary; 02983 rb_ary_push(ary, obj); 02984 } 02985 02986 void 02987 rb_gc_register_address(VALUE *addr) 02988 { 02989 rb_objspace_t *objspace = &rb_objspace; 02990 struct gc_list *tmp; 02991 02992 tmp = ALLOC(struct gc_list); 02993 tmp->next = global_List; 02994 tmp->varptr = addr; 02995 global_List = tmp; 02996 } 02997 02998 void 02999 rb_gc_unregister_address(VALUE *addr) 03000 { 03001 rb_objspace_t *objspace = &rb_objspace; 03002 struct gc_list *tmp = global_List; 03003 03004 if (tmp->varptr == addr) { 03005 global_List = tmp->next; 03006 xfree(tmp); 03007 return; 03008 } 03009 while (tmp->next) { 03010 if (tmp->next->varptr == addr) { 03011 struct gc_list *t = tmp->next; 03012 03013 tmp->next = tmp->next->next; 03014 xfree(t); 03015 break; 03016 } 03017 tmp = tmp->next; 03018 } 03019 } 03020 03021 #define GC_NOTIFY 0 03022 03023 static int 03024 garbage_collect(rb_objspace_t *objspace) 03025 { 03026 if (GC_NOTIFY) printf("start garbage_collect()\n"); 03027 03028 if (!heaps) { 03029 return FALSE; 03030 } 03031 if (!ready_to_gc(objspace)) { 03032 return TRUE; 03033 } 03034 03035 gc_prof_timer_start(objspace); 03036 03037 rest_sweep(objspace); 03038 03039 during_gc++; 03040 gc_marks(objspace); 03041 03042 gc_prof_sweep_timer_start(objspace); 03043 gc_sweep(objspace); 03044 gc_prof_sweep_timer_stop(objspace); 03045 03046 gc_prof_timer_stop(objspace, Qtrue); 03047 if (GC_NOTIFY) printf("end garbage_collect()\n"); 03048 return TRUE; 03049 } 03050 03051 static void * 03052 gc_with_gvl(void *ptr) 03053 { 03054 return (void *)(VALUE)garbage_collect((rb_objspace_t *)ptr); 03055 } 03056 03057 static int 03058 garbage_collect_with_gvl(rb_objspace_t *objspace) 03059 { 03060 if (dont_gc) return TRUE; 03061 if (ruby_thread_has_gvl_p()) { 03062 return garbage_collect(objspace); 03063 } 03064 else { 03065 if (ruby_native_thread_p()) { 03066 return (int)(VALUE)rb_thread_call_with_gvl(gc_with_gvl, (void *)objspace); 03067 } 03068 else { 03069 /* no ruby thread */ 03070 fprintf(stderr, "[FATAL] failed to allocate memory\n"); 03071 exit(EXIT_FAILURE); 03072 } 03073 } 03074 } 03075 03076 int 03077 rb_garbage_collect(void) 03078 { 03079 return garbage_collect(&rb_objspace); 03080 } 03081 03082 #undef Init_stack 03083 03084 void 03085 Init_stack(volatile VALUE *addr) 03086 { 03087 ruby_init_stack(addr); 03088 } 03089 03090 /* 03091 * call-seq: 03092 * GC.start -> nil 03093 * gc.garbage_collect -> nil 03094 * ObjectSpace.garbage_collect -> nil 03095 * 03096 * Initiates garbage collection, unless manually disabled. 03097 * 03098 */ 03099 03100 VALUE 03101 rb_gc_start(void) 03102 { 03103 rb_gc(); 03104 return Qnil; 03105 } 03106 03107 void 03108 rb_gc(void) 03109 { 03110 rb_objspace_t *objspace = &rb_objspace; 03111 garbage_collect(objspace); 03112 if (!finalizing) finalize_deferred(objspace); 03113 free_unused_heaps(objspace); 03114 } 03115 03116 int 03117 rb_during_gc(void) 03118 { 03119 rb_objspace_t *objspace = &rb_objspace; 03120 return during_gc; 03121 } 03122 03123 /* 03124 * call-seq: 03125 * GC.count -> Integer 03126 * 03127 * The number of times GC occurred. 03128 * 03129 * It returns the number of times GC occurred since the process started. 03130 * 03131 */ 03132 03133 static VALUE 03134 gc_count(VALUE self) 03135 { 03136 return UINT2NUM(rb_objspace.count); 03137 } 03138 03139 /* 03140 * call-seq: 03141 * GC.stat -> Hash 03142 * 03143 * Returns a Hash containing information about the GC. 03144 * 03145 * The hash includes information about internal statistics about GC such as: 03146 * 03147 * { 03148 * :count=>0, 03149 * :heap_used=>12, 03150 * :heap_length=>12, 03151 * :heap_increment=>0, 03152 * :heap_live_num=>7539, 03153 * :heap_free_num=>88, 03154 * :heap_final_num=>0, 03155 * :total_allocated_object=>7630, 03156 * :total_freed_object=>88 03157 * } 03158 * 03159 * The contents of the hash are implementation specific and may be changed in 03160 * the future. 03161 * 03162 * This method is only expected to work on C Ruby. 03163 * 03164 */ 03165 03166 static VALUE 03167 gc_stat(int argc, VALUE *argv, VALUE self) 03168 { 03169 rb_objspace_t *objspace = &rb_objspace; 03170 VALUE hash; 03171 static VALUE sym_count; 03172 static VALUE sym_heap_used, sym_heap_length, sym_heap_increment; 03173 static VALUE sym_heap_live_num, sym_heap_free_num, sym_heap_final_num; 03174 static VALUE sym_total_allocated_object, sym_total_freed_object; 03175 if (sym_count == 0) { 03176 sym_count = ID2SYM(rb_intern_const("count")); 03177 sym_heap_used = ID2SYM(rb_intern_const("heap_used")); 03178 sym_heap_length = ID2SYM(rb_intern_const("heap_length")); 03179 sym_heap_increment = ID2SYM(rb_intern_const("heap_increment")); 03180 sym_heap_live_num = ID2SYM(rb_intern_const("heap_live_num")); 03181 sym_heap_free_num = ID2SYM(rb_intern_const("heap_free_num")); 03182 sym_heap_final_num = ID2SYM(rb_intern_const("heap_final_num")); 03183 sym_total_allocated_object = ID2SYM(rb_intern_const("total_allocated_object")); 03184 sym_total_freed_object = ID2SYM(rb_intern_const("total_freed_object")); 03185 } 03186 03187 if (rb_scan_args(argc, argv, "01", &hash) == 1) { 03188 if (!RB_TYPE_P(hash, T_HASH)) 03189 rb_raise(rb_eTypeError, "non-hash given"); 03190 } 03191 03192 if (hash == Qnil) { 03193 hash = rb_hash_new(); 03194 } 03195 03196 rest_sweep(objspace); 03197 03198 rb_hash_aset(hash, sym_count, SIZET2NUM(objspace->count)); 03199 /* implementation dependent counters */ 03200 rb_hash_aset(hash, sym_heap_used, SIZET2NUM(objspace->heap.used)); 03201 rb_hash_aset(hash, sym_heap_length, SIZET2NUM(objspace->heap.length)); 03202 rb_hash_aset(hash, sym_heap_increment, SIZET2NUM(objspace->heap.increment)); 03203 rb_hash_aset(hash, sym_heap_live_num, SIZET2NUM(objspace_live_num(objspace))); 03204 rb_hash_aset(hash, sym_heap_free_num, SIZET2NUM(objspace->heap.free_num)); 03205 rb_hash_aset(hash, sym_heap_final_num, SIZET2NUM(objspace->heap.final_num)); 03206 rb_hash_aset(hash, sym_total_allocated_object, SIZET2NUM(objspace->total_allocated_object_num)); 03207 rb_hash_aset(hash, sym_total_freed_object, SIZET2NUM(objspace->total_freed_object_num)); 03208 03209 return hash; 03210 } 03211 03212 /* 03213 * call-seq: 03214 * GC.stress -> true or false 03215 * 03216 * Returns current status of GC stress mode. 03217 */ 03218 03219 static VALUE 03220 gc_stress_get(VALUE self) 03221 { 03222 rb_objspace_t *objspace = &rb_objspace; 03223 return ruby_gc_stress ? Qtrue : Qfalse; 03224 } 03225 03226 /* 03227 * call-seq: 03228 * GC.stress = bool -> bool 03229 * 03230 * Updates the GC stress mode. 03231 * 03232 * When stress mode is enabled, the GC is invoked at every GC opportunity: 03233 * all memory and object allocations. 03234 * 03235 * Enabling stress mode will degrade performance, it is only for debugging. 03236 */ 03237 03238 static VALUE 03239 gc_stress_set(VALUE self, VALUE flag) 03240 { 03241 rb_objspace_t *objspace = &rb_objspace; 03242 rb_secure(2); 03243 ruby_gc_stress = RTEST(flag); 03244 return flag; 03245 } 03246 03247 /* 03248 * call-seq: 03249 * GC.enable -> true or false 03250 * 03251 * Enables garbage collection, returning +true+ if garbage 03252 * collection was previously disabled. 03253 * 03254 * GC.disable #=> false 03255 * GC.enable #=> true 03256 * GC.enable #=> false 03257 * 03258 */ 03259 03260 VALUE 03261 rb_gc_enable(void) 03262 { 03263 rb_objspace_t *objspace = &rb_objspace; 03264 int old = dont_gc; 03265 03266 dont_gc = FALSE; 03267 return old ? Qtrue : Qfalse; 03268 } 03269 03270 /* 03271 * call-seq: 03272 * GC.disable -> true or false 03273 * 03274 * Disables garbage collection, returning +true+ if garbage 03275 * collection was already disabled. 03276 * 03277 * GC.disable #=> false 03278 * GC.disable #=> true 03279 * 03280 */ 03281 03282 VALUE 03283 rb_gc_disable(void) 03284 { 03285 rb_objspace_t *objspace = &rb_objspace; 03286 int old = dont_gc; 03287 03288 dont_gc = TRUE; 03289 return old ? Qtrue : Qfalse; 03290 } 03291 03292 void 03293 rb_gc_set_params(void) 03294 { 03295 char *malloc_limit_ptr, *heap_min_slots_ptr, *free_min_ptr; 03296 03297 if (rb_safe_level() > 0) return; 03298 03299 malloc_limit_ptr = getenv("RUBY_GC_MALLOC_LIMIT"); 03300 if (malloc_limit_ptr != NULL) { 03301 int malloc_limit_i = atoi(malloc_limit_ptr); 03302 if (RTEST(ruby_verbose)) 03303 fprintf(stderr, "malloc_limit=%d (%d)\n", 03304 malloc_limit_i, initial_malloc_limit); 03305 if (malloc_limit_i > 0) { 03306 initial_malloc_limit = malloc_limit_i; 03307 } 03308 } 03309 03310 heap_min_slots_ptr = getenv("RUBY_HEAP_MIN_SLOTS"); 03311 if (heap_min_slots_ptr != NULL) { 03312 int heap_min_slots_i = atoi(heap_min_slots_ptr); 03313 if (RTEST(ruby_verbose)) 03314 fprintf(stderr, "heap_min_slots=%d (%d)\n", 03315 heap_min_slots_i, initial_heap_min_slots); 03316 if (heap_min_slots_i > 0) { 03317 initial_heap_min_slots = heap_min_slots_i; 03318 initial_expand_heap(&rb_objspace); 03319 } 03320 } 03321 03322 free_min_ptr = getenv("RUBY_FREE_MIN"); 03323 if (free_min_ptr != NULL) { 03324 int free_min_i = atoi(free_min_ptr); 03325 if (RTEST(ruby_verbose)) 03326 fprintf(stderr, "free_min=%d (%d)\n", free_min_i, initial_free_min); 03327 if (free_min_i > 0) { 03328 initial_free_min = free_min_i; 03329 } 03330 } 03331 } 03332 03333 void 03334 rb_objspace_reachable_objects_from(VALUE obj, void (func)(VALUE, void *), void *data) 03335 { 03336 rb_objspace_t *objspace = &rb_objspace; 03337 03338 if (markable_object_p(objspace, obj)) { 03339 struct mark_func_data_struct mfd; 03340 mfd.mark_func = func; 03341 mfd.data = data; 03342 objspace->mark_func_data = &mfd; 03343 gc_mark_children(objspace, obj); 03344 objspace->mark_func_data = 0; 03345 } 03346 } 03347 03348 /* 03349 ------------------------ Extended allocator ------------------------ 03350 */ 03351 03352 static void vm_xfree(rb_objspace_t *objspace, void *ptr); 03353 03354 static void * 03355 negative_size_allocation_error_with_gvl(void *ptr) 03356 { 03357 rb_raise(rb_eNoMemError, "%s", (const char *)ptr); 03358 return 0; /* should not be reached */ 03359 } 03360 03361 static void 03362 negative_size_allocation_error(const char *msg) 03363 { 03364 if (ruby_thread_has_gvl_p()) { 03365 rb_raise(rb_eNoMemError, "%s", msg); 03366 } 03367 else { 03368 if (ruby_native_thread_p()) { 03369 rb_thread_call_with_gvl(negative_size_allocation_error_with_gvl, (void *)msg); 03370 } 03371 else { 03372 fprintf(stderr, "[FATAL] %s\n", msg); 03373 exit(EXIT_FAILURE); 03374 } 03375 } 03376 } 03377 03378 static void * 03379 ruby_memerror_body(void *dummy) 03380 { 03381 rb_memerror(); 03382 return 0; 03383 } 03384 03385 static void 03386 ruby_memerror(void) 03387 { 03388 if (ruby_thread_has_gvl_p()) { 03389 rb_memerror(); 03390 } 03391 else { 03392 if (ruby_native_thread_p()) { 03393 rb_thread_call_with_gvl(ruby_memerror_body, 0); 03394 } 03395 else { 03396 /* no ruby thread */ 03397 fprintf(stderr, "[FATAL] failed to allocate memory\n"); 03398 exit(EXIT_FAILURE); 03399 } 03400 } 03401 } 03402 03403 void 03404 rb_memerror(void) 03405 { 03406 rb_thread_t *th = GET_THREAD(); 03407 if (!nomem_error || 03408 (rb_thread_raised_p(th, RAISED_NOMEMORY) && rb_safe_level() < 4)) { 03409 fprintf(stderr, "[FATAL] failed to allocate memory\n"); 03410 exit(EXIT_FAILURE); 03411 } 03412 if (rb_thread_raised_p(th, RAISED_NOMEMORY)) { 03413 rb_thread_raised_clear(th); 03414 GET_THREAD()->errinfo = nomem_error; 03415 JUMP_TAG(TAG_RAISE); 03416 } 03417 rb_thread_raised_set(th, RAISED_NOMEMORY); 03418 rb_exc_raise(nomem_error); 03419 } 03420 03421 static void * 03422 aligned_malloc(size_t alignment, size_t size) 03423 { 03424 void *res; 03425 03426 #if defined __MINGW32__ 03427 res = __mingw_aligned_malloc(size, alignment); 03428 #elif defined _WIN32 && !defined __CYGWIN__ 03429 res = _aligned_malloc(size, alignment); 03430 #elif defined(HAVE_POSIX_MEMALIGN) 03431 if (posix_memalign(&res, alignment, size) == 0) { 03432 return res; 03433 } 03434 else { 03435 return NULL; 03436 } 03437 #elif defined(HAVE_MEMALIGN) 03438 res = memalign(alignment, size); 03439 #else 03440 char* aligned; 03441 res = malloc(alignment + size + sizeof(void*)); 03442 aligned = (char*)res + alignment + sizeof(void*); 03443 aligned -= ((VALUE)aligned & (alignment - 1)); 03444 ((void**)aligned)[-1] = res; 03445 res = (void*)aligned; 03446 #endif 03447 03448 #if defined(_DEBUG) || defined(GC_DEBUG) 03449 /* alignment must be a power of 2 */ 03450 assert((alignment - 1) & alignment == 0); 03451 assert(alignment % sizeof(void*) == 0); 03452 #endif 03453 return res; 03454 } 03455 03456 static void 03457 aligned_free(void *ptr) 03458 { 03459 #if defined __MINGW32__ 03460 __mingw_aligned_free(ptr); 03461 #elif defined _WIN32 && !defined __CYGWIN__ 03462 _aligned_free(ptr); 03463 #elif defined(HAVE_MEMALIGN) || defined(HAVE_POSIX_MEMALIGN) 03464 free(ptr); 03465 #else 03466 free(((void**)ptr)[-1]); 03467 #endif 03468 } 03469 03470 static inline size_t 03471 vm_malloc_prepare(rb_objspace_t *objspace, size_t size) 03472 { 03473 if ((ssize_t)size < 0) { 03474 negative_size_allocation_error("negative allocation size (or too big)"); 03475 } 03476 if (size == 0) size = 1; 03477 03478 #if CALC_EXACT_MALLOC_SIZE 03479 size += sizeof(size_t); 03480 #endif 03481 03482 if ((ruby_gc_stress && !ruby_disable_gc_stress) || 03483 (malloc_increase+size) > malloc_limit) { 03484 garbage_collect_with_gvl(objspace); 03485 } 03486 03487 return size; 03488 } 03489 03490 static inline void * 03491 vm_malloc_fixup(rb_objspace_t *objspace, void *mem, size_t size) 03492 { 03493 ATOMIC_SIZE_ADD(malloc_increase, size); 03494 03495 #if CALC_EXACT_MALLOC_SIZE 03496 ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, size); 03497 ATOMIC_SIZE_INC(objspace->malloc_params.allocations); 03498 ((size_t *)mem)[0] = size; 03499 mem = (size_t *)mem + 1; 03500 #endif 03501 03502 return mem; 03503 } 03504 03505 #define TRY_WITH_GC(alloc) do { \ 03506 if (!(alloc) && \ 03507 (!garbage_collect_with_gvl(objspace) || \ 03508 !(alloc))) { \ 03509 ruby_memerror(); \ 03510 } \ 03511 } while (0) 03512 03513 static void * 03514 vm_xmalloc(rb_objspace_t *objspace, size_t size) 03515 { 03516 void *mem; 03517 03518 size = vm_malloc_prepare(objspace, size); 03519 TRY_WITH_GC(mem = malloc(size)); 03520 return vm_malloc_fixup(objspace, mem, size); 03521 } 03522 03523 static void * 03524 vm_xrealloc(rb_objspace_t *objspace, void *ptr, size_t size) 03525 { 03526 void *mem; 03527 #if CALC_EXACT_MALLOC_SIZE 03528 size_t oldsize; 03529 #endif 03530 03531 if ((ssize_t)size < 0) { 03532 negative_size_allocation_error("negative re-allocation size"); 03533 } 03534 03535 if (!ptr) return vm_xmalloc(objspace, size); 03536 03537 /* 03538 * The behavior of realloc(ptr, 0) is implementation defined. 03539 * Therefore we don't use realloc(ptr, 0) for portability reason. 03540 * see http://www.open-std.org/jtc1/sc22/wg14/www/docs/dr_400.htm 03541 */ 03542 if (size == 0) { 03543 vm_xfree(objspace, ptr); 03544 return 0; 03545 } 03546 if (ruby_gc_stress && !ruby_disable_gc_stress) 03547 garbage_collect_with_gvl(objspace); 03548 03549 #if CALC_EXACT_MALLOC_SIZE 03550 size += sizeof(size_t); 03551 ptr = (size_t *)ptr - 1; 03552 oldsize = ((size_t *)ptr)[0]; 03553 #endif 03554 03555 mem = realloc(ptr, size); 03556 if (!mem) { 03557 if (garbage_collect_with_gvl(objspace)) { 03558 mem = realloc(ptr, size); 03559 } 03560 if (!mem) { 03561 ruby_memerror(); 03562 } 03563 } 03564 ATOMIC_SIZE_ADD(malloc_increase, size); 03565 03566 #if CALC_EXACT_MALLOC_SIZE 03567 ATOMIC_SIZE_ADD(objspace->malloc_params.allocated_size, size - oldsize); 03568 ((size_t *)mem)[0] = size; 03569 mem = (size_t *)mem + 1; 03570 #endif 03571 03572 return mem; 03573 } 03574 03575 static void 03576 vm_xfree(rb_objspace_t *objspace, void *ptr) 03577 { 03578 #if CALC_EXACT_MALLOC_SIZE 03579 size_t size; 03580 ptr = ((size_t *)ptr) - 1; 03581 size = ((size_t*)ptr)[0]; 03582 if (size) { 03583 ATOMIC_SIZE_SUB(objspace->malloc_params.allocated_size, size); 03584 ATOMIC_SIZE_DEC(objspace->malloc_params.allocations); 03585 } 03586 #endif 03587 03588 free(ptr); 03589 } 03590 03591 void * 03592 ruby_xmalloc(size_t size) 03593 { 03594 return vm_xmalloc(&rb_objspace, size); 03595 } 03596 03597 static inline size_t 03598 xmalloc2_size(size_t n, size_t size) 03599 { 03600 size_t len = size * n; 03601 if (n != 0 && size != len / n) { 03602 rb_raise(rb_eArgError, "malloc: possible integer overflow"); 03603 } 03604 return len; 03605 } 03606 03607 void * 03608 ruby_xmalloc2(size_t n, size_t size) 03609 { 03610 return vm_xmalloc(&rb_objspace, xmalloc2_size(n, size)); 03611 } 03612 03613 static void * 03614 vm_xcalloc(rb_objspace_t *objspace, size_t count, size_t elsize) 03615 { 03616 void *mem; 03617 size_t size; 03618 03619 size = xmalloc2_size(count, elsize); 03620 size = vm_malloc_prepare(objspace, size); 03621 03622 TRY_WITH_GC(mem = calloc(1, size)); 03623 return vm_malloc_fixup(objspace, mem, size); 03624 } 03625 03626 void * 03627 ruby_xcalloc(size_t n, size_t size) 03628 { 03629 return vm_xcalloc(&rb_objspace, n, size); 03630 } 03631 03632 void * 03633 ruby_xrealloc(void *ptr, size_t size) 03634 { 03635 return vm_xrealloc(&rb_objspace, ptr, size); 03636 } 03637 03638 void * 03639 ruby_xrealloc2(void *ptr, size_t n, size_t size) 03640 { 03641 size_t len = size * n; 03642 if (n != 0 && size != len / n) { 03643 rb_raise(rb_eArgError, "realloc: possible integer overflow"); 03644 } 03645 return ruby_xrealloc(ptr, len); 03646 } 03647 03648 void 03649 ruby_xfree(void *x) 03650 { 03651 if (x) 03652 vm_xfree(&rb_objspace, x); 03653 } 03654 03655 03656 /* Mimic ruby_xmalloc, but need not rb_objspace. 03657 * should return pointer suitable for ruby_xfree 03658 */ 03659 void * 03660 ruby_mimmalloc(size_t size) 03661 { 03662 void *mem; 03663 #if CALC_EXACT_MALLOC_SIZE 03664 size += sizeof(size_t); 03665 #endif 03666 mem = malloc(size); 03667 #if CALC_EXACT_MALLOC_SIZE 03668 /* set 0 for consistency of allocated_size/allocations */ 03669 ((size_t *)mem)[0] = 0; 03670 mem = (size_t *)mem + 1; 03671 #endif 03672 return mem; 03673 } 03674 03675 #if CALC_EXACT_MALLOC_SIZE 03676 /* 03677 * call-seq: 03678 * GC.malloc_allocated_size -> Integer 03679 * 03680 * Returns the size of memory allocated by malloc(). 03681 * 03682 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+. 03683 */ 03684 03685 static VALUE 03686 gc_malloc_allocated_size(VALUE self) 03687 { 03688 return UINT2NUM(rb_objspace.malloc_params.allocated_size); 03689 } 03690 03691 /* 03692 * call-seq: 03693 * GC.malloc_allocations -> Integer 03694 * 03695 * Returns the number of malloc() allocations. 03696 * 03697 * Only available if ruby was built with +CALC_EXACT_MALLOC_SIZE+. 03698 */ 03699 03700 static VALUE 03701 gc_malloc_allocations(VALUE self) 03702 { 03703 return UINT2NUM(rb_objspace.malloc_params.allocations); 03704 } 03705 #endif 03706 03707 /* 03708 ------------------------------ WeakMap ------------------------------ 03709 */ 03710 03711 struct weakmap { 03712 st_table *obj2wmap; /* obj -> [ref,...] */ 03713 st_table *wmap2obj; /* ref -> obj */ 03714 VALUE final; 03715 }; 03716 03717 static int 03718 wmap_mark_map(st_data_t key, st_data_t val, st_data_t arg) 03719 { 03720 gc_mark_ptr((rb_objspace_t *)arg, (VALUE)val); 03721 return ST_CONTINUE; 03722 } 03723 03724 static void 03725 wmap_mark(void *ptr) 03726 { 03727 struct weakmap *w = ptr; 03728 st_foreach(w->obj2wmap, wmap_mark_map, (st_data_t)&rb_objspace); 03729 rb_gc_mark(w->final); 03730 } 03731 03732 static int 03733 wmap_free_map(st_data_t key, st_data_t val, st_data_t arg) 03734 { 03735 rb_ary_resize((VALUE)val, 0); 03736 return ST_CONTINUE; 03737 } 03738 03739 static void 03740 wmap_free(void *ptr) 03741 { 03742 struct weakmap *w = ptr; 03743 st_foreach(w->obj2wmap, wmap_free_map, 0); 03744 st_free_table(w->obj2wmap); 03745 st_free_table(w->wmap2obj); 03746 } 03747 03748 size_t rb_ary_memsize(VALUE ary); 03749 static int 03750 wmap_memsize_map(st_data_t key, st_data_t val, st_data_t arg) 03751 { 03752 *(size_t *)arg += rb_ary_memsize((VALUE)val); 03753 return ST_CONTINUE; 03754 } 03755 03756 static size_t 03757 wmap_memsize(const void *ptr) 03758 { 03759 size_t size; 03760 const struct weakmap *w = ptr; 03761 if (!w) return 0; 03762 size = sizeof(*w); 03763 size += st_memsize(w->obj2wmap); 03764 size += st_memsize(w->wmap2obj); 03765 st_foreach(w->obj2wmap, wmap_memsize_map, (st_data_t)&size); 03766 return size; 03767 } 03768 03769 static const rb_data_type_t weakmap_type = { 03770 "weakmap", 03771 { 03772 wmap_mark, 03773 wmap_free, 03774 wmap_memsize, 03775 } 03776 }; 03777 03778 static VALUE 03779 wmap_allocate(VALUE klass) 03780 { 03781 struct weakmap *w; 03782 VALUE obj = TypedData_Make_Struct(klass, struct weakmap, &weakmap_type, w); 03783 w->obj2wmap = st_init_numtable(); 03784 w->wmap2obj = st_init_numtable(); 03785 w->final = rb_obj_method(obj, ID2SYM(rb_intern("finalize"))); 03786 return obj; 03787 } 03788 03789 static int 03790 wmap_final_func(st_data_t *key, st_data_t *value, st_data_t arg, int existing) 03791 { 03792 VALUE wmap, ary; 03793 if (!existing) return ST_STOP; 03794 wmap = (VALUE)arg, ary = (VALUE)*value; 03795 rb_ary_delete_same(ary, wmap); 03796 if (!RARRAY_LEN(ary)) return ST_DELETE; 03797 return ST_CONTINUE; 03798 } 03799 03800 static VALUE 03801 wmap_finalize(VALUE self, VALUE objid) 03802 { 03803 st_data_t orig, wmap, data; 03804 VALUE obj, rids; 03805 long i; 03806 struct weakmap *w; 03807 03808 TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w); 03809 /* Get reference from object id. */ 03810 obj = obj_id_to_ref(objid); 03811 03812 /* obj is original referenced object and/or weak reference. */ 03813 orig = (st_data_t)obj; 03814 if (st_delete(w->obj2wmap, &orig, &data)) { 03815 rids = (VALUE)data; 03816 for (i = 0; i < RARRAY_LEN(rids); ++i) { 03817 wmap = (st_data_t)RARRAY_PTR(rids)[i]; 03818 st_delete(w->wmap2obj, &wmap, NULL); 03819 } 03820 } 03821 03822 wmap = (st_data_t)obj; 03823 if (st_delete(w->wmap2obj, &wmap, &orig)) { 03824 wmap = (st_data_t)obj; 03825 st_update(w->obj2wmap, orig, wmap_final_func, wmap); 03826 } 03827 return self; 03828 } 03829 03830 /* Creates a weak reference from the given key to the given value */ 03831 static VALUE 03832 wmap_aset(VALUE self, VALUE wmap, VALUE orig) 03833 { 03834 st_data_t data; 03835 VALUE rids; 03836 struct weakmap *w; 03837 03838 TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w); 03839 rb_define_final(orig, w->final); 03840 rb_define_final(wmap, w->final); 03841 if (st_lookup(w->obj2wmap, (st_data_t)orig, &data)) { 03842 rids = (VALUE)data; 03843 } 03844 else { 03845 rids = rb_ary_tmp_new(1); 03846 st_insert(w->obj2wmap, (st_data_t)orig, (st_data_t)rids); 03847 } 03848 rb_ary_push(rids, wmap); 03849 st_insert(w->wmap2obj, (st_data_t)wmap, (st_data_t)orig); 03850 return nonspecial_obj_id(orig); 03851 } 03852 03853 /* Retrieves a weakly referenced object with the given key */ 03854 static VALUE 03855 wmap_aref(VALUE self, VALUE wmap) 03856 { 03857 st_data_t data; 03858 VALUE obj; 03859 struct weakmap *w; 03860 rb_objspace_t *objspace = &rb_objspace; 03861 03862 TypedData_Get_Struct(self, struct weakmap, &weakmap_type, w); 03863 if (!st_lookup(w->wmap2obj, (st_data_t)wmap, &data)) return Qnil; 03864 obj = (VALUE)data; 03865 if (!is_id_value(objspace, obj)) return Qnil; 03866 if (!is_live_object(objspace, obj)) return Qnil; 03867 return obj; 03868 } 03869 03870 03871 /* 03872 ------------------------------ GC profiler ------------------------------ 03873 */ 03874 03875 static inline void gc_prof_set_heap_info(rb_objspace_t *, gc_profile_record *); 03876 #define GC_PROFILE_RECORD_DEFAULT_SIZE 100 03877 03878 static double 03879 getrusage_time(void) 03880 { 03881 #if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_PROCESS_CPUTIME_ID) 03882 struct timespec ts; 03883 03884 if (clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts) == 0) { 03885 return ts.tv_sec + ts.tv_nsec * 1e-9; 03886 } 03887 return 0.0; 03888 #elif defined RUSAGE_SELF 03889 struct rusage usage; 03890 struct timeval time; 03891 getrusage(RUSAGE_SELF, &usage); 03892 time = usage.ru_utime; 03893 return time.tv_sec + time.tv_usec * 1e-6; 03894 #elif defined _WIN32 03895 FILETIME creation_time, exit_time, kernel_time, user_time; 03896 ULARGE_INTEGER ui; 03897 LONG_LONG q; 03898 double t; 03899 03900 if (GetProcessTimes(GetCurrentProcess(), 03901 &creation_time, &exit_time, &kernel_time, &user_time) == 0) 03902 { 03903 return 0.0; 03904 } 03905 memcpy(&ui, &user_time, sizeof(FILETIME)); 03906 q = ui.QuadPart / 10L; 03907 t = (DWORD)(q % 1000000L) * 1e-6; 03908 q /= 1000000L; 03909 #ifdef __GNUC__ 03910 t += q; 03911 #else 03912 t += (double)(DWORD)(q >> 16) * (1 << 16); 03913 t += (DWORD)q & ~(~0 << 16); 03914 #endif 03915 return t; 03916 #else 03917 return 0.0; 03918 #endif 03919 } 03920 03921 static inline void 03922 gc_prof_timer_start(rb_objspace_t *objspace) 03923 { 03924 if (objspace->profile.run) { 03925 size_t count = objspace->profile.count; 03926 03927 if (!objspace->profile.record) { 03928 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE; 03929 objspace->profile.record = malloc(sizeof(gc_profile_record) * objspace->profile.size); 03930 } 03931 if (count >= objspace->profile.size) { 03932 objspace->profile.size += 1000; 03933 objspace->profile.record = realloc(objspace->profile.record, sizeof(gc_profile_record) * objspace->profile.size); 03934 } 03935 if (!objspace->profile.record) { 03936 rb_bug("gc_profile malloc or realloc miss"); 03937 } 03938 MEMZERO(&objspace->profile.record[count], gc_profile_record, 1); 03939 objspace->profile.record[count].gc_time = getrusage_time(); 03940 objspace->profile.record[objspace->profile.count].gc_invoke_time = 03941 objspace->profile.record[count].gc_time - objspace->profile.invoke_time; 03942 } 03943 } 03944 03945 static inline void 03946 gc_prof_timer_stop(rb_objspace_t *objspace, int marked) 03947 { 03948 if (objspace->profile.run) { 03949 double gc_time = 0; 03950 size_t count = objspace->profile.count; 03951 gc_profile_record *record = &objspace->profile.record[count]; 03952 03953 gc_time = getrusage_time() - record->gc_time; 03954 if (gc_time < 0) gc_time = 0; 03955 record->gc_time = gc_time; 03956 record->is_marked = !!(marked); 03957 gc_prof_set_heap_info(objspace, record); 03958 objspace->profile.count++; 03959 } 03960 } 03961 03962 #if !GC_PROFILE_MORE_DETAIL 03963 03964 static inline void 03965 gc_prof_mark_timer_start(rb_objspace_t *objspace) 03966 { 03967 if (RUBY_DTRACE_GC_MARK_BEGIN_ENABLED()) { 03968 RUBY_DTRACE_GC_MARK_BEGIN(); 03969 } 03970 } 03971 03972 static inline void 03973 gc_prof_mark_timer_stop(rb_objspace_t *objspace) 03974 { 03975 if (RUBY_DTRACE_GC_MARK_END_ENABLED()) { 03976 RUBY_DTRACE_GC_MARK_END(); 03977 } 03978 } 03979 03980 static inline void 03981 gc_prof_sweep_timer_start(rb_objspace_t *objspace) 03982 { 03983 if (RUBY_DTRACE_GC_SWEEP_BEGIN_ENABLED()) { 03984 RUBY_DTRACE_GC_SWEEP_BEGIN(); 03985 } 03986 } 03987 03988 static inline void 03989 gc_prof_sweep_timer_stop(rb_objspace_t *objspace) 03990 { 03991 if (RUBY_DTRACE_GC_SWEEP_END_ENABLED()) { 03992 RUBY_DTRACE_GC_SWEEP_END(); 03993 } 03994 } 03995 03996 static inline void 03997 gc_prof_set_malloc_info(rb_objspace_t *objspace) 03998 { 03999 } 04000 04001 static inline void 04002 gc_prof_set_heap_info(rb_objspace_t *objspace, gc_profile_record *record) 04003 { 04004 size_t live = objspace_live_num(objspace); 04005 size_t total = heaps_used * HEAP_OBJ_LIMIT; 04006 04007 record->heap_total_objects = total; 04008 record->heap_use_size = live * sizeof(RVALUE); 04009 record->heap_total_size = total * sizeof(RVALUE); 04010 } 04011 04012 #else 04013 04014 static inline void 04015 gc_prof_mark_timer_start(rb_objspace_t *objspace) 04016 { 04017 if (RUBY_DTRACE_GC_MARK_BEGIN_ENABLED()) { 04018 RUBY_DTRACE_GC_MARK_BEGIN(); 04019 } 04020 if (objspace->profile.run) { 04021 size_t count = objspace->profile.count; 04022 04023 objspace->profile.record[count].gc_mark_time = getrusage_time(); 04024 } 04025 } 04026 04027 static inline void 04028 gc_prof_mark_timer_stop(rb_objspace_t *objspace) 04029 { 04030 if (RUBY_DTRACE_GC_MARK_END_ENABLED()) { 04031 RUBY_DTRACE_GC_MARK_END(); 04032 } 04033 if (objspace->profile.run) { 04034 double mark_time = 0; 04035 size_t count = objspace->profile.count; 04036 gc_profile_record *record = &objspace->profile.record[count]; 04037 04038 mark_time = getrusage_time() - record->gc_mark_time; 04039 if (mark_time < 0) mark_time = 0; 04040 record->gc_mark_time = mark_time; 04041 } 04042 } 04043 04044 static inline void 04045 gc_prof_sweep_timer_start(rb_objspace_t *objspace) 04046 { 04047 if (RUBY_DTRACE_GC_SWEEP_BEGIN_ENABLED()) { 04048 RUBY_DTRACE_GC_SWEEP_BEGIN(); 04049 } 04050 if (objspace->profile.run) { 04051 size_t count = objspace->profile.count; 04052 04053 objspace->profile.record[count].gc_sweep_time = getrusage_time(); 04054 } 04055 } 04056 04057 static inline void 04058 gc_prof_sweep_timer_stop(rb_objspace_t *objspace) 04059 { 04060 if (RUBY_DTRACE_GC_SWEEP_END_ENABLED()) { 04061 RUBY_DTRACE_GC_SWEEP_END(); 04062 } 04063 if (objspace->profile.run) { 04064 double sweep_time = 0; 04065 size_t count = objspace->profile.count; 04066 gc_profile_record *record = &objspace->profile.record[count]; 04067 04068 sweep_time = getrusage_time() - record->gc_sweep_time;\ 04069 if (sweep_time < 0) sweep_time = 0;\ 04070 record->gc_sweep_time = sweep_time; 04071 } 04072 } 04073 04074 static inline void 04075 gc_prof_set_malloc_info(rb_objspace_t *objspace) 04076 { 04077 if (objspace->profile.run) { 04078 gc_profile_record *record = &objspace->profile.record[objspace->profile.count]; 04079 if (record) { 04080 record->allocate_increase = malloc_increase; 04081 record->allocate_limit = malloc_limit; 04082 } 04083 } 04084 } 04085 04086 static inline void 04087 gc_prof_set_heap_info(rb_objspace_t *objspace, gc_profile_record *record) 04088 { 04089 size_t live = objspace->heap.live_num; 04090 size_t total = heaps_used * HEAP_OBJ_LIMIT; 04091 04092 record->heap_use_slots = heaps_used; 04093 record->heap_live_objects = live; 04094 record->heap_free_objects = total - live; 04095 record->heap_total_objects = total; 04096 record->have_finalize = deferred_final_list ? Qtrue : Qfalse; 04097 record->heap_use_size = live * sizeof(RVALUE); 04098 record->heap_total_size = total * sizeof(RVALUE); 04099 } 04100 04101 #endif /* !GC_PROFILE_MORE_DETAIL */ 04102 04103 04104 /* 04105 * call-seq: 04106 * GC::Profiler.clear -> nil 04107 * 04108 * Clears the GC profiler data. 04109 * 04110 */ 04111 04112 static VALUE 04113 gc_profile_clear(void) 04114 { 04115 rb_objspace_t *objspace = &rb_objspace; 04116 04117 if (GC_PROFILE_RECORD_DEFAULT_SIZE * 2 < objspace->profile.size) { 04118 objspace->profile.size = GC_PROFILE_RECORD_DEFAULT_SIZE * 2; 04119 objspace->profile.record = realloc(objspace->profile.record, sizeof(gc_profile_record) * objspace->profile.size); 04120 if (!objspace->profile.record) { 04121 rb_memerror(); 04122 } 04123 } 04124 MEMZERO(objspace->profile.record, gc_profile_record, objspace->profile.size); 04125 objspace->profile.count = 0; 04126 return Qnil; 04127 } 04128 04129 /* 04130 * call-seq: 04131 * GC::Profiler.raw_data -> [Hash, ...] 04132 * 04133 * Returns an Array of individual raw profile data Hashes ordered 04134 * from earliest to latest by +:GC_INVOKE_TIME+. 04135 * 04136 * For example: 04137 * 04138 * [ 04139 * { 04140 * :GC_TIME=>1.3000000000000858e-05, 04141 * :GC_INVOKE_TIME=>0.010634999999999999, 04142 * :HEAP_USE_SIZE=>289640, 04143 * :HEAP_TOTAL_SIZE=>588960, 04144 * :HEAP_TOTAL_OBJECTS=>14724, 04145 * :GC_IS_MARKED=>false 04146 * }, 04147 * # ... 04148 * ] 04149 * 04150 * The keys mean: 04151 * 04152 * +:GC_TIME+:: 04153 * Time elapsed in seconds for this GC run 04154 * +:GC_INVOKE_TIME+:: 04155 * Time elapsed in seconds from startup to when the GC was invoked 04156 * +:HEAP_USE_SIZE+:: 04157 * Total bytes of heap used 04158 * +:HEAP_TOTAL_SIZE+:: 04159 * Total size of heap in bytes 04160 * +:HEAP_TOTAL_OBJECTS+:: 04161 * Total number of objects 04162 * +:GC_IS_MARKED+:: 04163 * Returns +true+ if the GC is in mark phase 04164 * 04165 * If ruby was built with +GC_PROFILE_MORE_DETAIL+, you will also have access 04166 * to the following hash keys: 04167 * 04168 * +:GC_MARK_TIME+:: 04169 * +:GC_SWEEP_TIME+:: 04170 * +:ALLOCATE_INCREASE+:: 04171 * +:ALLOCATE_LIMIT+:: 04172 * +:HEAP_USE_SLOTS+:: 04173 * +:HEAP_LIVE_OBJECTS+:: 04174 * +:HEAP_FREE_OBJECTS+:: 04175 * +:HAVE_FINALIZE+:: 04176 * 04177 */ 04178 04179 static VALUE 04180 gc_profile_record_get(void) 04181 { 04182 VALUE prof; 04183 VALUE gc_profile = rb_ary_new(); 04184 size_t i; 04185 rb_objspace_t *objspace = (&rb_objspace); 04186 04187 if (!objspace->profile.run) { 04188 return Qnil; 04189 } 04190 04191 for (i =0; i < objspace->profile.count; i++) { 04192 prof = rb_hash_new(); 04193 rb_hash_aset(prof, ID2SYM(rb_intern("GC_TIME")), DBL2NUM(objspace->profile.record[i].gc_time)); 04194 rb_hash_aset(prof, ID2SYM(rb_intern("GC_INVOKE_TIME")), DBL2NUM(objspace->profile.record[i].gc_invoke_time)); 04195 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SIZE")), SIZET2NUM(objspace->profile.record[i].heap_use_size)); 04196 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_SIZE")), SIZET2NUM(objspace->profile.record[i].heap_total_size)); 04197 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_TOTAL_OBJECTS")), SIZET2NUM(objspace->profile.record[i].heap_total_objects)); 04198 rb_hash_aset(prof, ID2SYM(rb_intern("GC_IS_MARKED")), objspace->profile.record[i].is_marked); 04199 #if GC_PROFILE_MORE_DETAIL 04200 rb_hash_aset(prof, ID2SYM(rb_intern("GC_MARK_TIME")), DBL2NUM(objspace->profile.record[i].gc_mark_time)); 04201 rb_hash_aset(prof, ID2SYM(rb_intern("GC_SWEEP_TIME")), DBL2NUM(objspace->profile.record[i].gc_sweep_time)); 04202 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_INCREASE")), SIZET2NUM(objspace->profile.record[i].allocate_increase)); 04203 rb_hash_aset(prof, ID2SYM(rb_intern("ALLOCATE_LIMIT")), SIZET2NUM(objspace->profile.record[i].allocate_limit)); 04204 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_USE_SLOTS")), SIZET2NUM(objspace->profile.record[i].heap_use_slots)); 04205 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_LIVE_OBJECTS")), SIZET2NUM(objspace->profile.record[i].heap_live_objects)); 04206 rb_hash_aset(prof, ID2SYM(rb_intern("HEAP_FREE_OBJECTS")), SIZET2NUM(objspace->profile.record[i].heap_free_objects)); 04207 rb_hash_aset(prof, ID2SYM(rb_intern("HAVE_FINALIZE")), objspace->profile.record[i].have_finalize); 04208 #endif 04209 rb_ary_push(gc_profile, prof); 04210 } 04211 04212 return gc_profile; 04213 } 04214 04215 static void 04216 gc_profile_dump_on(VALUE out, VALUE (*append)(VALUE, VALUE)) 04217 { 04218 rb_objspace_t *objspace = &rb_objspace; 04219 size_t count = objspace->profile.count; 04220 04221 if (objspace->profile.run && count) { 04222 int index = 1; 04223 size_t i; 04224 gc_profile_record r; 04225 append(out, rb_sprintf("GC %"PRIuSIZE" invokes.\n", objspace->count)); 04226 append(out, rb_str_new_cstr("Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC Time(ms)\n")); 04227 for (i = 0; i < count; i++) { 04228 r = objspace->profile.record[i]; 04229 #if !GC_PROFILE_MORE_DETAIL 04230 if (r.is_marked) { 04231 #endif 04232 append(out, rb_sprintf("%5d %19.3f %20"PRIuSIZE" %20"PRIuSIZE" %20"PRIuSIZE" %30.20f\n", 04233 index++, r.gc_invoke_time, r.heap_use_size, 04234 r.heap_total_size, r.heap_total_objects, r.gc_time*1000)); 04235 #if !GC_PROFILE_MORE_DETAIL 04236 } 04237 #endif 04238 } 04239 #if GC_PROFILE_MORE_DETAIL 04240 append(out, rb_str_new_cstr("\n\n" \ 04241 "More detail.\n" \ 04242 "Index Allocate Increase Allocate Limit Use Slot Have Finalize Mark Time(ms) Sweep Time(ms)\n")); 04243 index = 1; 04244 for (i = 0; i < count; i++) { 04245 r = objspace->profile.record[i]; 04246 append(out, rb_sprintf("%5d %17"PRIuSIZE" %17"PRIuSIZE" %9"PRIuSIZE" %14s %25.20f %25.20f\n", 04247 index++, r.allocate_increase, r.allocate_limit, 04248 r.heap_use_slots, (r.have_finalize ? "true" : "false"), 04249 r.gc_mark_time*1000, r.gc_sweep_time*1000)); 04250 } 04251 #endif 04252 } 04253 } 04254 04255 /* 04256 * call-seq: 04257 * GC::Profiler.result -> String 04258 * 04259 * Returns a profile data report such as: 04260 * 04261 * GC 1 invokes. 04262 * Index Invoke Time(sec) Use Size(byte) Total Size(byte) Total Object GC time(ms) 04263 * 1 0.012 159240 212940 10647 0.00000000000001530000 04264 */ 04265 04266 static VALUE 04267 gc_profile_result(void) 04268 { 04269 VALUE str = rb_str_buf_new(0); 04270 gc_profile_dump_on(str, rb_str_buf_append); 04271 return str; 04272 } 04273 04274 /* 04275 * call-seq: 04276 * GC::Profiler.report 04277 * GC::Profiler.report(io) 04278 * 04279 * Writes the GC::Profiler.result to <tt>$stdout</tt> or the given IO object. 04280 * 04281 */ 04282 04283 static VALUE 04284 gc_profile_report(int argc, VALUE *argv, VALUE self) 04285 { 04286 VALUE out; 04287 04288 if (argc == 0) { 04289 out = rb_stdout; 04290 } 04291 else { 04292 rb_scan_args(argc, argv, "01", &out); 04293 } 04294 gc_profile_dump_on(out, rb_io_write); 04295 04296 return Qnil; 04297 } 04298 04299 /* 04300 * call-seq: 04301 * GC::Profiler.total_time -> float 04302 * 04303 * The total time used for garbage collection in seconds 04304 */ 04305 04306 static VALUE 04307 gc_profile_total_time(VALUE self) 04308 { 04309 double time = 0; 04310 rb_objspace_t *objspace = &rb_objspace; 04311 size_t i; 04312 04313 if (objspace->profile.run && objspace->profile.count) { 04314 for (i = 0; i < objspace->profile.count; i++) { 04315 time += objspace->profile.record[i].gc_time; 04316 } 04317 } 04318 return DBL2NUM(time); 04319 } 04320 04321 /* 04322 * call-seq: 04323 * GC::Profiler.enabled? -> true or false 04324 * 04325 * The current status of GC profile mode. 04326 */ 04327 04328 static VALUE 04329 gc_profile_enable_get(VALUE self) 04330 { 04331 rb_objspace_t *objspace = &rb_objspace; 04332 return objspace->profile.run ? Qtrue : Qfalse; 04333 } 04334 04335 /* 04336 * call-seq: 04337 * GC::Profiler.enable -> nil 04338 * 04339 * Starts the GC profiler. 04340 * 04341 */ 04342 04343 static VALUE 04344 gc_profile_enable(void) 04345 { 04346 rb_objspace_t *objspace = &rb_objspace; 04347 04348 objspace->profile.run = TRUE; 04349 return Qnil; 04350 } 04351 04352 /* 04353 * call-seq: 04354 * GC::Profiler.disable -> nil 04355 * 04356 * Stops the GC profiler. 04357 * 04358 */ 04359 04360 static VALUE 04361 gc_profile_disable(void) 04362 { 04363 rb_objspace_t *objspace = &rb_objspace; 04364 04365 objspace->profile.run = FALSE; 04366 return Qnil; 04367 } 04368 04369 #ifdef GC_DEBUG 04370 04371 /* 04372 ------------------------------ DEBUG ------------------------------ 04373 */ 04374 04375 void 04376 rb_gcdebug_print_obj_condition(VALUE obj) 04377 { 04378 rb_objspace_t *objspace = &rb_objspace; 04379 04380 if (is_pointer_to_heap(objspace, (void *)obj)) { 04381 fprintf(stderr, "pointer to heap?: true\n"); 04382 } 04383 else { 04384 fprintf(stderr, "pointer to heap?: false\n"); 04385 return; 04386 } 04387 fprintf(stderr, "marked?: %s\n", 04388 MARKED_IN_BITMAP(GET_HEAP_BITMAP(obj), obj) ? "true" : "false"); 04389 if (is_lazy_sweeping(objspace)) { 04390 fprintf(stderr, "lazy sweeping?: true\n"); 04391 fprintf(stderr, "swept?: %s\n", 04392 is_swept_object(objspace, obj) ? "done" : "not yet"); 04393 } 04394 else { 04395 fprintf(stderr, "lazy sweeping?: false\n"); 04396 } 04397 } 04398 04399 static VALUE 04400 gcdebug_sential(VALUE obj, VALUE name) 04401 { 04402 fprintf(stderr, "WARNING: object %s(%p) is inadvertently collected\n", (char *)name, (void *)obj); 04403 return Qnil; 04404 } 04405 04406 void 04407 rb_gcdebug_sentinel(VALUE obj, const char *name) 04408 { 04409 rb_define_final(obj, rb_proc_new(gcdebug_sential, (VALUE)name)); 04410 } 04411 #endif /* GC_DEBUG */ 04412 04413 04414 /* 04415 * Document-class: ObjectSpace 04416 * 04417 * The ObjectSpace module contains a number of routines 04418 * that interact with the garbage collection facility and allow you to 04419 * traverse all living objects with an iterator. 04420 * 04421 * ObjectSpace also provides support for object finalizers, procs that will be 04422 * called when a specific object is about to be destroyed by garbage 04423 * collection. 04424 * 04425 * include ObjectSpace 04426 * 04427 * a = "A" 04428 * b = "B" 04429 * c = "C" 04430 * 04431 * define_finalizer(a, proc {|id| puts "Finalizer one on #{id}" }) 04432 * define_finalizer(a, proc {|id| puts "Finalizer two on #{id}" }) 04433 * define_finalizer(b, proc {|id| puts "Finalizer three on #{id}" }) 04434 * 04435 * _produces:_ 04436 * 04437 * Finalizer three on 537763470 04438 * Finalizer one on 537763480 04439 * Finalizer two on 537763480 04440 * 04441 */ 04442 04443 /* 04444 * Document-class: ObjectSpace::WeakMap 04445 * 04446 * An ObjectSpace::WeakMap object holds references to 04447 * any objects, but those objects can get garbage collected. 04448 * 04449 * This class is mostly used internally by WeakRef, please use 04450 * +lib/weakref.rb+ for the public interface. 04451 */ 04452 04453 /* Document-class: GC::Profiler 04454 * 04455 * The GC profiler provides access to information on GC runs including time, 04456 * length and object space size. 04457 * 04458 * Example: 04459 * 04460 * GC::Profiler.enable 04461 * 04462 * require 'rdoc/rdoc' 04463 * 04464 * GC::Profiler.report 04465 * 04466 * GC::Profiler.disable 04467 * 04468 * See also GC.count, GC.malloc_allocated_size and GC.malloc_allocations 04469 */ 04470 04471 /* 04472 * The GC module provides an interface to Ruby's mark and 04473 * sweep garbage collection mechanism. 04474 * 04475 * Some of the underlying methods are also available via the ObjectSpace 04476 * module. 04477 * 04478 * You may obtain information about the operation of the GC through 04479 * GC::Profiler. 04480 */ 04481 04482 void 04483 Init_GC(void) 04484 { 04485 VALUE rb_mObSpace; 04486 VALUE rb_mProfiler; 04487 04488 rb_mGC = rb_define_module("GC"); 04489 rb_define_singleton_method(rb_mGC, "start", rb_gc_start, 0); 04490 rb_define_singleton_method(rb_mGC, "enable", rb_gc_enable, 0); 04491 rb_define_singleton_method(rb_mGC, "disable", rb_gc_disable, 0); 04492 rb_define_singleton_method(rb_mGC, "stress", gc_stress_get, 0); 04493 rb_define_singleton_method(rb_mGC, "stress=", gc_stress_set, 1); 04494 rb_define_singleton_method(rb_mGC, "count", gc_count, 0); 04495 rb_define_singleton_method(rb_mGC, "stat", gc_stat, -1); 04496 rb_define_method(rb_mGC, "garbage_collect", rb_gc_start, 0); 04497 04498 rb_mProfiler = rb_define_module_under(rb_mGC, "Profiler"); 04499 rb_define_singleton_method(rb_mProfiler, "enabled?", gc_profile_enable_get, 0); 04500 rb_define_singleton_method(rb_mProfiler, "enable", gc_profile_enable, 0); 04501 rb_define_singleton_method(rb_mProfiler, "raw_data", gc_profile_record_get, 0); 04502 rb_define_singleton_method(rb_mProfiler, "disable", gc_profile_disable, 0); 04503 rb_define_singleton_method(rb_mProfiler, "clear", gc_profile_clear, 0); 04504 rb_define_singleton_method(rb_mProfiler, "result", gc_profile_result, 0); 04505 rb_define_singleton_method(rb_mProfiler, "report", gc_profile_report, -1); 04506 rb_define_singleton_method(rb_mProfiler, "total_time", gc_profile_total_time, 0); 04507 04508 rb_mObSpace = rb_define_module("ObjectSpace"); 04509 rb_define_module_function(rb_mObSpace, "each_object", os_each_obj, -1); 04510 rb_define_module_function(rb_mObSpace, "garbage_collect", rb_gc_start, 0); 04511 04512 rb_define_module_function(rb_mObSpace, "define_finalizer", define_final, -1); 04513 rb_define_module_function(rb_mObSpace, "undefine_finalizer", undefine_final, 1); 04514 04515 rb_define_module_function(rb_mObSpace, "_id2ref", id2ref, 1); 04516 04517 nomem_error = rb_exc_new3(rb_eNoMemError, 04518 rb_obj_freeze(rb_str_new2("failed to allocate memory"))); 04519 OBJ_TAINT(nomem_error); 04520 OBJ_FREEZE(nomem_error); 04521 04522 rb_define_method(rb_cBasicObject, "__id__", rb_obj_id, 0); 04523 rb_define_method(rb_mKernel, "object_id", rb_obj_id, 0); 04524 04525 rb_define_module_function(rb_mObSpace, "count_objects", count_objects, -1); 04526 04527 { 04528 VALUE rb_cWeakMap = rb_define_class_under(rb_mObSpace, "WeakMap", rb_cObject); 04529 rb_define_alloc_func(rb_cWeakMap, wmap_allocate); 04530 rb_define_method(rb_cWeakMap, "[]=", wmap_aset, 2); 04531 rb_define_method(rb_cWeakMap, "[]", wmap_aref, 1); 04532 rb_define_private_method(rb_cWeakMap, "finalize", wmap_finalize, 1); 04533 } 04534 04535 #if CALC_EXACT_MALLOC_SIZE 04536 rb_define_singleton_method(rb_mGC, "malloc_allocated_size", gc_malloc_allocated_size, 0); 04537 rb_define_singleton_method(rb_mGC, "malloc_allocations", gc_malloc_allocations, 0); 04538 #endif 04539 } 04540