Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 15 additions & 3 deletions mrbgems/mruby-string-ext/src/string.c
Original file line number Diff line number Diff line change
Expand Up @@ -2201,15 +2201,27 @@ str_prepend(mrb_state *mrb, mrb_value self)

char *p = RSTRING_PTR(self);

/* Move original content to the end */
/* Move original content to the end. The original self data now lives
at p + total_prepend_len, which we use as the source for any
self-referencing arguments (e.g., s.prepend(s, s)) to avoid reading
data that has already been overwritten by earlier copies. */
memmove(p + total_prepend_len, p, self_len);

/* Copy prepended strings in order */
mrb_int offset = 0;
for (mrb_int i = 0; i < argc; i++) {
mrb_int arg_len = RSTRING_LEN(argv[i]);
const char *src;
mrb_int arg_len;
if (mrb_obj_eq(mrb, self, argv[i])) {
src = p + total_prepend_len;
arg_len = self_len;
}
else {
src = RSTRING_PTR(argv[i]);
arg_len = RSTRING_LEN(argv[i]);
}
if (arg_len > 0) {
memcpy(p + offset, RSTRING_PTR(argv[i]), arg_len);
memcpy(p + offset, src, arg_len);
offset += arg_len;
}
}
Expand Down
15 changes: 15 additions & 0 deletions mrbgems/mruby-string-ext/test/string.rb
Original file line number Diff line number Diff line change
Expand Up @@ -492,6 +492,21 @@ def assert_upto(exp, receiver, *args)
g = "world"
assert_equal "hello world", g.prepend("", "hello ", "")
assert_equal "hello world", g

# Self-referencing arguments (GHSA-3hgj-g76g-878c)
h = "A" * 100
h.prepend(h, h)
assert_equal 300, h.length
assert_equal "A" * 300, h

# Mixed self-reference and literal
i = "AB"
i.prepend("XYZ", i)
assert_equal "XYZABAB", i

j = "AB"
j.prepend(j, "X", j)
assert_equal "ABXABAB", j
end

assert('String#ljust') do
Expand Down
Loading