Skip to content

Stdlib: random_bytes() — TypeError + numeric-string length parity (ext/standard/random.c) #4626

Description

@PurHur

Category

stdlib

Problem

random_bytes() exists on VM/JIT/AOT for integer lengths, but argument validation does not match Zend:

  • Non-int/non-numeric-string operands raise LogicException (random_bytes() only supports integers in this compiler build) instead of TypeError.
  • Numeric strings like "16" are rejected; Zend coerces via zend_parse_parameters long handling.
  • Negative/zero lengths should follow Zend (ValueError / TypeError per php-src version).

php-src reference

Repro (failure today)

<?php
declare(strict_types=1);

// happy path (works today)
echo strlen(random_bytes(8)), "\n";

// numeric string — Zend accepts
try {
    echo strlen(random_bytes('16')), "\n";
} catch (Throwable $e) {
    echo 'numeric-string:', get_class($e), ':', $e->getMessage(), "\n";
}

// invalid type — Zend TypeError
try {
    random_bytes([]);
} catch (Throwable $e) {
    echo 'array:', get_class($e), "\n";
}
./script/docker-exec.sh -- bash -lc 'source script/php-env.sh
php repro_random_bytes_type.php
php bin/vm.php repro_random_bytes_type.php
php bin/jit.php repro_random_bytes_type.php
'
Call Zend PHP 8.x This compiler
random_bytes(8) 8 byte string OK
random_bytes('16') 16-byte string LogicException
random_bytes([]) TypeError LogicException

Scope (this repo)

Module Path
VM ext/standard/random_bytes.php, ext/standard/VmString.php
JIT ext/standard/JitRandomBytes.php (or inline in random_bytes::call)
Shared coercion reuse numeric-string helpers from #4176 pattern
Tests test/compliance/cases/stdlib/random_bytes_type.phpt, random_bytes_jit_type.phpt

Done when

  • random_bytes('16') returns 16 bytes on VM/JIT/AOT
  • Non-stringable/non-numeric operand → TypeError (Zend message subset)
  • Invalid length (negative) → ValueError like Zend
  • Existing random_bytes*.phpt still green
  • ./script/ci-fast.sh --filter random_bytes green

Verification

./script/docker-exec.sh -- bash -lc 'source script/php-env.sh && vendor/bin/phpunit --filter random_bytes'

Related

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:compilerCompiler / CFG / JITarea:vmVirtual machineenhancementNew feature or requestimplementation-readySpec complete: repro, php-src ref, done-when — safe for workers to claimphase-4:stdlibPhase 4 – stdlib for web apps

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions