Skip to content

iterator_count runs indefinitely if iterator doesn't complete #8235

Closed

Description

@goodevilgenius

Description

The following code:

<?php
function fibonacci(): Generator
{
    yield $a = 1;
    yield $b = 2;

    start:
    yield $c = $a + $b;
    $a = $b;
    $b = $c;
    goto start;
}

$gen = fibonacci();
iterator_count($gen);

Resulted in this output:

// None. Program stalls

But I expected this output instead:

// some sort of exception

When an iterator never finishes, the iterator_count method simply hangs. This is in contrast to the iterator_to_array method, which throws a fatal error when it runs out of memory. Since iterator_count will continue running, and eventually overflow, no exception is thrown.

This is obviously a tricky situation. But it would be useful if there were some way to detect that an iterator is unlikely to finish, and throw an exception of some sort, rather than simply allowing the program to hang.

I've observed this behavior in multiple versions of PHP (8.0+), as well as multiple operating systems (desktop Linux, Android, and macOS)

PHP Version

8.1.3

Operating System

Darwin 21.3.0

Activity

  1. damianwadley commented on Mar 21, 2022

    @damianwadley
    Member

    Normally this sort of "PHP code runs for a long time without running out of memory due to some infinite loop" problem is covered by the max_execution_time setting. Does that make sense as a solution here too?

  2. cmb69 commented on Mar 21, 2022

    @cmb69
    Member

    Since iterator_count will continue running, and eventually overflow, no exception is thrown.

    I think we need to bail out in case of overflow:

    (*(zend_long*)puser)++;

    While that may not happen in practice, wrapping around certainly makes no sense.

  3. added a commit that references this issue on Apr 27, 2022
    56c55bc
  4. self-assigned this
    on Apr 27, 2022
  5. added 2 commits that reference this issue on May 3, 2022
    e004e1a
    e5d9859
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions