375 Commits
Author SHA1 Message Date
Hiroshi SHIBATAandClaude Opus 5 fa1bbf4163 Use rb_len_t for byte lengths in random.c
Random.urandom converts its size with NUM2LEN instead of the unsigned macro, so a negative Integer raises ArgumentError without wrapping through the whole unsigned range first, and a size beyond the signed range raises RangeError the way Random#bytes already does. Neither error was covered before.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-09 14:00:15 +09:00
Hiroshi SHIBATAandClaude Opus 5 cc3ba11012 Use rb_len_t in the C API for lengths and indices
Once rb_len_t widens this changes the `long *` output parameters of rb_range_beg_len(), rb_str_subpos(), rb_arithmetic_sequence_beg_len_step(), ruby_enc_find_basename() and ruby_enc_find_extname(), so extensions passing `long *` to them will need to be updated. The extension guides list these signatures verbatim and follow along.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-09 14:00:15 +09:00
Hiroshi SHIBATAandClaude Fable 5 c0ade935f6 Remove CryptGenRandom fallback
`BCryptGenRandom` with `BCRYPT_USE_SYSTEM_PREFERRED_RNG` is available
on every supported Windows version and `bcrypt.lib` is linked
unconditionally on both mswin and mingw, so the deprecated CryptoAPI
fallback is unreachable in practice.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 13:26:25 +09:00
John HawthornandLuke Gruber daffaaee73 Mark most TypedData types as THREAD_SAFE_FREE
Set RUBY_TYPED_THREAD_SAFE_FREE on TypedData types whose dfree function
is trivially safe, and only frees its own memory

Types not yet marked as THREAD_SAFE_FREE:
- id2ref_tbl_type: sets the process-global id2ref_tbl to NULL.
- mutex_data_type: unlinks itself from another thread's keeping_mutexes list.
- autoload_data_type: deletes nodes from a shared intrusive list.
- autoload_const_type: deletes itself from a shared list.
- rb_cont_data_type: mutates the shared fiber pool and the global first_jit_cont list.
- rb_fiber_data_type: delegates to cont_free.
- FiberPoolDataType: mutates shared fiber pool free-lists.
- ractor_data_type: reconfigures global VM event-hook flags and call caches.
- exported_object_registry: frees a global table under the VM lock.
- rb_box_data_type (Box::Entry): unlinks classext from other live class and module objects.
- box_ext_cleanup_type: dereferences another String object and calls unlink.
- monitor_data_type: uses the default free, so the flag has no effect.

Co-authored-by: Luke Gruber <luke.gruber@shopify.com>
2026-06-23 13:30:26 -07:00
Nobuyoshi Nakada e21a4b0174 win32: Limit the size up to the rounded-up half of the max range 2026-06-02 11:21:14 +09:00
Nobuyoshi Nakada aecfd0ae5b win32: Release crypt provider in end proc
End procs are executed in reverse order of registration.  Since the
crypt provider is initialized very early on via `Init_RandomSeedCore`,
no other end procs are executed after the crypt provider is released.
Finalizers are called after end procs, but their order is unspecified,
so there is still no guarantee that this crypt provider will be
available for use by other end procs.
2026-06-02 11:21:14 +09:00
Nobuyoshi Nakada bab8120bfd Separate the case default_seed_bits is 0 2026-03-09 14:46:16 +09:00
Nobuyoshi Nakada 7bcb5178dd Mix upper bits when st_index_t is shorter than uint64_t
As well as when `uint64_t` is not available.  Although we now assume
that `uint64_t` is always available, even on 32-bit platforms, the
size of `st_index_t` is the same as a pointer and would be shorter
than 64-bit.
2026-03-09 14:46:16 +09:00
Peter Zhu 9e78353c0f Fix maybe uninitialized warnings in random.c
Fixes the following compiler warnings:

    random.c: In function `random_init`:
    random.c:416:38: warning: `rng` may be used uninitialized in this function [-Wmaybe-uninitialized]
      416 |     unsigned int major = rng->version.major;
          |                          ~~~~~~~~~~~~^~~~~~
    random.c: In function `random_bytes`:
    random.c:1284:8: warning: `rng` may be used uninitialized in this function [-Wmaybe-uninitialized]
    1284 |     rng->get_bytes(rnd, ptr, n);
         |     ~~~^~~~~~~~~~~
    random.c:1299:34: note: `rng` was declared here
    1299 |     const rb_random_interface_t *rng;
         |                                  ^~~
    random.c: In function `rand_random_number`:
    random.c:1606:12: warning: `rng` may be used uninitialized in this function [-Wmaybe-uninitialized]
    1606 |     return rand_range(obj, rng, rnd, vmax);
         |            ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    random.c:1624:34: note: `rng` was declared here
    1624 |     const rb_random_interface_t *rng;
          |                                  ^~~
    random.c: In function `random_rand`:
    random.c:1120:15: warning: `rng` may be used uninitialized in this function [-Wmaybe-uninitialized]
    1120 |     return rng->get_int32(rnd);
         |            ~~~^~~~~~~~~~~
    random.c:1573:34: note: `rng` was declared here
    1573 |     const rb_random_interface_t *rng;
         |                                  ^~~
