1/*
2   +----------------------------------------------------------------------+
3   | Zend Engine                                                          |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1998-2015 Zend Technologies Ltd. (http://www.zend.com) |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 2.00 of the Zend license,     |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.zend.com/license/2_00.txt.                                |
11   | If you did not receive a copy of the Zend license and are unable to  |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@zend.com so we can mail you a copy immediately.              |
14   +----------------------------------------------------------------------+
15   | Authors: Nikita Popov <nikic@php.net>                                |
16   |          Bob Weinand <bobwei9@hotmail.com>                           |
17   +----------------------------------------------------------------------+
18*/
19
20/* $Id$ */
21
22#include "zend.h"
23#include "zend_API.h"
24#include "zend_interfaces.h"
25#include "zend_exceptions.h"
26#include "zend_generators.h"
27
28ZEND_API zend_class_entry *zend_ce_generator;
29ZEND_API zend_class_entry *zend_ce_ClosedGeneratorException;
30static zend_object_handlers zend_generator_handlers;
31
32static zend_object *zend_generator_create(zend_class_entry *class_type);
33
34static void zend_generator_cleanup_unfinished_execution(zend_generator *generator) /* {{{ */
35{
36    zend_execute_data *execute_data = generator->execute_data;
37
38    if (generator->send_target) {
39        Z_TRY_DELREF_P(generator->send_target);
40        generator->send_target = NULL;
41    }
42
43    if (execute_data->opline != execute_data->func->op_array.opcodes) {
44        /* -1 required because we want the last run opcode, not the next to-be-run one. */
45        uint32_t op_num = execute_data->opline - execute_data->func->op_array.opcodes - 1;
46
47        /* There may be calls to zend_vm_stack_free_call_frame(), which modifies the VM stack
48         * globals, so need to load/restore those. */
49        zend_vm_stack original_stack = EG(vm_stack);
50        original_stack->top = EG(vm_stack_top);
51        EG(vm_stack_top) = generator->stack->top;
52        EG(vm_stack_end) = generator->stack->end;
53        EG(vm_stack) = generator->stack;
54
55        zend_cleanup_unfinished_execution(execute_data, op_num, 0);
56
57        generator->stack = EG(vm_stack);
58        generator->stack->top = EG(vm_stack_top);
59        EG(vm_stack_top) = original_stack->top;
60        EG(vm_stack_end) = original_stack->end;
61        EG(vm_stack) = original_stack;
62    }
63}
64/* }}} */
65
66ZEND_API void zend_generator_close(zend_generator *generator, zend_bool finished_execution) /* {{{ */
67{
68    if (Z_TYPE(generator->value) != IS_UNDEF) {
69        zval_ptr_dtor(&generator->value);
70        ZVAL_UNDEF(&generator->value);
71    }
72
73    if (Z_TYPE(generator->key) != IS_UNDEF) {
74        zval_ptr_dtor(&generator->key);
75        ZVAL_UNDEF(&generator->key);
76    }
77
78    if (Z_TYPE(generator->values) != IS_UNDEF) {
79        zval_ptr_dtor(&generator->values);
80        ZVAL_UNDEF(&generator->values);
81    }
82
83    if (generator->execute_data) {
84        zend_execute_data *execute_data = generator->execute_data;
85
86        if (execute_data->symbol_table) {
87            zend_clean_and_cache_symbol_table(execute_data->symbol_table);
88        }
89        /* always free the CV's, in the symtable are only not-free'd IS_INDIRECT's */
90        zend_free_compiled_variables(execute_data);
91
92        if (Z_OBJ(execute_data->This)) {
93            OBJ_RELEASE(Z_OBJ(execute_data->This));
94        }
95
96        /* A fatal error / die occurred during the generator execution. Trying to clean
97         * up the stack may not be safe in this case. */
98        if (CG(unclean_shutdown)) {
99            generator->execute_data = NULL;
100            return;
101        }
102
103        zend_vm_stack_free_extra_args(generator->execute_data);
104
105        /* Some cleanups are only necessary if the generator was closued
106         * before it could finish execution (reach a return statement). */
107        if (!finished_execution) {
108            zend_generator_cleanup_unfinished_execution(generator);
109        }
110
111        /* Free closure object */
112        if (EX_CALL_INFO() & ZEND_CALL_CLOSURE) {
113            OBJ_RELEASE((zend_object *) EX(func)->common.prototype);
114        }
115
116        efree(generator->stack);
117        generator->execute_data = NULL;
118    }
119}
120/* }}} */
121
122static void zend_generator_dtor_storage(zend_object *object) /* {{{ */
123{
124    zend_generator *generator = (zend_generator*) object;
125    zend_execute_data *ex = generator->execute_data;
126    uint32_t op_num, finally_op_num, finally_op_end;
127    int i;
128
129    if (!ex || !(ex->func->op_array.fn_flags & ZEND_ACC_HAS_FINALLY_BLOCK)) {
130        return;
131    }
132
133    /* -1 required because we want the last run opcode, not the
134     * next to-be-run one. */
135    op_num = ex->opline - ex->func->op_array.opcodes - 1;
136
137    /* Find next finally block */
138    finally_op_num = 0;
139    finally_op_end = 0;
140    for (i = 0; i < ex->func->op_array.last_try_catch; i++) {
141        zend_try_catch_element *try_catch = &ex->func->op_array.try_catch_array[i];
142
143        if (op_num < try_catch->try_op) {
144            break;
145        }
146
147        if (op_num < try_catch->finally_op) {
148            finally_op_num = try_catch->finally_op;
149            finally_op_end = try_catch->finally_end;
150        }
151    }
152
153    /* If a finally block was found we jump directly to it and
154     * resume the generator. */
155    if (finally_op_num) {
156        zval *fast_call = ZEND_CALL_VAR(ex, ex->func->op_array.opcodes[finally_op_end].op1.var);
157
158        Z_OBJ_P(fast_call) = EG(exception);
159        EG(exception) = NULL;
160        fast_call->u2.lineno = (uint32_t)-1;
161
162        ex->opline = &ex->func->op_array.opcodes[finally_op_num];
163        generator->flags |= ZEND_GENERATOR_FORCED_CLOSE;
164        zend_generator_resume(generator);
165    }
166}
167/* }}} */
168
169static zend_generator *zend_generator_get_child(zend_generator_node *node, zend_generator *leaf);
170
171static void zend_generator_free_storage(zend_object *object) /* {{{ */
172{
173    zend_generator *generator = (zend_generator*) object;
174
175    zend_generator_close(generator, 0);
176
177    if (!Z_ISUNDEF(generator->retval)) {
178        zval_ptr_dtor(&generator->retval);
179    }
180
181    if (generator->node.children > 4) {
182        zend_hash_destroy(&generator->node.child.ht);
183    }
184
185    zend_object_std_dtor(&generator->std);
186
187    if (generator->iterator) {
188        zend_iterator_dtor(generator->iterator);
189    }
190
191    if (generator->node.children == 0) {
192        zend_generator *root = generator->node.ptr.root, *next;
193        while (root != generator) {
194            next = zend_generator_get_child(&root->node, generator);
195            OBJ_RELEASE(&root->std);
196            root = next;
197        }
198    }
199}
200/* }}} */
201
202static zend_object *zend_generator_create(zend_class_entry *class_type) /* {{{ */
203{
204    zend_generator *generator;
205
206    generator = emalloc(sizeof(zend_generator));
207    memset(generator, 0, sizeof(zend_generator));
208
209    /* The key will be incremented on first use, so it'll start at 0 */
210    generator->largest_used_integer_key = -1;
211
212    ZVAL_UNDEF(&generator->retval);
213    ZVAL_UNDEF(&generator->values);
214
215    /* By default we have a tree of only one node */
216    generator->node.parent = NULL;
217    generator->node.children = 0;
218    generator->node.ptr.root = generator;
219
220    zend_object_std_init(&generator->std, class_type);
221    generator->std.handlers = &zend_generator_handlers;
222
223    return (zend_object*)generator;
224}
225/* }}} */
226
227/* Requires globals EG(scope), EG(This) and EG(current_execute_data). */
228ZEND_API void zend_generator_create_zval(zend_execute_data *call, zend_op_array *op_array, zval *return_value) /* {{{ */
229{
230    zend_generator *generator;
231    zend_execute_data *current_execute_data;
232    zend_execute_data *execute_data;
233    zend_vm_stack current_stack = EG(vm_stack);
234
235    current_stack->top = EG(vm_stack_top);
236
237    /* Create new execution context. We have to back up and restore
238     * EG(current_execute_data) here. */
239    current_execute_data = EG(current_execute_data);
240    execute_data = zend_create_generator_execute_data(call, op_array, return_value);
241    EG(current_execute_data) = current_execute_data;
242
243    object_init_ex(return_value, zend_ce_generator);
244
245    if (Z_OBJ(call->This)) {
246        Z_ADDREF(call->This);
247    }
248
249    /* Save execution context in generator object. */
250    generator = (zend_generator *) Z_OBJ_P(return_value);
251    generator->execute_data = execute_data;
252    generator->stack = EG(vm_stack);
253    generator->stack->top = EG(vm_stack_top);
254    EG(vm_stack_top) = current_stack->top;
255    EG(vm_stack_end) = current_stack->end;
256    EG(vm_stack) = current_stack;
257
258    /* EX(return_value) keeps pointer to zend_object (not a real zval) */
259    execute_data->return_value = (zval*)generator;
260
261    memset(&generator->execute_fake, 0, sizeof(zend_execute_data));
262    Z_OBJ(generator->execute_fake.This) = (zend_object *) generator;
263}
264/* }}} */
265
266static ZEND_COLD zend_function *zend_generator_get_constructor(zend_object *object) /* {{{ */
267{
268    zend_throw_error(NULL, "The \"Generator\" class is reserved for internal use and cannot be manually instantiated");
269
270    return NULL;
271}
272/* }}} */
273
274ZEND_API zend_execute_data *zend_generator_check_placeholder_frame(zend_execute_data *ptr)
275{
276    if (!ptr->func && Z_OBJ(ptr->This)) {
277        if (Z_OBJCE(ptr->This) == zend_ce_generator) {
278            zend_generator *generator = (zend_generator *) Z_OBJ(ptr->This);
279            zend_generator *root = (generator->node.children < 1 ? generator : generator->node.ptr.leaf)->node.ptr.root;
280            zend_execute_data *prev = ptr->prev_execute_data;
281            if (generator->node.parent != root) {
282                do {
283                    generator->execute_data->prev_execute_data = prev;
284                    prev = generator->execute_data;
285                    generator = generator->node.parent;
286                } while (generator->node.parent != root);
287            }
288            generator->execute_data->prev_execute_data = prev;
289            ptr = generator->execute_data;
290        }
291    }
292    return ptr;
293}
294
295static void zend_generator_throw_exception(zend_generator *generator, zval *exception)
296{
297    /* Throw the exception in the context of the generator. Decrementing the opline
298     * to pretend the exception happened during the YIELD opcode. */
299    zend_execute_data *original_execute_data = EG(current_execute_data);
300    EG(current_execute_data) = generator->execute_data;
301    generator->execute_data->opline--;
302    if (exception) {
303        zend_throw_exception_object(exception);
304    } else {
305        zend_throw_exception_internal(NULL);
306    }
307    generator->execute_data->opline++;
308    EG(current_execute_data) = original_execute_data;
309}
310
311static zend_generator *zend_generator_get_child(zend_generator_node *node, zend_generator *leaf)
312{
313    switch (node->children) {
314        case 0:
315            return NULL;
316        case 1:
317            return node->child.array[0].child;
318
319#define ZEND_GEN_GET_CHILD(x) \
320            if (node->child.array[x].leaf == leaf) { \
321                return node->child.array[x].child; \
322            }
323        case 4:
324            ZEND_GEN_GET_CHILD(3)
325        case 3:
326            ZEND_GEN_GET_CHILD(2)
327        case 2:
328            ZEND_GEN_GET_CHILD(1)
329            ZEND_GEN_GET_CHILD(0)
330            ZEND_ASSERT(0); // we never should have no matching child
331    }
332
333    return zend_hash_index_find_ptr(&node->child.ht, (zend_ulong) leaf);
334}
335
336static zend_generator_node *zend_generator_search_multi_children_node(zend_generator_node *node)
337{
338    while (node->children == 1) {
339        node = &node->child.array[0].child->node;
340    }
341    return node->children > 1 ? node : NULL;
342}
343
344static void zend_generator_add_single_child(zend_generator_node *node, zend_generator *child, zend_generator *leaf)
345{
346    if (node->children < 4) {
347        node->child.array[node->children].leaf = leaf;
348        node->child.array[node->children].child = child;
349    } else if (node->children > 4) {
350        zend_hash_index_add_ptr(&node->child.ht, (zend_ulong) leaf, child);
351    } else {
352        struct {
353            zend_generator *leaf;
354            zend_generator *child;
355        } array[4];
356        int i;
357
358        memcpy(&array, &node->child.array, sizeof(array));
359        zend_hash_init(&node->child.ht, 5, sigh, NULL, 0);
360        for (i = 0; i < 4; i++) {
361            zend_hash_index_add_ptr(&node->child.ht, (zend_ulong) array[i].leaf, array[i].child);
362        }
363        zend_hash_index_add_ptr(&node->child.ht, (zend_ulong) leaf, child);
364    }
365
366    node->children++;
367}
368
369static void zend_generator_merge_child_nodes(zend_generator_node *dest, zend_generator_node *src, zend_generator *child)
370{
371    if (src->children <= 4) {
372        int i = src->children;
373        while (i--) {
374            zend_generator_add_single_child(dest, child, src->child.array[i].leaf);
375        }
376    } else {
377        zend_ulong leaf;
378        ZEND_HASH_FOREACH_NUM_KEY(&src->child.ht, leaf) {
379            zend_generator_add_single_child(dest, child, (zend_generator *) leaf);
380        } ZEND_HASH_FOREACH_END();
381    }
382}
383
384/* Make attention so that the root of each subtree of the Generators tree is referenced once per leaf */
385static void zend_generator_add_child(zend_generator *generator, zend_generator *child)
386{
387    zend_generator *leaf = child->node.children ? child->node.ptr.leaf : child;
388    zend_generator_node *multi_children_node;
389    zend_bool was_leaf = generator->node.children == 0;
390
391    if (was_leaf) {
392        zend_generator *next = generator->node.parent;
393        leaf->node.ptr.root = generator->node.ptr.root;
394        ++GC_REFCOUNT(&generator->std); /* we need to increment the generator refcount here as it became integrated into the tree (no leaf), but we must not increment the refcount of the *whole* path in tree */
395        generator->node.ptr.leaf = leaf;
396
397        while (next) {
398            if (next->node.children > 1) {
399                if (next->node.children > 4) {
400                    zend_generator *child = zend_hash_index_find_ptr(&next->node.child.ht, (zend_ulong) generator);
401                    zend_hash_index_del(&next->node.child.ht, (zend_ulong) generator);
402                    zend_hash_index_add_ptr(&next->node.child.ht, (zend_ulong) leaf, child);
403                } else {
404                    switch (next->node.children) {
405#define ZEND_GEN_UPDATE_CHILD(x) \
406                            if (next->node.child.array[x].leaf == generator) { \
407                                next->node.child.array[x].leaf = leaf; \
408                                break; \
409                            }
410                        case 4:
411                            ZEND_GEN_UPDATE_CHILD(3)
412                        case 3:
413                            ZEND_GEN_UPDATE_CHILD(2)
414                        case 2:
415                            ZEND_GEN_UPDATE_CHILD(1)
416                            ZEND_GEN_UPDATE_CHILD(0)
417                            ZEND_ASSERT(0); // we never should have no matching child
418                    }
419                }
420            }
421
422            next->node.ptr.leaf = leaf;
423            next = next->node.parent;
424        }
425
426        zend_generator_add_single_child(&generator->node, child, leaf);
427    } else if (generator->node.children == 1) {
428        multi_children_node = zend_generator_search_multi_children_node(&generator->node);
429        if (multi_children_node) {
430            generator->node.children = 0;
431            zend_generator_merge_child_nodes(&generator->node, multi_children_node, generator->node.child.array[0].child);
432        }
433    }
434
435    if (!was_leaf) {
436        multi_children_node = zend_generator_search_multi_children_node(&child->node);
437    } else {
438        multi_children_node = (zend_generator_node *) 0x1;
439    }
440
441    {
442        zend_generator *parent = generator->node.parent, *cur = generator;
443
444        if (multi_children_node > (zend_generator_node *) 0x1) {
445            zend_generator_merge_child_nodes(&generator->node, multi_children_node, child);
446        } else {
447            zend_generator_add_single_child(&generator->node, child, leaf);
448        }
449        while (parent) {
450            if (parent->node.children > 1) {
451                if (multi_children_node == (zend_generator_node *) 0x1) {
452                    multi_children_node = zend_generator_search_multi_children_node(&child->node);
453                }
454                if (multi_children_node) {
455                    zend_generator_merge_child_nodes(&parent->node, multi_children_node, cur);
456                } else {
457                    zend_generator_add_single_child(&parent->node, cur, leaf);
458                }
459            }
460            cur = parent;
461            parent = parent->node.parent;
462        }
463    }
464}
465
466void zend_generator_yield_from(zend_generator *generator, zend_generator *from)
467{
468    zend_generator_add_child(from, generator);
469
470    generator->node.parent = from;
471    zend_generator_get_current(generator);
472    --GC_REFCOUNT(&from->std);
473}
474
475ZEND_API zend_generator *zend_generator_get_current(zend_generator *generator)
476{
477    zend_generator *leaf;
478    zend_generator *root, *old_root;
479
480    if (generator->node.parent == NULL) {
481        /* we're not in yield from mode */
482        return generator;
483    }
484
485    leaf = generator->node.children ? generator->node.ptr.leaf : generator;
486    root = leaf->node.ptr.root;
487
488    if (root->execute_data && root->node.parent == NULL) {
489        /* generator still running */
490        return root;
491    }
492
493    /* generator at the root had stopped */
494    if (root != generator) {
495        old_root = root;
496        root = zend_generator_get_child(&root->node, leaf);
497    } else {
498        old_root = NULL;
499    }
500
501    while (!root->execute_data && root != generator) {
502        OBJ_RELEASE(&old_root->std);
503        old_root = root;
504
505        root = zend_generator_get_child(&root->node, leaf);
506    }
507
508    if (root->node.parent) {
509        if (root->node.parent->execute_data == NULL) {
510            if (EXPECTED(EG(exception) == NULL)) {
511                zend_op *yield_from = (zend_op *) root->execute_data->opline - 1;
512
513                if (yield_from->opcode == ZEND_YIELD_FROM && !(yield_from->result_type & EXT_TYPE_UNUSED)) {
514                    if (Z_ISUNDEF(root->node.parent->retval)) {
515                        /* Throw the exception in the context of the generator */
516                        zend_execute_data *original_execute_data = EG(current_execute_data);
517                        EG(current_execute_data) = root->execute_data;
518
519                        if (root == generator) {
520                            root->execute_data->prev_execute_data = original_execute_data;
521                        } else {
522                            root->execute_data->prev_execute_data = &generator->execute_fake;
523                            generator->execute_fake.prev_execute_data = original_execute_data;
524                        }
525
526                        zend_throw_exception(zend_ce_ClosedGeneratorException, "Generator yielded from aborted, no return value available", 0);
527
528                        EG(current_execute_data) = original_execute_data;
529                    } else {
530                        ZVAL_COPY(ZEND_CALL_VAR(root->execute_data, yield_from->result.var), &root->node.parent->retval);
531                    }
532                }
533            }
534
535            root->node.parent = NULL;
536        } else {
537            do {
538                root = root->node.parent;
539                ++GC_REFCOUNT(&root->std);
540            } while (root->node.parent);
541        }
542    }
543
544    if (old_root) {
545        OBJ_RELEASE(&old_root->std);
546    }
547
548    return leaf->node.ptr.root = root;
549}
550
551static int zend_generator_get_next_delegated_value(zend_generator *generator) /* {{{ */
552{
553    zval *value;
554    if (Z_TYPE(generator->values) == IS_ARRAY) {
555        HashTable *ht = Z_ARR(generator->values);
556        HashPosition pos = Z_FE_POS(generator->values);
557
558        Bucket *p;
559        do {
560            if (UNEXPECTED(pos >= ht->nNumUsed)) {
561                /* Reached end of array */
562                goto failure;
563            }
564
565            p = &ht->arData[pos];
566            value = &p->val;
567            if (Z_TYPE_P(value) == IS_INDIRECT) {
568                value = Z_INDIRECT_P(value);
569            }
570            pos++;
571        } while (Z_ISUNDEF_P(value));
572
573        zval_ptr_dtor(&generator->value);
574        ZVAL_COPY(&generator->value, value);
575
576        zval_ptr_dtor(&generator->key);
577        if (p->key) {
578            ZVAL_STR_COPY(&generator->key, p->key);
579        } else {
580            ZVAL_LONG(&generator->key, p->h);
581        }
582
583        Z_FE_POS(generator->values) = pos;
584    } else {
585        zend_object_iterator *iter = (zend_object_iterator *) Z_OBJ(generator->values);
586
587        if (iter->index++ > 0) {
588            iter->funcs->move_forward(iter);
589            if (UNEXPECTED(EG(exception) != NULL)) {
590                goto failure;
591            }
592        }
593
594        if (iter->funcs->valid(iter) == FAILURE) {
595            /* reached end of iteration */
596            goto failure;
597        }
598
599        value = iter->funcs->get_current_data(iter);
600        if (UNEXPECTED(EG(exception) != NULL || !value)) {
601            goto failure;
602        }
603
604        zval_ptr_dtor(&generator->value);
605        ZVAL_COPY(&generator->value, value);
606
607        zval_ptr_dtor(&generator->key);
608        if (iter->funcs->get_current_key) {
609            iter->funcs->get_current_key(iter, &generator->key);
610            if (UNEXPECTED(EG(exception) != NULL)) {
611                ZVAL_UNDEF(&generator->key);
612                goto failure;
613            }
614        } else {
615            ZVAL_LONG(&generator->key, iter->index);
616        }
617    }
618    return SUCCESS;
619
620failure:
621    zval_ptr_dtor(&generator->values);
622    ZVAL_UNDEF(&generator->values);
623    return FAILURE;
624}
625/* }}} */
626
627ZEND_API void zend_generator_resume(zend_generator *orig_generator) /* {{{ */
628{
629    zend_generator *generator;
630
631    /* The generator is already closed, thus can't resume */
632    if (!orig_generator->execute_data) {
633        return;
634    }
635
636    generator = zend_generator_get_current(orig_generator);
637
638try_again:
639    if (generator->flags & ZEND_GENERATOR_CURRENTLY_RUNNING) {
640        zend_throw_error(NULL, "Cannot resume an already running generator");
641        return;
642    }
643
644    if (!Z_ISUNDEF(generator->values)) {
645        if (zend_generator_get_next_delegated_value(generator) == SUCCESS) {
646            return;
647        }
648        /* If there are no more deletegated values, resume the generator
649         * after the "yield from" expression. */
650    }
651
652    if ((orig_generator->flags & ZEND_GENERATOR_DO_INIT) && !Z_ISUNDEF(generator->value)) {
653        /* We must not advance Generator if we yield from a Generator being currently run */
654        return;
655    }
656
657    /* Drop the AT_FIRST_YIELD flag */
658    orig_generator->flags &= ~ZEND_GENERATOR_AT_FIRST_YIELD;
659
660    {
661        /* Backup executor globals */
662        zend_execute_data *original_execute_data = EG(current_execute_data);
663        zend_class_entry *original_scope = EG(scope);
664        zend_vm_stack original_stack = EG(vm_stack);
665        original_stack->top = EG(vm_stack_top);
666
667        /* Set executor globals */
668        EG(current_execute_data) = generator->execute_data;
669        EG(scope) = generator->execute_data->func->common.scope;
670        EG(vm_stack_top) = generator->stack->top;
671        EG(vm_stack_end) = generator->stack->end;
672        EG(vm_stack) = generator->stack;
673
674        /* We want the backtrace to look as if the generator function was
675         * called from whatever method we are current running (e.g. next()).
676         * So we have to link generator call frame with caller call frame. */
677        if (generator == orig_generator) {
678            generator->execute_data->prev_execute_data = original_execute_data;
679        } else {
680            /* We need some execute_data placeholder in stacktrace to be replaced
681             * by the real stack trace when needed */
682            generator->execute_data->prev_execute_data = &orig_generator->execute_fake;
683            orig_generator->execute_fake.prev_execute_data = original_execute_data;
684        }
685
686        /* Resume execution */
687        generator->flags |= ZEND_GENERATOR_CURRENTLY_RUNNING;
688        zend_execute_ex(generator->execute_data);
689        generator->flags &= ~ZEND_GENERATOR_CURRENTLY_RUNNING;
690
691        /* Unlink generator call_frame from the caller and backup vm_stack_top */
692        if (generator->execute_data) {
693            generator->stack = EG(vm_stack);
694            generator->stack->top = EG(vm_stack_top);
695        }
696
697        /* Restore executor globals */
698        EG(current_execute_data) = original_execute_data;
699        EG(scope) = original_scope;
700        EG(vm_stack_top) = original_stack->top;
701        EG(vm_stack_end) = original_stack->end;
702        EG(vm_stack) = original_stack;
703
704        /* If an exception was thrown in the generator we have to internally
705         * rethrow it in the parent scope.
706         * In case we did yield from, the Exception must be rethrown into
707         * its calling frame (see above in if (check_yield_from). */
708        if (UNEXPECTED(EG(exception) != NULL)) {
709            if (generator == orig_generator) {
710                zend_generator_close(generator, 0);
711                zend_throw_exception_internal(NULL);
712            } else {
713                generator = zend_generator_get_current(orig_generator);
714                zend_generator_throw_exception(generator, NULL);
715                goto try_again;
716            }
717        }
718
719        /* yield from was used, try another resume. */
720        if ((generator != orig_generator && !Z_ISUNDEF(generator->retval)) || (generator->execute_data && (generator->execute_data->opline - 1)->opcode == ZEND_YIELD_FROM)) {
721            generator = zend_generator_get_current(orig_generator);
722            goto try_again;
723        }
724    }
725}
726/* }}} */
727
728static void zend_generator_ensure_initialized(zend_generator *generator) /* {{{ */
729{
730    if (generator->execute_data && Z_TYPE(generator->value) == IS_UNDEF && generator->node.parent == NULL) {
731        generator->flags |= ZEND_GENERATOR_DO_INIT;
732        zend_generator_resume(generator);
733        generator->flags &= ~ZEND_GENERATOR_DO_INIT;
734        generator->flags |= ZEND_GENERATOR_AT_FIRST_YIELD;
735    }
736}
737/* }}} */
738
739static void zend_generator_rewind(zend_generator *generator) /* {{{ */
740{
741    zend_generator_ensure_initialized(generator);
742
743    if (!(generator->flags & ZEND_GENERATOR_AT_FIRST_YIELD)) {
744        zend_throw_exception(NULL, "Cannot rewind a generator that was already run", 0);
745    }
746}
747/* }}} */
748
749/* {{{ proto void Generator::rewind()
750 * Rewind the generator */
751ZEND_METHOD(Generator, rewind)
752{
753    zend_generator *generator;
754
755    if (zend_parse_parameters_none() == FAILURE) {
756        return;
757    }
758
759    generator = (zend_generator *) Z_OBJ_P(getThis());
760
761    zend_generator_rewind(generator);
762}
763/* }}} */
764
765/* {{{ proto bool Generator::valid()
766 * Check whether the generator is valid */
767ZEND_METHOD(Generator, valid)
768{
769    zend_generator *generator;
770
771    if (zend_parse_parameters_none() == FAILURE) {
772        return;
773    }
774
775    generator = (zend_generator *) Z_OBJ_P(getThis());
776
777    zend_generator_ensure_initialized(generator);
778
779    zend_generator_get_current(generator);
780
781    RETURN_BOOL(Z_TYPE(generator->value) != IS_UNDEF || generator->node.parent != NULL);
782}
783/* }}} */
784
785/* {{{ proto mixed Generator::current()
786 * Get the current value */
787ZEND_METHOD(Generator, current)
788{
789    zend_generator *generator, *root;
790
791    if (zend_parse_parameters_none() == FAILURE) {
792        return;
793    }
794
795    generator = (zend_generator *) Z_OBJ_P(getThis());
796
797    zend_generator_ensure_initialized(generator);
798
799    root = zend_generator_get_current(generator);
800    if (Z_TYPE(root->value) != IS_UNDEF) {
801        zval *value = &root->value;
802
803        ZVAL_DEREF(value);
804        ZVAL_COPY(return_value, value);
805    }
806}
807/* }}} */
808
809/* {{{ proto mixed Generator::key()
810 * Get the current key */
811ZEND_METHOD(Generator, key)
812{
813    zend_generator *generator, *root;
814
815    if (zend_parse_parameters_none() == FAILURE) {
816        return;
817    }
818
819    generator = (zend_generator *) Z_OBJ_P(getThis());
820
821    zend_generator_ensure_initialized(generator);
822
823    root = zend_generator_get_current(generator);
824    if (Z_TYPE(root->key) != IS_UNDEF) {
825        zval *key = &root->key;
826
827        ZVAL_DEREF(key);
828        ZVAL_COPY(return_value, key);
829    }
830}
831/* }}} */
832
833/* {{{ proto void Generator::next()
834 * Advances the generator */
835ZEND_METHOD(Generator, next)
836{
837    zend_generator *generator;
838
839    if (zend_parse_parameters_none() == FAILURE) {
840        return;
841    }
842
843    generator = (zend_generator *) Z_OBJ_P(getThis());
844
845    zend_generator_ensure_initialized(generator);
846
847    zend_generator_resume(generator);
848}
849/* }}} */
850
851/* {{{ proto mixed Generator::send(mixed value)
852 * Sends a value to the generator */
853ZEND_METHOD(Generator, send)
854{
855    zval *value;
856    zend_generator *generator, *root;
857
858    if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &value) == FAILURE) {
859        return;
860    }
861
862    generator = (zend_generator *) Z_OBJ_P(getThis());
863
864    zend_generator_ensure_initialized(generator);
865
866    /* The generator is already closed, thus can't send anything */
867    if (!generator->execute_data) {
868        return;
869    }
870
871    root = zend_generator_get_current(generator);
872    /* Put sent value in the target VAR slot, if it is used */
873    if (root->send_target) {
874        if (Z_REFCOUNTED_P(root->send_target)) Z_DELREF_P(root->send_target);
875        ZVAL_COPY(root->send_target, value);
876    }
877
878    zend_generator_resume(generator);
879
880    root = zend_generator_get_current(generator);
881    if (Z_TYPE(root->value) != IS_UNDEF) {
882        zval *value = &root->value;
883
884        ZVAL_DEREF(value);
885        ZVAL_COPY(return_value, value);
886    }
887}
888/* }}} */
889
890/* {{{ proto mixed Generator::throw(Exception exception)
891 * Throws an exception into the generator */
892ZEND_METHOD(Generator, throw)
893{
894    zval *exception, exception_copy;
895    zend_generator *generator;
896
897    if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &exception) == FAILURE) {
898        return;
899    }
900
901    ZVAL_DUP(&exception_copy, exception);
902
903    generator = (zend_generator *) Z_OBJ_P(getThis());
904
905    zend_generator_ensure_initialized(generator);
906
907    if (generator->execute_data) {
908        zend_generator *root = zend_generator_get_current(generator);
909
910        zend_generator_throw_exception(root, &exception_copy);
911
912        zend_generator_resume(generator);
913
914        root = zend_generator_get_current(generator);
915        if (Z_TYPE(root->value) != IS_UNDEF) {
916            zval *value = &root->value;
917
918            ZVAL_DEREF(value);
919            ZVAL_COPY(return_value, value);
920        }
921    } else {
922        /* If the generator is already closed throw the exception in the
923         * current context */
924        zend_throw_exception_object(&exception_copy);
925    }
926}
927/* }}} */
928
929/* {{{ proto mixed Generator::getReturn()
930 * Retrieves the return value of the generator */
931ZEND_METHOD(Generator, getReturn)
932{
933    zend_generator *generator;
934
935    if (zend_parse_parameters_none() == FAILURE) {
936        return;
937    }
938
939    generator = (zend_generator *) Z_OBJ_P(getThis());
940
941    zend_generator_ensure_initialized(generator);
942    if (EG(exception)) {
943        return;
944    }
945
946    if (Z_ISUNDEF(generator->retval)) {
947        /* Generator hasn't returned yet -> error! */
948        zend_throw_exception(NULL,
949            "Cannot get return value of a generator that hasn't returned", 0);
950        return;
951    }
952
953    ZVAL_COPY(return_value, &generator->retval);
954}
955/* }}} */
956
957/* {{{ proto void Generator::__wakeup()
958 * Throws an Exception as generators can't be serialized */
959ZEND_METHOD(Generator, __wakeup)
960{
961    /* Just specifying the zend_class_unserialize_deny handler is not enough,
962     * because it is only invoked for C unserialization. For O the error has
963     * to be thrown in __wakeup. */
964
965    if (zend_parse_parameters_none() == FAILURE) {
966        return;
967    }
968
969    zend_throw_exception(NULL, "Unserialization of 'Generator' is not allowed", 0);
970}
971/* }}} */
972
973/* get_iterator implementation */
974
975static void zend_generator_iterator_dtor(zend_object_iterator *iterator) /* {{{ */
976{
977    zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
978    generator->iterator = NULL;
979    zval_ptr_dtor(&iterator->data);
980    zend_iterator_dtor(iterator);
981}
982/* }}} */
983
984static int zend_generator_iterator_valid(zend_object_iterator *iterator) /* {{{ */
985{
986    zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
987
988    zend_generator_ensure_initialized(generator);
989
990    zend_generator_get_current(generator);
991
992    return Z_TYPE(generator->value) != IS_UNDEF || generator->node.parent != NULL ? SUCCESS : FAILURE;
993}
994/* }}} */
995
996static zval *zend_generator_iterator_get_data(zend_object_iterator *iterator) /* {{{ */
997{
998    zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data), *root;
999
1000    zend_generator_ensure_initialized(generator);
1001
1002    root = zend_generator_get_current(generator);
1003
1004    return &root->value;
1005}
1006/* }}} */
1007
1008static void zend_generator_iterator_get_key(zend_object_iterator *iterator, zval *key) /* {{{ */
1009{
1010    zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data), *root;
1011
1012    zend_generator_ensure_initialized(generator);
1013
1014    root = zend_generator_get_current(generator);
1015
1016    if (Z_TYPE(root->key) != IS_UNDEF) {
1017        zval *zv = &root->key;
1018
1019        ZVAL_DEREF(zv);
1020        ZVAL_COPY(key, zv);
1021    } else {
1022        ZVAL_NULL(key);
1023    }
1024}
1025/* }}} */
1026
1027static void zend_generator_iterator_move_forward(zend_object_iterator *iterator) /* {{{ */
1028{
1029    zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1030
1031    zend_generator_ensure_initialized(generator);
1032
1033    zend_generator_resume(generator);
1034}
1035/* }}} */
1036
1037static void zend_generator_iterator_rewind(zend_object_iterator *iterator) /* {{{ */
1038{
1039    zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1040
1041    zend_generator_rewind(generator);
1042}
1043/* }}} */
1044
1045static zend_object_iterator_funcs zend_generator_iterator_functions = {
1046    zend_generator_iterator_dtor,
1047    zend_generator_iterator_valid,
1048    zend_generator_iterator_get_data,
1049    zend_generator_iterator_get_key,
1050    zend_generator_iterator_move_forward,
1051    zend_generator_iterator_rewind
1052};
1053
1054zend_object_iterator *zend_generator_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
1055{
1056    zend_object_iterator *iterator;
1057    zend_generator *generator = (zend_generator*)Z_OBJ_P(object);
1058
1059    if (!generator->execute_data) {
1060        zend_throw_exception(NULL, "Cannot traverse an already closed generator", 0);
1061        return NULL;
1062    }
1063
1064    if (by_ref && !(generator->execute_data->func->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE)) {
1065        zend_throw_exception(NULL, "You can only iterate a generator by-reference if it declared that it yields by-reference", 0);
1066        return NULL;
1067    }
1068
1069    iterator = generator->iterator = emalloc(sizeof(zend_object_iterator));
1070
1071    zend_iterator_init(iterator);
1072
1073    iterator->funcs = &zend_generator_iterator_functions;
1074    ZVAL_COPY(&iterator->data, object);
1075
1076    return iterator;
1077}
1078/* }}} */
1079
1080ZEND_BEGIN_ARG_INFO(arginfo_generator_void, 0)
1081ZEND_END_ARG_INFO()
1082
1083ZEND_BEGIN_ARG_INFO_EX(arginfo_generator_send, 0, 0, 1)
1084    ZEND_ARG_INFO(0, value)
1085ZEND_END_ARG_INFO()
1086
1087ZEND_BEGIN_ARG_INFO_EX(arginfo_generator_throw, 0, 0, 1)
1088    ZEND_ARG_INFO(0, exception)
1089ZEND_END_ARG_INFO()
1090
1091static const zend_function_entry generator_functions[] = {
1092    ZEND_ME(Generator, rewind,   arginfo_generator_void, ZEND_ACC_PUBLIC)
1093    ZEND_ME(Generator, valid,    arginfo_generator_void, ZEND_ACC_PUBLIC)
1094    ZEND_ME(Generator, current,  arginfo_generator_void, ZEND_ACC_PUBLIC)
1095    ZEND_ME(Generator, key,      arginfo_generator_void, ZEND_ACC_PUBLIC)
1096    ZEND_ME(Generator, next,     arginfo_generator_void, ZEND_ACC_PUBLIC)
1097    ZEND_ME(Generator, send,     arginfo_generator_send, ZEND_ACC_PUBLIC)
1098    ZEND_ME(Generator, throw,    arginfo_generator_throw, ZEND_ACC_PUBLIC)
1099    ZEND_ME(Generator, getReturn,arginfo_generator_void, ZEND_ACC_PUBLIC)
1100    ZEND_ME(Generator, __wakeup, arginfo_generator_void, ZEND_ACC_PUBLIC)
1101    ZEND_FE_END
1102};
1103
1104void zend_register_generator_ce(void) /* {{{ */
1105{
1106    zend_class_entry ce;
1107
1108    INIT_CLASS_ENTRY(ce, "Generator", generator_functions);
1109    zend_ce_generator = zend_register_internal_class(&ce);
1110    zend_ce_generator->ce_flags |= ZEND_ACC_FINAL;
1111    zend_ce_generator->create_object = zend_generator_create;
1112    zend_ce_generator->serialize = zend_class_serialize_deny;
1113    zend_ce_generator->unserialize = zend_class_unserialize_deny;
1114
1115    /* get_iterator has to be assigned *after* implementing the inferface */
1116    zend_class_implements(zend_ce_generator, 1, zend_ce_iterator);
1117    zend_ce_generator->get_iterator = zend_generator_get_iterator;
1118    zend_ce_generator->iterator_funcs.funcs = &zend_generator_iterator_functions;
1119
1120    memcpy(&zend_generator_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
1121    zend_generator_handlers.free_obj = zend_generator_free_storage;
1122    zend_generator_handlers.dtor_obj = zend_generator_dtor_storage;
1123    zend_generator_handlers.clone_obj = NULL;
1124    zend_generator_handlers.get_constructor = zend_generator_get_constructor;
1125
1126    INIT_CLASS_ENTRY(ce, "ClosedGeneratorException", NULL);
1127    zend_ce_ClosedGeneratorException = zend_register_internal_class_ex(&ce, zend_ce_exception);
1128}
1129/* }}} */
1130
1131/*
1132 * Local variables:
1133 * tab-width: 4
1134 * c-basic-offset: 4
1135 * indent-tabs-mode: t
1136 * End:
1137 */
1138