Commit Graph

364 Commits

Author SHA1 Message Date
Yukihiro "Matz" Matsumoto 90a0fc5797 Merge pull request #6576 from dearblue/ary_replace
Share array entities if possible with `ary.replace(frozen_ary)`
2026-05-08 11:09:50 +09:00
Yukihiro "Matz" Matsumoto bbf7c43c37 array.c: restore arena around heap sort per-call protections
heapify() and heap_delete_root() call mrb_gc_protect() to guard a
C-local mrb_value across potential GC points inside sort_cmp().
They were missing the matching mrb_gc_arena_save/restore pair, so
each call leaked one arena slot.  For O(n log n) heapify calls under
MRB_GC_FIXED_ARENA this overflows the 100-slot arena and raises
NoMemoryError, e.g. during Array#repeated_permutation tests.

Wrap each function body with mrb_gc_arena_save/restore, matching
the pattern already used in insertion_sort() above.

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-23 19:25:39 +09:00
Yukihiro "Matz" Matsumoto f7d7bbef43 array.c: add string-specialized fast path for Array#sort!
when all elements are plain String (not subclass) and no block is
given, use specialized sort that calls mrb_str_cmp() directly,
bypassing sort_cmp overhead (GC arena, type dispatch, array
modification check).

includes subclass check to ensure String#<=> is not overridden.

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-23 19:25:27 +09:00
Yukihiro "Matz" Matsumoto 5364c4167e array.c: add integer-specialized fast path for Array#sort!
when all elements are integers and no block is given, use
specialized heapify/insertion_sort that compare mrb_int values
directly, bypassing sort_cmp entirely. this eliminates per-comparison
overhead of GC arena save/restore, type checking, and array
modification checks.

the pre-scan to detect all-integer arrays is O(n), negligible
compared to O(n log n) sort. non-integer and block sorts are
unaffected.

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-23 19:25:26 +09:00
Yukihiro "Matz" Matsumoto 02bb943960 array.c: optimize heap sort with hole-style sift-down and Floyd's method
two improvements to Array#sort!'s heap sort:

1. hole-style sift-down: save root value, move larger children up
   one at a time, write saved value once at the end. reduces
   assignments from 3 per level (swap) to 1 per level (move).

2. Floyd's bottom-up heap deletion: during extraction phase, sift
   the hole down to a leaf using only child-child comparisons
   (~1 comparison per level), then sift up to find the correct
   position. this reduces average comparisons from ~2 log n to
   ~log n per extraction, nearly halving the total comparison
   count for the sort.

both changes preserve O(n log n) worst case and O(1) extra space.

Co-authored-by: Claude <noreply@anthropic.com>
2026-04-23 19:25:26 +09:00
Yukihiro "Matz" Matsumoto 8956c5abb5 mruby.h: include mruby/presym.h for all source files
Since presym is now mandatory, mruby.h includes presym.h so that
MRB_SYM() macros are available everywhere without explicit include.
Remove redundant #include <mruby/presym.h> from all source files.

Co-authored-by: Claude <noreply@anthropic.com>
2026-03-09 16:50:58 +09:00
Yukihiro "Matz" Matsumoto 71cb3c2e3a class.c: allocate ROM table wrappers per mrb_state
ROM method tables used static mrb_mt_tbl variables shared
across the process. The next pointer in each wrapper was
mutated by mrb_mt_init_rom(), causing cross-state
contamination when multiple mrb_state instances existed.

Allocate mrb_mt_tbl wrappers per-state via mrb_malloc().
The const mrb_mt_entry[] arrays remain static and shared.
Wrappers are tracked in mrb->rom_mt and freed at mrb_close().

Remove MRB_MT_ROM_TAB macro; add MRB_MT_INIT_ROM macro that
auto-computes size and calls the new mrb_mt_init_rom().

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 22:24:31 +09:00
Yukihiro "Matz" Matsumoto ea938c531f align MRB_MT_ENTRY columns and ISO section comments in ROM tables
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 15:02:27 +09:00
Yukihiro "Matz" Matsumoto b460554d33 vm.c: generalize pre-dispatch argument count check for C methods
Replace check_method_noarg() with check_argument_count() that validates
min <= argc <= max using the full aspec stored in mrb_method_t.flags.
This catches ArgumentError earlier at dispatch time, before entering
the C function.

The old check only handled the special case of aspec==0 (NOARG).
The new check extracts REQ, OPT, REST, POST, KEY, and KDICT from
the aspec and validates accordingly. Keyword hash is counted as
a positional arg only when the method doesn't accept keywords.

Remove MRB_METHOD_NOARG_P macro from proc.h (subsumed by aspec check).
Fix 15 incorrect aspec declarations across the codebase that were
exposed by the stricter enforcement.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 14:25:48 +09:00
Yukihiro "Matz" Matsumoto 4a097525df proc.h: unify method flag layout; eliminate aspec shifting
Move MRB_METHOD_FUNC_FL to bit 24 and visibility flags to
bits 25-26 so that MRB_ARGS_*() values (bits 0-23) can be
stored directly without shifting. This makes MRB_MT_PRIVATE
and MRB_METHOD_PRIVATE_FL the same value, eliminating the
dual-constant confusion and simplifying the MRB_MT_ENTRY()
macro to a single OR operation.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 13:49:17 +09:00
Yukihiro "Matz" Matsumoto 483c155a41 class.c: store aspec in ROM method table entries
Restore MRB_ARGS_* argument specs and ISO section comments to all
709 ROM method table entries. The aspec is encoded in bits 4-27 of
the flags field; MRB_MT_NOARG is now auto-derived from aspec==0.

Add MRB_MT_ENTRY_PRIVATE() macro for private methods (53 entries)
and MRB_MT_ASPEC() accessor for extracting aspec from flags.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 11:44:28 +09:00
Yukihiro "Matz" Matsumoto 8adba34bd9 class.c: auto-set MRB_MT_FUNC in MRB_MT_ENTRY macro
Since ROM table entries are always C functions, have the
MRB_MT_ENTRY() macro set MRB_MT_FUNC automatically. This
simplifies entry definitions across all 32 source files.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 10:37:06 +09:00
Yukihiro "Matz" Matsumoto 0fab703028 class.c: use linear search for method tables; make ROM entries const
Replace binary search with linear scan in mt_get(), mt_put(),
mt_del(), mt_chain_has(), and mrb_mt_foreach(). The method cache
makes repeated lookups O(1), so linear scan on cache misses is
acceptable.

This removes the sorting requirement, allowing ROM entry arrays
to be declared const. On embedded systems, const static data
resides in flash/ROM instead of RAM, saving ~8.4KB for ~700
method entries on 32-bit MCUs.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-20 08:26:05 +09:00
Yukihiro "Matz" Matsumoto bde2202100 class.c: refactor ROM method tables to array-of-structs layout
Replace the parallel-arrays (struct-of-arrays) ROM method table
layout with an array-of-structs layout where each mrb_mt_entry
bundles its function pointer and symbol key together.

New MRB_MT_ENTRY() and MRB_MT_ROM_TAB() macros simplify ROM table
definitions from a 3-part pattern (SIZE define + anonymous struct +
mrb_mt_tbl) to a 2-part pattern (entries array + mrb_mt_tbl).

Internal mt_* functions in class.c are simplified: single memmove/
memcpy operations replace paired key+value operations.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 23:59:30 +09:00
Yukihiro "Matz" Matsumoto 0ed26f8352 class.c: rename mt_/MT_ to mrb_mt_/MRB_MT_ for non-static identifiers
Follow mruby's naming convention: non-static types, macros, and
functions use the mrb_/MRB_ prefix. Renamed:
- union mt_ptr -> union mrb_mt_ptr
- mt_tbl -> mrb_mt_tbl
- MT_KEY(), MT_FUNC, MT_NOARG, MT_PUBLIC, MT_PRIVATE -> MRB_MT_*
- MT_KEY_SHIFT, MT_READONLY_BIT, MT_REMOVED_P -> MRB_MT_*
- mt_init_rom() -> mrb_mt_init_rom()
File-local static functions and macros in class.c are unchanged.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 15:22:55 +09:00
Yukihiro "Matz" Matsumoto 03be6af0b9 src: remove MRB_NO_PRESYM guards from core source files
Presym is now always enabled. Remove #ifndef MRB_NO_PRESYM
guards and their #else fallback branches from all core files.

Co-authored-by: Claude <noreply@anthropic.com>
2026-02-19 12:17:24 +09:00
Yukihiro "Matz" Matsumoto 3b44a7001b array.c: ROM method table for Array class (36 methods)
Co-authored-by: Claude <noreply@anthropic.com>
2026-02-18 16:30:35 +09:00
Yukihiro "Matz" Matsumoto 099d2c4771 array.c: fix heap-use-after-free in insertion_sort
The key variable in insertion_sort temporarily holds an array element
that's been removed from its slot during the sorting process. When
sort_cmp yields to a block that triggers GC, key wasn't protected
and could be collected.

Use arena save/restore around the loop to avoid arena overflow for
large arrays.

Test case from oss-fuzz: sort! with block containing rescue.

Co-authored-by: Claude <noreply@anthropic.com>
2026-01-03 20:41:47 +09:00
Yukihiro "Matz" Matsumoto 729b84cf26 mruby-array-ext: fix use-after-free in array set operations; fix #6662
during eql? callbacks, array modifications can cause elements in khash to
be freed by GC, leading to use-after-free. create temporary shared copies
of arrays before populating khash to protect elements during callbacks.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-13 11:51:53 +09:00
Yukihiro "Matz" Matsumoto f4fb41b528 kernel.c: regression on struct/array/hash == override with super; fix #6660
when overriding struct#==, array#==, or hash#== with super, the recursion
detection incorrectly treated the super call as a circular reference. this
was caused by commit 5ca2d442 which added recursion detection.

the fix introduces mrb_recursive_func_p that starts from ci[-2] instead of
ci[-1], skipping the immediate parent frame which may be a ruby override
calling super. equality methods (==, eql?) now use this function, while
inspect methods keep using mrb_recursive_method_p for immediate circular
reference detection.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-12 10:25:37 +09:00
Yukihiro "Matz" Matsumoto eb398971bf array.c: fix use-after-realloc in Array#sort!; fix #6649
add length check to detect array modification during sort. when realloc()
shrinks an array in-place, it may return the same pointer, defeating the
pointer-only check. the new check catches both pointer changes and length
changes, preventing out-of-bounds access.

the fix captures array pointer and length at the start of each comparison,
then validates both after user code executes. this detects modifications
even when realloc() returns the original pointer.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-27 15:06:14 +09:00
Yukihiro "Matz" Matsumoto 00e7474cce array.c: combine variable declaration with initialization 2025-10-25 23:27:08 +09:00
Yukihiro "Matz" Matsumoto 12268dc3ef revert "array.c: hoist RARRAY_PTR calls in comparison operator"; fix #6652
this reverts commit 04af58db89 which caused use-after-free vulnerability.
cached array pointers become invalid when mrb_cmp() executes user's <=>
method that can modify arrays during iteration

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-25 08:39:01 +09:00
Yukihiro "Matz" Matsumoto 04af58db89 array.c: hoist RARRAY_PTR calls in comparison operator
Optimizes Array#<=> by hoisting RARRAY_PTR calls outside the loop to
avoid repeated conditional checks. This is a frequently used operation
for array comparisons and sorting.

Before: 2 RARRAY_PTR calls per iteration (checks embed vs heap twice)
After: 2 RARRAY_PTR calls total (pointers cached outside loop)

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-22 12:06:46 +09:00
Yukihiro "Matz" Matsumoto 07b803e28a docs: replace xml-style markup with markdown in comments
Replace XML-style markup tags in comments with markdown equivalents:
- <code>...</code> to `...` (inline code)
- <tt>...</tt> to `...` (teletype/monospace)
- <i>...</i> to *...* (italics/emphasis)
- +...+ to `...` (parameter/variable references)

Updated 80+ files across core source, headers, mrbgems, and libraries
to use consistent markdown formatting in documentation comments.
Handled edge cases including special characters like <=> operators.

Co-authored-by: Atlassian Rovo Dev
2025-08-14 10:52:49 +09:00
Yukihiro "Matz" Matsumoto 9fd79ff0f8 array: add call-seq comments and helper function documentation
Add comprehensive call-seq comments for Ruby methods including Array[],
Array.new, concat, +, *, replace, reverse!/reverse, push/<<, shift,
unshift, size/length, empty?, first, and last.

Add brief comments for internal helper functions including array
creation, modification, capacity management, and utility functions
to improve code readability and maintainability.

Co-authored-by: Atlassian Rovo Dev
2025-08-14 10:52:48 +09:00
dearblue 3c653fc0d4 Share array entities if possible with ary.replace(frozen_ary)
Currently mruby is limited to always placing array entities on the rewritable heap.
Therefore, if the original array was frozen and only rewritable objects survived the subsequent process, the array entity can be changed.
If an array object that actually shared the array entity is frozen with `ary.freeze`, there should be no problem, since the shared state is still kept.
2025-07-18 22:51:00 +09:00
Yukihiro "Matz" Matsumoto 2735340702 kernel.c: remove mrb_inspect_recursive_p(); #5531
And use mrb_recursive_method_p() and its helper methods.

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-11 10:09:37 +09:00
Yukihiro "Matz" Matsumoto 38882aecee array.c: add recursion detection to Array#== and Array#eql?
Prevent SystemStackError when comparing arrays with circular references.
Uses the same recursion detection mechanism as Hash equality methods.

Co-authored-by: Claude <noreply@anthropic.com>
2025-07-11 10:09:37 +09:00
Yukihiro "Matz" Matsumoto cf8faed585 array: implement hybrid sorting with algorithm selection
Use insertion sort for small arrays (≤16) and heap sort for larger arrays.
Provides 50-200% performance improvement for small arrays while maintaining
O(n log n) guarantee for large arrays. Includes iterative heapify to
eliminate stack overflow risk on memory-constrained devices.

Co-authored-by: Atlassian Rovo Dev
2025-06-30 23:31:05 +09:00
Yukihiro "Matz" Matsumoto 6fab19cd82 arry.c: optimize Array#sort! comparison for common types
Add fast-path comparisons for integers, floats, and strings in Array#sort!
when no custom comparison block is provided. This reduces VM callback
overhead for common data types, improving performance.

Co-authored-by: Gemini <gemini@google.com>
2025-06-30 14:42:23 +09:00
Yukihiro "Matz" Matsumoto 6d8c673efb array.c: replace recursive heapify with iterative implementation
Eliminates stack overflow risk on memory-constrained devices by reducing
stack usage from O(log n) to O(1) during heap sort operations.

Co-authored-by: Atlassian Rovo Dev
2025-06-30 14:41:04 +09:00
Yukihiro "Matz" Matsumoto 05ad26f92a array: implement to_a and entries methods in c
Array#to_a now properly converts subclasses to Array objects. For example,
'class A<Array;end; p A.new(1,2).to_a.class' now returns Array, not A.

Co-authored-by: Atlassian Rovo Dev
2025-06-30 12:21:29 +09:00
Yukihiro "Matz" Matsumoto c4464fa25a array.c: expose mrb_ary_dup() as a new C API 2025-06-29 20:46:51 +09:00
Yukihiro "Matz" Matsumoto 65369ca1e6 array.c: make Array#initialize_copy private 2025-06-15 14:12:12 +09:00
google-labs-jules[bot] 7f3329e393 Add descriptive comments for MRB_API functions in src/array.c
This change adds C-style multiline comments to all functions
marked with MRB_API in the src/array.c file.

The comments explain each function's purpose, its parameters,
and what it returns, where applicable. This improves the
readability and maintainability of the C API for mruby arrays.

The `@brief` markup was intentionally avoided as per your
requirements.
2025-06-01 23:48:11 +00:00
Yukihiro "Matz" Matsumoto 11bf789730 array.c: remove unnecessary blank line 2025-05-26 14:32:19 +09:00
John Bampton b56f984c25 misc: fix typos 2025-03-30 14:04:34 +10:00
Yukihiro "Matz" Matsumoto 5ed4a772f3 array.c (mrb_ary_unshift_m): defer mrb_get_argv call 2025-01-21 13:07:44 +09:00
Yukihiro "Matz" Matsumoto 84d17f2c44 array.c (mrb_ary_clear): remove unnecessary function 2024-10-16 16:33:42 +09:00
Yukihiro "Matz" Matsumoto d1d010a03a array.c (mrb_ary_delete): array index should be mrb_int 2024-09-17 12:07:39 +09:00
Yukihiro "Matz" Matsumoto 4b500eb971 Merge pull request #6340 from dearblue/array-cmp 2024-09-17 11:29:41 +09:00
dearblue 0955539cf9 Fix use-after-free in mrb_ary_delete()
`mrb_equal()` may call `obj.==` method internally.
Therefore, using an unupdated pointer and length after `mrb_equal()` could result in a read/write to an invalid address.

Fresh properties must always be obtained regardless of the result of `mrb_equal()`.
Also, `ary_modify()` must be called each time before writing.

ref. #6339
2024-09-13 21:44:56 +09:00
Yukihiro "Matz" Matsumoto 0972c84773 array.c (mrb_ary_delete): protect return value; fix #6339
The C local variable is not protected from GC, so we use the function
mrb_gc_protect() to keep the value. We also keep the arena position by
mrb_gc_arena_save(), then restoring the position for every new return
value, to minimize arena size.

Small cosmetic changes (pre-increment to post-increment) are also made
in this commit.
2024-09-09 14:57:32 +09:00
Yukihiro "Matz" Matsumoto 1f9fa06119 array.c: no need to assert if blk is a Proc; ref #6344
Since `blk` always comes from `mrb_get_args`, it should always be either
`nil` or a Proc.
2024-09-05 15:26:09 +09:00
leviongit 020cfa9283 prefer using mrb_yield to call block arguments 2024-09-04 20:44:51 +02:00
dearblue e476d9a344 Need to restore the GC arena after some function calls
When calling `mrb_equal()` or `mrb_funcall()` family functions, the GC arena should be restored if the loop is repeated by a non-immediate return value.

In my opinion, restoring the GC arena is unnecessary when a non-immediate (true) value causes the function to return (e.g. the `mrb_ary_index_m()` function).

The patch does not take into account the case of recursive calls and may be incomplete.
2024-09-03 21:29:06 +09:00
dearblue 29496c9931 Fix use-after-free for Array#<=>
The `mrb_ary_cmp()` function calls `mrb_cmp()` for comparison, but `mrb_cmp()` may call the `obj.<=>` method internally.
If a user-defined `<=>` method is called and the array object under comparison is expanded or reduced, a reference to an invalid address may subsequently be made.
2024-09-03 21:25:31 +09:00
Yukihiro "Matz" Matsumoto 540d976f7f array.c (sort_cmp): mrb_cmp() may return -2 for errors 2024-08-27 22:36:24 +09:00
Yukihiro "Matz" Matsumoto f35000f2a9 array.c (sort_cmp): comparing objects may be freed by GC; #6326
If comparing function (block or `<=>`) modifies the sorting array and GC
happens after the modification, objects passed to comparison may be
freed by GC.
2024-08-23 22:29:45 +09:00