2025-12-28 16:25:49 -05:00
Nobuyoshi Nakada 44e762a99c Extract rb_random_interface_t alongside rb_random_t as well 2025-12-29 02:01:12 +09:00
Nobuyoshi Nakada cdb9893c55 Win32: Drop support for older than MSVC 8.0/_MSC_VER 1400
Visual C++ 2005 (8.0):
- _MSC_VER: 1400
- MSVCRT_VERSION: 80
2025-11-19 11:03:42 +09:00
Jason Garber 01e27acbec [DOC] Clarify differences between Kernel.rand and Random.rand when given a Float max
* [DOC] Clarify differences between Kernel.rand and Random.rand

* `Kernel.rand` converts the `max` Float argument to Integer and returns Integer values
* `Random.rand` preserves the `max` Float argument and returns Float values
* Added examples demonstrating the behavioral differences
2025-09-03 13:44:47 +09:00
John Hawthorn 0b098a93db Add missing write barriers to Random
We recently converted this to be WB_PROTECTED, but missed some locations
the seed was set.

This is a little bit confusing because as far as I can tell some of the
seeds are set in Ractor local storage, and others on actual objects.
2025-08-18 12:00:15 -07:00
Peter Zhu 24d0b458cd Make Random write-barrier protected 2025-08-07 09:27:22 -04:00
Nobuyoshi Nakada d84a811f31 [Bug #21448] Reorder trials in fill_random_bytes
First try dedicated system calls, such as `getrandom` or `getentropy`,
next possible libraries, then fallback to `/dev/urandom`.
2025-06-22 02:00:56 +09:00
Kazuki Yamaguchi 0cec4a14fb Restore getrandom(2) path for Linux with glibc 2.36 or later
This is a follow-up to commit b120f5e38d (avoid fork-unsafe arc4random
implementations, 2018-09-04).

Avoid defining a no-op fill_random_bytes_syscall() if arc4random_buf(3)
exists, but we are unsure if it is fork-safe. Check for other options
instead. IOW, see if getrandom(2) is available.

glibc 2.36, released in 2022, started to provide arc4random_buf(3) on
Linux. This causes fill_random_bytes_syscall() to use neither of them
and makes Random.urandom solely rely on getentropy(3) via
fill_random_bytes_urandom().

While the glibc implementation is safe, I did not add it to the list
because using getrandom(2) directly is preferable on Linux.
2025-06-21 19:57:19 +09:00
Nobuyoshi Nakada 1181a682a6 [Bug #21448] Use getentropy(2) only on macOS
If this is not a system call, then it is using getrandom (which would
have been tried already), and cannot be used as a replacement for the
random devices.
2025-06-21 16:52:16 +09:00
Yusuke Endoh 8aeb67de7d Remove a useless condition expression
`len` is always at least 1 here.
2024-11-30 00:03:07 +09:00
Yusuke Endoh 50a34637a4 Avoid illegal pointer
When loading a crafted marshal data of Random, a pointer to an illegal
address was created. I don't think there is any harm since the data is
normalized before access, but just to be safe, I add a check to make it
an error.
2024-11-29 03:01:46 +09:00
Nobuyoshi Nakada 335cb28886 Do not try random devices immediately twice
Do not retry `fill_random_bytes` in `Init_RandomSeedCore`, just after
it failed first.

In other places, `rand_init_default` and `random_seed`, no more tweeks
needed once it succeeded
2024-06-07 10:42:41 +09:00
Nobuyoshi Nakada 5b4734d51d win32: Allocate the wrapper for crypt provider handle first
Also use a typed data.
2024-06-07 10:42:41 +09:00
Jean Boussier d4f3dcf4df Refactor VM root modules
This `st_table` is used to both mark and pin classes
defined from the C API. But `vm->mark_object_ary` already
does both much more efficiently.

Currently a Ruby process starts with 252 rooted classes,
which uses `7224B` in an `st_table` or `2016B` in an `RArray`.

So a baseline of 5kB saved, but since `mark_object_ary` is
preallocated with `1024` slots but only use `405` of them,
it's a net `7kB` save.

`vm->mark_object_ary` is also being refactored.

Prior to this changes, `mark_object_ary` was a regular `RArray`, but
since this allows for references to be moved, it was marked a second
time from `rb_vm_mark()` to pin these objects.

This has the detrimental effect of marking these references on every
minors even though it's a mostly append only list.

But using a custom TypedData we can save from having to mark
all the references on minor GC runs.

Addtionally, immediate values are now ignored and not appended
to `vm->mark_object_ary` as it's just wasted space.
2024-03-06 15:33:43 -05:00
Nobuyoshi Nakada 55335eab80 Use STATIC_ASSERT 2024-01-13 23:43:07 +09:00
6816e8efcf Free everything at shutdown
when the RUBY_FREE_ON_SHUTDOWN environment variable is set, manually free memory at shutdown.

Co-authored-by: Nobuyoshi Nakada <nobu@ruby-lang.org>
Co-authored-by: Peter Zhu <peter@peterzhu.ca>
2023-12-07 15:52:35 -05:00
zverok 381a373ab9 [DOC] Improve Random::Formatter docs
* Make its usage more obvious (by providing more detailed
  examples);
* Include mention of it into Random itself;
* Small cleanups of docs.
2022-12-11 18:49:56 +02:00
Nobuyoshi Nakada b7e8876704 [Bug #19100] Add init_int32 function to rb_random_interface_t
Distinguish initialization by single word from initialization by
array.
2022-11-10 12:06:13 +09:00
Nobuyoshi Nakada 6eaed20e14 Add version to the interface of Random extensions 2022-11-10 11:59:45 +09:00
Nobuyoshi Nakada f6bf5e2c5f Respect USE_COMMON_RANDOM macro by a command line option [ci skip] 2022-10-17 18:36:09 +09:00
Nobuyoshi Nakada b584c106d9 Fix debug messages [ci skip] 2022-10-17 18:36:08 +09:00
Takashi Kokubun 5b21e94beb Expand tabs [ci skip]
[Misc #18891]
2022-07-21 09:42:04 -07:00
Nobuyoshi Nakada 5a75151a01 [DOC] Mark up the code for Kernel#rand as the same as Random#rand 2022-01-13 11:34:09 +09:00
Nobuyoshi Nakada fae0b66431 Remove deprecated Random::DEFAULT [Feature #17351] 2022-01-01 18:55:52 +09:00
Chris AtLee 1dd10e1892 [DOC] Add documentation for Random.rand and Random.seed 2021-12-20 00:50:46 +09:00
Nobuyoshi Nakada cf54de637c [DOC] random number by range 2021-12-16 18:00:23 +09:00
Nobuyoshi Nakada 446a11f2c1 [DOC] Add call sequences of Random using a range 2021-12-13 19:56:11 +09:00
Nobuyoshi Nakada dc490aced3 [DOC] Improve Random::Formatter description and example 2021-12-13 19:55:44 +09:00
Nobuyoshi Nakada bcc2bb28b0 Fix stack buffer overflow
https://hackerone.com/reports/1306859
2021-12-10 01:04:59 +09:00
Nobuyoshi Nakada 66b0847602 Check the reading size range 2021-11-06 17:39:37 +09:00
Kazuki Yamaguchi 9541b3b7c0 random.c: simplify Random object deallocation
This is a follow-up for commit 265c002239 ("Do not allocate
ractor-local storage in dfree function during GC", 2021-02-09).

The comparison with the default rb_random_mt_t is useless in the first
place, since it is never equal: no actual Random object is associated
with it.

[Bug #17653] https://bugs.ruby-lang.org/issues/17653
2021-10-27 15:44:27 +09:00
Nobuyoshi Nakada e0ef4899f3 [Win32] Prefer Cryptography Next Generation API
[BCryptGenRandom] is available since Windows Vista / Windows
Server 2008.

Regarding [CryptGenRandom]:
> This API is deprecated. New and existing software should start
> using Cryptography Next Generation APIs. Microsoft may remove
> this API in future releases.

[BCryptGenRandom]: https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptgenrandom
[CryptGenRandom]: https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptgenrandom
2021-10-02 21:22:33 +09:00
Nobuyoshi Nakada 0eb679f70c HCRYPTPROV is not a HANDLE
Even though it is called "handle" and prefixed with "H", and its
value looks like a handle.
2021-09-24 12:12:38 +09:00
S-H-GAMELINKS 83a5e2bb5c Using RB_FLOAT_TYPE_P macro 2021-09-12 11:16:31 +09:00
Nobuyoshi Nakada 04be8e84db Use C99-defined macros to classify a floating-point number 2021-08-27 12:41:30 +09:00
David Carlier 8d2af51a78 netbsd coroutine uses assembly instead and little build fix. 2021-08-24 10:52:04 +09:00
卜部昌平 0fbdaaf7c9 rand_bytes: prefer rng->get_bytes
Because why not.  There was no use case of rng->get_bytes before this
changeset.
2021-06-24 12:48:17 +09:00
Peter Zhu 3d2e7e2ab5 Fix compilation errors in FreeBSD
__FreeBSD_version is defined in sys/param.h.
2021-05-04 20:38:03 -04:00
Benoit Daloze 0764d323d8 Fix -Wundef warnings for patterns #if HAVE
* See [Feature #17752]
* Using this to detect them:
  git grep -P 'if\s+HAVE' | grep -Pv 'HAVE_LONG_LONG|/ChangeLog|HAVE_TYPEOF'
2021-05-04 14:56:55 +02:00
Nobuyoshi Nakada 9e71f1aa4c Include CommonCrypto/CommonCryptoError.h for old Xcode 2021-03-19 18:56:41 +09:00
Nobuyoshi Nakada 4ea96f1d4f Use CommonRandom if available 2021-03-19 15:23:03 +09:00
Nobuyoshi Nakada bf089d786a Fixed syntax error with gcc on macOS
Security/Authorization.h defines AuthorizationExternalForm by
using clang extension which allows variably modified types in a
file scope.  As we just need high-level accessors only, include
Security/SecRandom.h instead.
2021-03-04 11:28:39 +09:00