php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #81514 Using Enum as key in WeakMap triggers GC + SegFault
Submitted: 2021-10-08 04:25 UTC Modified: 2021-10-08 08:11 UTC
From: james at lucas dot net dot au Assigned:
Status: Closed Package: Reproducible crash
PHP Version: 8.1.0RC3 OS: MacOS/Linux
Private report: No CVE-ID: None
 [2021-10-08 04:25 UTC] james at lucas dot net dot au
Description:
------------
Enum keys in WeakMaps are Garbage collected after first retrieval (via offsetGet or foreach) which should not occur as they are singletons (per https://wiki.php.net/rfc/enumerations#splobjectstorage_and_weakmaps).

After the Enum is gone from the WeakMap an additional offsetGet for the Enum key triggers a Segfault instead of Object TestEnum#1 not contained in WeakMap.

This does not occur when using plain objects

Test script:
---------------
<?php declare(strict_types=1);

echo 'WeakMap with object as key' . PHP_EOL;
$map = new WeakMap();
$obj1 = new stdClass();
$map->offsetSet($obj1, 'string');
echo 'Map contains ' . count($map) . ' objects' . PHP_EOL;
$map->offsetGet($obj1);
echo 'Map contains ' . count($map) . ' objects' . PHP_EOL . PHP_EOL;
$map->offsetGet($obj1);

echo 'WeakMap with Enum as key' . PHP_EOL;
enum TestEnum {
    case A;
}
$map = new WeakMap();

$map->offsetSet(TestEnum::A, 'a string');
echo 'Map contains ' . count($map) . ' objects' . PHP_EOL;
$map->offsetGet(TestEnum::A);
echo 'Map contains ' . count($map) . ' objects' . PHP_EOL . PHP_EOL; // <-- Map will no longer contain ENUM
$map->offsetGet(TestEnum::A); // <-- Segfault Here
echo "done";

Expected result:
----------------
WeakMap with object as key
Map contains 1 objects
Map contains 1 objects

WeakMap with Enum as key
Map contains 1 objects
Map contains 1 objects

done


Actual result:
--------------
WeakMap with object as key
Map contains 1 objects
Map contains 1 objects

WeakMap with Enum as key
Map contains 1 objects
Map contains 0 objects

Segmentation fault: 11


Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2021-10-08 08:11 UTC] nikic@php.net
-Status: Open +Status: Verified
 [2021-10-08 08:33 UTC] git@php.net
Automatic comment on behalf of nikic
Revision: https://github.com/php/php-src/commit/bd3e5363836df9c7d05b74f6c7bc53ccc145c535
Log: Fixed bug #81514
 [2021-10-08 08:33 UTC] git@php.net
-Status: Verified +Status: Closed
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Nov 21 08:01:29 2024 UTC