105 Commits
Author SHA1 Message Date
Hiroshi SHIBATAandClaude Opus 5.5 4e746b14fd Make rb_len_t 64 bits on mswin
long is 32 bits on mswin while pointers are 64 bits, so String, Array and MatchData could not reach 2GiB there. config.h now sets SIZEOF_RB_LEN_T to 8 on mswin64, and value.h then defines rb_len_t as int64_t. mingw still uses long.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 16:07:39 +09:00
Peter Zhu 96d57e2403 Make rb_str_no_gvl_safe_acquire public C API
This commit renames rb_str_tmp_frozen_no_embed_acquire to rb_str_no_gvl_safe_acquire
and makes it part of the public C API.

There is currently no way for C extensions that use no GVL operations to
safely read from a string because it has no way of guaranteeing that the
string is not embedded. Embedded strings are not safe for no GVL operations
because GC compaction can run, which will mprotect the memory region and
will cause any read to SEGV.

See https://github.com/ruby/ruby/pull/9817 for when rb_str_tmp_frozen_no_embed_acquire
was introduced.
2026-10-01 10:02:46 +09:00
Randy Stauner 323c1df196 [Bug #22387] Fix termlen in str_shared_replace
The buffer is copied over based on the new string's termlen
so we can just set the new encoding raw instead of recalculating
based on the old encoding's termlen.
2026-09-30 21:49:17 +01:00
Randy Stauner b58bea071d Fix buffer size accounting for rb_str_tmp_frozen roots
capa does not include the terminator, so when a buffer moves
between strings with different terminator lengths the capacity has to
be converted or we will try to free the buffer with the wrong size:

    [BUG] buffer 0x00005030039ff768 freed with old_size=18, but was allocated with size=17
    [BUG] buffer 0x00005631adc48f48 freed with old_size=8268, but was allocated with size=8269

Three related fixes:

* `rb_str_tmp_frozen_release`: convert tmp's capacity to orig's
  terminator length when handing the buffer back.  This is the inverse
  of a calculation added to `rb_str_tmp_frozen_no_embed_acquire` in
  91619f0230.

* `heap_str_make_shared`: since bdf3032e35
  the root created by `rb_str_tmp_frozen_acquire` does not copy the
  encoding of the string it takes the buffer from, so the two can have
  different terminator lengths and the root's capacity has to be
  adjusted as well, otherwise the root frees fewer bytes than were
  allocated once its only child stops sharing the buffer.  termlen is
  passed in because the caller assigns the encoding of the root after
  this function returns.

* `rb_str_tmp_frozen_no_embed_acquire`: unset `STR_BORROWED` on the
  root.  `STR_SET_SHARED` sets `STR_BORROWED` on roots with
  `klass == 0` to mark the ones that may have other children, but this
  root only ever has orig as its child, so unset it like
  `heap_str_make_shared` does.  Any string that starts sharing the
  root later will set the flag again.  Without this
  `rb_str_tmp_frozen_release` never gives the buffer back, so strings
  written by `io_fwrite` stay shared and are copied on their next
  modification.

The release and make_shared adjustments go together
as they were previously canceling each other out.
2026-09-26 21:24:18 +02:00
Randy Stauner 57213d44ce [Bug #22383] Fix inverted STR_SHARED check in rb_str_tmp_frozen_release
45a2c95d0f mistakenly rewrote

    FL_TEST_RAW(orig, STR_SHARED) && !FL_TEST_RAW(orig, STR_TMPLOCK|RUBY_FL_FREEZE)

as

    FL_TEST_RAW(orig, STR_SHARED | STR_TMPLOCK) == STR_TMPLOCK

requiring orig to not be shared, the opposite of the original
condition.  orig always shares the buffer with tmp here, so the buffer
was never given back and the string stayed shared until its next
modification copied it.  The code then read aux.shared from strings
that are not shared, where the union holds aux.capa.

This should be backported to 4.0
2026-09-25 11:03:48 -04:00
Peter Zhu 66c8e49a18 Unify STR_DUPLICATE_MAX_EMBED_LEN and STR_SUBSEQ_MAX_EMBED_SIZE 2026-08-07 19:58:21 -04:00
Peter Zhu 349071baf0 Fix definition of STR_DUPLICATE_MAX_EMBED_LEN in Test_RbStrDup 2026-08-07 13:03:19 -04:00
Peter Zhu eb9d72aea1 Max length for embedding duplicated strings
We should cap the max length for embedding duplicated strings because it
could be costly in performance and memory usage for very large embedded
strings. Instead, we can use a view into the parent string and perform
copy-on-write.
2026-07-26 14:55:18 -04:00
Jean Boussier 2c574ca7e2 Symbol#to_s now returns a frozen string.
[Feature #22137]

It has returned a chilled string, hence emitting deprecation
warnings for two versions.
2026-07-10 10:02:00 +02:00
Peter Zhu 36ced7351e Change test_capacity_embedded for dynamic slot size
If the slot size is dynamic, a string of length (max_embed_len - 1) will
have exact capacity rather than rounded up to max_embed_len.
2026-07-07 06:18:10 -04:00
Peter Zhu 86a6b79e5d Decouple Test_StrSetLen from slot size
Array#join now pre-calculates the length, so the string created in the
tests were embedded anyways.
2026-07-07 00:45:34 -04:00
Matt Valentine-House 208b173c25 Look up slot sizes for allocations in a table
Also remove BASE_SLOT_SIZE.
2026-03-09 15:09:53 +00:00
Nobuyoshi Nakada 78b7646bdb [Bug #21842] Let rb_interned_str return US-ASCII if possible 2026-01-17 14:19:15 +09:00
John HawthornandJean Boussier f483befd90 Add shape_id to RBasic under 32 bit
This makes `RBobject` `4B` larger on 32 bit systems
but simplifies the implementation a lot.

[Feature #21353]

Co-authored-by: Jean Boussier <byroot@ruby-lang.org>
2025-05-26 10:31:54 +02:00
Jean Boussier 83f57ca3d2 String.new(capacity:) don't substract termlen
[Bug #20585]

This was changed in 36a06efdd9 because
`String.new(1024)` would end up allocating `1025` bytes, but the problem
with this change is that the caller may be trying to right size a String.

So instead, we should just better document the behavior of `capacity:`.
2024-06-19 15:11:07 +02:00
tompng 04467218ce Add rb_str_resize coderange test 2024-06-13 18:27:02 +02:00
Jean Boussier 730e3b2ce0 Stop exposing rb_str_chilled_p
[Feature #20205]

Now that chilled strings no longer appear as frozen, there is no
need to offer an API to check for chilled strings.

We however need to change `rb_check_frozen_internal` to no
longer be a macro, as it needs to check for chilled strings.
2024-06-02 13:53:35 +02:00
Étienne BarriéandJean Boussier 2b08406cd0 Expose rb_str_chilled_p
Some extensions (like stringio) may need to differentiate between
chilled strings and frozen strings.

They can now use rb_str_chilled_p but must check for its presence since
the function will be removed when chilled strings are removed.

[Bug #20389]

[Feature #20205]

Co-authored-by: Jean Boussier <byroot@ruby-lang.org>
2024-03-26 12:54:54 +01:00
Thomas Marshall 7e4b1f8e19 [Bug #20322] Fix rb_enc_interned_str_cstr null encoding
The documentation for `rb_enc_interned_str_cstr` notes that `enc` can be
a null pointer, but this currently causes a segmentation fault when
trying to autoload the encoding. This commit fixes the issue by checking
for NULL before calling `rb_enc_autoload`.
2024-03-03 10:43:35 +00:00
Hiroshi SHIBATA 1d972498eb Use Encoding::CESU_8 for test case
Encoding::Windows_31J is already loaded in mswin platform
2024-01-25 16:06:06 +09:00
Nobuyoshi Nakada 1910bd4247 String for string literal is not resizable 2023-11-08 00:59:45 +09:00
Jean Boussier ac8ec004e5 Make String.new size pools aware.
If the required capacity would fit in an embded string,
returns one.

This can reduce malloc churn for code that use string buffers.
2023-11-02 23:34:58 +01:00
Nobuyoshi Nakada 6b66b5fded [Bug #19902] Update the coderange regarding the changed region 2023-09-26 15:35:40 +09:00
Peter Zhu 4b6c584023 Remove --disable-gems for assert_separately
assert_separately adds --disable=gems so we don't need to add
--disable-gems when calling assert_separately.
2023-08-03 09:11:08 +09:00
Peter Zhu 7577c101ed Unify length field for embedded and heap strings (#7908)
* Unify length field for embedded and heap strings

The length field is of the same type and position in RString for both
embedded and heap allocated strings, so we can unify it.

* Remove RSTRING_EMBED_LEN
2023-06-06 10:19:20 -04:00
Peter Zhu 1da2e7fca3 [Feature #19579] Remove !USE_RVARGC code (#7655)
Remove !USE_RVARGC code

[Feature #19579]

The Variable Width Allocation feature was turned on by default in Ruby
3.2. Since then, we haven't received bug reports or backports to the
non-Variable Width Allocation code paths, so we assume that nobody is
using it. We also don't plan on maintaining the non-Variable Width
Allocation code, so we are going to remove it.
2023-04-04 17:30:06 -04:00
Benoit Daloze 6abe20e87b Remove Encoding#replicate 2023-01-11 13:41:41 +01:00
Jemma IssroffandAaron Patterson 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
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 018036c282 Remove assert_equal that will never be run
`@s1.set_len(3)` will raise so the `assert_equal` will never be ran.
2022-01-28 13:33:03 -05:00
Peter Zhu 2d81a718ec Make embedded string length a long for VWA
A short (2 bytes) will cause unaligned struct accesses when strings are
used as a buffer to directly store binary data.
2022-01-12 12:00:55 -05:00
Nobuyoshi Nakada 39bc5de833 Remove tainted and trusted features
Already these had been announced to be removed in 3.2.
2021-12-26 23:28:54 +09:00
Peter Zhu a5b6598192 [Feature #18239] Implement VWA for strings
This commit adds support for embedded strings with variable capacity and
uses Variable Width Allocation to allocate strings.
2021-10-25 13:26:23 -04:00
Nobuyoshi Nakada 391abc543c Scan the coderange in the given encoding 2021-06-26 16:05:15 +09:00
Jean Boussier 7e8a9af9db rb_enc_interned_str: handle autoloaded encodings
If called with an autoloaded encoding that was not yet
initialized, `rb_enc_interned_str` would crash with
a NULL pointer exception.

See: https://github.com/ruby/ruby/pull/4119#issuecomment-800189841
2021-03-22 21:37:48 +09:00
Jean Boussier 6bef49427a Fix rb_interned_str_* functions to not assume static strings
Fixes [Feature #13381]

When passed a `fake_str`, `register_fstring` would create new strings
with `str_new_static`. That's not what was expected, and answer
almost no use cases.
2020-11-30 17:33:28 +09:00
Jeremy Evans 58325daae3 Make String methods return String instances when called on a subclass instance
This modifies the following String methods to return String instances
instead of subclass instances:

* String#*
* String#capitalize
* String#center
* String#chomp
* String#chop
* String#delete
* String#delete_prefix
* String#delete_suffix
* String#downcase
* String#dump
* String#each/#each_line
* String#gsub
* String#ljust
* String#lstrip
* String#partition
* String#reverse
* String#rjust
* String#rpartition
* String#rstrip
* String#scrub
* String#slice!
* String#slice/#[]
* String#split
* String#squeeze
* String#strip
* String#sub
* String#succ/#next
* String#swapcase
* String#tr
* String#tr_s
* String#upcase

This also fixes a bug in String#swapcase where it would return the
receiver instead of a copy of the receiver if the receiver was the
empty string.

Some string methods were left to return subclass instances:

* String#+@
* String#-@

Both of these methods will return the receiver (subclass instance)
in some cases, so it is best to keep the returned class consistent.

Fixes [#10845]
2020-11-20 16:30:23 -08:00
Nobuyoshi Nakada daa04c5562 Word array instead of splitting 2020-03-08 17:39:22 +09:00
Yusuke Endoh 0c0278b90a test/-ext-/string/test_fstring.rb: suppress a warning for taint 2019-11-18 09:25:49 -06:00
Jeremy Evans ffd0820ab3 Deprecate taint/trust and related methods, and make the methods no-ops
This removes the related tests, and puts the related specs behind
version guards.  This affects all code in lib, including some
libraries that may want to support older versions of Ruby.
2019-11-18 01:00:25 +02:00
NARUSE, Yui bea322a352 Revert "[EXPERIMENTAL] Make Symbol#to_s return a frozen String [Feature #16150]"
This reverts commit 6ffc045a81.
2019-11-05 17:30:54 +09:00
卜部昌平 11b6ff12af more use of RbConfig::LIMITS
`8 * RbConfig::SIZEOF` ... is not straight.
2019-10-08 11:21:20 +09:00
Yusuke Endoh fc66947c61 test/-ext-/string/test_fstring.rb: suppress "possibly useless use of -@"
"in void context" by assigning the result to a dummy variable.
2019-09-30 20:22:29 +09:00
Benoit Daloze 6ffc045a81 [EXPERIMENTAL] Make Symbol#to_s return a frozen String
* Always the same frozen String for a given Symbol.
* Avoids extra allocations whenever calling Symbol#to_s.
* See [Feature #16150]
2019-09-26 10:23:02 +02:00
Alan Wu 93faa011d3 Tag string shared roots to fix use-after-free
The buffer deduplication codepath in rb_fstring can be used to free the buffer
of shared string roots, which leads to use-after-free.

Introudce a new flag to tag strings that at one point have been a shared root.
Check for it in rb_fstring to avoid freeing buffers that are shared by
multiple strings. This change is based on nobu's idea in [ruby-core:94838].

The included test case test for the sequence of calls to internal functions
that lead to this bug. See attached ticket for Ruby level repros.

[Bug #16151]
2019-09-26 15:30:18 +09:00
John Hawthorn 04bc4c0662 Resize capacity for fstring
When a string is #frozen, it's capacity is resized to fit (if it is much
larger), since we know it will no longer be mutated.

    > puts ObjectSpace.dump(String.new("a"*30, capacity: 1000))
    {"type":"STRING", "class":"0x7feaf00b7bf0", "bytesize":30, "capacity":1000, "value":"...
    > puts ObjectSpace.dump(String.new("a"*30, capacity: 1000).freeze)
    {"type":"STRING", "class":"0x7feaf00b7bf0", "frozen":true, "bytesize":30, "value":"...

(ObjectSpace.dump doesn't show capacity if capacity is equal to bytesize)

Previously, if we dedup into an fstring, using String#-@, capacity would
not be reduced.

    > puts ObjectSpace.dump(-String.new("a"*30, capacity: 1000))
    {"type":"STRING", "class":"0x7feaf00b7bf0", "frozen":true, "fstring":true, "bytesize":30, "capacity":1000, "value":"...

This commit makes rb_fstring call rb_str_resize, the same as
rb_str_freeze does.

Closes: https://github.com/ruby/ruby/pull/2256
2019-06-26 15:01:48 +09:00
Nobuyoshi Nakada 3840791b7e Get rid of error with frozen string literal
[Bug #14194]
2019-06-23 07:56:43 +09:00
Alan Wu c06ddfee87 str_duplicate: Don't share with a frozen shared string
This is a follow up for 3f9562015e.
Before this commit, it was possible to create a shared string which
shares with another shared string by passing a frozen shared string
to `str_duplicate`.

Such string looks like:

```
 --------                    -----------------
 | root | ------ owns -----> | root's buffer |
 --------                    -----------------
     ^                             ^   ^
 -----------                       |   |
 | shared1 | ------ references -----   |
 -----------                           |
     ^                                 |
 -----------                           |
 | shared2 | ------ references ---------
 -----------
```

This is bad news because `rb_fstring(shared2)` can make `shared1`
independent, which severs the reference from `shared1` to `root`:

```c
/* from fstr_update_callback() */
str = str_new_frozen(rb_cString, shared2);  /* can return shared1 */
if (STR_SHARED_P(str)) { /* shared1 is also a shared string */
    str_make_independent(str);  /* no frozen check */
}
```

If `shared1` was the only reference to `root`, then `root` can be
reclaimed by the GC, leaving `shared2` in a corrupted state:

```
 -----------                         --------------------
 | shared1 | -------- owns --------> | shared1's buffer |
 -----------                         --------------------
      ^
      |
 -----------                         -------------------------
 | shared2 | ------ references ----> | root's buffer (freed) |
 -----------                         -------------------------
```

Here is a reproduction script for the situation this commit fixes.

```ruby
a = ('a' * 24).strip.freeze.strip
-a
p a
4.times { GC.start }
p a
```

 - string.c (str_duplicate): always share with the root string when
   the original is a shared string.
 - test_rb_str_dup.rb: specifically test `rb_str_dup` to make
   sure it does not try to share with a shared string.

[Bug #15792]

Closes: https://github.com/ruby/ruby/pull/2159
2019-05-09 10:04:19 +09:00
shyouhei b57915eddc Add FrozenError as a subclass of RuntimeError
FrozenError will be used instead of RuntimeError for exceptions
raised when there is an attempt to modify a frozen object. The
reason for this change is to differentiate exceptions related
to frozen objects from generic exceptions such as those generated
by Kernel#raise without an exception class.

From: Jeremy Evans <code@jeremyevans.net>
Signed-off-by: Urabe Shyouhei <shyouhei@ruby-lang.org>


git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@61131 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2017-12-12 00:46:34 +00:00
naruse 7a96d788dc Add test for Bug::String.buf_new
git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60993 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
2017-12-03 12:06:16 +00:00