Skip to content

mruby-string-ext: fix String#prepend with self-referencing arguments#6780

Merged
matz merged 1 commit into
masterfrom
fix/string-prepend-overflow
Apr 11, 2026
Merged

mruby-string-ext: fix String#prepend with self-referencing arguments#6780
matz merged 1 commit into
masterfrom
fix/string-prepend-overflow

Conversation

@matz
Copy link
Copy Markdown
Member

@matz matz commented Apr 10, 2026

Summary

String#prepend(s, s) read RSTRING_LEN(argv[i]) in the copy loop after mrb_str_resize had already updated the receiver's length, causing memcpy to write past the allocated buffer. Introduced in 2cd8eb386, only on master/stable (not yet released).

Detect self-references with mrb_obj_eq() and read from the memmoved original data at p + total_prepend_len using the captured self_len. This also handles mixed cases like s.prepend("X", s) where earlier writes would otherwise corrupt the source of later reads.

Test plan

  • rake CONFIG=host-debug all test:run:serial — 1809 lib + 100 bintest OK
  • Regression tests added for s.prepend(s, s), s.prepend("XYZ", s), and s.prepend(s, "X", s)

String#prepend(s, s) read RSTRING_LEN(argv[i]) in the copy loop after
mrb_str_resize had already updated the receiver's length, causing the
memcpy to write past the allocated buffer.

Detect self-references with mrb_obj_eq() and read from the memmoved
original data at p + total_prepend_len using the captured self_len.
This also handles mixed cases like s.prepend("X", s) where earlier
writes would otherwise corrupt the source of later reads.

Co-authored-by: Claude <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request fixes a bug in String#prepend where self-referencing arguments (e.g., s.prepend(s)) could lead to incorrect data being copied because the original string's content was being overwritten during the prepend operation. The fix ensures that if an argument is the string itself, the source pointer is adjusted to the new location of the original data. New test cases have been added to verify this behavior. I have no feedback to provide.

@matz matz merged commit 18ba026 into master Apr 11, 2026
32 checks passed
@matz matz deleted the fix/string-prepend-overflow branch April 11, 2026 07:32
matz added a commit that referenced this pull request Apr 12, 2026
Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant