Commit Graph

6271 Commits

Author SHA1 Message Date
Yukihiro "Matz" Matsumoto 8a29ab591e vm.c: use mrb_obj_ptr()->c for faster class check in GETIDX/SETIDX
Replace mrb_obj_class() with direct mrb_obj_ptr(va)->c access:

- Skips unnecessary mrb_immediate_p() check (these types are never immediate)
- Skips mrb_class_real() traversal for singleton classes
- Objects with singleton methods now fall back to method dispatch
  (correct behavior since they might have overridden []/[]=)

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-25 18:01:44 +09:00
Yukihiro "Matz" Matsumoto 115438aa1e vm.c: optimize OP_SETIDX for Array and Hash; ref #6675
Add inline optimizations for Array#[]= and Hash#[]= in OP_SETIDX,
matching the pattern established for OP_GETIDX:

- Array class: use mrb_ary_set() directly (integer index only)
- Hash class: use mrb_hash_set() directly
- Subclasses: fall back to method dispatch (can override []=)
- String: unchanged (complex 2-3 argument signature)

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-25 18:01:44 +09:00
Yukihiro "Matz" Matsumoto 5102ef8022 vm.c: allow String subclasses to override []; ref #6675
Apply the same pattern as the Array/Hash fix: the OP_GETIDX optimization
now only applies to instances of the String class itself. Subclasses
fall back to method dispatch, allowing them to override the [] method.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-25 18:01:44 +09:00
Yukihiro "Matz" Matsumoto d65fb765ef vm.c: allow Array subclasses to override []; ref #6675
Apply the same pattern as the Hash fix: the OP_GETIDX optimization
now only applies to instances of the Array class itself. Subclasses
fall back to method dispatch, allowing them to override the [] method.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-25 18:01:43 +09:00
Yukihiro "Matz" Matsumoto 35af869d7d vm.c: allow Hash subclasses to override []; close #6675
The OP_GETIDX optimization now only applies to instances of the Hash
class itself. Subclasses fall back to method dispatch, allowing them
to override the [] method. This fixes compatibility with libraries
like mruby-hashie that rely on aliasing/overriding [] in subclasses.

Trade-off: Hash#[] cannot be overridden on the Hash class itself
(only on subclasses). This is a reasonable semantic for mruby since
subclassing is the proper pattern for customization.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-25 18:01:43 +09:00
Yukihiro "Matz" Matsumoto 768a1f7752 string.c: add mrb_strcasecmp_p for case-insensitive comparison
Move casecmp_p from mruby-string-ext and mruby-encoding to core as
mrb_strcasecmp_p (predicate function returning mrb_bool). Add
MRB_STR_CASECMP_P macro to internal.h for comparing mrb_value strings
with literal strings.

This eliminates code duplication and avoids static function name
collision for future amalgamation support.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-23 10:41:21 +09:00
Yukihiro "Matz" Matsumoto d5c93fc724 class.c, variable.c: rename bsearch_idx to avoid name collision
Rename static bsearch_idx functions to disambiguate:
- class.c: mt_bsearch_idx (method table)
- variable.c: iv_bsearch_idx (instance variable table)

This prepares for future amalgamation support.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-23 08:32:23 +09:00
Yukihiro "Matz" Matsumoto 7e28e68dca string.c: add mrb_utf8_to_buf() to consolidate UTF-8 encoding
Extract duplicated UTF-8 codepoint-to-bytes encoding into a shared
function in src/string.c. Update all gems to use it:

- mruby-sprintf: %c specifier
- mruby-io: putc
- mruby-string-ext: Integer#chr
- mruby-pack: pack("U")
- mruby-compiler: Unicode escapes in parser

Also use existing mrb_utf8len() in io.c for character length detection.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-18 16:30:03 +09:00
Yukihiro "Matz" Matsumoto e76ce24860 mruby-compiler: add one-line pattern matching
add support for one-line pattern matching syntax:
- 'expr in pattern' returns true/false
- 'expr => pattern' raises NoMatchingPatternError on mismatch

add NODE_MATCH_PAT node type for both forms, distinguished by
raise_on_fail flag. grammar rules placed at expr level to avoid
conflict with rescue clause's exception variable syntax.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-18 16:27:26 +09:00
Yukihiro "Matz" Matsumoto 2494a712dd vm.c: extract alias resolution logic to MRB_PROC_RESOLVE_ALIAS macro
reduce code duplication by introducing MRB_PROC_RESOLVE_ALIAS macro
to handle alias proc resolution in a consistent way across 5 locations.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-02 23:12:36 +09:00
Yukihiro "Matz" Matsumoto ffd3252dd0 proc.c: fix Method#== for aliased methods and comparison bug; fix #6668
follow alias chains in mrb_proc_eql() to compare underlying procs,
making Method#== return true for aliased methods as in CRuby.

also fix typo where p1 was checked instead of p2 in CFUNC comparison.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-01 18:20:45 +09:00
Yukihiro "Matz" Matsumoto 78f9b5c52f string.c: simplify memcmp guard with ternary operator
refactored the NULL pointer guard in mrb_str_cmp() from an if-else
block to a more concise ternary operator. functionality remains the
same: avoids undefined behavior by skipping memcmp() when comparing
zero-length strings.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-01 18:20:43 +09:00
Yukihiro "Matz" Matsumoto 6122fdfee9 string.c: guard memcmp() call to avoid undefined behavior with NULL pointers
passing NULL pointers to memcmp() is undefined behavior per C standard,
even when size is 0. memcmp() is declared with nonnull attributes,
and ASAN can detect this violation.

in mrb_str_cmp(), when comparing two empty strings or when the minimum
length is 0, we now skip the memcmp() call and directly set retval to 0.
this avoids the undefined behavior while maintaining correct comparison
semantics.

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-01 18:20:43 +09:00
dearblue 50ecc1fd2c Arranging VM dispatch macros
Consolidate duplicate common code.
2025-11-23 14:45:22 +09:00
Yukihiro "Matz" Matsumoto 1c7a0d4e96 vm.c: add type check before calling mrb_hash_size() on keyword dict
the keyword argument handling code was checking if kdict is not nil
before calling mrb_hash_size(), but didn't verify it's actually a hash.
malformed bytecode could cause a non-hash value to be stored in the
keyword dictionary register, leading to a NULL pointer dereference in
h_size(). add mrb_hash_p() check to prevent the crash.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-16 19:38:33 +09:00
Yukihiro "Matz" Matsumoto 8e50a45f3e mrb_print_error: handle NULL gracefully to simplify error checking
made mrb_print_error() handle NULL by printing "Failed to allocate
mrb_state" when mrb is NULL. since mrb_close() already handles NULL,
this allows simplified error checking pattern:

  if (!MRB_OPEN_SUCCESS(mrb)) {
    mrb_print_error(mrb);  // handles NULL
    mrb_close(mrb);        // handles NULL
    return EXIT_FAILURE;
  }

updated all binary tools (mruby, mirb, mrdb, mrbtest) to use this
simplified pattern, removing nested if checks.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-14 00:49:55 +09:00
Yukihiro "Matz" Matsumoto 05ffe0c441 mrb_open: return mrb_state with exc set on init failure
changed mrb_open() and mrb_open_core() to return mrb_state with mrb->exc
set (instead of NULL) when initialization fails. this allows callers to
programmatically inspect error details, which is essential for embedded
systems without stderr. return NULL only for true allocation failure.

added MRB_OPEN_SUCCESS(mrb) macro to check initialization success, since
mrb != NULL no longer guarantees success. updated all binary tools
(mruby, mirb, mrdb, mrbtest) to use new pattern: check MRB_OPEN_SUCCESS,
print exception details via mrb_print_error if available, then mrb_close.

mrb_core_init_protect now preserves exception in mrb->exc instead of
printing and clearing it, giving caller control over error handling.

breaking change: callers must use MRB_OPEN_SUCCESS(mrb) or check both
mrb != NULL && mrb->exc == NULL. old NULL-only checks will miss
initialization failures.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-13 19:10:46 +09:00
Yukihiro "Matz" Matsumoto 92640097ab variable.c: skip const_added hook during bootstrapping; fix #6613
dd96afd added const_added hook call to mrb_const_set(), but calling
mrb_funcall_argv() during core initialization (before bootstrapping
completes) fails on bare metal platforms where VM is not fully ready.
skip hook during mrb->bootstrapping phase, matching pattern used in
class.c for method cache clearing.

Co-authored-by: Claude <noreply@anthropic.com>
2025-11-13 16:46:50 +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 a9ed9190d3 class.c: combine variable declaration with initialization 2025-11-08 14:09:16 +09:00
Yukihiro "Matz" Matsumoto b99233bc45 etc.c: combine variable declaration with initialization 2025-11-08 14:08:23 +09:00
Yukihiro "Matz" Matsumoto b592d02d63 gc.c: combine variable declaration with initialization 2025-11-08 14:07:41 +09:00
Yukihiro "Matz" Matsumoto 33ec660cff kernel.c: combine variable declaration with initialization 2025-11-08 14:07:00 +09:00
Yukihiro "Matz" Matsumoto 9f91d5d1a2 load.c: combine variable declaration with initialization 2025-11-08 14:06:11 +09:00
Yukihiro "Matz" Matsumoto 717ac087ff object.c: combine variable declaration with initialization 2025-11-08 14:05:27 +09:00
Yukihiro "Matz" Matsumoto ed82cea4ca proc.c: combine variable declaration with initialization 2025-11-08 14:04:39 +09:00
Yukihiro "Matz" Matsumoto fa8c460c61 range.c: combine variable declaration with initialization 2025-11-08 14:04:11 +09:00
Yukihiro "Matz" Matsumoto 098812d10c string.c: combine variable declaration with initialization 2025-11-08 13:58:43 +09:00
Yukihiro "Matz" Matsumoto 1d3393caf5 variable.c: combine variable declaration with initialization 2025-11-08 13:57:32 +09:00
Yukihiro "Matz" Matsumoto 2c47e84cab Merge pull request #6656 from dearblue/combination_init.2 2025-10-29 11:01:29 +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
dearblue c28223ac5b Fix integer overflow in allocation size calculation
Passing a large integer value as the first argument to `Array#ary_combination_init` could cause an incorrect memory allocation due to integer overflow.
This would result in an invalid write during the subsequent zero-fill of the memory.

