Since these are expressed as "nPk" or "nCk" in mathematics, rename `n` to `k` and `array_size` to `n`.
Additionally, rename the parameters `#__repeated_combination` and `#__combination_init` from `n` to `k`.
However, the parameter `n` in `#repeated_permutation` and `#repeated_combination` remains unchanged to align with CRuby.
compile_error is the chokepoint for all regex-compile errors;
mrb_raisef longjmps out of re_compile, abandoning the stack-local
re_compiler struct. Three connected bugs:
1. Memory leak: c->code and c->classes (grown by emit/add_class
via mrb_realloc) were never freed before raising, leaking on
any compile error like /[/. c->stripped was already cleaned up
here for the same reason; the other two buffers were missed.
2. Use-after-free: c->src aliases c->stripped when RE_FLAG_EXTENDED
is set, but the original code freed c->stripped before passing
c->src to mrb_raisef's "%s" formatter. Format the message into
an mrb_value first (mruby's GC-managed string survives the
longjmp), then free, then raise.
3. Heap-buffer-overflow: strip_extended returns a non-NUL-terminated
buffer of size len. Even with format-before-free, "%s" called
strlen and read past the buffer end. Use mruby's %l directive
which takes an explicit (char*, size_t) and avoids strlen.
Reported by OSS-Fuzz (clusterfuzz testcase 5394267353972736).
Co-authored-by: Claude <noreply@anthropic.com>
Two UBSan issues exposed by sprintf("%f", 1e-7) and similar:
1. uscale() shifted hi by c.s without bounding c.s, hitting UB
when c.s >= 64. The mask line had `c.s & 63`, but the actual
`hi >> c.s` line did not, so the partial guard was incomplete.
On x86 the hardware silently masks the shift, producing wrong
output ("1844674407370.955078" for 1e-7) instead of crashing.
When c.s >= 64 the value rounds to 0 with sticky=1, so we can
bail early.
2. count_digits(0) called bits_len64(0) -> clz64(0), which is UB.
The only other bits_len64 caller already guards d == 0; align
count_digits with that pattern. Returning 1 (since "0" is one
digit) preserves output formatting.
Reported by OSS-Fuzz (clusterfuzz testcase 5210395240628224).
Co-authored-by: Claude <noreply@anthropic.com>
The first-byte bitmap (bm[16]) is intentionally ASCII-only
(include/re_internal.h:75 documents it as 128 bits / ASCII), and
the matcher at re_exec.c:39 short-circuits for bytes >= 128. But
first_set_walk's RE_CHAR case wrote bm[a >> 3] without checking
a, overflowing the 16-byte stack buffer for any pattern
containing a byte >= 128.
When a >= 128, return FALSE so compute_first_set marks the filter
unusable, matching the bail-out pattern already used for RE_NCLASS
and RE_ANY. The pattern still compiles and matches; only the
first-byte optimization is skipped.
Reported by OSS-Fuzz (clusterfuzz testcase 4909069193510912).
Co-authored-by: Claude <noreply@anthropic.com>
Since `Kernel#puts` is undefined in unit tests, using `Kernel#print` is required.
Previously, for example, running `rake test` with the following build configuration caused the tests to fail.
```ruby
MRuby::Build.new do
toolchain
enable_debug
enable_test
enable_bintest
gem core: "mruby-bin-mrb"
end
```
io_puts_ary recursed unconditionally on nested arrays. For cyclic
arrays (a = []; a << a; puts a) or pathologically deep arrays,
this caused a C stack overflow.
Add a depth cap (IO_PUTS_MAX_DEPTH = 16); on overflow, write
"[...]\n" and return, matching CRuby's behavior on cycles. The
pattern mirrors mruby-set's MAX_NESTED_DEPTH for the same problem
shape (pure C recursion not dispatched as a Ruby method).
Reported by OSS-Fuzz (clusterfuzz testcase 6233530857488384).
Co-authored-by: Claude <noreply@anthropic.com>
mrb_const_set may invoke const_added via mrb_funcall_argv, which
re-enters the VM and can reallocate cibase. This invalidates the
local ci pointer (and thus the regs macro that expands to ci->stack),
causing a use-after-free on the next opcode dispatch.
OP_SETMCNST and the OP_GET* / OP_*IDX opcodes already follow this
pattern; align OP_SETCONST with them.
Reported by OSS-Fuzz (clusterfuzz testcase 5886006653157376).
Co-authored-by: Claude <noreply@anthropic.com>
Bumps the bundler-dependencies group with 1 update in the / directory: [yard](https://yardoc.org).
Updates `yard` from 0.9.42 to 0.9.43
---
updated-dependencies:
- dependency-name: yard
dependency-version: 0.9.43
dependency-type: direct:production
update-type: version-update:semver-patch
dependency-group: bundler-dependencies
...
Signed-off-by: dependabot[bot] <support@github.com>
The mruby C style places `else` on its own line. Reformat the
remaining `} else if (...)` occurrence in the C action block of
NODE_SYMBOLS dump.
Co-authored-by: Claude <noreply@anthropic.com>
The mruby C style places `else` on its own line. Reformat the
remaining `} else {` / `} else if (...)` occurrences.
Co-authored-by: Claude <noreply@anthropic.com>
`build.bins` is for compiled binaries with bare names; entries are
fed through `exefile()` in `tasks/bin.rake`, which appends
`exts.executable` (e.g. `.exe`) when no extension is present.
When `ENV['OS']` is not `Windows_NT` but the toolchain has
`exts.executable=".exe"` (e.g. cross builds, or environments where
`OS` is unset under visualcpp), `mruby-bin-config` ended up with a
file task at `.../mruby-config` while rake asked for
`.../mruby-config.exe`, aborting with "Don't know how to build task".
Skip the `bins` path and call `build.define_installer` directly with
`mruby_config_path`, mirroring the existing `iscross` branch. The
file task path now always matches the script content's extension
(`.bat` on Windows, no extension elsewhere).
close#6807, reported by UENO, M. (@eunos-1128).
Co-authored-by: Claude <noreply@anthropic.com>
This reverts commit eed32b752b.
Windows's Winsock getaddrinfo does not consult the hosts file for
"localhost" because an internal hard-coded rule short-circuits first,
so the Add-Content step had no effect on the failing tests. Remove
the ineffective workaround now that a skip guard replaces it.
Co-authored-by: Claude <noreply@anthropic.com>
This reverts commit 7ae25febbb.
CI runs with this change showed Dnscache was already Running on all
Windows jobs and Resolve-DnsName resolved "localhost" successfully,
yet Winsock getaddrinfo still failed. The service start and probe
had no effect on the failing tests, so they add noise without value.
Co-authored-by: Claude <noreply@anthropic.com>
This reverts commit a69d12aa54.
The diagnostic served its purpose: it isolated the failure to
Winsock's getaddrinfo for the "localhost" hostname. The permanent
fix (skip guard) is now in place, so remove the temporary probe.
Co-authored-by: Claude <noreply@anthropic.com>
Addrinfo.getaddrinfo("localhost", ...) and Addrinfo.foreach("localhost",
...) crash on GitHub Actions Windows runners (Windows Server 2022 and
2025, both mingw-gcc and MSVC). Diagnostic showed 127.0.0.1 as a
numeric literal resolves fine via Winsock getaddrinfo, but "localhost"
as a hostname returns WSAHOST_NOT_FOUND under every address family
(AF_INET, AF_INET6, AF_UNSPEC, nil). PowerShell Resolve-DnsName on
the same runner succeeds, so the failure is Winsock-specific rather
than OS-level. Earlier workarounds (Dnscache service start, hosts
file append) had no effect.
Skip both tests on Windows with the existing SocketTest.win? guard,
matching the pattern already used for Addrinfo.unix and
Addrinfo#afamily. Linux and macOS coverage is unaffected.
Co-authored-by: Claude <noreply@anthropic.com>
Addrinfo.getaddrinfo on the Windows CI runners fails for "localhost"
regardless of address family (diagnostic commit a69d12aa54 showed
127.0.0.1 literal resolves fine while "localhost" never does under
AF_INET, AF_INET6, AF_UNSPEC, or nil). That rules out the earlier
KB4057932/AF_INET hypothesis and points at the Dnscache service
being stopped on the runner image.
Start Dnscache if not already running (and set it to Automatic),
then Resolve-DnsName localhost to print the OS-level resolver view
to the log. Existing hosts file and diagnostic assert stay in place
so the single CI round exposes both the service state and its
effect on getaddrinfo.
Co-authored-by: Claude <noreply@anthropic.com>
Addrinfo.getaddrinfo("localhost", 53, AF_INET, SOCK_STREAM) crashes
on GitHub Actions Windows runners with WSAHOST_NOT_FOUND, while the
same call works on Linux and macOS. Earlier hypotheses (winsock link
missing; hosts file not populated) have been ruled out on CI.
Probe five variants in one run to isolate the failing condition:
numeric literal 127.0.0.1, localhost with AF_UNSPEC, localhost with
nil family, localhost with AF_INET6, and the original AF_INET path.
Results go to stdout via puts so they are visible in CI logs. This
commit is temporary and will be reverted once the real fix lands.
Co-authored-by: Claude <noreply@anthropic.com>
GitHub Actions Windows Server 2022/2025 runner images ship with the
localhost entries commented out in C:\Windows\System32\drivers\etc\hosts
and rely on the DNS Client service's built-in rule. That path is subject
to Microsoft KB4057932 (getaddrinfo fails with WSAHOST_NOT_FOUND after
an AF_INET6 negative cache), which makes Addrinfo.getaddrinfo("localhost",
53, AF_INET, ...) in mrbgems/mruby-socket/test/addrinfo.rb flaky on CI.
Prepend explicit 127.0.0.1/::1 localhost entries to the hosts file on
all three Windows CI jobs (two mingw-gcc matrix entries and Windows-VC)
before running the build, so the resolver avoids the DNS negative cache
path and returns the expected IPv4 address.
Co-authored-by: Claude <noreply@anthropic.com>
Commit be6413f0d86a ("mruby-task: migrate HAL to ports/ directories")
moved the Windows HAL source into mruby-task/ports/win/ but dropped
the linker.libraries declaration that previously lived in
hal-win-task/mrbgem.rake. Both mingw and MSVC builds now fail to link
task_hal.o/obj with undefined references to timeBeginPeriod,
timeEndPeriod, timeSetEvent, and timeKillEvent. Re-declare winmm
under a for_windows? guard.
Co-authored-by: Claude <noreply@anthropic.com>
Commit 9965f11cfe1c ("mruby-io: migrate HAL to ports/ directories")
moved the Windows HAL source into mruby-io/ports/win/ but dropped the
linker.libraries declaration that previously lived in
hal-win-io/mrbgem.rake. Both mingw and MSVC builds now fail to link
with undefined references to closesocket, WSAStartup, WSACleanup,
select, and WSAGetLastError referenced from io.c and io_hal.c.
Re-declare ws2_32 under a for_windows? guard.
Co-authored-by: Claude <noreply@anthropic.com>
Commit d9e107c801 ("mruby-socket: migrate HAL to ports/ directories")
moved the Windows HAL source into mruby-socket/ports/win/ but dropped
the linker.libraries declarations that previously lived in
hal-win-socket/mrbgem.rake. Both mingw and MSVC builds now fail to
link with undefined references to WSAStartup, socket, send, and other
Winsock APIs. Re-declare wsock32 and ws2_32 under a for_windows? guard.
Co-authored-by: Claude <noreply@anthropic.com>
Cover zero operands, power-of-2 fast path, negative operands,
balanced multi-limb pairs with a shared Fibonacci factor, highly
unbalanced pairs (to exercise the Euclidean fallback), and
Fibonacci neighbors (always coprime). Declare a test dependency
on mruby-numeric-ext since Integer#gcd is defined there.
Co-authored-by: Claude <noreply@anthropic.com>
Replace the classical Euclidean main loop (mpz_mod per iteration)
with Stein's binary GCD: subtract + factor out trailing 2s on
odd-maintained operands. Keep an mpz_mod fallback for heavily
unbalanced pairs (the smaller operand has at least two fewer limbs)
where one long division replaces many Stein subtracts.
The old loop allocated a temporary mpz_t every iteration to hold the
mod result; the Stein loop is allocation-free thanks to the in-place
paths in mpz_sub and mpz_div_2exp. This matches the "memory first"
priority and also happens to be faster on typical inputs because
mpz_mod's setup cost dominates when the quotient is small (the
classical Fibonacci-neighbor worst case).
Also add a small mpz_swap helper used by the new loop.
Benchmark (bin/mruby benchmark/bm_bigint_gcd.rb, median of 3):
case before after ratio
single-limb 42 ms 50 ms 1.19 (fast-path
unchanged;
noise)
fib(200) vs fib(201) 82 ms 23 ms 0.28
balanced ~700-bit shared 46 ms 32 ms 0.70
unbalanced big vs small 35 ms 28 ms 0.80
power-of-2 path 38 ms 42 ms 1.11 (fast-path
unchanged;
noise)
balanced ~2800-bit shared 19 ms 15 ms 0.79
Co-authored-by: Claude <noreply@anthropic.com>
The preceding comment claimed "Binary GCD (Stein's algorithm)",
but the multi-limb main loop is classical Euclidean using mpz_mod.
Only the prelude (factoring out common 2s, single-limb and
power-of-2 fast paths) is Stein-flavored. Describe what the code
actually does so readers are not misled.
Co-authored-by: Claude <noreply@anthropic.com>
Per gemini-code-assist review on #6790: the documentation still
showed the pre-#6790 union mrb_mt_ptr member order (proc first)
and the C99 designated-initializer form of MRB_MT_ENTRY. Update
both to match the merged code, and add a note explaining why func
must come first in the union.
Co-authored-by: Claude <noreply@anthropic.com>
Per gemini-code-assist review on #6791: replace member-by-member
assignment with C89/C++98-style positional aggregate initialization,
keeping the macro a single declaration and matching the existing
pool_storage initializer style in the same macro.
Co-authored-by: Claude <noreply@anthropic.com>
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>
The mrb_match_data struct stores `source` and `regexp` as plain
mrb_value members of a C-allocated struct, which the GC does not
scan. Under MRB_GC_STRESS the source string could be collected
while the MatchData was still alive, causing md[0] to read freed
memory (observed as "\xff\xff\xff").
Also stash source and regexp as instance variables on the MatchData
object so they remain reachable via the object's iv_tbl during GC.
The C struct members continue to provide fast direct access, and
no other call sites need to change.
Co-authored-by: Claude <noreply@anthropic.com>
Remove early return of hardcoded 0 for zero floats. Instead, normalize
-0.0 to +0.0 and pass through mrb_byte_hash() for better distribution.
The previous second condition (f == -0.0) was dead code since IEEE 754
-0.0 == 0.0 is true.
Co-authored-by: Claude <noreply@anthropic.com>
Use FNV-1a (xor-then-multiply) instead of FNV-1 for better avalanche
in byte hashing. Strengthen the hash finalizer in mrb_obj_hash_code()
with multiply-xorshift to improve distribution for integer and symbol
keys with power-of-two table sizes.
Co-authored-by: Claude <noreply@anthropic.com>
Replace printf("%c", val) with pack("CCC") for outputting raw
bytes. printf("%c") with values >= 128 produces invalid UTF-8
on CRuby, corrupting the PPM output. Also remove unused
arguments from the "255\n" format string.
Co-authored-by: Claude <noreply@anthropic.com>
Add hw-adc gem with analog-to-digital conversion support:
- Common Ruby API with read, read_raw, and read_voltage
- ports/esp32/ using ESP-IDF ADC oneshot driver
- ports/rp2040/ using Pico SDK ADC hardware
Based on picoruby-adc by HASUMI Hitoshi.
Co-authored-by: Claude <noreply@anthropic.com>
Add hw-pwm gem with pulse width modulation support:
- Common Ruby API with frequency, duty, period_us, pulse_width_us
- ports/esp32/ using LEDC peripheral
- ports/rp2040/ using Pico SDK PWM hardware
Based on picoruby-pwm by HASUMI Hitoshi.
Co-authored-by: Claude <noreply@anthropic.com>
Add hw-spi gem with SPI communication support:
- Common Ruby API with write, read, and full-duplex transfer
- ports/esp32/ using ESP-IDF SPI master driver
- ports/rp2040/ using Pico SDK
Based on picoruby-spi by HASUMI Hitoshi.
Co-authored-by: Claude <noreply@anthropic.com>
Move hal-posix-task and hal-win-task into
mruby-task/ports/posix/ and mruby-task/ports/win/.
Remove HAL auto-detection logic from mrbgem.rake. Update
cosmopolitan.rb to use conf.ports :posix instead of explicit
hal-* gem references.
Co-authored-by: Claude <noreply@anthropic.com>
Move hal-posix-socket and hal-win-socket into
mruby-socket/ports/posix/ and mruby-socket/ports/win/.
Remove HAL auto-detection logic from mrbgem.rake.
Co-authored-by: Claude <noreply@anthropic.com>