Граф коммитов

2574 Коммитов

Автор SHA1 Сообщение Дата
Peter Zhu b9109b270d Get error from dln_open when USE_SHARED_GC
Before, if dln_open failed to open RUBY_GC_LIBRARY_PATH, it would segfault
because it would try to raise an error, which cannot happen because the
GC has not been initialized yet.

This commit changes dln_open to return the error that occurred so the
caller can handle the error.
2024-04-23 15:29:42 -04:00
Matt Valentine-House 4218e6bbd5 Remove unused define popcount_bits 2024-04-19 11:39:20 +01:00
Aaron Patterson 147ca9585e Implement equality for CI comparison when CC searching
When we're searching for CCs, compare the argc and flags for CI rather
than comparing pointers.  This means we don't need to store a reference
to the CI, and it also naturally "de-duplicates" CC objects.

We can observe the effect with the following code:

```ruby
require "objspace"

hash = {}

p ObjectSpace.memsize_of(Hash)

eval ("a".."zzz").map { |key|
  "hash.merge(:#{key} => 1)"
}.join("; ")

p ObjectSpace.memsize_of(Hash)
```

On master:

```
$ ruby -v test.rb
ruby 3.4.0dev (2024-04-15T16:21:41Z master d019b3baec) [arm64-darwin23]
test.rb:3: warning: assigned but unused variable - hash
3424
527736
```

On this branch:

```
$ make runruby
compiling vm.c
linking miniruby
builtin_binary.inc updated
compiling builtin.c
linking static-library libruby.3.4-static.a
ln -sf ../../rbconfig.rb .ext/arm64-darwin23/rbconfig.rb
linking ruby
ld: warning: ignoring duplicate libraries: '-ldl', '-lobjc', '-lpthread'
RUBY_ON_BUG='gdb -x ./.gdbinit -p' ./miniruby -I./lib -I. -I.ext/common  ./tool/runruby.rb --extout=.ext  -- --disable-gems  ./test.rb
2240
2368
```

Co-authored-by: John Hawthorn <jhawthorn@github.com>
2024-04-18 09:06:33 -07:00
Peter Zhu 81240493a3 Remove unused rb_size_pool_slot_size 2024-04-18 10:19:42 -04:00
Matt Valentine-House 0727d32b56 Don't verify during gc_enter when gc is disabled.
RGENGC_CHECK_MODE >=3 fails with an incinsistency in the old object
count during ec_finalization.

This is due to inconsistency introduced to the object graph using T_DATA
finalizers.

This is explained in commit 79df14c04b,
which disabled gc during finalization to work around this.

```
    /* prohibit GC because force T_DATA finalizers can break an object graph consistency */
    dont_gc_on()
```

This object graph inconsistency also seems to break RGENGC_CHECK_MODE >=
3, when it attempt to verify the object age relationships during
finalization at VM shutdown (gc_enter is called during finalization).

This commit stops the internal consistency check during gc_enter only
when RGENGC_CHECK_MODE >= 3 and when gc is disabled.

This fixes `make btest` with `-DRGENGC_CHECK_MODE=3`
2024-04-17 23:29:23 +01:00
Matt Valentine-House 3a4035a790 Reduce the number of references to need_major_gc 2024-04-17 21:16:47 +01:00
Peter Zhu 814dedcee2 Remove unused ruby_sighandler_t 2024-04-17 14:01:59 -04:00
Peter Zhu ee6e591b6a Use unsigned long long for object ID
Since unsigned long long are minumum 64 bits, we have at least 10**17
object IDs available, so there is no chance it will overflow.
2024-04-17 13:33:17 -04:00
Peter Zhu 209e2f277e Don't allow T_NIL in gc_is_moveable_obj
gc_is_moveable_obj is only given GC managed objects, and T_NIL cannot be
a GC managed type.
2024-04-17 09:49:11 -04:00
Matt Valentine-House 2470565993 Inline single use variables 2024-04-17 13:31:45 +01:00
Peter Zhu d6debba817 Don't check for dynamic symbol in gc_is_moveable_obj
All GC managed symbols are dynamic symbols so we don't need to check it.
2024-04-16 14:34:52 -04:00
Peter Zhu e5df8897fe Don't check for thread in gc_sweep_page
We should always have a thread when we sweep so we don't need to check
that it exists.
2024-04-16 13:24:46 -04:00
Matt Valentine-House 065710c0f5 Initialize external GC Library
Co-Authored-By: Peter Zhu <peter@peterzhu.ca>
2024-04-15 19:50:47 +01:00
Peter Zhu 9bab179ca3 Don't treat flonum specially in object ID
flonum is just a special constant, so we don't need to treat it in any
special way.
2024-04-12 11:27:08 -04:00
Peter Zhu edec690e03 Refactor how object IDs work for special consts
We don't need to treat static symbols in any special way since they
can't be confused with other special consts or GC managed objects.
2024-04-12 11:27:08 -04:00
Peter Zhu f2369de2a4 Remove redundant cast
ptr is already of the VALUE type, so we don't need to cast it.
2024-04-11 12:08:03 -04:00
Peter Zhu f389a211b5 Fix indentation in switch statement in gc.c 2024-04-10 16:32:49 -04:00
Nobuyoshi Nakada b006919200 `objspace_each_pages` is also only used if GC compression is possible 2024-04-06 18:51:24 +09:00
Peter Zhu 1f84e1099e [DOC] Add nodoc for GC.remove_stress_to_class
This method is only available when compiled with GC_DEBUG_STRESS_TO_CLASS
is enabled, so it's not available on release builds of Ruby.
2024-04-05 13:46:47 -04:00
Peter Zhu 46ebc48e62 [DOC] Add nodoc for GC.add_stress_to_class
This method is only available when compiled with GC_DEBUG_STRESS_TO_CLASS
is enabled, so it's not available on release builds of Ruby.
2024-04-05 13:45:12 -04:00
Peter Zhu dbe8886f4d Remove deprecated function rb_gc_force_recycle
This function has been deprecated since Ruby 3.1, so we should remove it
for Ruby 3.4.
2024-04-05 11:39:54 -04:00
Matt Valentine-House ef19234b10 Merge rb_objspace_alloc and Init_heap.
Co-Authored-By: Peter Zhu <peter@peterzhu.ca>
2024-04-04 15:00:57 +01:00
Peter Zhu 24a7407960 Remove with_gc functions in darray
We can wrap in DURING_GC_COULD_MALLOC_REGION instead.
2024-04-02 13:26:24 -04:00
Peter Zhu fa0a62413a Don't check for dynamic symbol when reference updating
All symbols in the GC are dynamic symbols, so we don't need to check it.
2024-03-28 11:54:16 -04:00
KJ Tsanaktsidis dc9d2455b6 Add a missing asan_unpoisoning_p in gc_set_candidate_object_i
It walks the heap, and checks for T_NONE and T_ZOMBIE objects, so it
needs to unpoison these slots before accessing them when ASAN is
enabled.
2024-03-28 09:49:10 +11:00
Peter Zhu c50b6425b4 Remove st_lookup when updating object ID 2024-03-27 11:41:08 -04:00
Peter Zhu 4566843b3e Check FL_SEEN_OBJ_ID before looking up in table
This is an optimization for compaction so that we only lookup in the
obj_to_id_tbl table only when FL_SEEN_OBJ_ID is set.
2024-03-27 11:41:08 -04:00
Peter Zhu aa794cc5a2 Turn GC off at boot on Windows
This is to stop crashes like:

    .\miniruby.exe: [BUG] Segmentation fault
    ruby 3.4.0dev (2024-03-26T15:38:26Z pull/10370/merge 040ea2ae2f) [x64-mswin64_140]

    -- Control frame information -----------------------------------------------
    c:0001 p:0000 s:0003 E:000d00 DUMMY  [FINISH]

    -- Threading information ---------------------------------------------------
    Total ractor count: 1
    Ruby thread count for this ractor: 1

    -- C level backtrace information -------------------------------------------
    C:\Windows\SYSTEM32\ntdll.dll(NtWaitForSingleObject+0x14) [0x00007FFA091AFC74]
    C:\Windows\System32\KERNELBASE.dll(WaitForSingleObjectEx+0x93) [0x00007FFA05BB4513]
    D:\a\ruby\ruby\build\miniruby.exe(rb_print_backtrace+0x3e) [0x00007FF64E536EFE] d:\a\ruby\ruby\src\vm_dump.c:844
    D:\a\ruby\ruby\build\miniruby.exe(rb_vm_bugreport+0x1ae) [0x00007FF64E5370B2] d:\a\ruby\ruby\src\vm_dump.c:1154
    D:\a\ruby\ruby\build\miniruby.exe(rb_bug_for_fatal_signal+0x77) [0x00007FF64E3FF357] d:\a\ruby\ruby\src\error.c:1087
    D:\a\ruby\ruby\build\miniruby.exe(sigsegv+0x71) [0x00007FF64E4C79E5] d:\a\ruby\ruby\src\signal.c:926
    C:\Windows\System32\ucrtbase.dll(seh_filter_exe+0x233) [0x00007FFA0521CE03]
    D:\a\ruby\ruby\build\miniruby.exe(`__scrt_common_main_seh'::`1'::filt$0+0x16) [0x00007FF64E594DA0] f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl:269
    C:\Windows\SYSTEM32\VCRUNTIME140.dll(_C_specific_handler+0x9f) [0x00007FF9E54AF73F]
    C:\Windows\SYSTEM32\ntdll.dll(_chkstk+0x11f) [0x00007FFA091B4C2F]
    C:\Windows\SYSTEM32\ntdll.dll(RtlWalkFrameChain+0x14bf) [0x00007FFA09114CEF]
    C:\Windows\SYSTEM32\ntdll.dll(KiUserExceptionDispatcher+0x2e) [0x00007FFA091B399E]
    D:\a\ruby\ruby\build\miniruby.exe(newobj_of+0x6d) [0x00007FF64E418615] d:\a\ruby\ruby\src\gc.c:2949
    D:\a\ruby\ruby\build\miniruby.exe(rb_wb_protected_newobj_of+0x32) [0x00007FF64E41C7DA] d:\a\ruby\ruby\src\gc.c:2974
    D:\a\ruby\ruby\build\miniruby.exe(str_new0+0x64) [0x00007FF64E4E7F48] d:\a\ruby\ruby\src\string.c:887
    D:\a\ruby\ruby\build\miniruby.exe(rb_enc_str_new+0x40) [0x00007FF64E4D89B8] d:\a\ruby\ruby\src\string.c:945
    D:\a\ruby\ruby\build\miniruby.exe(iseq_compile_each0+0xdd7) [0x00007FF64E3B4A23] d:\a\ruby\ruby\src\compile.c:10368
    D:\a\ruby\ruby\build\miniruby.exe(iseq_compile_each+0x74) [0x00007FF64E3B3C40] d:\a\ruby\ruby\src\compile.c:9971
2024-03-27 09:39:23 -04:00
Peter Zhu f14e52c8c4 Fix setting GC stress at boot when objspace not available 2024-03-27 09:39:23 -04:00
eileencodes e16086b7f2 Refactor init_copy gc attributes
This PR moves `rb_copy_wb_protected_attribute` and
`rb_gc_copy_finalizer` into a single function called
`rb_gc_copy_attributes` to be called by `init_copy`. This reduces the
surface area of the GC API.

Co-authored-by: Peter Zhu <peter@peterzhu.ca>
2024-03-26 14:29:36 -04:00
Peter Zhu 9cf754b648 Fix --debug=gc_stress flag
ruby_env_debug_option gets called after Init_gc_stress, so the
--debug=gc_stress flag never works.
2024-03-25 13:07:39 -04:00
KJ Tsanaktsidis 2535a09e85 Check ASAN fake stacks when marking non-current threads
Currently, we check the values on the machine stack & register state to
see if they're actually a pointer to an ASAN fake stack, and mark the
values on the fake stack too if required. However, we are only doing
that for the _current_ thread (the one actually running the GC), not for
any other thread in the program.

Make rb_gc_mark_machine_context (which is called for marking non-current
threads) perform the same ASAN fake stack handling that
mark_current_machine_context performs.

[Bug #20310]
2024-03-25 14:57:04 +11:00
KJ Tsanaktsidis 48d3bdddba Move asan_fake_stack_handle to EC, not thread
It's really a property of the EC; each fiber (which has its own EC) also
has its own asan_fake_stack_handle.

[Bug #20310]
2024-03-25 14:57:04 +11:00
Peter Zhu 806edd2956 Pass objspace into heap_check_moved_i 2024-03-21 10:43:07 -04:00
Peter Zhu 9a6a6b4ba6 Pass objspace into root_obj_check_moved_i 2024-03-21 10:43:07 -04:00
Peter Zhu e07441f05f Make rb_aligned_malloc private
It is not used anywhere else.
2024-03-20 10:27:41 -04:00
Peter Zhu 4469729558 Remove rb_raw_obj_info_basic
It's not used outside of gc.c.
2024-03-18 10:19:11 -04:00
Peter Zhu 185112f4ff Remove unused macro TF 2024-03-15 16:03:26 -04:00
Peter Zhu 59785680dd Remove unused macro GC_NOTIFY in gc.c 2024-03-15 15:44:05 +09:00
Peter Zhu c2170e5c2b Fix typo from gloabl_object_list to global_object_list 2024-03-14 13:52:20 -04:00
Peter Zhu 4559a161af Move gloabl_object_list from objspace to VM
This is to be consistent with the mark_object_ary that is in the VM.
2024-03-14 13:29:59 -04:00
Peter Zhu ff51dc5654 [Feature #20265] Remove rb_newobj_of and RB_NEWOBJ_OF 2024-03-14 12:53:04 -04:00
Peter Zhu 8e1831406f [Feature #20265] Remove rb_newobj and RB_NEWOBJ 2024-03-14 12:53:04 -04:00
Peter Zhu 3896f9940e Make special const and too complex shapes before T_OBJECT shapes 2024-03-13 09:55:52 -04:00
Peter Zhu 6b0434c0f7 Don't create per size pool shapes for non-T_OBJECT 2024-03-13 09:55:52 -04:00
Peter Zhu 6ad347a105 Don't directly read the SIZE_POOL_COUNT in shapes
This removes the assumption about SIZE_POOL_COUNT for shapes.
2024-03-13 09:55:52 -04:00
Peter Zhu e12bc5c572 Remove dead function rb_obj_rgengc_promoted_p 2024-03-11 11:04:20 -04:00
Peter Zhu 9f31577987 Reuse rb_gc_writebarrier_unprotect in rb_copy_wb_protected_attribute 2024-03-11 09:30:15 -04:00
Jean Boussier d4f3dcf4df Refactor VM root modules
This `st_table` is used to both mark and pin classes
defined from the C API. But `vm->mark_object_ary` already
does both much more efficiently.

Currently a Ruby process starts with 252 rooted classes,
which uses `7224B` in an `st_table` or `2016B` in an `RArray`.

So a baseline of 5kB saved, but since `mark_object_ary` is
preallocated with `1024` slots but only use `405` of them,
it's a net `7kB` save.

`vm->mark_object_ary` is also being refactored.

Prior to this changes, `mark_object_ary` was a regular `RArray`, but
since this allows for references to be moved, it was marked a second
time from `rb_vm_mark()` to pin these objects.

This has the detrimental effect of marking these references on every
minors even though it's a mostly append only list.

But using a custom TypedData we can save from having to mark
all the references on minor GC runs.

Addtionally, immediate values are now ignored and not appended
to `vm->mark_object_ary` as it's just wasted space.
2024-03-06 15:33:43 -05:00
Jean Boussier b4a69351ec Move FL_SINGLETON to FL_USER1
This frees FL_USER0 on both T_MODULE and T_CLASS.

Note: prior to this, FL_SINGLETON was never set on T_MODULE,
so checking for `FL_SINGLETON` without first checking that
`FL_TYPE` was `T_CLASS` was valid. That's no longer the case.
2024-03-06 13:11:41 -05:00
Peter Zhu 5a3ae06a09 Remove dead function rb_obj_rgengc_writebarrier_protected_p 2024-03-01 15:41:16 -05:00
Peter Zhu 6f31dd495c Don't check_rvalue_consistency in is_markable_object
is_markable_object is called by rb_objspace_markable_object_p, which
may pass a T_NONE object. check_rvalue_consistency will fail if a T_NONE
object is passed in.
2024-03-01 13:38:49 -05:00
Peter Zhu d3ae5808bb Remove each_machine_stack_value
The function is only used by rb_gc_mark_machine_stack.
2024-02-29 14:26:31 -05:00
Peter Zhu 3d61477900 Remove unused gc_mark_stack_values 2024-02-29 13:23:50 -05:00
Peter Zhu 6665ec26db Remove check for is_markable_object in gc_mark_stack_values
gc_mark_and_pin already checks for is_markable_object.
2024-02-29 13:23:50 -05:00
Peter Zhu 4c0f0b90a4 Assume that FL_FINALIZE is in finalizer_table
If FL_FINALIZE is set but not in finalizer_table, then rb_bug.
2024-02-29 11:07:53 -05:00
Peter Zhu 8a918b456c Add gc_each_object for walking the heap 2024-02-29 10:57:24 -05:00
Peter Zhu 950c60623b Delete from finalizer_table before running finalizer
The finalizer could trigger a GC, which would cause FL_FINALIZE to be
out of sync with the finalizer table.
2024-02-29 09:38:13 -05:00
Peter Zhu d5bca0668c Unset FL_FINALIZE before running the finalizer
The finalizer could trigger a GC, so FL_FINALIZE could get out of sync
with the finalizer table.
2024-02-29 09:37:38 -05:00
Peter Zhu 4b92b60f0b Use array initialization rather than for loop 2024-02-28 14:54:21 -05:00
Peter Zhu 5481dbef07 Make rb_define_finalizer_no_check private 2024-02-28 13:45:19 -05:00
Peter Zhu dcc976add9 Remove unused rb_gc_id2ref_obj_tbl 2024-02-28 12:21:38 -05:00
Peter Zhu 7b69563b36 Add check for finalizer in verify_internal_constency
This adds a check in GC.verify_internal_constency that FL_FINALIZE flags
is set if, and only if it is in finalizer_table.
2024-02-28 10:41:11 -05:00
Peter Zhu 48f433fd40 Change T_ZOMBIE flag check from an assertion
Assertions are only enable on debug builds, so it will now check for
flags of T_ZOMBIE objects on all builds in GC.verify_internal_consistency.
2024-02-28 10:41:11 -05:00
Peter Zhu e8e2415bb3 Use RB_SPECIAL_CONST_P instead of rb_special_const_p
rb_special_const_p returns a VALUE (Qtrue or Qfalse), so we shouldn't
assume that Qfalse is 0. We should instead use RB_SPECIAL_CONST_P.
2024-02-27 21:11:11 -05:00
Peter Zhu 08731182b8 Change is_garbage_object to return a bool 2024-02-27 14:52:02 -05:00
Peter Zhu 3c44f6da6c Simplify is_garbage_object 2024-02-27 14:52:02 -05:00
Peter Zhu 1f740cd111 Remove is_swept_object
The name is misleading, as it seems like the function checks whether the
object is swept or not. But the function only checks whether the page is
before or after sweeping.
2024-02-27 12:10:48 -05:00
Peter Zhu 2396b7a62f Change is_live_object to return a bool 2024-02-27 10:03:42 -05:00
Peter Zhu 9ba53cb688 Simplify is_live_object 2024-02-27 10:03:42 -05:00
Peter Zhu 78ae6dbb11 Remove rb_objspace_marked_object_p
rb_objspace_marked_object_p is no longer used in the objspace module, so
we can remove it.
2024-02-26 17:05:34 -05:00
Peter Zhu 7538703d1b Make rb_objspace_data_type_memsize private
rb_objspace_data_type_memsize is not used in the objspace module, so we
can make it private.
2024-02-26 17:05:34 -05:00
Peter Zhu c9b6cd4223 Remove unused rb_objspace_each_objects_without_setup 2024-02-26 14:34:24 -05:00
Peter Zhu 27e3e44390 Fix verify_internal_consistency_i for zombie objects
FL_FINALIZE is now kept for zombie objects.
2024-02-26 11:38:44 -05:00
Peter Zhu 83e676e5f9 Don't lookup finalizers if FL_FINALIZE flag not set
The FL_FINALIZE flag is set when there are finalizers for the object. We
can improver performance by not looking up in the table if the flag is
not set.

Using the following C extension:

    #include "ruby/ruby.h"

    static void data_free(void *_ptr) {}

    static const rb_data_type_t data_type = {
        "my_type",
        {
            NULL,
            data_free,
        },
        0, 0, 0
    };

    static VALUE data_alloc(VALUE klass) {
        return TypedData_Wrap_Struct(klass, &data_type, (void *)1);
    }

    void Init_myext(void) {
        VALUE my_klass = rb_define_class("MyClass", rb_cObject);
        rb_define_alloc_func(my_klass, data_alloc);
    }

And the following benchmark:

    require "benchmark"

    final_objs = 1_000_000.times.map do
      o = Object.new
      ObjectSpace.define_finalizer(o, proc {})
      o
    end

    puts(Benchmark.measure do
      100_000_000.times do
        MyClass.new
      end
    end)

Before:

    10.974190   0.355037  11.329227 ( 11.416772)

After:

    7.664310   0.347598   8.011908 (  8.268969)
2024-02-26 09:20:05 -05:00
Peter Zhu e65315a725 Extract imemo functions from gc.c into imemo.c 2024-02-22 11:35:09 -05:00
Peter Zhu 330830dd1a Add IMEMO_NEW
Rather than exposing that an imemo has a flag and four fields, this
changes the implementation to only expose one field (the klass) and
fills the rest with 0. The type will have to fill in the values themselves.
2024-02-21 11:33:05 -05:00
Peter Zhu 402690c3b6 Fix incomplete switch statement in imemo_memsize
The switch statement is not exhaustive, meaning the "unreachable"
comment was not correct. This commit fixes it by making the list
exhaustive and adding an rb_bug in the default case.
2024-02-21 10:13:36 -05:00
John Hawthorn 1c97abaaba De-dup identical callinfo objects
Previously every call to vm_ci_new (when the CI was not packable) would
result in a different callinfo being returned this meant that every
kwarg callsite had its own CI.

When calling, different CIs result in different CCs. These CIs and CCs
both end up persisted on the T_CLASS inside cc_tbl. So in an eval loop
this resulted in a memory leak of both types of object. This also likely
resulted in extra memory used, and extra time searching, in non-eval
cases.

For simplicity in this commit I always allocate a CI object inside
rb_vm_ci_lookup, but ideally we would lazily allocate it only when
needed. I hope to do that as a follow up in the future.
2024-02-20 18:55:00 -08:00
Peter Zhu 97d4363d3b [DOC] Improve docs for GC.latest_compact_info 2024-02-20 17:39:46 -05:00
Peter Zhu c184aa8740 Use rb_gc_mark_and_move for imemo 2024-02-20 10:39:30 -05:00
Peter Zhu 24645cff0d Removed duplicated variable in push_mark_stack 2024-02-16 13:27:16 -05:00
Peter Zhu 4411cdeef9 Fix typo in gc.c 2024-02-16 11:44:27 -05:00
Peter Zhu 28709d591d Remove unused argument in cc_table_free 2024-02-14 16:25:05 -05:00
Peter Zhu ae8db4b65a Remove unused function rb_cc_table_free 2024-02-14 15:52:15 -05:00
Peter Zhu 1d3b306753 Move rb_class_allocate_instance from gc.c to object.c 2024-02-14 13:43:02 -05:00
Alan Wu 5add999dee Comment about not marking RSYMBOL(obj)->fstr [ci skip] 2024-02-13 14:49:54 -05:00
Peter Zhu 190a55d27f Drill newobj cache instead of ractor 2024-02-12 09:43:38 -05:00
Peter Zhu a50e35888b Free all remaining objects in rb_objspace_free_objects
rb_objspace_call_finalizer didn't free fibers and neither did
rb_objspace_free_objects, which caused fibers to be reported as leaked
when using RUBY_FREE_AT_EXIT. This commit changes rb_objspace_free_objects
to free all remaining Ruby objects.
2024-02-06 10:54:05 -05:00
KJ Tsanaktsidis 4f4f3a6dec Don't check __asan_region_is_poisoned in objspace_each_objects
This returns whether or not _any_ piece of memory in the range is
poisoned, not if _all_ of it is. That means that currently, with ASAN
enabled, pages which contain a single poisoned object are skipped
entirely from being iterated with objspace_each* family of functions.

[Bug #20220]
2024-02-06 22:23:42 +11:00
Peter Zhu d0b774cfb8 Remove null checks for xfree
xfree can handle null values, so we don't need to check it.
2024-01-19 10:25:02 -05:00
KJ Tsanaktsidis 61da90c1b8 Mark asan fake stacks during machine stack marking
ASAN leaves a pointer to the fake frame on the stack; we can use the
__asan_addr_is_in_fake_stack API to work out the extent of the fake
stack and thus mark any VALUEs contained therein.

[Bug #20001]
2024-01-19 09:55:12 +11:00
Peter Zhu cc7b19e048 [DOC] Improve docs for GC.compact 2024-01-15 11:27:31 -05:00
Alan Wu e59dd7094f Pass more T_DATA to obj_free() under RUBY_FREE_AT_EXIT
T_DATA without a pointer or free function may still have ivars set on
them that need to be freed. The following leaked generic ivars for
example:

    converter = Encoding::Converter.allocate
    converter.instance_variable_set(:@foo, 1)

    STACK OF 1 INSTANCE OF 'ROOT LEAK: <malloc in objspace_xmalloc0>':
    <snip>
    12  miniruby    0x10286ec50 ivar_set + 140  variable.c:1850
    11  miniruby    0x102876afc generic_ivar_set + 136  variable.c:1668
2024-01-12 13:28:36 -05:00
KJ Tsanaktsidis ac0ba3c07e Revert "Allow each_stack_location to accept context for the callback"
This reverts commit 179228cd83.
2024-01-12 17:58:54 +11:00
KJ Tsanaktsidis 688a6ff510 Revert "Mark asan fake stacks during machine stack marking"
This reverts commit d10bc3a2b8.
2024-01-12 17:58:54 +11:00
KJ Tsanaktsidis d10bc3a2b8 Mark asan fake stacks during machine stack marking
ASAN leaves a pointer to the fake frame on the stack; we can use the
__asan_addr_is_in_fake_stack API to work out the extent of the fake
stack and thus mark any VALUEs contained therein.

[Bug #20001]
2024-01-12 17:29:48 +11:00
KJ Tsanaktsidis 179228cd83 Allow each_stack_location to accept context for the callback
This is preparing for a more specialised, asan-aware version of
gc_mark_maybe which needs some additional context passed through.

[Bug #20001]
2024-01-12 17:29:48 +11:00
KJ Tsanaktsidis 25f5b83689 Fix crash when printing RGENGC_DEBUG=5 output from GC
I was trying to debug an (unrelated) issue in the GC, and wanted to turn
on the trace-level GC output by compiling it with -DRGENGC_DEBUG=5.
Unfortunately, this actually causes a crash in newobj_init() because the
code there tries to log the obj_info() of the newly created object.
However, the object is not actually sufficiently set up for some of the
things that obj_info() tries to do:

* The instance variable table for a class is not yet initialized, and
  when using variable-length RVALUES, said ivar table is embedded in
  as-yet unitialized memory after the struct RValue. Attempting to read
  this, as obj_info() does, causes a crash.
* T_DATA variables need to dereference their ->type field to print out
  the underlying C type name, which is not set up until newobj_fill() is
  called.

To fix this, create a new method `obj_info_basic`, which dumps out only
the parts of the object that are valid before the object is fully
initialized.

[Fixes #18795]
2024-01-11 10:44:57 +11:00
Peter Zhu 8940922d18 [DOC] Improve doc for GC.latest_compact_info 2024-01-10 09:46:19 -05:00
Peter Zhu d9bad91c34 [DOC] Fix docs for GC.compact
GC.compact returns GC.latest_compact_info and not GC.latest_gc_info.
2024-01-07 22:26:12 -05:00
Nobuyoshi Nakada c30b8ae947
Adjust styles and indents [ci skip] 2024-01-08 00:50:41 +09:00
Rian McGuire 7db35e10c3 Fix GC.measure_total_time regression
Commit 93ac7405b8 introduced a regression
where measurements would still be taken after setting
GC.measure_total_time = false.

Fixes [Bug #20157]
2024-01-06 17:36:35 +11:00
Peter Zhu 70618a48f7 Fix off-by-one error for declarative marking
The for loops for marking and reference updating declaratively marked
TypedData objects did not mark/reference update the very last element.

When RGENGC_CHECK_MODE is turned on, this caused the test in Enumerator
to fail with:

    tool/lib/test/unit/testcase.rb:173:in `rescue in run': failed to allocate memory (NoMemoryError)
2023-12-24 20:37:59 -05:00
HParker 7ef90b3978 Correct free_on_exit env var to free_at_exit 2023-12-20 14:36:32 +09:00
Peter Zhu 32ecda354f Support `GC.auto_compact = :empty` on debug builds
This commit adds `GC.auto_compact = :empty` which will run
auto-compaction sorting pages by empty slots so the most amount of
objects will be moved. This will make it easier to write tests for
auto-compaction.
2023-12-19 18:29:36 -05:00
Peter Zhu 50d39219a9 Use RICLASS_OWNS_M_TBL_P
It's more consistent with gc_mark_children.
2023-12-19 15:21:28 -05:00
Koichi Sasada f9a48548cf restore the stack pointer on finalizer
When error on finalizer, the exception will be ignored.
To restart the code, we need to restore the stack pointer.

fix [Bug #20042]
2023-12-19 17:59:49 +09:00
Peter Zhu f35fec7710 Reset pinned_slots at the beginning of GC
pinned_slots is not being reset every GC, which causes this assertion to
fail:

```
Assertion Failed: gc.c:7076:gc_pin:GET_HEAP_PAGE(obj)->pinned_slots <= GET_HEAP_PAGE(obj)->total_slots
```

This commit changes it to reset it at the beginning of every compaction
GC cycle.
2023-12-18 10:37:21 -05:00
HParker 474b4c42f4 free ractors with ractor_free
Previously with RUBY_FREE_ON_EXIT, ractors where being xfree-ed which is incorrect since they are not xmalloced.
Instead we can free ractors with ractor free during shutdown. This change only effects main ractor freeing when RUBY_FREE_ON_EXIT is set.

Co-authored-by: John Hawthorn <john@hawthorn.email>
2023-12-15 10:31:15 -05:00
Peter Zhu 912016f626 Call obj_free for T_DATA, T_FILE objects on exit
Previously, T_DATA and T_FILE objects did not have their instance
variables freed on exit which would be reported as a memory leak with
RUBY_FREE_ON_EXIT. This commit changes it to use obj_free which also
frees the generic instance variables.

Co-authored-by: Alan Wu <XrXr@users.noreply.github.com>
2023-12-14 08:52:32 -05:00
John Hawthorn d7dad64465 Unlock freelist before assigning
Co-authored-by: Matthew Draper <matthew@trebex.net>
2023-12-13 15:26:52 -08:00
Peter Zhu f8ddcecbdf [Bug #20061] Clear mark bits when rb_free_on_exit
When compiling with cppflags=-DRGENGC_CHECK_MODE, the following crashes:

```
$ RUBY_FREE_ON_EXIT=1 ./miniruby -e 0
-e: [BUG] obj_free: RVALUE_MARKED(0x0000000103570020 [3LM    ] T_CLASS (anon)) != FALSE
```

This commit clears the mark bits when rb_free_on_exit is enabled.
2023-12-13 10:39:06 -05:00
Koichi Sasada c4c39082af add `flags` to `rb_postponed_job_preregister`
for future extensions.
2023-12-10 15:39:06 +09:00
KJ Tsanaktsidis f8effa209a Change the semantics of rb_postponed_job_register
Our current implementation of rb_postponed_job_register suffers from
some safety issues that can lead to interpreter crashes (see bug #1991).
Essentially, the issue is that jobs can be called with the wrong
arguments.

We made two attempts to fix this whilst keeping the promised semantics,
but:
  * The first one involved masking/unmasking when flushing jobs, which
    was believed to be too expensive
  * The second one involved a lock-free, multi-producer, single-consumer
    ringbuffer, which was too complex

The critical insight behind this third solution is that essentially the
only user of these APIs are a) internal, or b) profiling gems.

For a), none of the usages actually require variable data; they will
work just fine with the preregistration interface.

For b), generally profiling gems only call a single callback with a
single piece of data (which is actually usually just zero) for the life
of the program. The ringbuffer is complex because it needs to support
multi-word inserts of job & data (which can't be atomic); but nobody
actually even needs that functionality, really.

So, this comit:
  * Introduces a pre-registration API for jobs, with a GVL-requiring
    rb_postponed_job_prereigster, which returns a handle which can be
    used with an async-signal-safe rb_postponed_job_trigger.
  * Deprecates rb_postponed_job_register (and re-implements it on top of
    the preregister function for compatability)
  * Moves all the internal usages of postponed job register
    pre-registration
2023-12-10 15:00:37 +09:00
Adam Hess 6816e8efcf Free everything at shutdown
when the RUBY_FREE_ON_SHUTDOWN environment variable is set, manually free memory at shutdown.

Co-authored-by: Nobuyoshi Nakada <nobu@ruby-lang.org>
Co-authored-by: Peter Zhu <peter@peterzhu.ca>
2023-12-07 15:52:35 -05:00
Peter Zhu 0dc40bd2b7 Check need_major_gc during GC stress
need_major_gc is set when a major GC is required. However, if
gc_stress_no_major is also set, then it will not actually run a major
GC.

For example, the following script will sometimes crash:

```
GC.stress = 1
50000.times.map { [] }
```

With the following message:

```
[BUG] cannot create a new page after major GC
```
2023-12-07 10:49:06 -05:00
KJ Tsanaktsidis cbc0e0bef0 Fix GC.verify_compaction_references not moving every object
The intention of GC.verify_compaction_references is, I believe, to force
every single movable object to be moved, so that it's possible to debug
native extensions which not correctly updating their references to
objects they mark as movable.

To do this, it doubles the number of allocated pages for each size pool,
and sorts the heap pages so that the free ones are swept first; thus,
every object in an old page should be moved into a free slot in one of
the new pages.

This worked fine until movement of objects _between_ size pools during
compaction was implemented. That causes some problems for
verify_compaction_references:

* We were doubling the number of pages in each size pool, but actually
  if some objects need to move into a _different_ pool, there's no
  guarantee that they'll be enough room in that one.
* It's possible for the sweep & compact cursors to meet in one size pool
  before all the objects that want to move into that size pool from
  another are processed by the compaction.

You can see these problems by changing some of the movement tests in
test_gc_compact.rb to try and move e.g. 50,000 objects instead of
500; the test is not able to actually move all of the objects in a
single compaction run.

To fix this, we do two things in verify_compaction_references:

* Firstly, we add enough pages to every size pool to make them the same
  size. This ensures that their compact cursors will all have space to
  move during compaction (even if that means empty pages are
  pointlessly compacted)
* Then, we examine every object and determine where it _wants_ to be
  compacted into. We use this information to add additional pages to
  each size pool to handle all objects which should live there.

With these two changes, we can move arbitrary amounts of objects into
the correct size pool in a single call to verify_compaction_references.

My _motivation_ for performing this work was to try and fix some test
stability issues in test_gc_compact.rb. I now no longer think that we
actually see this particular bug in rubyci.org, but I also think
verify_compaction_references should do what it says on the tin, so it's
worth keeping.

[Bug #20022]
2023-12-07 10:19:35 -05:00
KJ Tsanaktsidis 5d832d16d9 Add objspace_each_pages to gc.c
This works like objspace_each_obj, except instead of being called with
the start & end address of each page, it's called with the page
structure itself.

[Bug #20022]
2023-12-07 10:19:35 -05:00
Soutaro Matsumoto 4f213ea1ba
Fix SEGV caused by `GC::Profiler.raw_data` (#9122) 2023-12-07 10:37:00 +09:00
Peter Zhu 12e3b07455 Re-embed when removing Object instance variables
Objects with the same shape must always have the same "embeddedness"
(either embedded or heap allocated) because YJIT assumes so. However,
using remove_instance_variable, it's possible that some objects are
embedded and some are heap allocated because it does not re-embed heap
allocated objects.

This commit changes remove_instance_variable to re-embed Object
instance variables when it becomes small enough.
2023-12-06 11:34:07 -05:00
Nobuyoshi Nakada 9c5e1b7189
Fix format specifiers for `size_t` 2023-12-04 10:39:17 +09:00
Peter Zhu b77551adee Remove unneeded local variables 2023-12-01 15:21:01 -05:00
Peter Zhu 80ea7fbad8 Pin embedded shared strings
Embedded shared strings cannot be moved because strings point into the
slot of the shared string. There may be code using the RSTRING_PTR on
the stack, which would pin the string but not pin the shared string,
causing it to move.
2023-12-01 15:04:31 -05:00
Alan Wu fcabe2df39
Remove written-but-never-read `me->def.body.refined.owner`
This also removes aliasing rule violations; the anonymous structs were
distinct types from `rb_method_refined_t`.
2023-11-29 01:41:40 +00:00
Peter Zhu e3875dd0f8 Don't incremental mark when GC stressful
Incremental marking prevents the GC from fully executing, so it may fail
to catch certain bugs.
2023-11-27 11:13:47 -05:00
Peter Zhu 7835ebce97 Set compaction after major GC has been determined
do_full_mark can change in gc_start, so we want to set auto-compaction
only after do_full_mark has been properly set.
2023-11-27 10:23:43 -05:00
Peter Zhu 269c705f93 Fix compaction for generic ivars
When generic instance variable has a shape, it is marked movable. If it
it transitions to too complex, it needs to update references otherwise
it may have incorrect references.
2023-11-24 13:29:04 -05:00
KJ Tsanaktsidis e201b81f79 Mark cc->cme_ for refinement callcaches as well
This is required for the same reason that super CC needs it.
See 36023d5cb7.

Reproducer:

    def cached_foo_callsite(obj) = obj.foo

    class Foo
      def foo = :v1

      module R
        refine Foo do
          def foo = :unused
        end
      end
    end

    obj = Foo.new
    cached_foo_callsite(obj) # set up cc with cme for foo=:v1

    class Foo
      def foo = :v2
    end
    GC.start # cme for foo=:v1 collected, if not reachable by cached_foo_callsite

    cached_foo_callsite(obj)

[Bug #19994]
2023-11-24 13:16:15 -05:00
Peter Zhu 99e1f7b607 Abort GC on shutdown
On large Ruby applications, shutdown may be slow if a major GC has just
started because rb_objspace_call_finalizer completes the GC.

This commit adds gc_abort which discards the mark stack if during
incremental marking and stops sweeping if during lazy sweeping.
2023-11-24 09:28:34 -05:00
Alan Wu 1ffaff884e Allow ivars movement in too_complex RCLASSes to fix crash
Previously, because gc_update_object_references() did not update the
VALUEs in the too_complex ivar st_table for T_CLASS and T_MODULE
objects, GC compaction could finish with corrupted objects.

 - start with `klass`, not too_complex
 - GC incremental step marks `klass` and its ivars
 - ruby code makes `klass` too_complex
 - GC compaction runs and move `klass` ivars, but because `klass` is
   too_complex, its ivars are not updated by gc_update_object_references(),
   leaving T_NONE or T_MOVED objects in the ivar table.

Co-authored-by: Peter Zhu <peter@peterzhu.ca>
2023-11-23 20:30:18 -05:00
Alan Wu 22de08811e Avoid marking IDs in too_complex tables and rename gc_update_tbl_refs()
Marking both keys and values versus marking just values is an important
distinction, but previously, gc_update_tbl_refs() and gc_update_table_refs()
had names that were too similar.

The st_table storing ivars for too_complex T_OBJECTs have IDs as keys,
but we were marking the IDs unnecessary previously, maybe due to the
confusing naming.
2023-11-23 20:30:18 -05:00
Alan Wu ecdb112881 Fix `rp(too_complex_t_object)` tripping assert
Previously, it tripped the assert about too_complex in
ROBJECT_IV_CAPACITY(). This fixes double faults for some crashes and
helps with use during development.
2023-11-23 12:16:57 -05:00
Aaron Patterson 6fce8c7980 Don't try compacting ivars on Classes that are "too complex"
Too complex classes use a hash table to store ivs, and should always pin
their IVs.  We shouldn't touch those classes in compaction.
2023-11-20 16:09:48 -08:00
Peter Zhu ad03320743 Support declarative marked TypedData objects on VWA 2023-11-20 18:59:01 -05:00
Jean Boussier 940f2e7f18 size_pool_idx_for_size: Include debugging info in error message
We ran into that case on our CI, including some sizes would help
debug it much easier.
2023-11-17 14:22:07 +01:00
Jean Boussier f1b95095d6 Revert "Wrap rb_objspace_reachable_objects_from_root with RB_VM_LOCK"
This reverts commit 76dc327eef.
2023-11-13 08:57:57 +01:00
Jean Boussier a1887f4dc2 Revert "Fix crash caused by concurrent ObjectSpace.dump_all calls"
This reverts commit 9a62fd3cba.
2023-11-13 08:57:57 +01:00
KJ Tsanaktsidis 9a62fd3cba Fix crash caused by concurrent ObjectSpace.dump_all calls
Since the callback defined in the objspace module might give up the GVL,
we need to make sure the right cr->mfd value is set back after the GVL
is re-obtained.
2023-11-12 17:50:37 +01:00
KJ Tsanaktsidis 76dc327eef Wrap rb_objspace_reachable_objects_from_root with RB_VM_LOCK
rb_objspace_reachable_objects_from has it too, so I figure it's most
likely required for _from_root as well.
2023-11-12 17:50:37 +01:00
Nobuyoshi Nakada 1fe2bc4b22
RCLASS_EXT is never NULL now 2023-11-11 15:57:44 +09:00
Jean Boussier a9f45aac6e rb_data_free: Fix freeing embedded TypedData
The previous implementation was using the pointer given
by `DATA_PTR` in all cases. But in the case of an embedded
TypedData, that pointer is garbage, we need to use RTYPEDDATA_GET_DATA
to get the proper data pointer.

Co-Authored-By: Étienne Barrié <etienne.barrie@gmail.com>
2023-11-10 15:56:42 +01:00
Peter Zhu 392238e3fd Implement embedded TypedData objects
This commit adds a new flag RUBY_TYPED_EMBEDDABLE that allows the data
of a TypedData object to be embedded after the object itself. This will
improve cache locality and allow us to save the 8 byte data pointer.

Co-Authored-By: Jean Boussier <byroot@ruby-lang.org>
2023-11-07 15:48:06 -05:00
Peter Zhu 38ba040d8b Make every initial size pool shape a root shape
This commit makes every initial size pool shape a root shape and assigns
it a capacity of 0.
2023-11-02 13:42:11 -04:00
Peter Zhu 7979c009a7 Fix bug for removed weak references
rb_darray_foreach gives a pointer to the entry, so we need to deference
it to read the value.
2023-10-27 11:00:12 -04:00
Aaron Patterson a3f66e09f6 geniv objects can become too complex 2023-10-24 10:52:06 -07:00
Jean Boussier e5364ea496 rb_shape_transition_shape_capa: use optimal sizes transitions
Previously the growth was 3(embed), 6, 12, 24, ...

With this change it's now 3(embed), 8, 16, 32, 64, ... by default.

However, since power of two isn't the best size for all allocators,
if `malloc_usable_size` is vailable, we use it to discover the best
offset.

On Linux/glibc 2.35 for instance, the growth will be 3(embed), 7, 15, 31
to avoid wasting 8B per object.

Test program:

```c

size_t test(size_t slots) {
    size_t allocated = slots * VALUE_SIZE;
    void *test_ptr = malloc(allocated);
    size_t wasted = malloc_usable_size(test_ptr) - allocated;
    free(test_ptr);
    fprintf(stderr, "slots = %lu, wasted_bytes = %lu\n", slots, wasted);
    return wasted;
}

int main(int argc, char *argv[]) {
    size_t best_padding = 0;
    size_t padding = 0;
    for (padding = 0; padding <= 2; padding++) {
        size_t wasted = test(8 - padding);
        if (wasted == 0) {
            best_padding = padding;
            break;
        }
    }

    size_t index = 0;
    fprintf(stderr, "=============== naive ================\n");

    size_t list_size = 4;
    for (index = 0; index < 10; index++) {
        test(list_size);
        list_size *= 2;
    }

    fprintf(stderr, "=============== auto-padded (-%lu) ================\n", best_padding);

    list_size = 4;
    for (index = 0; index < 10; index ++) {
        test(list_size - best_padding);
        list_size *= 2;
    }

    fprintf(stderr, "\n\n");
    return 0;
}
```

```
===== glibc ======
slots = 8, wasted_bytes = 8
slots = 7, wasted_bytes = 0
=============== naive ================
slots = 4, wasted_bytes = 8
slots = 8, wasted_bytes = 8
slots = 16, wasted_bytes = 8
slots = 32, wasted_bytes = 8
slots = 64, wasted_bytes = 8
slots = 128, wasted_bytes = 8
slots = 256, wasted_bytes = 8
slots = 512, wasted_bytes = 8
slots = 1024, wasted_bytes = 8
slots = 2048, wasted_bytes = 8
=============== auto-padded (-1) ================
slots = 3, wasted_bytes = 0
slots = 7, wasted_bytes = 0
slots = 15, wasted_bytes = 0
slots = 31, wasted_bytes = 0
slots = 63, wasted_bytes = 0
slots = 127, wasted_bytes = 0
slots = 255, wasted_bytes = 0
slots = 511, wasted_bytes = 0
slots = 1023, wasted_bytes = 0
slots = 2047, wasted_bytes = 0
```

```
==========  jemalloc =======
slots = 8, wasted_bytes = 0
=============== naive ================
slots = 4, wasted_bytes = 0
slots = 8, wasted_bytes = 0
slots = 16, wasted_bytes = 0
slots = 32, wasted_bytes = 0
slots = 64, wasted_bytes = 0
slots = 128, wasted_bytes = 0
slots = 256, wasted_bytes = 0
slots = 512, wasted_bytes = 0
slots = 1024, wasted_bytes = 0
slots = 2048, wasted_bytes = 0
=============== auto-padded (-0) ================
slots = 4, wasted_bytes = 0
slots = 8, wasted_bytes = 0
slots = 16, wasted_bytes = 0
slots = 32, wasted_bytes = 0
slots = 64, wasted_bytes = 0
slots = 128, wasted_bytes = 0
slots = 256, wasted_bytes = 0
slots = 512, wasted_bytes = 0
slots = 1024, wasted_bytes = 0
slots = 2048, wasted_bytes = 0
```
2023-10-23 09:33:15 +02:00
Yusuke Endoh 833c930bd6 Remove unneeded checks
Follow up of 591336a0f2
2023-10-16 03:58:30 +09:00
Nobuyoshi Nakada a075c55d0c Manage `rb_strterm_t` without imemo 2023-10-14 11:08:43 +09:00
HParker c74dc8b4af Use reference counting to avoid memory leak in kwargs
Tracks other callinfo that references the same kwargs and frees them when all references are cleared.

[bug #19906]

Co-authored-by: Peter Zhu <peter@peterzhu.ca>
2023-10-01 10:55:19 -04:00