Skip to content

Fix GH-25340: ReflectionEnumBackedCase can be used on a non-backed enum via a constructor trick - #25872

Open
shuhuNB515 wants to merge 1 commit into
php:masterfrom
shuhuNB515:fix-gh-25340
Open

shuhuNB515 wants to merge 1 commit into
php:masterfrom
shuhuNB515:fix-gh-25340

Conversation

@shuhuNB515

Copy link
Copy Markdown

Fixes GH-25340

Problem

When a subclass of ReflectionEnumBackedCase invokes ReflectionClassConstant::__construct() directly (bypassing the backed-enum check in ReflectionEnumBackedCase::__construct()), a subsequent call to getBackingValue() explodes:

<?php
enum NotBacked { case A; }

class FU extends ReflectionEnumBackedCase {
    public function __construct($class, $const) {
        ReflectionClassConstant::__construct($class, $const);
    }
}

(new FU('NotBacked', 'A'))->getBackingValue();
  • Debug build: ZEND_ASSERT(intern->ce->enum_backing_type != IS_UNDEF) fails.
  • Release build: zend_enum_fetch_case_value() reads property slot 1 (OBJ_PROP_NUM(zobj, 1)) of a unit enum case object, which has no such slot — an out-of-bounds read.

Fix

Replace the assertion in ReflectionEnumBackedCase::getBackingValue() with a runtime check that throws a ReflectionException ("Enum case %s::%s is not a backed case"), consistent with the error message thrown by ReflectionEnumBackedCase::__construct() and with the existing IS_UNDEF guard in _enum_case_string().

Verification

  • Reproduced the assertion failure on an unpatched debug build (PHP 8.7.0-dev).
  • With the patch: the repro throws Enum case NotBacked::A is not a backed case.
  • New test ext/reflection/tests/ReflectionEnumBackedCase_getBackingValue_003.phpt covers this.
  • ext/reflection suite: 570 passed, 0 failed.
  • Zend/tests/enum suite: 149 passed, 0 failed.

… enum via a constructor trick

When a subclass of ReflectionEnumBackedCase invokes
ReflectionClassConstant::__construct() directly, the backed-enum check
in ReflectionEnumBackedCase::__construct() is bypassed. A subsequent
call to getBackingValue() then hit a ZEND_ASSERT() in debug builds, and
performed an out-of-bounds property read (via
zend_enum_fetch_case_value()) in release builds, because a unit enum
case object has no backing value slot.

Replace the assertion with a runtime check that throws a
ReflectionException, consistent with the error message thrown by
ReflectionEnumBackedCase::__construct().
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.

ReflectionEnumBackedCase can be used on a non-backed enum via a constructor trick

1 participant