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

2352 Коммитов

Автор SHA1 Сообщение Дата
Matt Valentine-House 72aba64fff Merge gc.h and internal/gc.h
[Feature #19425]
2023-02-09 10:32:29 -05:00
Peter Zhu 861d70e383 Rename iseq_mark_and_update to iseq_mark_and_move
The new name is more consistent.
2023-02-08 12:43:25 -05:00
Jean Boussier 3ab3455145 Add RUBY_GC_HEAP_INIT_SIZE_%d_SLOTS to pre-init pools granularly
The old RUBY_GC_HEAP_INIT_SLOTS isn't really usable anymore as
it initalize all the pools by the same factor, but it's unlikely
that pools will need similar sizes.

In production our 40B pool is 5 to 6 times bigger than our 80B pool.
2023-02-08 09:26:07 +01:00
Jean byroot Boussier 4713b084da Revert "Revert "Consider DATA objects without a mark function as protected""
This reverts commit 6eae8e5f51.
2023-02-07 22:33:12 +01:00
Jean Boussier 6eae8e5f51 Revert "Consider DATA objects without a mark function as protected"
This reverts commit 6e4c242130.
2023-02-07 15:22:06 +01:00
Jean Boussier 6e4c242130 Consider DATA objects without a mark function as protected
It's not uncommon for simple binding to wrap structs without
any Ruby object references. Hence with no `mark` function.

Might as well mark them as protected by a write barrier.
2023-02-07 11:48:49 +01:00
Peter Zhu c6f84e9189 [Bug #19398] Memory leak in WeakMap
There's a memory leak in ObjectSpace::WeakMap due to not freeing
the `struct weakmap`. It can be seen in the following script:

```
100.times do
  10000.times do
    ObjectSpace::WeakMap.new
  end

  # Output the Resident Set Size (memory usage, in KB) of the current Ruby process
  puts `ps -o rss= -p #{$$}`
end
```
2023-02-01 13:23:55 -05:00
Kunshan Wang de724487f0 Copying GC support for EXIVAR
Instance variables held in gen_ivtbl are marked with rb_gc_mark.  It
prevents the referenced objects from moving, which is bad for copying
garbage collectors.

This commit allows those instance variables to be updated during
gc_update_object_references.
2023-01-31 09:24:26 -05:00
Peter Zhu 41bf2354e3 Add rb_gc_mark_and_move and implement on iseq
This commit adds rb_gc_mark_and_move which takes a pointer to an object
and marks it during marking phase and updates references during compaction.
This allows for marking and reference updating to be combined into a
single function, which reduces code duplication and prevents bugs if
marking and reference updating goes out of sync.

This commit also implements rb_gc_mark_and_move on iseq as an example.
2023-01-19 11:23:35 -05:00
Peter Zhu abff5f6203 Move classpath to rb_classext_t
This commit moves the classpath (and tmp_classpath) from instance
variables to the rb_classext_t. This improves performance as we no
longer need to set an instance variable when assigning a classpath to
a class.

I benchmarked with the following script:

```ruby
name = :MyClass

puts(Benchmark.measure do
  10_000_000.times do |i|
    Object.const_set(name, Class.new)
    Object.send(:remove_const, name)
  end
end)
```

Before this patch:

```
  5.440119   0.025264   5.465383 (  5.467105)
```

After this patch:

```
  4.889646   0.028325   4.917971 (  4.942678)
```
2023-01-11 11:06:58 -05:00
Peter Zhu 3be2acfafd Fix re-embedding of strings during compaction
The reference updating code for strings is not re-embedding strings
because the code is incorrectly wrapped inside of a
`if (STR_SHARED_P(obj))` clause. Shared strings can't be re-embedded
so this ends up being a no-op. This means that strings can be moved to a
large size pool during compaction, but won't be re-embedded, which would
waste the space.
2023-01-09 08:49:29 -05:00
Peter Zhu 3bcf92d8af Allow malloc during gc when GC has been disabled
We should allow malloc during GC when GC has been explicitly disabled
since garbage_collect_with_gvl won't do anything if GC has been disabled.
2023-01-04 09:10:58 -05:00
Peter Zhu 184739f1e2 [ci skip] Remove trailing semicolon in gc.c 2023-01-03 11:43:43 -05:00
Peter Zhu 90a80eb076 Fix integer underflow when using HEAP_INIT_SLOTS
There is an integer underflow when the environment variable
RUBY_GC_HEAP_INIT_SLOTS is less than the number of slots currently
in the Ruby heap.

[Bug #19284]
2022-12-30 09:01:50 -05:00
Nobuyoshi Nakada 5df7118445
Skip insanely memory consuming tests
These tests do not only consume hundreds GiB bytes memory, result in
`rb_bug` when `RUBY_DEBUG` is enabled.
2022-12-26 15:01:44 +09:00
Peter Zhu 39e70eef72 [DOC] Fix formatting for GC.compact 2022-12-20 15:18:36 -05:00
Peter Zhu 9f4472cad7 [DOC] Escape all usages of GC
RDoc was making every usage of the word "GC" link to the page for GC
(which is the same page).
2022-12-20 15:16:36 -05:00
Peter Zhu 63fe03aa4e [DOC] Fix call-seq for GC methods
RDoc parses the last arrow in the call-seq as the arrow for the return
type. It was getting confused over the arrow in the hash.
2022-12-20 15:09:14 -05:00
Peter Zhu ae53986834 [DOC] Fix formatting for GC#latest_compact_info 2022-12-20 15:06:06 -05:00
Peter Zhu 80e56d1438 Fix thrashing of major GC when size pool is small
If a size pooll is small, then `min_free_slots < heap_init_slots` is true.
This means that min_free_slots will be set to heap_init_slots. This
causes `swept_slots < min_free_slots` to be true in a later if statement.
The if statement could trigger a major GC which could cause major GC
thrashing.
2022-12-20 11:32:51 -05:00
Peter Zhu e7915d6d70 Fix misfire of compaction read barrier
gc_compact_move incorrectly returns false when destination heap is full
after sweeping. It returns false even if destination heap is different
than source heap (returning false means that the source heap has
finished compacting). This causes the source page to get locked, which
causes a read barrier fire when we try to compact the source heap again.
2022-12-19 17:09:08 -05:00
Peter Zhu 8275cad1e1 Fix buffer overrun when re-embedding objects
We eagerly set the new shape of an object when moving an object during
compaction. This new shape may have a different capacity than the
current original shape capacity. This means that we cannot copy from the
original buffer using size of the new capacity. Instead, we should use
the ivar count (which is less than or equal to both the new and original
capacities).

Co-Authored-By: Matt Valentine-House <matt@eightbitraptor.com>
2022-12-19 13:13:26 -05:00
Peter Zhu 6e3bc67103 Hard crash when allocating in GC when RUBY_DEBUG
Not all builds have RGENGC_CHECK_MODE set, so it should also crash when
RUBY_DEBUG is set.
2022-12-17 09:18:54 -05:00
Peter Zhu 965f4259db Move check for GC to xmalloc and xcalloc
Moves the check earlier to before we actually perform the allocation.
2022-12-17 09:16:26 -05:00
Peter Zhu 2ccf6e5394 Don't allow allocating memory during GC
Allocating memory (xmalloc and xrealloc) during GC could cause GC to
trigger, which would crash with `[BUG] during_gc != 0`. This is an
intermittent bug which could be hard to debug.

This commit changes it so that any memory allocation during GC will
emit a warning. When debug flags are enabled it will also cause a crash.
2022-12-16 10:01:53 -05:00
Peter Zhu 5e81cf8fd0 Refactor to only attempt to move movable objects
Moves check for gc_is_moveable_obj from try_move to gc_compact_plane.

Co-Authored-By: Matt Valentine-House <matt@eightbitraptor.com>
2022-12-15 15:27:38 -05:00
Matt Valentine-House bfc66e07b7 Fix Object Movement allocation in GC
When moving Objects between size pools we have to assign a new shape.

This happened during updating references - we tried to create a new shape
tree that mirrored the existing tree, but based on the root shape of the
new size pool.

This causes allocations to happen if the new tree doesn't already exist,
potentially triggering a GC, during GC.

This commit changes object movement to look for a pre-existing new tree
during object movement, and if that tree does not exist, we don't move
the object to the new pool.

This allows us to remove the shape allocation from update references.

Co-Authored-By: Peter Zhu <peter@peterzhu.ca>
2022-12-15 15:27:38 -05:00
Jemma Issroff c1ab6ddc9a Transition complex objects to "too complex" shape
When an object becomes "too complex" (in other words it has too many
variations in the shape tree), we transition it to use a "too complex"
shape and use a hash for storing instance variables.

Without this patch, there were rare cases where shape tree growth could
"explode" and cause performance degradation on what would otherwise have
been cached fast paths.

This patch puts a limit on shape tree growth, and gracefully degrades in
the rare case where there could be a factorial growth in the shape tree.

For example:

```ruby
class NG; end

HUGE_NUMBER.times do
  NG.new.instance_variable_set(:"@unique_ivar_#{_1}", 1)
end
```

We consider objects to be "too complex" when the object's class has more
than SHAPE_MAX_VARIATIONS (currently 8) leaf nodes in the shape tree and
the object introduces a new variation (a new leaf node) associated with
that class.

For example, new variations on instances of the following class would be
considered "too complex" because those instances create more than 8
leaves in the shape tree:

```ruby
class Foo; end
9.times { Foo.new.instance_variable_set(":@uniq_#{_1}", 1) }
```

However, the following class is *not* too complex because it only has
one leaf in the shape tree:

```ruby
class Foo
  def initialize
    @a = @b = @c = @d = @e = @f = @g = @h = @i = nil
  end
end
9.times { Foo.new }
``

This case is rare, so we don't expect this change to impact performance
of most applications, but it needs to be handled.

Co-Authored-By: Aaron Patterson <tenderlove@ruby-lang.org>
2022-12-15 10:06:04 -08:00
Peter Zhu f50aa19da6 Revert "Fix Object Movement allocation in GC"
This reverts commit 9c54466e29.

We're seeing crashes in Shopify CI after this commit.
2022-12-15 12:00:30 -05:00
Matt Valentine-House 9c54466e29 Fix Object Movement allocation in GC
When moving Objects between size pools we have to assign a new shape.

This happened during updating references - we tried to create a new shape
tree that mirrored the existing tree, but based on the root shape of the
new size pool.

This causes allocations to happen if the new tree doesn't already exist,
potentially triggering a GC, during GC.

This commit changes object movement to look for a pre-existing new tree
during object movement, and if that tree does not exist, we don't move
the object to the new pool.

This allows us to remove the shape allocation from update references.

Co-Authored-By: Peter Zhu <peter@peterzhu.ca>
2022-12-15 09:04:30 -05:00
Matt Valentine-House 856e0279ec fix indentation: gc_compact_destination_pool
[ci skip]

Co-Authored-By: Peter Zhu <peter@peterzhu.ca>
2022-12-13 13:31:10 -05:00
Peter Zhu 0b4fda11ec [DOC] Don't document private methods in objspace 2022-12-12 09:48:06 -05:00
Mirek Klimos ea613c6360
Expose need_major_gc via GC.latest_gc_info (#6791) 2022-12-10 13:35:31 -05:00
Matt Valentine-House 12b5268679 Remove unused counter for heap_page->pinned_slots 2022-12-09 09:34:17 -05:00
Jemma Issroff 9c5e3671eb
Increment max_iv_count on class based on number of set_iv in initialize (#6788)
We can loosely predict the number of ivar sets on a class based on the
number of iv set instructions in the initialize method. This should give
us a more accurate estimate to use for initial size pool allocation,
which should in turn give us more cache hits.
2022-11-22 15:28:14 -05:00
Peter Zhu 5f95228c76 Add RVALUE_OVERHEAD and move ractor_belonging_id
This commit adds RVALUE_OVERHEAD for storing metadata at the end of the
slot. This commit moves the ractor_belonging_id in debug builds from the
flags to RVALUE_OVERHEAD which frees the 16 bits in the headers for
object shapes.
2022-11-21 11:26:26 -05:00
Aaron Patterson 10788166e7 Differentiate T_OBJECT shapes from other objects
We would like to differentiate types of objects via their shape.  This
commit adds a special T_OBJECT shape when we allocate an instance of
T_OBJECT.  This allows us to avoid testing whether an object is an
instance of a T_OBJECT or not, we can just check the shape.
2022-11-18 08:31:56 -08:00
S-H-GAMELINKS 1f4f6c9832 Using UNDEF_P macro 2022-11-16 18:58:33 +09:00
Jemma Issroff c726c48a3d Remove numiv from RObject
Since object shapes store the capacity of an object, we no longer
need the numiv field on RObjects. This gives us one extra slot which
we can use to give embedded objects one more instance variable (for a
total of 3 ivs). This commit removes the concept of numiv from RObject.
2022-11-10 10:11:34 -05:00
Jemma Issroff 5246f4027e Transition shape when object's capacity changes
This commit adds a `capacity` field to shapes, and adds shape
transitions whenever an object's capacity changes. Objects which are
allocated out of a bigger size pool will also make a transition from the
root shape to the shape with the correct capacity for their size pool
when they are allocated.

This commit will allow us to remove numiv from objects completely, and
will also mean we can guarantee that if two objects share shapes, their
IVs are in the same positions (an embedded and extended object cannot
share shapes). This will enable us to implement ivar sets in YJIT using
object shapes.

Co-Authored-By: Aaron Patterson <tenderlove@ruby-lang.org>
2022-11-10 10:11:34 -05:00
Yuta Saito 3a6cdeda89 [wasm] Scan machine stack based on `ec->machine.stack_{start,end}`
fiber machine stack is placed outside of C stack allocated by wasm-ld,
so highest stack address recorded by `rb_wasm_record_stack_base` is
invalid when running on non-main fiber.
Therefore, we should scan `stack_{start,end}` which always point a valid
stack range in any context.
2022-11-06 05:03:21 +09:00
Jemma Issroff 6e4b97f1da Increment max_iv_count on class in gc marking, not gc freeing
We were previously incrementing the max_iv_count on a class in gc
freeing. By the time we free an object though, we're not guaranteed its
class is still valid. Instead, we can do this when marking and we're
guaranteed the object still knows its class.
2022-11-04 11:41:10 -04:00
John Hawthorn 02f1554224
Implement object shapes for T_CLASS and T_MODULE (#6637)
* Avoid RCLASS_IV_TBL in marshal.c
* Avoid RCLASS_IV_TBL for class names
* Avoid RCLASS_IV_TBL for autoload
* Avoid RCLASS_IV_TBL for class variables
* Avoid copying RCLASS_IV_TBL onto ICLASSes
* Use object shapes for Class and Module IVs
2022-10-31 14:05:37 -07:00
Aaron Patterson 5e0432f59b
fix ASAN error in GC 2022-10-28 16:10:55 -07:00
Jemma Issroff a11952dac1 Rename `iv_count` on shapes to `next_iv_index`
`iv_count` is a misleading name because when IVs are unset, the new
shape doesn't decrement this value. `next_iv_count` is an accurate, and
more descriptive name.
2022-10-21 14:57:34 -07:00
Jemma Issroff 13bd617ea6 Remove unused class serial
Before object shapes, we were using class serial to invalidate
inline caches. Now that we use shape_id for inline cache keys,
the class serial is unnecessary.

Co-Authored-By: Aaron Patterson <tenderlove@ruby-lang.org>
2022-10-21 14:56:48 -07:00
Nobuyoshi Nakada e72c5044ce
Check writebarrier arguments only when RGENGC_CHECK_MODE [ci skip]
The commit 575ae50d16a03ed23357ec4ea0dbf7167fc26c8c was for debugging
the failure triggered by f55212bce9, and
it was fixed at the commit 39f7eddec4.
2022-10-21 10:02:16 +09:00
Nobuyoshi Nakada 9a0a165a5d Check writebarrier arguments 2022-10-20 15:43:34 -04:00
Aaron Patterson eeea633eb2 Stop zeroing memory on allocation / copy
Shapes gives us an almost exact count of instance variables on an
object.  Since we know the number of instance variables that have been
set, we will never access slots that haven't been initialized with an
IV.
2022-10-19 07:54:46 -07:00
Sergey Fedorov 567725ed30
Fix and improve coroutines for Darwin (macOS) ppc/ppc64. (#5975) 2022-10-19 23:49:45 +13:00
Aaron Patterson f0654b1027 More precisely iterate over Object instance variables
Shapes provides us with an (almost) exact count of instance variables.
We only need to check for Qundef when an IV has been "undefined"
Prefer to use ROBJECT_IV_COUNT when iterating IVs
2022-10-15 10:44:10 -07:00
Nobuyoshi Nakada 5ccb625fbb
Use `roomof` macro for rounding up divisions 2022-10-14 19:23:25 +09:00
Jemma Issroff ad63b668e2
Revert "Revert "This commit implements the Object Shapes technique in CRuby.""
This reverts commit 9a6803c90b.
2022-10-11 08:40:56 -07:00
Samuel Williams e4f91bbdba
Add IO#timeout attribute and use it for blocking IO operations. (#5653) 2022-10-07 21:48:38 +13:00
Nobuyoshi Nakada 40ceceb1a5 [Bug #19028] Suppress GCC 12 `-Wuse-after-free` false warning
GCC 12 introduced a new warning flag `-Wuse-after-free`, however it
has a false positive at `realloc` when optimization is disabled, since
the memory requested for reallocation is guaranteed to not be touched.
This workaround is very unclear why the false warning is suppressed by
a statement-expression GCC extension.
2022-10-04 21:53:59 +09:00
Aaron Patterson 9a6803c90b
Revert "This commit implements the Object Shapes technique in CRuby."
This reverts commit 68bc9e2e97d12f80df0d113e284864e225f771c2.
2022-09-30 16:01:50 -07:00
Jemma Issroff d594a5a8bd
This commit implements the Object Shapes technique in CRuby.
Object Shapes is used for accessing instance variables and representing the
"frozenness" of objects.  Object instances have a "shape" and the shape
represents some attributes of the object (currently which instance variables are
set and the "frozenness").  Shapes form a tree data structure, and when a new
instance variable is set on an object, that object "transitions" to a new shape
in the shape tree.  Each shape has an ID that is used for caching. The shape
structure is independent of class, so objects of different types can have the
same shape.

For example:

```ruby
class Foo
  def initialize
    # Starts with shape id 0
    @a = 1 # transitions to shape id 1
    @b = 1 # transitions to shape id 2
  end
end

class Bar
  def initialize
    # Starts with shape id 0
    @a = 1 # transitions to shape id 1
    @b = 1 # transitions to shape id 2
  end
end

foo = Foo.new # `foo` has shape id 2
bar = Bar.new # `bar` has shape id 2
```

Both `foo` and `bar` instances have the same shape because they both set
instance variables of the same name in the same order.

This technique can help to improve inline cache hits as well as generate more
efficient machine code in JIT compilers.

This commit also adds some methods for debugging shapes on objects.  See
`RubyVM::Shape` for more details.

For more context on Object Shapes, see [Feature: #18776]

Co-Authored-By: Aaron Patterson <tenderlove@ruby-lang.org>
Co-Authored-By: Eileen M. Uchitelle <eileencodes@gmail.com>
Co-Authored-By: John Hawthorn <john@hawthorn.email>
2022-09-28 08:26:21 -07:00
Nobuyoshi Nakada a05b261464 Always use the longer version of `TRY_WITH_GC` 2022-09-28 23:51:38 +09:00
Aaron Patterson 06abfa5be6
Revert this until we can figure out WB issues or remove shapes from GC
Revert "* expand tabs. [ci skip]"

This reverts commit 830b5b5c35.

Revert "This commit implements the Object Shapes technique in CRuby."

This reverts commit 9ddfd2ca00.
2022-09-26 16:10:11 -07:00
git 830b5b5c35 * expand tabs. [ci skip]
Tabs were expanded because the file did not have any tab indentation in unedited lines.
Please update your editor config, and use misc/expand_tabs.rb in the pre-commit hook.
2022-09-27 01:21:58 +09:00
Jemma Issroff 9ddfd2ca00 This commit implements the Object Shapes technique in CRuby.
Object Shapes is used for accessing instance variables and representing the
"frozenness" of objects.  Object instances have a "shape" and the shape
represents some attributes of the object (currently which instance variables are
set and the "frozenness").  Shapes form a tree data structure, and when a new
instance variable is set on an object, that object "transitions" to a new shape
in the shape tree.  Each shape has an ID that is used for caching. The shape
structure is independent of class, so objects of different types can have the
same shape.

For example:

```ruby
class Foo
  def initialize
    # Starts with shape id 0
    @a = 1 # transitions to shape id 1
    @b = 1 # transitions to shape id 2
  end
end

class Bar
  def initialize
    # Starts with shape id 0
    @a = 1 # transitions to shape id 1
    @b = 1 # transitions to shape id 2
  end
end

foo = Foo.new # `foo` has shape id 2
bar = Bar.new # `bar` has shape id 2
```

Both `foo` and `bar` instances have the same shape because they both set
instance variables of the same name in the same order.

This technique can help to improve inline cache hits as well as generate more
efficient machine code in JIT compilers.

This commit also adds some methods for debugging shapes on objects.  See
`RubyVM::Shape` for more details.

For more context on Object Shapes, see [Feature: #18776]

Co-Authored-By: Aaron Patterson <tenderlove@ruby-lang.org>
Co-Authored-By: Eileen M. Uchitelle <eileencodes@gmail.com>
Co-Authored-By: John Hawthorn <john@hawthorn.email>
2022-09-26 09:21:30 -07:00
Samuel Williams 22af2e9084 Rework vm_core to use `int first_lineno` struct member. 2022-09-26 00:41:16 +13:00
Nobuyoshi Nakada ff07e5c264
Skip poisoned regions
Poisoned regions cannot be accessed without unpoisoning outside gc.c.
Specifically, debug.gem is terminated by AddressSanitizer.

```
SUMMARY: AddressSanitizer: use-after-poison iseq_collector.c:39 in iseq_i
```
2022-08-09 20:11:48 +09:00
Peter Zhu 229cf263df Lock the VM for rb_gc_writebarrier_unprotect
When using Ractors, rb_gc_writebarrier_unprotect requries a VM lock
since it modifies the bitmaps.
2022-07-28 10:02:12 -04:00
Peter Zhu 1c16645216 Make array slices views rather than copies
Before this commit, if the slice fits in VWA, it would make a copy
rather than a view. This is slower as it requires a memcpy of the
contents.
2022-07-28 10:02:12 -04:00
Peter Zhu 2375afb8d6 Refactor gc_ref_update_array 2022-07-28 10:02:12 -04:00
Nobuyoshi Nakada 5d5c1d0fbd
Suppress use-after-free warning by gcc-12 2022-07-28 09:06:42 +09:00
Nobuyoshi Nakada f42230ff22
Adjust styles [ci skip] 2022-07-27 18:42:27 +09:00
git 3b1ed03d8c * expand tabs. [ci skip]
Tabs were expanded because the file did not have any tab indentation in unedited lines.
Please update your editor config, and use misc/expand_tabs.rb in the pre-commit hook.
2022-07-27 01:40:03 +09:00
Jemma Issroff 36d0c71ace
Refactored poisoning and unpoisoning freelist to simpler API 2022-07-26 09:39:31 -07:00
Peter Zhu efb91ff19b Rename rb_ary_tmp_new to rb_ary_hidden_new
rb_ary_tmp_new suggests that the array is temporary in some way, but
that's not true, it just creates an array that's hidden and not on the
transient heap. This commit renames it to rb_ary_hidden_new.
2022-07-26 09:12:09 -04:00
Nobuyoshi Nakada b30b727c24
Fix format specifier
`uintptr_t` is not always `unsigned long`, but can be casted to void
pointer safely.
2022-07-25 09:18:36 +09:00
Takashi Kokubun 5b21e94beb Expand tabs [ci skip]
[Misc #18891]
2022-07-21 09:42:04 -07:00
Peter Zhu cdbb9b8555 [Bug #18929] Fix heap creation thrashing in GC
Before this commit, if we don't have enough slots after sweeping but
had pages on the tomb heap, then the GC would frequently allocate and
deallocate pages. This is because after sweeping it would set
allocatable pages (since there were not enough slots) but free the
pages on the tomb heap.

This commit reuses pages on the tomb heap if there's not enough slots
after sweeping.
2022-07-21 10:46:32 -04:00
Peter Zhu 1c9acb6bb1 Refactor macros of array.c
Move some macros in array.c to internal/array.h so that other files
can also access these macros.
2022-07-21 09:02:45 -04:00
Daniel Colson 32e406d6d3 Ensure _id2ref finds symbols with the correct type
Prior to this commit it was possible to call `ObjectSpace._id2ref` with
an offset static symbol object_id and get back a new, incorrectly tagged
symbol:

```
> sensible_sym = ObjectSpace._id2ref(:a.object_id)
=> :a
> nonsense_sym = ObjectSpace._id2ref(:a.object_id + 40)
=> :a
> sensible_sym == nonsense_sym
=> false
```

`nonsense_sym` ends up tagged with `RUBY_ID_INSTANCE` instead of
`RB_ID_LOCAL`. That means we can do silly things like:

```
> foo = Object.new
> foo.instance_variable_set(:a, 123)
(irb):2:in `instance_variable_set': `a' is not allowed as an instance variable name (NameError)
> foo.instance_variable_set(ObjectSpace._id2ref(:a.object_id + 40), 123)
=> 123
> foo.instance_variables
=> [:a]
```

This was happening because `get_id_entry` ignores the tag bits when
looking up the symbol. So `rb_id2str(symid)` would return a value and
then we'd continue on with the nonsense `symid`.

This commit prevents the situation by checking that the `symid` actually
matches what we get back from `get_id_entry`. Now we get a `RangeError`
for the nonsense id:

```
> ObjectSpace._id2ref(:a.object_id)
=> :a
> ObjectSpace._id2ref(:a.object_id + 40)
(irb):1:in `_id2ref': 0x000000000013f408 is not symbol id value (RangeError)
```

Co-authored-by: John Hawthorn <jhawthorn@github.com>
2022-07-20 10:38:44 -07:00
Peter Zhu 86d061294d [Bug #18928] Fix crash in WeakMap
In wmap_live_p, if is_pointer_to_heap returns false, then the page is
either in the tomb or has already been freed, so the object is dead. In
this case, wmap_live_p should return false.
2022-07-20 08:40:31 -04:00
Nobuyoshi Nakada 472740de41
Fix free objects count condition
Free objects have `T_NONE` as the builtin type.  A pointer to a valid
array element will never be `NULL`.
2022-07-20 17:39:54 +09:00
Peter Zhu 7424ea184f Implement Objects on VWA
This commit implements Objects on Variable Width Allocation. This allows
Objects with more ivars to be embedded (i.e. contents directly follow the
object header) which improves performance through better cache locality.
2022-07-15 09:21:07 -04:00
Matt Valentine-House 214ed4cbc6 [Feature #18901] Support size pool movement for Arrays
This commit enables Arrays to move between size pools during compaction.
This can occur if the array is mutated such that it would fit in a
different size pool when embedded.

The move is carried out in two stages:

1. The RVALUE is moved to a destination heap during object movement
   phase of compaction
2. The array data is re-embedded and the original buffer free'd if
   required. This happens during the update references step
2022-07-12 08:50:33 -04:00
Matt Valentine-House a6dd859aff Add expand_heap option to GC.verify_compaction_references
In order to reliably test compaction we need to be able to move objects
between size pools.

In order for this to happen there must be pages in a size pool into
which we can allocate.

The existing implementation of `double_heap` only doubled the existing
number of pages in the heap, so if a size pool had a low number of pages
(or 0) it's not guaranteed that enough space will be created to move
objects into that size pool.

This commit deprecates the `double_heap` option and replaces it with
`expand_heap` instead.

expand heap will expand each heap by enough pages to hold a number of
slots defined by `GC_HEAP_INIT_SLOTS` or by `heap->total_pags` whichever
is larger.

If both `double_heap` and `expand_heap` are present, a deprecation
warning will be shown for `double_heap` and the `expand_heap` behaviour
will take precedence

Given that this is an API intended for debugging and testing GC
compaction I'm not concerned about the extra memory usage or time taken
to create the pages. However, for completeness:

Running the following `test.rb` and using `time` on my Macbook Pro shows
the following memory usage and time impact:

pp "RSS (kb): #{`ps -o rss #{Process.pid}`.lines.last.to_i}"
GC.verify_compaction_references(double_heap: true, toward: :empty)
pp "RSS (kb): #{`ps -o rss #{Process.pid}`.lines.last.to_i}"

❯ time make run
./miniruby -I./lib -I. -I.ext/common  -r./arm64-darwin21-fake  ./test.rb
"RSS (kb): 24000"
<internal:gc>:251: warning: double_heap is deprecated and will be removed
"RSS (kb): 25232"

________________________________________________________
Executed in  124.37 millis    fish           external
   usr time   82.22 millis    0.09 millis   82.12 millis
   sys time   28.76 millis    2.61 millis   26.15 millis

❯ time make run
./miniruby -I./lib -I. -I.ext/common  -r./arm64-darwin21-fake  ./test.rb
"RSS (kb): 24000"
"RSS (kb): 49040"

________________________________________________________
Executed in  150.13 millis    fish           external
   usr time  103.32 millis    0.10 millis  103.22 millis
   sys time   35.73 millis    2.59 millis   33.14 millis
2022-07-11 09:00:03 -04:00
Nobuyoshi Nakada ec09ba58d1
Extract `atomic_inc_wraparound` function 2022-07-10 17:56:36 +09:00
Nobuyoshi Nakada b1b8172328
Add `asan_unpoisoning_object` to execute the block with unpoisoning 2022-07-10 13:11:07 +09:00
Nobuyoshi Nakada ec303e49af
Split `rb_raw_obj_info` 2022-07-10 13:11:07 +09:00
Nobuyoshi Nakada 233054a609
Cycle `obj_info_buffers_index` atomically 2022-07-10 13:11:06 +09:00
Nobuyoshi Nakada a006dcb73f
`APPEND_S` for no conversion formats 2022-07-10 13:07:40 +09:00
Nobuyoshi Nakada 2bf0313561
Rewrite `APPENDF` using variadic arguments 2022-07-10 13:03:22 +09:00
Nobuyoshi Nakada 51025a9013
Use `size_t` for `rb_raw_obj_info` 2022-07-10 13:03:22 +09:00
Nobuyoshi Nakada fbe3651466
Use `asan_unpoison_object_temporary` 2022-07-10 13:03:22 +09:00
Nobuyoshi Nakada b16f44ad4f
Get rid of static buffer in `obj_info` 2022-07-10 13:03:21 +09:00
Nobuyoshi Nakada 61c7ae4d27 Gather heap page size conditions combination
When similar combination of conditions are separated in two places, it
is harder to make sure the conditional blocks match each other,
2022-07-07 22:39:59 +09:00
Peter Zhu f36859869f Improve error message for segv in read_barrier_handler
If the page_body is a null pointer, then read_barrier_handler will
crash with an unrelated message. This commit improves the error message.

Before:

test.rb:1: [BUG] Couldn't unprotect page 0x0000000000000000, errno: Cannot allocate memory

After:

test.rb:1: [BUG] read_barrier_handler: segmentation fault at 0x14
2022-07-07 09:39:28 -04:00
Peter Zhu d6c98626da Fix crash in compaction due to unlocked page
The page of src could be partially compacted, so it may contain
T_MOVED. Sweeping a page may read objects on this page, so we
need to lock the page.
2022-07-07 09:39:28 -04:00
Peter Zhu d7c5a6d49b Fix typo in gc_compact_move
The page we're sweeping is on the destination heap `dheap`, not the
source heap `heap`.
2022-07-07 09:39:28 -04:00
Nobuyoshi Nakada f681f9ae24
Adjust indents [ci skip] 2022-07-06 00:45:06 +09:00
Nobuyoshi Nakada cab10a2c50
Extract `protect_page_body` to fix mismatched braces 2022-06-18 10:20:46 +09:00
KJ Tsanaktsidis 05ffc037ad Disable Mach exception handlers when read barriers in place
The GC compaction mechanism implements a kind of read barrier by marking
some (OS) pages as unreadable, and installing a SIGBUS/SIGSEGV handler
to detect when they're accessed and invalidate an attempt to move the
object.

Unfortunately, when a debugger is attached to the Ruby interpreter on
Mac OS, the debugger will trap the EXC_BAD_ACCES mach exception before
the runtime can transform that into a SIGBUS signal and dispatch it.
Thus, execution gets stuck; any attempt to continue from the debugger
re-executes the line that caused the exception and no forward progress
can be made.

This makes it impossible to debug either the Ruby interpreter or a C
extension whilst compaction is in use.

To fix this, we disable the EXC_BAD_ACCESS handler when installing the
SIGBUS/SIGSEGV handlers, and re-enable them once the compaction is done.
The debugger will still trap on the attempt to read the bad page, but it
will be trapping the SIGBUS signal, rather than the EXC_BAD_ACCESS mach
exception. It's possible to continue from this in the debugger, which
invokes the signal handler and allows forward progress to be made.
2022-06-18 00:10:16 +09:00
Nobuyoshi Nakada 2c19086323
Suppress code unused unless GC_CAN_COMPILE_COMPACTION 2022-06-17 10:47:16 +09:00
Peter Zhu 79eaaf2d0b Include runtime checks for compaction support
Commit 0c36ba5319 changed GC compaction
methods to not be implemented when not supported. However, that commit
only does compile time checks (which currently only checks for WASM),
but there are additional compaction support checks during run time.

This commit changes it so that GC compaction methods aren't defined
during run time if the platform does not support GC compaction.

[Bug #18829]
2022-06-16 10:18:46 -04:00
Peter Zhu 52d42e7023 Rename GC_COMPACTION_SUPPORTED
Naming this macro GC_COMPACTION_SUPPORTED is misleading because it
only checks whether compaction is supported at compile time.

[Bug #18829]
2022-06-16 10:18:46 -04:00
Takashi Kokubun 1162523bae
Remove MJIT worker thread (#6006)
[Misc #18830]
2022-06-15 09:40:54 -07:00
Matt Valentine-House 56cc3e99b6 Move String RVALUES between pools
And re-embed any strings that can now fit inside the slot they've been
moved to
2022-06-13 10:11:27 -07:00
Peter Zhu 8d57336360 Fix major GC thrashing
Only growth heaps are allowed to start major GCs. Before this patch,
growth heaps are defined as size pools that freed more slots than had
empty slots (i.e. there were more dead objects that empty space).

But if the size pool is relatively stable and tightly packed with mostly
old objects and has allocatable pages, then it would be incorrectly
classified as a growth heap and trigger major GC. But since it's stable,
it would not use any of the allocatable pages and forever be classified
as a growth heap, causing major GC thrashing. This commit changes the
definition of growth heap to require that the size pool to have no
allocatable pages.
2022-06-08 12:09:19 -04:00
Peter Zhu d1b6c8a1cc Fix compilation error when USE_RVARGC=0
force_major_gc_count was not defined when USE_RVARGC=0.
2022-06-08 11:25:31 -04:00
Peter Zhu fafe68185c Add key force_major_gc_count to GC.stat_heap
force_major_gc_count is the number of times the size pool forced major
GC to run.
2022-06-08 10:03:00 -04:00
Peter Zhu c4bf24ee46 Remove while loop over heap_prepare
Having a while loop over `heap_prepare` makes the GC logic difficult to
understand (it is difficult to understand when and why `heap_prepare`
yields a free page). It is also a source of bugs and can cause an infinite
loop if `heap_page` never yields a free page.
2022-06-07 09:56:20 -04:00
Nobuyoshi Nakada af90433876
Typedef built-in function types 2022-06-02 16:05:35 +09:00
Nobuyoshi Nakada b96a3a6fd2
Move `GC.verify_compaction_references` [Bug #18779]
Define `GC.verify_compaction_references` as a built-in ruby method,
according to GC compaction support via `GC::OPTS`.
2022-06-02 15:32:00 +09:00
Nobuyoshi Nakada dfc8060756
Adjust indent and nesting [ci skip] 2022-06-02 14:34:48 +09:00
Mike Dalessio 0c36ba5319 Define unsupported GC compaction methods as rb_f_notimplement
Fixes [Bug #18779]

Define the following methods as `rb_f_notimplement` on unsupported
platforms:

- GC.compact
- GC.auto_compact
- GC.auto_compact=
- GC.latest_compact_info
- GC.verify_compaction_references

This change allows users to call `GC.respond_to?(:compact)` to
properly test for compaction support. Previously, it was necessary to
invoke `GC.compact` or `GC.verify_compaction_references` and check if
those methods raised `NotImplementedError` to determine if compaction
was supported.

This follows the precedent set for other platform-specific
methods. For example, in `process.c` for methods such as
`Process.fork`, `Process.setpgid`, and `Process.getpriority`.
2022-05-24 09:40:03 -07:00
Mike Dalessio 0de1495f35 Move compaction-related methods into gc.c
These methods are removed from gc.rb and added to gc.c:

- GC.compact
- GC.auto_compact
- GC.auto_compact=
- GC.latest_compact_info
- GC.verify_compaction_references

This is a prefactor to allow setting these methods to
`rb_f_notimplement` in a followup commit.
2022-05-24 09:40:03 -07:00
Matt Valentine-House 708e839dee Fix compiler warning when USE_RVARGC=0 2022-05-13 16:26:41 -04:00
Kaíque Kandy Koga a85cdb5a6e
Write have instead of have have [ci skip 2022-05-10 13:07:16 +09:00
Peter Zhu 85479b34f7 Don't allocate new page on finish sweeping
We don't need to allocate a new page in gc_sweep_finish_size_pool.
It can be allocated when needed.
2022-05-09 08:45:24 -04:00
Peter Zhu e28e9c63c6 Fix heap_extend_pages when total_slots is 0
Some size pools may not have any pages/slots, so total_slots is 0. This
causes a divide-by-zero in the calculation. This commit adds a special
case to catch the case when total_slots is 0 and returns the number of
pages for heap_init_slots.
2022-05-09 08:45:24 -04:00
Peter Zhu f7d480378a Grow size pools with no or few slots
If the size pool has no or few pages/slots, then min_free_slots will
be a very small number (or even 0). Then the heap won't be eligible to
grow, causing GC thrashing or infinite loops.
2022-05-09 08:45:24 -04:00
Peter Zhu b3f3cb0c38 Call gc_sweep_finish_size_pool on size pools with no pages
Size pools with no pages won't be swept so gc_sweep_finish_size_pool
will never be called on it, but gc_sweep_finish_size_pool must be called
to grow the size pool.
2022-05-09 08:45:24 -04:00
Peter Zhu 033e58cf2c Fix gc_page_sweep when last bitmap plane is not used
Depending on alignment, the last bitmap plane may not used. Then it will
appear as if all of the objects on that plane is unmarked, which will
cause a buffer overrun when we try to free the object. This commit
changes the loop to calculate the number of planes used
(bitmap_plane_count).
2022-05-09 08:45:24 -04:00
Alan Wu cae85c528c Mark RCLASS_INCLUDER
Since 4d8f76286b, we need to dereference
the includer field on iclasses, so we need to mark it to make sure
it's alive.

Sometimes during compaction we crash because the field is dangling,
though I have a hard time constructing such a situation. See
http://ci.rvm.jp/results/trunk@ruby-iga/3947725
2022-05-05 17:37:07 -04:00
Jemma Issroff d7df8c6964 Unpoison freelist when iterating over it in gc_sweep_page 2022-05-04 12:49:15 -07:00
Peter Zhu bff31b3208 Remove unneeded cast
`start` is of type uintptr_t so it does not need to be casted to VALUE.
2022-05-04 09:24:03 -04:00
Alan Wu 379f5a6e8e Update reference for RCLASS_INCLUDER during compaction
We didn't update the includer field during compaction so it could become
a dangling pointer after compaction. It's only recently that we started
to dereference the field, and we were only comparing the pointer before
then, so the omission only recently started to cause crashes.

By instrumenting object.c:833 with `rp(includer);`, you can see the
includer field become `T_NONE` with the following script:

```ruby
mod = Module.new do
  protected def foo = 1
end

klass = Class.new do
  include Module.new
  def run
    foo
  end
end

klass.include(mod)

GC.verify_compaction_references(double_heap: true, toward: :empty)

klass.new.run
```

I found a crash in a private application that this patch fixes, but
wasn't able to develop a small reproducer. Hence the above demo that
requires instrumentation.
2022-05-03 16:48:46 -04:00
Nobuyoshi Nakada df1594e4b5
Parenthize macro arguments 2022-04-13 22:55:20 +09:00
Kazuhiro NISHIYAMA 48ffa28044
Fix a typo [ci skip] 2022-04-12 19:14:39 +09:00
S-H-GAMELINKS 5b467400d2 [DOC]Some link prefix replace 2022-04-09 17:43:46 +09:00
Nobuyoshi Nakada 5af507f527
Update `heap_pages_deferred_final` atomically 2022-04-07 12:19:18 +09:00
Eric Wong a19b2d59fc ruby_gc_set_params: update malloc_limit when env is set
During VM startup, rb_objspace_alloc sets malloc_limit
(objspace->malloc_params.limit) before ruby_gc_set_params is called, thus
nullifying the effect of RUBY_GC_MALLOC_LIMIT before the initial GC run.

The call sequence is as follows:

  main.c::main()
    ruby_init
      ruby_setup
        Init_BareVM
          rb_objspace_alloc // malloc_limit = gc_params.malloc_limit_min;
    ruby_options
      ruby_process_options
        process_options
          ruby_gc_set_params // RUBY_GC_MALLOC_LIMIT => gc_params.malloc_limit_min

With ruby_gc_set_params setting malloc_limit, RUBY_GC_MALLOC_LIMIT
affects the process sooner.

[ruby-core:107170]
2022-04-04 21:46:02 +00:00
Peter Zhu ea9c09a92c Disable mmap on WASM
WASM does not have proper support for mmap.
2022-04-04 09:27:14 -04:00
Peter Zhu c482ee4025 Make heap page sizes 64KiB by default
Commit dde164e968 decoupled incremental
marking from page sizes. This commit changes Ruby heap page sizes to
64KiB. Doing so will have several benefits:

1. We can use compaction on systems with 64KiB system page sizes (e.g.
   PowerPC).
2. Larger page sizes will allow Variable Width Allocation to increase
   slot sizes and embed larger objects.
3. Since commit 002fa28599, macOS has 64
   KiB pages. Making page sizes 64 KiB will bring these systems to
   parity.

I have attached some bechmark results below.

Discourse:
    On Discourse, we saw much better p99 performance (e.g. for "categories"
    it went from 214ms on master to 134ms on branch, for "home" it went
    from 265ms to 251ms). We don’t see much change in p60, p75, and p90
    performance. We also see a slight decrease in memory usage by 1.04x.

    Branch RSS: 354.9MB
    Master RSS: 368.2MB

railsbench:
    On rails bench, we don’t see a big change in RPS or p99
    performance. We don’t see a big difference in memory usage.

    Branch RPS: 826.27
    Master RPS: 824.85

    Branch p99: 1.67
    Master p99: 1.72

    Branch RSS: 88.72MB
    Master RSS: 88.48MB

liquid:
    We don’t see a significant change in liquid performance.

    Branch parse & render: 28.653 I/s
    Master parse & render: 28.563 i/s
2022-04-04 09:27:14 -04:00
Matt Valentine-House 651b832c1b extract magic number from gc_sweep_step 2022-04-01 10:52:18 -04:00
Peter Zhu fe21b7794a Use mmap for heap page allocation only
Currently, rb_aligned_malloc uses mmap if Ruby heap pages can be
allocated through mmap (when system heap page size <= Ruby heap page
size). If Ruby heap page sizes is increased to 64KiB, then mmap will
be used on systems with 64KiB system page sizes. However, the transient
heap also uses rb_aligned_malloc and requires 32KiB alignment. This
would break in the current implementation since it would allocate sizes
through mmap that is not a multiple of the system page size.

This commit adds heap_page_body_allocate which will use mmap when
possible and changes rb_aligned_malloc to not use mmap (and only
use posix_memalign).
2022-04-01 10:27:18 -04:00
Matt Valentine-House d8352ff3ac [Feature #18619] remove FL_FROM_FREELIST 2022-04-01 08:45:52 -04:00
Matt Valentine-House c26a85fc96 [Feature #18619] Remove redundant compaction path 2022-04-01 08:45:52 -04:00
Matt Valentine-House 76572e5a7f [Feature #18619] Reverse the order of compaction movement
This commit changes the way compaction moves objects and sweeps pages in
order to better facilitate object movement between size pools.

Previously we would move the scan cursor first until we found an empty
slot and then we'd decrement the compact cursor until we found something
to move into that slot. We would sweep the page that contained the scan
cursor before trying to fill it

In this algorithm we first move the compact cursor down until we find an
object to move - We then take a free page from the desired destination
heap (always the same heap in this current iteration of the code).

If there is no free page we sweep the page at the sweeping_page cursor,
add it to the free pages, and advance the cursor to the next page, and
try again.

We sweep one page from each size pool in this way, and then repeat that
process until all the size pools are compacted (all the cursors have
met), and then we update references and sweep the rest of the heap.
2022-04-01 08:45:52 -04:00
Matt Valentine-House bb037f6d86 Remove hard-coded swept slots threshold 2022-03-31 14:39:59 -04:00
Peter Zhu dde164e968 Decouple incremental marking step from page sizes
Currently, the number of incremental marking steps is calculated based
on the number of pooled pages available. This means that if we make Ruby
heap pages larger, it would run fewer incremental marking steps (which
would mean each incremental marking step takes longer).

This commit changes incremental marking to run after every
INCREMENTAL_MARK_STEP_ALLOCATIONS number of allocations. This means that
the behaviour of incremental marking remains the same regardless of the
Ruby heap page size.

I've benchmarked against discourse benchmarks and did not get a
significant change in response times beyond the margin of error. This is
expected as this new incremental marking algorithm behaves very
similarly to the previous one.
2022-03-30 09:33:17 -04:00
Nobuyoshi Nakada 42a0bed351
Prefix ccan headers (#4568)
* Prefixed ccan headers

* Remove unprefixed names in ccan/build_assert

* Remove unprefixed names in ccan/check_type

* Remove unprefixed names in ccan/container_of

* Remove unprefixed names in ccan/list

Co-authored-by: Samuel Williams <samuel.williams@oriontransfer.co.nz>
2022-03-30 20:36:31 +13:00
Peter Zhu ae650f0372 Remove unneeded function declarations in gc.c 2022-03-28 10:02:45 -04:00
Peter Zhu 5f10bd634f Add ISEQ_BODY macro
Use ISEQ_BODY macro to get the rb_iseq_constant_body of the ISeq. Using
this macro will make it easier for us to change the allocation strategy
of rb_iseq_constant_body when using Variable Width Allocation.
2022-03-24 10:03:51 -04:00
John Hawthorn 19f331f588 Dedup superclass array in leaf sibling classes
Previously, we would build a new `superclasses` array for each class,
even though for all immediate subclasses of a class, the array is
identical.

This avoids duplicating the arrays on leaf classes (those without
subclasses) by calculating and storing a "superclasses including self"
array on a class when it's first inherited and sharing that among all
superclasses.

An additional trick used is that the "superclass array including self"
is valid as "self"'s superclass array. It just has it's own class at the
end. We can use this to avoid an extra pointer of storage and can use
one bit of a flag to track that we've "upgraded" the array.
2022-03-03 11:23:27 -08:00
John Hawthorn b13a7c8e36 Constant time class to class ancestor lookup
Previously when checking ancestors, we would walk all the way up the
ancestry chain checking each parent for a matching class or module.

I believe this was especially unfriendly to CPU cache since for each
step we need to check two cache lines (the class and class ext).

This check is used quite often in:
* case statements
* rescue statements
* Calling protected methods
* Class#is_a?
* Module#===
* Module#<=>

I believe it's most common to check a class against a parent class, to
this commit aims to improve that (unfortunately does not help checking
for an included Module).

This is done by storing on each class the number and an array of all
parent classes, in order (BasicObject is at index 0). Using this we can
check whether a class is a subclass of another in constant time since we
know the location to expect it in the hierarchy.
2022-02-23 19:57:42 -08:00
Peter Zhu 71afa8164d Change darray size to size_t and add functions that use GC malloc
Changes size and capacity of darray to size_t to support more
elements.

Adds functions to darray that use GC allocation functions.
2022-02-16 09:50:29 -05:00
Koichi Sasada 1ae630db26 `wmap#each` should check liveness of keys
`ObjectSpace::WeakMap#each*` should check key's liveness.
fix [Bug #18586]
2022-02-16 13:31:46 +09:00
Koichi Sasada 76e594d515 fix GC event synchronization
(1) gc_verify_internal_consistency() use barrier locking
    for consistency while `during_gc == true` at the end
    of the sweep on `RGENGC_CHECK_MODE >= 2`.
(2) `rb_objspace_reachable_objects_from()` is called without
    VM synchronization and it checks `during_gc != true`.

So (1) and (2) causes BUG because of `during_gc == true`.
To prevent this error, wait for VM barrier on `during_gc == false`
and introduce VM locking on `rb_objspace_reachable_objects_from()`.

http://ci.rvm.jp/results/trunk-asserts@phosphorus-docker/3830088
2022-02-14 17:17:55 +09:00
Peter Zhu 2617532499 Free cached mark stack chunks when freeing objspace
Cached mark stack chunks should also be freed when freeing objspace.
2022-02-10 09:33:42 -05:00
Peter Zhu af321ea727 Move total_freed_pages to size pool 2022-02-03 15:06:55 -05:00
Peter Zhu a9221406aa Move total_allocated_pages to size pool 2022-02-03 15:06:55 -05:00
Peter Zhu 424374d330 Fix case when gc_marks_continue does not yield slots
gc_marks_continue will start sweeping when it finishes marking. However,
if the heap we are trying to allocate into is full, then the sweeping
may not yield any free slots. If we don't call gc_sweep_continue
immediate after this, then another GC will be started halfway during
lazy sweeping. gc_sweep_continue will either grow the heap or finish
sweeping.
2022-02-03 09:22:24 -05:00
Peter Zhu 7b77d46671 Decouple GC slot sizes from RVALUE
Add a new macro BASE_SLOT_SIZE that determines the slot size.

For Variable Width Allocation (compiled with USE_RVARGC=1), all slot
sizes are powers-of-2 multiples of BASE_SLOT_SIZE.

For USE_RVARGC=0, BASE_SLOT_SIZE is set to sizeof(RVALUE).
2022-02-02 09:52:04 -05:00
Peter Zhu 605f226142 Fix heap page iteration in gc_verify_heap_page
The for loops are not correctly iterating heap pages in
gc_verify_heap_page.
2022-01-31 09:42:20 -05:00
Nobuyoshi Nakada 67f4729ff0
[Bug#18556] Fallback `MAP_ ANONYMOUS`
Define `MAP_ANONYMOUS` to `MAP_ANON` if undefined on old systems.
2022-01-29 19:07:38 +09:00
Peter Zhu e714163011 Fix typo in assertion in gc.c 2022-01-26 09:45:22 -05:00
Nobuyoshi Nakada 16e7585557
Unpoison the cached object in the exact size 2022-01-26 14:34:25 +09:00
Peter Zhu 82f0580aa4 Call rb_id_table_foreach_values instead
These places never replace the value, so call rb_id_table_foreach_values
instead of rb_id_table_foreach_values_with_replace.
2022-01-25 16:51:16 -05:00
Peter Zhu 4d9ad91a35 Rename rb_id_table_foreach_with_replace
Renames rb_id_table_foreach_with_replace to
rb_id_table_foreach_values_with_replace and passes only the value to the
callback. We can use this in GC compaction when we cannot access the
global symbol array.
2022-01-25 16:51:16 -05:00
Peter Zhu b07879e553 Remove redundant if statement in try_move
The if statement is redundant since if `index == 0` then
`BITS_BITLENGTH * index == 0`.
2022-01-25 09:38:17 -05:00
Peter Zhu 87784fdeb2 Keep right operand within width when right shifting
NUM_IN_PAGE could return a value much larger than 64. According to the
C11 spec 6.5.7 paragraph 3 this is undefined behavior:

> If the value of the right operand is negative or is greater than or
> equal to the width of the promoted left operand, the behavior is
> undefined.

On most platforms, this is usually not a problem as the architecture
will mask off all out-of-range bits.
2022-01-24 14:34:12 -05:00
Peter Zhu 663833b08f [wasm] Disallow compaction
WebAssembly doesn't support signals so we can't use read
barriers so we can't use compaction.
2022-01-24 09:21:08 -05:00
Nobuyoshi Nakada 8f3e29c849
Fix format size qualifier on IL32P64 2022-01-19 13:33:14 +09:00
Yuta Saito bf1c4d254b [wasm] gc.c: scan wasm locals and c stack to mark living objects
WebAssembly has function local infinite registers and stack values, but
there is no way to scan the values in a call stack for now.
This implementation uses Asyncify to spilling out wasm locals into
linear memory.
2022-01-19 11:19:06 +09:00
Yuta Saito e7fb1fa041 [wasm] gc.c: disable read signal barrier for wasi
WASI currently does not yet support signal
2022-01-19 11:19:06 +09:00
Yuta Saito 23de01c7aa [wasm] eval_inter.h gc.c vm_core.h: include wasm/setjmp.h instead of sysroot header 2022-01-19 11:19:06 +09:00
Peter Zhu 6b7eff9086 Separately allocate class_serial on 32-bit systems
On 32-bit systems, VWA causes class_serial to not be aligned (it only
guarantees 4 byte alignment but class_serial is 8 bytes and requires 8
byte alignment). This commit uses a hack to allocate class_serial
through malloc. Once VWA allocates with 8 byte alignment in the future,
we will revert this commit.
2022-01-14 14:36:33 -05:00
Peter Zhu d9ef711f29 Improve string info in rb_raw_obj_info
Improve rb_raw_obj_info to output additional into about strings
including the length, capacity, and whether or not it is embedded.
2022-01-07 14:22:32 -05:00
Peter Zhu 6f7e02bf46 Remove assertion causing read barrier to trigger
GET_HEAP_PAGE reads the page. If during compaction there is a read
barrier on the page, it causes the read barrier to trigger.
2022-01-05 09:32:53 -05:00
Matt Valentine-House ad007bc6ea Switch `is_pointer_to_heap` to use library bsearch
This commit switches from a custom implemented bsearch algorithm to
use the one provided by the C standard library.

Because `is_pointer_to_heap` will only return true if the pointer
being searched for is a valid slot starting address within the heap
page body, we've extracted the bsearch call site into a more general
function so we can use it elsewhere.

The new function `heap_page_for_ptr` returns the heap page for any heap
page pointer, regardless of whether that is at the start of a slot or
in the middle of one.

We then use this function as the basis of `is_pointer_to_heap`.
2022-01-04 10:27:46 -05:00
Peter Zhu 615e9b2865 [Feature #18364] Add GC.stat_heap to get stats for memory heaps
GC.stat_heap will return stats for memory heaps. This is
used for the Variable Width Allocation feature.
2022-01-04 09:46:36 -05:00
Nobuyoshi Nakada 069cca6f74
Negative RBOOL usage 2022-01-01 17:02:04 +09:00
Nobuyoshi Nakada 002fa28599 On 64bit macOS, enlarge heap pages to reduce mmap calls [Bug #18447] 2021-12-29 20:53:43 +09:00
Nobuyoshi Nakada 7c738ce5e6
Remove deprecate rb_cData [Bug #18433]
Also enable the warning for T_DATA allocator.
2021-12-26 23:28:54 +09:00
Koichi Sasada 2da53b1468 `finalize_deferred` doesn't need VM lock
`finalize_list()` acquires VM lock to manipulate objspace state.
2021-12-23 16:50:17 +09:00
Koichi Sasada ca032d5eea undef `rb_vm_lookup_overloaded_cme()`
Some callable method entries (cme) can be a key of `overloaded_cme_table`
and the keys should be pinned because the table is numtable (VALUE is a key).
Before the patch GC checks the cme is in `overloaded_cme_table` by looking up
the table, but it needs VM locking.

It works well in normal GC marking because it is protected by the VM lock,
but it doesn't work on `rb_objspace_reachable_objects_from` because it doesn't
use VM lock.

Now, the number of target cmes are small enough, I decide to pin down
all possible cmes instead of using looking up the table.
2021-12-23 16:49:49 +09:00
Koichi Sasada ad450c9fe5 make `overloaded_cme_table` truly weak key map
`overloaded_cme_table` keeps cme -> monly_cme pairs to manage
corresponding `monly_cme` for `cme`. The lifetime of the `monly_cme`
should be longer than `monly_cme`, but the previous patch losts the
reference to the living `monly_cme`.

Now `overloaded_cme_table` values are always root (keys are only weak
reference), it means `monly_cme` does not freed until corresponding
`cme` is invalidated.

To make managing easy, move `overloaded_cme_table` to `rb_vm_t`.
2021-12-21 15:21:30 +09:00
Koichi Sasada df48db987d `mandatory_only_cme` should not be in `def`
`def` (`rb_method_definition_t`) is shared by multiple callable
method entries (cme, `rb_callable_method_entry_t`).

There are two issues:

* old -> young reference: `cme1->def->mandatory_only_cme = monly_cme`
  if `cme1` is young and `monly_cme` is young, there is no problem.
  Howevr, another old `cme2` can refer `def`, in this case, old `cme2`
  points young `monly_cme` and it violates gengc assumption.
* cme can have different `defined_class` but `monly_cme` only has
  one `defined_class`. It does not make sense and `monly_cme`
  should be created for a cme (not `def`).

To solve these issues, this patch allocates `monly_cme` per `cme`.
`cme` does not have another room to store a pointer to the `monly_cme`,
so this patch introduces `overloaded_cme_table`, which is weak key map
`[cme] -> [monly_cme]`.

`def::body::iseqptr::monly_cme` is deleted.

The first issue is reported by Alan Wu.
2021-12-21 11:03:09 +09:00
Alan Wu 39cf0b5314
Show whether object is garbage in rb_raw_obj_info()
When using `rp(obj)` for debugging during development, it may be
useful to know that an object is soon to be swept. Add a new letter to
the object dump for whether the object is garbage. It's easy to forget
about lazy sweep.
2021-12-20 16:13:34 -05:00
Peter Zhu 0e7d073914 Remove compaction support detection using sysconf
Except on Windows and MinGW, we can only use compaction on systems that
use mmap (only systems that use mmap can use the read barrier that
compaction requires). We don't need to separately detect whether we can
support compaction or not.
2021-12-14 09:16:18 -05:00
Nobuyoshi Nakada a2d4e1cda6 Fixed the check order in wmap_live_p [Bug #18392]
Check if the object is a pointer to heap before check the flag in
that object.
2021-12-07 21:55:41 +09:00
Nobuyoshi Nakada d6c5a30cfd ObjectSpace::WeakMap#inspect: check if living object [Bug #18392] 2021-12-07 21:55:41 +09:00
Peter Zhu 081539023a Refactor GC functions to have consistent naming
Refactor function names for consistency. Function with name xyz_page
should have a corresponding function named xyz_plane.
2021-12-03 10:26:26 -05:00
John Hawthorn 733500e9d0
Lazily create singletons on instance_{exec,eval} (#5146)
* Lazily create singletons on instance_{exec,eval}

Previously when instance_exec or instance_eval was called on an object,
that object would be given a singleton class so that method
definitions inside the block would be added to the object rather than
its class.

This commit aims to improve performance by delaying the creation of the
singleton class unless/until one is needed for method definition. Most
of the time instance_eval is used without any method definition.

This was implemented by adding a flag to the cref indicating that it
represents a singleton of the object rather than a class itself. In this
case CREF_CLASS returns the object's existing class, but in cases that
we are defining a method (either via definemethod or
VM_SPECIAL_OBJECT_CBASE which is used for undef and alias).

This also happens to fix what I believe is a bug. Previously
instance_eval behaved differently with regards to constant access for
true/false/nil than for all other objects. I don't think this was
intentional.

    String::Foo = "foo"
    "".instance_eval("Foo")   # => "foo"
    Integer::Foo = "foo"
    123.instance_eval("Foo")  # => "foo"
    TrueClass::Foo = "foo"
    true.instance_eval("Foo") # NameError: uninitialized constant Foo

This also slightly changes the error message when trying to define a method
through instance_eval on an object which can't have a singleton class.

Before:

    $ ruby -e '123.instance_eval { def foo; end }'
    -e:1:in `block in <main>': no class/module to add method (TypeError)

After:

    $ ./ruby -e '123.instance_eval { def foo; end }'
    -e:1:in `block in <main>': can't define singleton (TypeError)

IMO this error is a small improvement on the original and better matches
the (both old and new) message when definging a method using `def self.`

    $ ruby -e '123.instance_eval{ def self.foo; end }'
    -e:1:in `block in <main>': can't define singleton (TypeError)

Co-authored-by: Matthew Draper <matthew@trebex.net>

* Remove "under" argument from yield_under

* Move CREF_SINGLETON_SET into vm_cref_new

* Simplify vm_get_const_base

* Fix leaf VM_SPECIAL_OBJECT_CONST_BASE

Co-authored-by: Matthew Draper <matthew@trebex.net>
2021-12-02 15:53:39 -08:00
Matt Valentine-House f7bdfb39ef Don't clear the constant cache when finishing compaction
References are being updated correctly, so this is no longer necessary
2021-12-02 10:14:14 -05:00
Yuta Saito 6721ce1cc4 Cast tv_usec to int32_t to fit in tv_nsec
suseconds_t, which is the type of tv_usec, may be defined with a longer
size type than tv_nsec's type (long). So usec to nsec conversion needs
an explicit casting.
2021-12-02 15:53:43 +09:00
Kazuhiro NISHIYAMA 29877d944e Fix a function name in an error message 2021-11-26 20:12:49 +09:00
Kazuhiro NISHIYAMA 04951a1226 Remove unused function `size_pool_for_size`
```
compiling ../gc.c
../gc.c:2444:1: warning: unused function 'size_pool_for_size' [-Wunused-function]
size_pool_for_size(rb_objspace_t *objspace, size_t size)
^
1 warning generated.
```
2021-11-26 20:12:49 +09:00
Koichi Sasada 7f7c3a0a75 initialize allocated memory by VWA for assertions
When `RGENGC_CHECK_MODE` is enable, `obj_memsize_of` is called
in `newobj_init` and it expect the memory is zero-cleared.
2021-11-26 11:39:59 +09:00
Peter Zhu b0bbcaedc7 Revert "Add GC.stat_size_pool to get stats for a size pool"
This reverts commit 6157619bb6.

We'll wait for comments in the open ticket: https://bugs.ruby-lang.org/issues/18364
2021-11-25 11:01:50 -05:00
Peter Zhu 6157619bb6 Add GC.stat_size_pool to get stats for a size pool
GC.stat_size_pool will return stats for a particular size pool. This is
used for the Variable Width Allocation feature.
2021-11-25 10:33:17 -05:00
Peter Zhu 9aded89f40 Speed up Ractors for Variable Width Allocation
This commit adds a Ractor cache for every size pool. Previously, all VWA
allocated objects used the slowpath and locked the VM.

On a micro-benchmark that benchmarks String allocation:

VWA turned off:
  29.196591   0.889709  30.086300 (  9.434059)

VWA before this commit:
  29.279486  41.477869  70.757355 ( 12.527379)

VWA after this commit:
  16.782903   0.557117  17.340020 (  4.255603)
2021-11-23 10:51:27 -05:00
Jemma Issroff c4f45674a4 Removes unused HEAP_PAGE_BITMAP_PLANES constant from gc.c 2021-11-22 12:02:29 -05:00
Matt Valentine-House b680b632e5 Make RCLASS_EXT(c)->subclasses a doubly linked list
Updating RCLASS_PARENT_SUBCLASSES and RCLASS_MODULE_SUBCLASSES while
compacting can trigger the read barrier. This commit makes
RCLASS_SUBCLASSES a doubly linked list with a dedicated head object so
that we can add and remove entries from the list without having to touch
an object in the Ruby heap
2021-11-22 09:11:04 -05:00
Yusuke Endoh 4b1dd75e6c gc.c: Fix a compile error on some crossbuilds
http://rubyci.s3.amazonaws.com/crossruby/crossruby-master-wasm32_emscripten/log/20211118T233311Z.log.html.gz#make
```
compiling gc.c
gc.c:10629:47: error: implicit conversion loses integer precision: 'unsigned long long' to 'size_t' (aka 'unsigned long') [-Werror,-Wshorten-64-to-32]
    SET(time, objspace->profile.total_time_ns / (1000 * 1000) /* ns -> ms */);
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gc.c:10624:9: note: expanded from macro 'SET'
        return attr; \
        ~~~~~~ ^~~~
gc.c:10629:47: error: implicit conversion loses integer precision: 'unsigned long long' to 'unsigned long' [-Werror,-Wshorten-64-to-32]
    SET(time, objspace->profile.total_time_ns / (1000 * 1000) /* ns -> ms */);
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gc.c:10626:68: note: expanded from macro 'SET'
        rb_hash_aset(hash, gc_stat_symbols[gc_stat_sym_##name], SIZET2NUM(attr));
                                                                ~~~~~~~~~ ^~~~
2 errors generated.
```
2021-11-19 10:09:51 +09:00
Koichi Sasada c347038d4e GC measurement feature
* `GC.measure_total_time = true` enables total time measurement (default: true)
* `GC.measure_total_time` returns current flag.
* `GC.total_time` returns measured total time in nano seconds.
* `GC.stat(:time)` (and Hash) returns measured total time in milli seconds.
2021-11-19 08:32:07 +09:00
Koichi Sasada 349a179782 support `GC.stat(:time)` take 2 2021-11-19 08:32:07 +09:00
Koichi Sasada b1b73936c1 `Primitive.mandatory_only?` for fast path
Compare with the C methods, A built-in methods written in Ruby is
slower if only mandatory parameters are given because it needs to
check the argumens and fill default values for optional and keyword
parameters (C methods can check the number of parameters with `argc`,
so there are no overhead). Passing mandatory arguments are common
(optional arguments are exceptional, in many cases) so it is important
to provide the fast path for such common cases.

`Primitive.mandatory_only?` is a special builtin function used with
`if` expression like that:

```ruby
  def self.at(time, subsec = false, unit = :microsecond, in: nil)
    if Primitive.mandatory_only?
      Primitive.time_s_at1(time)
    else
      Primitive.time_s_at(time, subsec, unit, Primitive.arg!(:in))
    end
  end
```

and it makes two ISeq,

```
  def self.at(time, subsec = false, unit = :microsecond, in: nil)
    Primitive.time_s_at(time, subsec, unit, Primitive.arg!(:in))
  end

  def self.at(time)
    Primitive.time_s_at1(time)
  end
```

and (2) is pointed by (1). Note that `Primitive.mandatory_only?`
should be used only in a condition of an `if` statement and the
`if` statement should be equal to the methdo body (you can not
put any expression before and after the `if` statement).

A method entry with `mandatory_only?` (`Time.at` on the above case)
is marked as `iseq_overload`. When the method will be dispatch only
with mandatory arguments (`Time.at(0)` for example), make another
method entry with ISeq (2) as mandatory only method entry and it
will be cached in an inline method cache.

The idea is similar discussed in https://bugs.ruby-lang.org/issues/16254
but it only checks mandatory parameters or more, because many cases
only mandatory parameters are given. If we find other cases (optional
or keyword parameters are used frequently and it hurts performance),
we can extend the feature.
2021-11-15 15:58:56 +09:00
Matt Valentine-House a9a94540d6 Remove RCLASS(obj)->ptr when RVARGC is enabled
With RVARGC we always store the rb_classext_t in the same slot as the
RClass struct that refers to it. So we don't need to store the pointer
or access through the pointer anymore and can switch the RCLASS_EXT
macro to use an offset
2021-11-11 13:47:45 -05:00
Matt Valentine-House c53aecee3b fix a memory leak introduced in 8bbd319
This commit fixes a memory leak introduced in an early part of the
variable width allocation project that would prevent the rb_classext_t
struct from being free'd when the class is swept.
2021-11-11 08:54:48 -05:00
Peter Zhu 309406484b [Feature #18290] Deprecate rb_gc_force_recycle and remove invalidate_mark_stack_chunk
This commit deprecates rb_gc_force_recycle and coverts it to a no-op
function. Also removes invalidate_mark_stack_chunk since only
rb_gc_force_recycle uses it.
2021-11-08 14:05:54 -05:00
Matt Valentine-House d7279f0894 make obj_free return true when it frees an object
Previously obj_free returned true when it could not free a slot because
of a finalizer, and false when it successfully frees a slot.
2021-10-29 08:58:22 -07:00
Matt Valentine-House ed8540ebf4 Prefer size pool heap macros over direct access 2021-10-29 09:17:30 -04:00
Kazuhiro NISHIYAMA d844459377
Fix a warning
```
../gc.c:2342:45: warning: comparison of integers of different signs: 'short' and 'size_t' (aka 'unsigned long') [-Wsign-compare]
    GC_ASSERT(size_pools[pool_id].slot_size == slot_size);
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~
```

Add cast to short, because `GC_ASSERT`s in `size_pool_for_size`
already use cast to short.
2021-10-28 09:22:17 +09:00