Skip to content
Merged
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
16 changes: 13 additions & 3 deletions mrbgems/mruby-io/src/io.c
Original file line number Diff line number Diff line change
Expand Up @@ -992,10 +992,20 @@ io_puts_str(mrb_state *mrb, int fd, mrb_value str)
}
}

/* Maximum nesting depth for puts with arrays; guards against cyclic and
pathologically deep arrays causing C stack overflow. */
#define IO_PUTS_MAX_DEPTH 16

/* Recursive helper for puts with arrays */
static void
io_puts_ary(mrb_state *mrb, int fd, mrb_value ary)
io_puts_ary(mrb_state *mrb, int fd, mrb_value ary, int depth)
{
if (depth >= IO_PUTS_MAX_DEPTH) {
mrb_value mark = mrb_str_new_lit(mrb, "[...]\n");
fd_write(mrb, fd, mark);
return;
}
Comment on lines +1003 to +1007

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

medium

When allocating temporary Ruby objects (like mark via mrb_str_new_lit) inside a recursive or loop-heavy C function, it is highly recommended to manage the GC arena using mrb_gc_arena_save and mrb_gc_arena_restore.

If a large array contains many cyclic or deeply nested arrays, this function will be called repeatedly, leading to many string allocations. Without restoring the arena, this can easily exceed the default GC arena limit (usually 100) and cause an arena overflow or excessive memory consumption.

Wrapping the allocation and write in an arena save/restore block prevents this accumulation.

  if (depth >= IO_PUTS_MAX_DEPTH) {
    int ai = mrb_gc_arena_save(mrb);
    mrb_value mark = mrb_str_new_lit(mrb, "[...]\n");
    fd_write(mrb, fd, mark);
    mrb_gc_arena_restore(mrb, ai);
    return;
  }


mrb_int len = RARRAY_LEN(ary);

if (len == 0) {
Expand All @@ -1008,7 +1018,7 @@ io_puts_ary(mrb_state *mrb, int fd, mrb_value ary)
for (mrb_int i = 0; i < len; i++) {
mrb_value elem = RARRAY_PTR(ary)[i];
if (mrb_array_p(elem)) {
io_puts_ary(mrb, fd, elem); /* Recursive call for nested arrays */
io_puts_ary(mrb, fd, elem, depth + 1);
}
else {
io_puts_str(mrb, fd, elem);
Expand Down Expand Up @@ -1040,7 +1050,7 @@ io_puts(mrb_state *mrb, mrb_value io)
for (mrb_int i = 0; i < argc; i++) {
mrb_value arg = argv[i];
if (mrb_array_p(arg)) {
io_puts_ary(mrb, fd, arg);
io_puts_ary(mrb, fd, arg, 0);
}
else {
io_puts_str(mrb, fd, arg);
Expand Down