To resolve the issue, it has been replaced with `mrb_calloc()`.
However, since the current `mrb_calloc()` returns `NULL` due to overflow, it has been modified to raise an exception as a clear error.
2025-10-26 21:02:20 +09:00
Yukihiro "Matz" Matsumoto 00e7474cce array.c: combine variable declaration with initialization 2025-10-25 23:27:08 +09:00
Yukihiro "Matz" Matsumoto 7eb6ca686c class.c: combine variable declaration with initialization 2025-10-25 23:14:52 +09:00
Yukihiro "Matz" Matsumoto f432f1772d dump.c: combine variable declaration with initialization 2025-10-25 23:10:24 +09:00
Yukihiro "Matz" Matsumoto 35f2e97d40 kernel.c: combine variable declaration with initialization 2025-10-25 22:37:31 +09:00
Yukihiro "Matz" Matsumoto d33aaecf39 numeric.c: combine variable declaration with initialization 2025-10-25 21:58:39 +09:00
Yukihiro "Matz" Matsumoto b171abade2 range.c: combine variable declaration with initialization 2025-10-25 19:48:14 +09:00
Yukihiro "Matz" Matsumoto 905bb7366b string.c: combine variable declaration with initialization 2025-10-25 15:50:41 +09:00
Yukihiro "Matz" Matsumoto 516d2bcc52 symbol.c: combine variable declaration with initialization 2025-10-25 15:39:32 +09:00
Yukihiro "Matz" Matsumoto 0211004cf2 variable.c: combine variable declaration with initialization 2025-10-25 09:36:48 +09:00
Yukihiro "Matz" Matsumoto 0bfc2164ed vm.c: combine variable declaration with initialization 2025-10-25 09:19:14 +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 036b40e265 gc.c: combine variable declaration with initialization
Co-authored-by: Claude <noreply@anthropic.com>
2025-10-23 11:34:21 +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 d1a48c03e2 gc.c: add mrbc stub for mrb_task_mark_all
added forward declaration in gc.c and stub implementation in mrbc stub.c
for mrb_task_mark_all to avoid link errors when mrbc is built without
mruby-task gem.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-11 12:41:39 +09:00
Yukihiro "Matz" Matsumoto 14b761e200 vm.c: suppress GCC 12+ dangling pointer warning for jmpbuf
add pragma to suppress -Wdangling-pointer warning for intentional
stack variable address storage in exception handling. the pointer
is safely managed and cleared before function returns.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-11 11:10:16 +09:00
Yukihiro "Matz" Matsumoto e7cbd8cc28 mruby-task: add gc protection and optimize task operations
Implements dual-mechanism GC protection and optimizes task lookup
using pointer arithmetic based on PicoRuby reference implementation.

GC Protection:
- Add mrb_gc_register/unregister to protect Task objects
- Implement mrb_task_mark_all() to mark task contexts during GC
- Store proc reference in mrb_task to prevent premature collection
- Integrate marking into gc.c root_scan_phase

Performance Optimizations:
- Add MRB2TASK macro for O(1) context-to-task conversion
- Optimize Task.current: O(n) queue search -> O(1) pointer arithmetic
- Optimize Task.pass: simplify to root context check
- Optimize Task.join: use MRB2TASK for current task lookup

Bug Fixes:
- Fix MRB_TASK_CREATED/STOPPED to use MRB_FIBER_TERMINATED
- Add safety check to prevent execution of terminated tasks
- Initialize callinfo PC to bytecode start in task_init_context

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:23 +09:00
Yukihiro "Matz" Matsumoto 47dfb771cf mruby-task: fix cooperative task yielding with Task.pass
this patch fixes several critical issues in the task scheduler:

1. vm integration for computed goto dispatch mode:
   - added task switching check in NEXT macro for computed goto
   - previous implementation only worked with switch dispatch mode
   - now Task.pass properly yields control to other tasks

2. task lifecycle tracking:
   - added 'started' flag to mrb_task structure
   - fixed first-run detection to avoid popping callinfo multiple times
   - vm overwrites context status during execution, making it unreliable

3. removed mrblib/task.rb:
   - empty Ruby method stubs were overriding C implementations
   - all task methods now properly implemented in C

4. cleaned up task scheduler loop:
   - proper task completion detection using switching flag
   - round-robin scheduling for tasks at same priority
   - clean scheduler exit when all tasks complete

tasks now cooperatively yield with Task.pass and complete cleanly.

Co-authored-by: Claude <noreply@anthropic.com>
2025-10-08 23:55:21 +09:00