Skip to content

Introduce loadable pseudo-random number generators. - #200

Open
Don-Ward wants to merge 26 commits into
uniconproject:masterfrom
Don-Ward:PrngLib
Open

Don-Ward wants to merge 26 commits into
uniconproject:masterfrom
Don-Ward:PrngLib

Conversation

@Don-Ward

@Don-Ward Don-Ward commented Mar 6, 2021

Copy link
Copy Markdown
Collaborator

N.B. The PRNG interface introduced here is subject to review and may change.

PRNGs are per-thread and may be changed with the new loadrng() standard
function. Two PRNGs are present:
IconEx A reimplementation of the traditional generator
as a loadable library.
Rabbit A cryptographically strong PRNG from the eSTREAM project.
Other PRNGs -- probably RanLux and the Mersenne Twister -- will follow.

@Don-Ward
Don-Ward force-pushed the PrngLib branch 3 times, most recently from f292b54 to 1bf0fdf Compare March 15, 2021 20:19

@etherx-dev etherx-dev left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

My head hurts... but i know that stumbling upon this project just made it worthwhile lol.

@Don-Ward
Don-Ward force-pushed the PrngLib branch 2 times, most recently from e88b1c1 to 5f062e4 Compare January 13, 2022 22:27
@Don-Ward
Don-Ward force-pushed the PrngLib branch 2 times, most recently from c78a020 to e8ea554 Compare February 28, 2022 21:02
@Don-Ward
Don-Ward force-pushed the PrngLib branch 2 times, most recently from 1a957f6 to b8f887c Compare March 10, 2022 22:41
@Don-Ward
Don-Ward force-pushed the PrngLib branch 2 times, most recently from ed0a88d to 6be1d9d Compare March 15, 2022 12:11
@Don-Ward
Don-Ward marked this pull request as ready for review March 15, 2022 13:34
@Don-Ward
Don-Ward requested review from Jafaral and cjeffery March 15, 2022 13:34
@Don-Ward
Don-Ward marked this pull request as draft March 22, 2022 11:32
@Don-Ward

Copy link
Copy Markdown
Collaborator Author

After initial feedback, it was decided to split up the PR into several smaller commits

Comment thread src/runtime/fmisc.r Resolved
Jafaral and others added 26 commits May 17, 2026 17:54
Update rttgram.y and regenerate rttparse.c and ltoken.h.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Teach RTT to parse the runtime C constructs that are safe
to understand directly. Keep explicit output directives for
code that must still bypass RTT parsing or preprocessing.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Replace runtime passthru sites with explicit raw C markers.
Leave parsed C constructs visible to RTT where the translator now
understands them.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Map __thread and _Thread_local to Thread_local instead of Static so
storage-class analysis (e.g. just_type) cannot confuse TLS with static.
Regenerate the Bison parser tables.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
Regenerate yyerror.c with merr -B so errtab state keys match the current
automaton; size yymaxstate/errtab to YYNSTATES - 1 / YYNSTATES from rttparse.c.
Include stdlib.h for calloc.

rttgram.y: note that token code 368 is reserved as YYUNDEF.

Signed-off-by: Jafar Al-Gharaibeh <[email protected]>
The hand calculated values in the firstd and firstp arrays are replaced with
compiler calculations using offsetof(). This should make future changes easier
and less prone to error.
Some configurations have a different number of mutexes, which leads to
a test failure (because the test output is not the same as the expected
result). This commit changes the output so that exact values are no longer
part of the output. The actual tests are unchanged.
Add runtime routines callable by a rnglib:
   getRngState
   getInitialBits
   putErrorCode
Add rnglib routines callable by the runtime:
   startRng
   putSeed
   getRandomFpt
   getErrorText
   getRandomBits  -- optional
   getRandomInt   -- optional

Add new standard functions:
   loadrng
   rngbits
   rngbitstring
   rngval
Add "loadable RNGs" to &features.
Add _RNG_LIBRARY to the preprocessor predefined symbols.
RngIconEx is a reimplemtation of the (Icon) built-in generator
as a loadable rnglib. It serves as an example for how implement a
loadable rng library.
Rabbit is a cryptographically secure random number generator from the
ESTREAM project. rngRbt implements it as a loadable rng library.
rngRlx++ is a reimplementation in C of the RanLux++ generator.
rngGSL isn't a random number generator as such; it provides an interface
to the generators in the GNU Scientific Library, if that is installed.
Add a new argument --enable-rnglibs to configure.
Detect the presence (or otherwise) of the GNU Scientific Library.
Add a test for --enable-rnglibs
…araibeh]

This is a slight rework of commit 27b385c. It is needed because the
PRNG code uses unicon_getrandom() in fmisc.r as well as init.r
@Don-Ward

Copy link
Copy Markdown
Collaborator Author

@greptile review

Comment thread src/runtime/fmisc.r
Comment on lines +2779 to +2800
blkbits = curtstate->rng->info.property.blockBits;
if (n == 0 ) n = blkbits;

/* What is the largest multiple of blkbits that fits in our buffer? */
maxbits = ((sizeof(bitbuff) * 8)/blkbits)*blkbits;

/* Allocate a string of the required size for the answer */
Protect(StrLoc(result) = alcstr(NULL, n), runerr(306));

/* Populate result with '0' and '1' characters.
* The bits are in the natural left to right reading order,
* i.e. the least significant bit is at the _end_ of the string.
*/
bstr = n + StrLoc(result);
bits = 0; bytes = sizeof(bitbuff) + 1;
while( bits < n ) {
if (bytes >= sizeof(bitbuff)) { /* get the next lot of bits */
if ( 0 < curtstate->rng->info.api.getRandomBits(Min(n - bits, maxbits), bitbuff)) {
bytes = 0;
} else {
fail; /* getRandomBits failed */
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 rngbitstring silently fails for any library with blockBits > 384

maxbits = ((sizeof(bitbuff)*8)/blkbits)*blkbits. When blkbits > 384, integer division truncates to 0, so maxbits = 0. The loop then calls getRandomBits(Min(n-bits, 0), bitbuff) — passing 0 bits every iteration. A well-behaved library returns 0 bytes for a zero-bit request, which fails the 0 < 0 check and causes rngbitstring to always fail. A library returning a positive value for a zero-bit request would spin forever since bits never advances.

The PR description explicitly plans to add Mersenne Twister next. Depending on how its blockBits is set, it could trigger this path. Additionally, if blkbits == 0 (incorrectly configured library), maxbits = ((48*8)/0)*0 is a division-by-zero crash.

The second if (n == 0) n = blkbits on line 2780 is also unreachable dead code — n was already set to blockBits on line 2745 whenever n == 0.

Consider validating blkbits > 0 before the division, and choosing maxbits as min(384, blkbits) so that libraries with blockBits > 384 are not broken outright.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/fmisc.r
Line: 2779-2800

Comment:
**`rngbitstring` silently fails for any library with `blockBits > 384`**

`maxbits = ((sizeof(bitbuff)*8)/blkbits)*blkbits`. When `blkbits > 384`, integer division truncates to `0`, so `maxbits = 0`. The loop then calls `getRandomBits(Min(n-bits, 0), bitbuff)` — passing `0` bits every iteration. A well-behaved library returns `0` bytes for a zero-bit request, which fails the `0 < 0` check and causes `rngbitstring` to always `fail`. A library returning a positive value for a zero-bit request would spin forever since `bits` never advances.

The PR description explicitly plans to add Mersenne Twister next. Depending on how its `blockBits` is set, it could trigger this path. Additionally, if `blkbits == 0` (incorrectly configured library), `maxbits = ((48*8)/0)*0` is a division-by-zero crash.

The second `if (n == 0) n = blkbits` on line 2780 is also unreachable dead code — `n` was already set to `blockBits` on line 2745 whenever `n == 0`.

Consider validating `blkbits > 0` before the division, and choosing `maxbits` as `min(384, blkbits)` so that libraries with `blockBits > 384` are not broken outright.

How can I resolve this? If you propose a fix, please make it concise.

Comment thread src/runtime/rmisc.r
Comment on lines 147 to 163
return Succeeded;
}
else if (strcmp(s,"&random") == 0) {
#ifdef RngLibrary
if (curtstate->rng == NULL) {
vp->dword = D_Kywdint; /* Built-in generator */
VarLoc(*vp) = &kywd_ran;
return Succeeded;
} else {
vp->dword = D_List | F_RngState | F_Var; /* RNG library */
VarLoc(*vp) = kywd_ran.vword.descptr;
return Succeeded;
}
#else
vp->dword = D_Kywdint;
VarLoc(*vp) = &kywd_ran;
return Succeeded;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 getvar("&random") does not allocate RNG state before returning variable reference

keyword.r always calls no_rng_state() before returning curtstate->Kywd_ran, ensuring the state block is allocated. getvar("&random") does not — it returns the variable reference with Kywd_ran potentially still nulldesc on a thread that has never generated a random value.

If Unicon code uses variable("&random") and then assigns through the resulting reference, rngAsgnState will return 0 because ChkNull(ts->Kywd_ran) is true, and the new-seed path will call putSeed. Inside putSeed, runtime.getRngState() returns NULL (because Kywd_ran.vword.bptr is NULL), and putSeed returns −1 — causing the assignment to silently fail rather than seeding the generator as the user intended.

A call to no_rng_state() should be inserted here, mirroring what keyword.r already does.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/runtime/rmisc.r
Line: 147-163

Comment:
**`getvar("&random")` does not allocate RNG state before returning variable reference**

`keyword.r` always calls `no_rng_state()` before returning `curtstate->Kywd_ran`, ensuring the state block is allocated. `getvar("&random")` does not — it returns the variable reference with `Kywd_ran` potentially still `nulldesc` on a thread that has never generated a random value.

If Unicon code uses `variable("&random")` and then assigns through the resulting reference, `rngAsgnState` will return 0 because `ChkNull(ts->Kywd_ran)` is true, and the new-seed path will call `putSeed`. Inside `putSeed`, `runtime.getRngState()` returns NULL (because `Kywd_ran.vword.bptr` is NULL), and `putSeed` returns −1 — causing the assignment to silently fail rather than seeding the generator as the user intended.

A call to `no_rng_state()` should be inserted here, mirroring what `keyword.r` already does.

How can I resolve this? If you propose a fix, please make it concise.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants