1 /*
2 +----------------------------------------------------------------------+
3 | Zend Engine |
4 +----------------------------------------------------------------------+
5 | Copyright (c) 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 #include "zend.h"
21 #include "zend_API.h"
22 #include "zend_hash.h"
23 #include "zend_interfaces.h"
24 #include "zend_exceptions.h"
25 #include "zend_generators.h"
26 #include "zend_closures.h"
27 #include "zend_generators_arginfo.h"
28 #include "zend_observer.h"
29 #include "zend_vm_opcodes.h"
30
31 ZEND_API zend_class_entry *zend_ce_generator;
32 ZEND_API zend_class_entry *zend_ce_ClosedGeneratorException;
33 static zend_object_handlers zend_generator_handlers;
34
35 static zend_object *zend_generator_create(zend_class_entry *class_type);
36
zend_generator_restore_call_stack(zend_generator * generator)37 ZEND_API void zend_generator_restore_call_stack(zend_generator *generator) /* {{{ */
38 {
39 zend_execute_data *call, *new_call, *prev_call = NULL;
40
41 call = generator->frozen_call_stack;
42 do {
43 new_call = zend_vm_stack_push_call_frame(
44 (ZEND_CALL_INFO(call) & ~ZEND_CALL_ALLOCATED),
45 call->func,
46 ZEND_CALL_NUM_ARGS(call),
47 Z_PTR(call->This));
48 memcpy(((zval*)new_call) + ZEND_CALL_FRAME_SLOT, ((zval*)call) + ZEND_CALL_FRAME_SLOT, ZEND_CALL_NUM_ARGS(call) * sizeof(zval));
49 new_call->extra_named_params = call->extra_named_params;
50 new_call->prev_execute_data = prev_call;
51 prev_call = new_call;
52
53 call = call->prev_execute_data;
54 } while (call);
55 generator->execute_data->call = prev_call;
56 efree(generator->frozen_call_stack);
57 generator->frozen_call_stack = NULL;
58 }
59 /* }}} */
60
zend_generator_freeze_call_stack(zend_execute_data * execute_data)61 ZEND_API zend_execute_data* zend_generator_freeze_call_stack(zend_execute_data *execute_data) /* {{{ */
62 {
63 size_t used_stack;
64 zend_execute_data *call, *new_call, *prev_call = NULL;
65 zval *stack;
66
67 /* calculate required stack size */
68 used_stack = 0;
69 call = EX(call);
70 do {
71 used_stack += ZEND_CALL_FRAME_SLOT + ZEND_CALL_NUM_ARGS(call);
72 call = call->prev_execute_data;
73 } while (call);
74
75 stack = emalloc(used_stack * sizeof(zval));
76
77 /* save stack, linking frames in reverse order */
78 call = EX(call);
79 do {
80 size_t frame_size = ZEND_CALL_FRAME_SLOT + ZEND_CALL_NUM_ARGS(call);
81
82 new_call = (zend_execute_data*)(stack + used_stack - frame_size);
83 memcpy(new_call, call, frame_size * sizeof(zval));
84 used_stack -= frame_size;
85 new_call->prev_execute_data = prev_call;
86 prev_call = new_call;
87
88 new_call = call->prev_execute_data;
89 zend_vm_stack_free_call_frame(call);
90 call = new_call;
91 } while (call);
92
93 execute_data->call = NULL;
94 ZEND_ASSERT(prev_call == (zend_execute_data*)stack);
95
96 return prev_call;
97 }
98 /* }}} */
99
zend_generator_revert_call_stack(zend_execute_data * call)100 static zend_execute_data* zend_generator_revert_call_stack(zend_execute_data *call)
101 {
102 zend_execute_data *prev = NULL;
103
104 do {
105 zend_execute_data *next = call->prev_execute_data;
106 call->prev_execute_data = prev;
107 prev = call;
108 call = next;
109 } while (call);
110
111 return prev;
112 }
113
zend_generator_cleanup_unfinished_execution(zend_generator * generator,zend_execute_data * execute_data,uint32_t catch_op_num)114 static void zend_generator_cleanup_unfinished_execution(
115 zend_generator *generator, zend_execute_data *execute_data, uint32_t catch_op_num) /* {{{ */
116 {
117 zend_op_array *op_array = &execute_data->func->op_array;
118 if (execute_data->opline != op_array->opcodes) {
119 /* -1 required because we want the last run opcode, not the next to-be-run one. */
120 uint32_t op_num = execute_data->opline - op_array->opcodes - 1;
121
122 if (UNEXPECTED(generator->frozen_call_stack)) {
123 /* Temporarily restore generator->execute_data if it has been NULLed out already. */
124 zend_execute_data *save_ex = generator->execute_data;
125 generator->execute_data = execute_data;
126 zend_generator_restore_call_stack(generator);
127 generator->execute_data = save_ex;
128 }
129
130 zend_cleanup_unfinished_execution(execute_data, op_num, catch_op_num);
131 }
132 }
133 /* }}} */
134
zend_generator_close(zend_generator * generator,bool finished_execution)135 ZEND_API void zend_generator_close(zend_generator *generator, bool finished_execution) /* {{{ */
136 {
137 if (EXPECTED(generator->execute_data)) {
138 zend_execute_data *execute_data = generator->execute_data;
139 /* Null out execute_data early, to prevent double frees if GC runs while we're
140 * already cleaning up execute_data. */
141 generator->execute_data = NULL;
142
143 if (EX_CALL_INFO() & ZEND_CALL_HAS_SYMBOL_TABLE) {
144 zend_clean_and_cache_symbol_table(execute_data->symbol_table);
145 }
146 /* always free the CV's, in the symtable are only not-free'd IS_INDIRECT's */
147 zend_free_compiled_variables(execute_data);
148 if (EX_CALL_INFO() & ZEND_CALL_HAS_EXTRA_NAMED_PARAMS) {
149 zend_free_extra_named_params(execute_data->extra_named_params);
150 }
151
152 if (EX_CALL_INFO() & ZEND_CALL_RELEASE_THIS) {
153 OBJ_RELEASE(Z_OBJ(execute_data->This));
154 }
155
156 /* A fatal error / die occurred during the generator execution.
157 * Trying to clean up the stack may not be safe in this case. */
158 if (UNEXPECTED(CG(unclean_shutdown))) {
159 generator->execute_data = NULL;
160 return;
161 }
162
163 zend_vm_stack_free_extra_args(execute_data);
164
165 /* Some cleanups are only necessary if the generator was closed
166 * before it could finish execution (reach a return statement). */
167 if (UNEXPECTED(!finished_execution)) {
168 zend_generator_cleanup_unfinished_execution(generator, execute_data, 0);
169 }
170
171 /* Free closure object */
172 if (EX_CALL_INFO() & ZEND_CALL_CLOSURE) {
173 OBJ_RELEASE(ZEND_CLOSURE_OBJECT(EX(func)));
174 }
175
176 efree(execute_data);
177 }
178 }
179 /* }}} */
180
zend_generator_remove_child(zend_generator_node * node,zend_generator * child)181 static void zend_generator_remove_child(zend_generator_node *node, zend_generator *child)
182 {
183 ZEND_ASSERT(node->children >= 1);
184 if (node->children == 1) {
185 node->child.single = NULL;
186 } else {
187 HashTable *ht = node->child.ht;
188 zend_hash_index_del(ht, (zend_ulong) child);
189 if (node->children == 2) {
190 zend_generator *other_child;
191 ZEND_HASH_FOREACH_PTR(ht, other_child) {
192 node->child.single = other_child;
193 break;
194 } ZEND_HASH_FOREACH_END();
195 zend_hash_destroy(ht);
196 efree(ht);
197 }
198 }
199 node->children--;
200 }
201
clear_link_to_leaf(zend_generator * generator)202 static zend_always_inline zend_generator *clear_link_to_leaf(zend_generator *generator) {
203 ZEND_ASSERT(!generator->node.parent);
204 zend_generator *leaf = generator->node.ptr.leaf;
205 if (leaf) {
206 leaf->node.ptr.root = NULL;
207 generator->node.ptr.leaf = NULL;
208 return leaf;
209 }
210 return NULL;
211 }
212
clear_link_to_root(zend_generator * generator)213 static zend_always_inline void clear_link_to_root(zend_generator *generator) {
214 ZEND_ASSERT(generator->node.parent);
215 if (generator->node.ptr.root) {
216 generator->node.ptr.root->node.ptr.leaf = NULL;
217 generator->node.ptr.root = NULL;
218 }
219 }
220
221 /* Check if the node 'generator' is running in a fiber */
check_node_running_in_fiber(zend_generator * generator)222 static inline bool check_node_running_in_fiber(zend_generator *generator) {
223 ZEND_ASSERT(generator->execute_data);
224
225 if (EXPECTED(generator->flags & ZEND_GENERATOR_IN_FIBER)) {
226 return true;
227 }
228
229 if (EXPECTED(generator->node.children == 0)) {
230 return false;
231 }
232
233 if (generator->node.children == 1) {
234 return check_node_running_in_fiber(generator->node.child.single);
235 }
236
237 zend_generator *child;
238 ZEND_HASH_FOREACH_PTR(generator->node.child.ht, child) {
239 if (check_node_running_in_fiber(child)) {
240 return true;
241 }
242 } ZEND_HASH_FOREACH_END();
243
244 return false;
245 }
246
zend_generator_dtor_storage(zend_object * object)247 static void zend_generator_dtor_storage(zend_object *object) /* {{{ */
248 {
249 zend_generator *generator = (zend_generator*) object;
250 zend_generator *current_generator = zend_generator_get_current(generator);
251 zend_execute_data *ex = generator->execute_data;
252 uint32_t op_num, try_catch_offset;
253 int i;
254
255 /* If current_generator is running in a fiber, there are 2 cases to consider:
256 * - If generator is also marked with ZEND_GENERATOR_IN_FIBER, then the
257 * entire path from current_generator to generator is executing in a
258 * fiber. Do not dtor now: These will be dtor when terminating the fiber.
259 * - If generator is not marked with ZEND_GENERATOR_IN_FIBER, and has a
260 * child marked with ZEND_GENERATOR_IN_FIBER, then this an intermediate
261 * node of case 1. Otherwise generator is not executing in a fiber and we
262 * can dtor.
263 */
264 if (current_generator->flags & ZEND_GENERATOR_IN_FIBER) {
265 if (check_node_running_in_fiber(generator)) {
266 /* Prevent finally blocks from yielding */
267 generator->flags |= ZEND_GENERATOR_FORCED_CLOSE;
268 return;
269 }
270 }
271
272 /* leave yield from mode to properly allow finally execution */
273 if (UNEXPECTED(Z_TYPE(generator->values) != IS_UNDEF)) {
274 zval_ptr_dtor(&generator->values);
275 ZVAL_UNDEF(&generator->values);
276 }
277
278 zend_generator *parent = generator->node.parent;
279 if (parent) {
280 zend_generator_remove_child(&parent->node, generator);
281 clear_link_to_root(generator);
282 generator->node.parent = NULL;
283 OBJ_RELEASE(&parent->std);
284 } else {
285 clear_link_to_leaf(generator);
286 }
287
288 if (EXPECTED(!ex) || EXPECTED(!(ex->func->op_array.fn_flags & ZEND_ACC_HAS_FINALLY_BLOCK))
289 || CG(unclean_shutdown)) {
290 zend_generator_close(generator, 0);
291 return;
292 }
293
294 /* -1 required because we want the last run opcode, not the
295 * next to-be-run one. */
296 op_num = ex->opline - ex->func->op_array.opcodes - 1;
297 try_catch_offset = -1;
298
299 /* Find the innermost try/catch that we are inside of. */
300 for (i = 0; i < ex->func->op_array.last_try_catch; i++) {
301 zend_try_catch_element *try_catch = &ex->func->op_array.try_catch_array[i];
302 if (op_num < try_catch->try_op) {
303 break;
304 }
305 if (op_num < try_catch->catch_op || op_num < try_catch->finally_end) {
306 try_catch_offset = i;
307 }
308 }
309
310 /* Walk try/catch/finally structures upwards, performing the necessary actions. */
311 while (try_catch_offset != (uint32_t) -1) {
312 zend_try_catch_element *try_catch = &ex->func->op_array.try_catch_array[try_catch_offset];
313
314 if (op_num < try_catch->finally_op) {
315 /* Go to finally block */
316 zval *fast_call =
317 ZEND_CALL_VAR(ex, ex->func->op_array.opcodes[try_catch->finally_end].op1.var);
318
319 zend_generator_cleanup_unfinished_execution(generator, ex, try_catch->finally_op);
320 zend_object *old_exception = EG(exception);
321 const zend_op *old_opline_before_exception = EG(opline_before_exception);
322 EG(exception) = NULL;
323 Z_OBJ_P(fast_call) = NULL;
324 Z_OPLINE_NUM_P(fast_call) = (uint32_t)-1;
325
326 ex->opline = &ex->func->op_array.opcodes[try_catch->finally_op];
327 generator->flags |= ZEND_GENERATOR_FORCED_CLOSE;
328 zend_generator_resume(generator);
329
330 if (old_exception) {
331 EG(opline_before_exception) = old_opline_before_exception;
332 if (EG(exception)) {
333 zend_exception_set_previous(EG(exception), old_exception);
334 } else {
335 EG(exception) = old_exception;
336 }
337 }
338
339 /* TODO: If we hit another yield inside try/finally,
340 * should we also jump to the next finally block? */
341 break;
342 } else if (op_num < try_catch->finally_end) {
343 zval *fast_call =
344 ZEND_CALL_VAR(ex, ex->func->op_array.opcodes[try_catch->finally_end].op1.var);
345 /* Clean up incomplete return statement */
346 if (Z_OPLINE_NUM_P(fast_call) != (uint32_t) -1) {
347 zend_op *retval_op = &ex->func->op_array.opcodes[Z_OPLINE_NUM_P(fast_call)];
348 if (retval_op->op2_type & (IS_TMP_VAR | IS_VAR)) {
349 zval_ptr_dtor(ZEND_CALL_VAR(ex, retval_op->op2.var));
350 }
351 }
352 /* Clean up backed-up exception */
353 if (Z_OBJ_P(fast_call)) {
354 OBJ_RELEASE(Z_OBJ_P(fast_call));
355 }
356 }
357
358 try_catch_offset--;
359 }
360
361 zend_generator_close(generator, 0);
362 }
363 /* }}} */
364
zend_generator_free_storage(zend_object * object)365 static void zend_generator_free_storage(zend_object *object) /* {{{ */
366 {
367 zend_generator *generator = (zend_generator*) object;
368
369 zend_generator_close(generator, 0);
370
371 /* we can't immediately free them in zend_generator_close() else yield from won't be able to fetch it */
372 zval_ptr_dtor(&generator->value);
373 zval_ptr_dtor(&generator->key);
374
375 if (EXPECTED(!Z_ISUNDEF(generator->retval))) {
376 zval_ptr_dtor(&generator->retval);
377 }
378
379 if (UNEXPECTED(generator->node.children > 1)) {
380 zend_hash_destroy(generator->node.child.ht);
381 efree(generator->node.child.ht);
382 }
383
384 zend_object_std_dtor(&generator->std);
385 }
386 /* }}} */
387
zend_generator_frame_gc(zend_get_gc_buffer * gc_buffer,zend_generator * generator)388 HashTable *zend_generator_frame_gc(zend_get_gc_buffer *gc_buffer, zend_generator *generator)
389 {
390 zend_execute_data *execute_data = generator->execute_data;
391 zend_execute_data *call = NULL;
392
393 zend_get_gc_buffer_add_zval(gc_buffer, &generator->value);
394 zend_get_gc_buffer_add_zval(gc_buffer, &generator->key);
395 zend_get_gc_buffer_add_zval(gc_buffer, &generator->retval);
396 zend_get_gc_buffer_add_zval(gc_buffer, &generator->values);
397
398 if (UNEXPECTED(generator->frozen_call_stack)) {
399 /* The frozen stack is linked in reverse order */
400 call = zend_generator_revert_call_stack(generator->frozen_call_stack);
401 }
402
403 HashTable *ht = zend_unfinished_execution_gc_ex(execute_data, call, gc_buffer, true);
404
405 if (UNEXPECTED(generator->frozen_call_stack)) {
406 zend_generator_revert_call_stack(call);
407 }
408
409 if (generator->node.parent) {
410 zend_get_gc_buffer_add_obj(gc_buffer, &generator->node.parent->std);
411 }
412
413 return ht;
414 }
415
zend_generator_get_gc(zend_object * object,zval ** table,int * n)416 static HashTable *zend_generator_get_gc(zend_object *object, zval **table, int *n) /* {{{ */
417 {
418 zend_generator *generator = (zend_generator*)object;
419 zend_execute_data *execute_data = generator->execute_data;
420
421 if (!execute_data) {
422 /* If the generator has been closed, it can only hold on to three values: The value, key
423 * and retval. These three zvals are stored sequentially starting at &generator->value. */
424 *table = &generator->value;
425 *n = 3;
426 return NULL;
427 }
428
429 if (generator->flags & ZEND_GENERATOR_CURRENTLY_RUNNING) {
430 /* If the generator is currently running, we certainly won't be able to GC any values it
431 * holds on to. The execute_data state might be inconsistent during execution (e.g. because
432 * GC has been triggered in the middle of a variable reassignment), so we should not try
433 * to inspect it here. */
434 *table = NULL;
435 *n = 0;
436 return NULL;
437 }
438
439 zend_get_gc_buffer *gc_buffer = zend_get_gc_buffer_create();
440 HashTable *ht = zend_generator_frame_gc(gc_buffer, generator);
441 zend_get_gc_buffer_use(gc_buffer, table, n);
442
443 return ht;
444 }
445 /* }}} */
446
zend_generator_create(zend_class_entry * class_type)447 static zend_object *zend_generator_create(zend_class_entry *class_type) /* {{{ */
448 {
449 zend_generator *generator = emalloc(sizeof(zend_generator));
450 memset(generator, 0, sizeof(zend_generator));
451
452 /* The key will be incremented on first use, so it'll start at 0 */
453 generator->largest_used_integer_key = -1;
454
455 ZVAL_UNDEF(&generator->retval);
456 ZVAL_UNDEF(&generator->values);
457
458 /* By default we have a tree of only one node */
459 generator->node.parent = NULL;
460 generator->node.children = 0;
461 generator->node.ptr.root = NULL;
462
463 zend_object_std_init(&generator->std, class_type);
464 return (zend_object*)generator;
465 }
466 /* }}} */
467
zend_generator_get_constructor(zend_object * object)468 static ZEND_COLD zend_function *zend_generator_get_constructor(zend_object *object) /* {{{ */
469 {
470 zend_throw_error(NULL, "The \"Generator\" class is reserved for internal use and cannot be manually instantiated");
471
472 return NULL;
473 }
474 /* }}} */
475
zend_generator_check_placeholder_frame(zend_execute_data * ptr)476 ZEND_API zend_execute_data *zend_generator_check_placeholder_frame(zend_execute_data *ptr)
477 {
478 if (!ptr->func && Z_TYPE(ptr->This) == IS_OBJECT) {
479 if (Z_OBJCE(ptr->This) == zend_ce_generator) {
480 zend_generator *generator = (zend_generator *) Z_OBJ(ptr->This);
481 zend_execute_data *prev = ptr->prev_execute_data;
482 ZEND_ASSERT(generator->node.parent && "Placeholder only used with delegation");
483 while (generator->node.parent->node.parent) {
484 generator->execute_data->prev_execute_data = prev;
485 prev = generator->execute_data;
486 generator = generator->node.parent;
487 }
488 generator->execute_data->prev_execute_data = prev;
489 ptr = generator->execute_data;
490 }
491 }
492 return ptr;
493 }
494
zend_generator_throw_exception(zend_generator * generator,zval * exception)495 static void zend_generator_throw_exception(zend_generator *generator, zval *exception)
496 {
497 zend_execute_data *original_execute_data = EG(current_execute_data);
498
499 /* Throw the exception in the context of the generator. Decrementing the opline
500 * to pretend the exception happened during the YIELD opcode. */
501 EG(current_execute_data) = generator->execute_data;
502 generator->execute_data->opline--;
503 ZEND_ASSERT(generator->execute_data->opline->opcode == ZEND_YIELD
504 || generator->execute_data->opline->opcode == ZEND_YIELD_FROM);
505 generator->execute_data->prev_execute_data = original_execute_data;
506
507 if (exception) {
508 zend_throw_exception_object(exception);
509 } else {
510 zend_rethrow_exception(EG(current_execute_data));
511 }
512
513 generator->execute_data->opline++;
514
515 /* if we don't stop an array/iterator yield from, the exception will only reach the generator after the values were all iterated over */
516 if (UNEXPECTED(Z_TYPE(generator->values) != IS_UNDEF)) {
517 zval_ptr_dtor(&generator->values);
518 ZVAL_UNDEF(&generator->values);
519 }
520
521 EG(current_execute_data) = original_execute_data;
522 }
523
zend_generator_add_child(zend_generator * generator,zend_generator * child)524 static void zend_generator_add_child(zend_generator *generator, zend_generator *child)
525 {
526 zend_generator_node *node = &generator->node;
527
528 if (node->children == 0) {
529 node->child.single = child;
530 } else {
531 if (node->children == 1) {
532 HashTable *ht = emalloc(sizeof(HashTable));
533 zend_hash_init(ht, 0, NULL, NULL, 0);
534 zend_hash_index_add_new_ptr(ht,
535 (zend_ulong) node->child.single, node->child.single);
536 node->child.ht = ht;
537 }
538
539 zend_hash_index_add_new_ptr(node->child.ht, (zend_ulong) child, child);
540 }
541
542 ++node->children;
543 }
544
zend_generator_yield_from(zend_generator * generator,zend_generator * from)545 void zend_generator_yield_from(zend_generator *generator, zend_generator *from)
546 {
547 ZEND_ASSERT(!generator->node.parent && "Already has parent?");
548 zend_generator *leaf = clear_link_to_leaf(generator);
549 if (leaf && !from->node.parent && !from->node.ptr.leaf) {
550 from->node.ptr.leaf = leaf;
551 leaf->node.ptr.root = from;
552 }
553 generator->node.parent = from;
554 zend_generator_add_child(from, generator);
555 generator->flags |= ZEND_GENERATOR_DO_INIT;
556 }
557
zend_generator_update_root(zend_generator * generator)558 ZEND_API zend_generator *zend_generator_update_root(zend_generator *generator)
559 {
560 zend_generator *root = generator->node.parent;
561 while (root->node.parent) {
562 root = root->node.parent;
563 }
564
565 clear_link_to_leaf(root);
566 root->node.ptr.leaf = generator;
567 generator->node.ptr.root = root;
568 return root;
569 }
570
get_new_root(zend_generator * generator,zend_generator * root)571 static zend_generator *get_new_root(zend_generator *generator, zend_generator *root)
572 {
573 while (!root->execute_data && root->node.children == 1) {
574 root = root->node.child.single;
575 }
576
577 if (root->execute_data) {
578 return root;
579 }
580
581 /* We have reached a multi-child node haven't found the root yet. We don't know which
582 * child to follow, so perform the search from the other direction instead. */
583 while (generator->node.parent->execute_data) {
584 generator = generator->node.parent;
585 }
586
587 return generator;
588 }
589
zend_generator_update_current(zend_generator * generator)590 ZEND_API zend_generator *zend_generator_update_current(zend_generator *generator)
591 {
592 zend_generator *old_root = generator->node.ptr.root;
593 ZEND_ASSERT(!old_root->execute_data && "Nothing to update?");
594
595 zend_generator *new_root = get_new_root(generator, old_root);
596
597 ZEND_ASSERT(old_root->node.ptr.leaf == generator);
598 generator->node.ptr.root = new_root;
599 new_root->node.ptr.leaf = generator;
600 old_root->node.ptr.leaf = NULL;
601
602 zend_generator *new_root_parent = new_root->node.parent;
603 ZEND_ASSERT(new_root_parent);
604 zend_generator_remove_child(&new_root_parent->node, new_root);
605
606 if (EXPECTED(EG(exception) == NULL) && EXPECTED((OBJ_FLAGS(&generator->std) & IS_OBJ_DESTRUCTOR_CALLED) == 0)) {
607 zend_op *yield_from = (zend_op *) new_root->execute_data->opline - 1;
608
609 if (yield_from->opcode == ZEND_YIELD_FROM) {
610 if (Z_ISUNDEF(new_root_parent->retval)) {
611 /* Throw the exception in the context of the generator */
612 zend_execute_data *original_execute_data = EG(current_execute_data);
613 EG(current_execute_data) = new_root->execute_data;
614
615 if (new_root == generator) {
616 new_root->execute_data->prev_execute_data = original_execute_data;
617 } else {
618 new_root->execute_data->prev_execute_data = &generator->execute_fake;
619 generator->execute_fake.prev_execute_data = original_execute_data;
620 }
621
622 /* ZEND_YIELD(_FROM) already advance, so decrement opline to throw from correct place */
623 new_root->execute_data->opline--;
624 zend_throw_exception(zend_ce_ClosedGeneratorException, "Generator yielded from aborted, no return value available", 0);
625
626 EG(current_execute_data) = original_execute_data;
627
628 if (!((old_root ? old_root : generator)->flags & ZEND_GENERATOR_CURRENTLY_RUNNING)) {
629 new_root->node.parent = NULL;
630 OBJ_RELEASE(&new_root_parent->std);
631 zend_generator_resume(generator);
632 return zend_generator_get_current(generator);
633 }
634 } else {
635 zval_ptr_dtor(&new_root->value);
636 ZVAL_COPY(&new_root->value, &new_root_parent->value);
637 ZVAL_COPY(ZEND_CALL_VAR(new_root->execute_data, yield_from->result.var), &new_root_parent->retval);
638 }
639 }
640 }
641
642 new_root->node.parent = NULL;
643 OBJ_RELEASE(&new_root_parent->std);
644
645 return new_root;
646 }
647
zend_generator_get_next_delegated_value(zend_generator * generator)648 static zend_result zend_generator_get_next_delegated_value(zend_generator *generator) /* {{{ */
649 {
650 zval *value;
651 if (Z_TYPE(generator->values) == IS_ARRAY) {
652 HashTable *ht = Z_ARR(generator->values);
653 HashPosition pos = Z_FE_POS(generator->values);
654
655 if (HT_IS_PACKED(ht)) {
656 do {
657 if (UNEXPECTED(pos >= ht->nNumUsed)) {
658 /* Reached end of array */
659 goto failure;
660 }
661
662 value = &ht->arPacked[pos];
663 pos++;
664 } while (Z_ISUNDEF_P(value));
665
666 zval_ptr_dtor(&generator->value);
667 ZVAL_COPY(&generator->value, value);
668
669 zval_ptr_dtor(&generator->key);
670 ZVAL_LONG(&generator->key, pos - 1);
671 } else {
672 Bucket *p;
673
674 do {
675 if (UNEXPECTED(pos >= ht->nNumUsed)) {
676 /* Reached end of array */
677 goto failure;
678 }
679
680 p = &ht->arData[pos];
681 value = &p->val;
682 pos++;
683 } while (Z_ISUNDEF_P(value));
684
685 zval_ptr_dtor(&generator->value);
686 ZVAL_COPY(&generator->value, value);
687
688 zval_ptr_dtor(&generator->key);
689 if (p->key) {
690 ZVAL_STR_COPY(&generator->key, p->key);
691 } else {
692 ZVAL_LONG(&generator->key, p->h);
693 }
694 }
695 Z_FE_POS(generator->values) = pos;
696 } else {
697 zend_object_iterator *iter = (zend_object_iterator *) Z_OBJ(generator->values);
698
699 if (iter->index++ > 0) {
700 iter->funcs->move_forward(iter);
701 if (UNEXPECTED(EG(exception) != NULL)) {
702 goto failure;
703 }
704 }
705
706 if (iter->funcs->valid(iter) == FAILURE) {
707 /* reached end of iteration */
708 goto failure;
709 }
710
711 value = iter->funcs->get_current_data(iter);
712 if (UNEXPECTED(EG(exception) != NULL) || UNEXPECTED(!value)) {
713 goto failure;
714 }
715
716 zval_ptr_dtor(&generator->value);
717 ZVAL_COPY(&generator->value, value);
718
719 zval_ptr_dtor(&generator->key);
720 if (iter->funcs->get_current_key) {
721 iter->funcs->get_current_key(iter, &generator->key);
722 if (UNEXPECTED(EG(exception) != NULL)) {
723 ZVAL_UNDEF(&generator->key);
724 goto failure;
725 }
726 } else {
727 ZVAL_LONG(&generator->key, iter->index);
728 }
729 }
730
731 return SUCCESS;
732
733 failure:
734 zval_ptr_dtor(&generator->values);
735 ZVAL_UNDEF(&generator->values);
736
737 return FAILURE;
738 }
739 /* }}} */
740
zend_generator_resume(zend_generator * orig_generator)741 ZEND_API void zend_generator_resume(zend_generator *orig_generator) /* {{{ */
742 {
743 zend_generator *generator = zend_generator_get_current(orig_generator);
744
745 /* The generator is already closed, thus can't resume */
746 if (UNEXPECTED(!generator->execute_data)) {
747 return;
748 }
749
750 try_again:
751 if (generator->flags & ZEND_GENERATOR_CURRENTLY_RUNNING) {
752 zend_throw_error(NULL, "Cannot resume an already running generator");
753 return;
754 }
755
756 if (UNEXPECTED((orig_generator->flags & ZEND_GENERATOR_DO_INIT) != 0 && !Z_ISUNDEF(generator->value))) {
757 /* We must not advance Generator if we yield from a Generator being currently run */
758 orig_generator->flags &= ~ZEND_GENERATOR_DO_INIT;
759 return;
760 }
761
762 if (EG(active_fiber)) {
763 orig_generator->flags |= ZEND_GENERATOR_IN_FIBER;
764 generator->flags |= ZEND_GENERATOR_IN_FIBER;
765 }
766
767 /* Drop the AT_FIRST_YIELD flag */
768 orig_generator->flags &= ~ZEND_GENERATOR_AT_FIRST_YIELD;
769
770 /* Backup executor globals */
771 zend_execute_data *original_execute_data = EG(current_execute_data);
772 uint32_t original_jit_trace_num = EG(jit_trace_num);
773
774 /* Set executor globals */
775 EG(current_execute_data) = generator->execute_data;
776 EG(jit_trace_num) = 0;
777
778 /* We want the backtrace to look as if the generator function was
779 * called from whatever method we are current running (e.g. next()).
780 * So we have to link generator call frame with caller call frame. */
781 if (generator == orig_generator) {
782 generator->execute_data->prev_execute_data = original_execute_data;
783 } else {
784 /* We need some execute_data placeholder in stacktrace to be replaced
785 * by the real stack trace when needed */
786 generator->execute_data->prev_execute_data = &orig_generator->execute_fake;
787 orig_generator->execute_fake.prev_execute_data = original_execute_data;
788 }
789
790 /* Ensure this is run after executor_data swap to have a proper stack trace */
791 if (UNEXPECTED(!Z_ISUNDEF(generator->values))) {
792 if (EXPECTED(zend_generator_get_next_delegated_value(generator) == SUCCESS)) {
793 /* Restore executor globals */
794 EG(current_execute_data) = original_execute_data;
795 EG(jit_trace_num) = original_jit_trace_num;
796
797 orig_generator->flags &= ~(ZEND_GENERATOR_DO_INIT | ZEND_GENERATOR_IN_FIBER);
798 generator->flags &= ~ZEND_GENERATOR_IN_FIBER;
799 return;
800 }
801 if (UNEXPECTED(EG(exception))) {
802 /* Decrementing opline_before_exception to pretend the exception
803 * happened during the YIELD_FROM opcode. */
804 if (generator->execute_data) {
805 ZEND_ASSERT(generator->execute_data->opline == EG(exception_op));
806 ZEND_ASSERT((EG(opline_before_exception)-1)->opcode == ZEND_YIELD_FROM);
807 EG(opline_before_exception)--;
808 }
809 }
810 /* If there are no more delegated values, resume the generator
811 * after the "yield from" expression. */
812 }
813
814 if (UNEXPECTED(generator->frozen_call_stack)) {
815 /* Restore frozen call-stack */
816 zend_generator_restore_call_stack(generator);
817 }
818
819 /* Resume execution */
820 generator->flags |= ZEND_GENERATOR_CURRENTLY_RUNNING;
821 if (!ZEND_OBSERVER_ENABLED) {
822 zend_execute_ex(generator->execute_data);
823 } else {
824 zend_observer_generator_resume(generator->execute_data);
825 zend_execute_ex(generator->execute_data);
826 if (generator->execute_data) {
827 /* On the final return, this will be called from ZEND_GENERATOR_RETURN */
828 zend_observer_fcall_end(generator->execute_data, &generator->value);
829 }
830 }
831 generator->flags &= ~(ZEND_GENERATOR_CURRENTLY_RUNNING | ZEND_GENERATOR_IN_FIBER);
832
833 generator->frozen_call_stack = NULL;
834 if (EXPECTED(generator->execute_data) &&
835 UNEXPECTED(generator->execute_data->call)) {
836 /* Frize call-stack */
837 generator->frozen_call_stack = zend_generator_freeze_call_stack(generator->execute_data);
838 }
839
840 /* Restore executor globals */
841 EG(current_execute_data) = original_execute_data;
842 EG(jit_trace_num) = original_jit_trace_num;
843
844 /* If an exception was thrown in the generator we have to internally
845 * rethrow it in the parent scope.
846 * In case we did yield from, the Exception must be rethrown into
847 * its calling frame (see above in if (check_yield_from). */
848 if (UNEXPECTED(EG(exception) != NULL)) {
849 if (generator == orig_generator) {
850 zend_generator_close(generator, 0);
851 if (!EG(current_execute_data)) {
852 zend_throw_exception_internal(NULL);
853 } else if (EG(current_execute_data)->func &&
854 ZEND_USER_CODE(EG(current_execute_data)->func->common.type)) {
855 zend_rethrow_exception(EG(current_execute_data));
856 }
857 } else {
858 generator = zend_generator_get_current(orig_generator);
859 zend_generator_throw_exception(generator, NULL);
860 orig_generator->flags &= ~ZEND_GENERATOR_DO_INIT;
861 goto try_again;
862 }
863 }
864
865 /* yield from was used, try another resume. */
866 if (UNEXPECTED((generator != orig_generator && !Z_ISUNDEF(generator->retval)) || (generator->execute_data && (generator->execute_data->opline - 1)->opcode == ZEND_YIELD_FROM))) {
867 generator = zend_generator_get_current(orig_generator);
868 goto try_again;
869 }
870
871 orig_generator->flags &= ~(ZEND_GENERATOR_DO_INIT | ZEND_GENERATOR_IN_FIBER);
872 }
873 /* }}} */
874
zend_generator_ensure_initialized(zend_generator * generator)875 static inline void zend_generator_ensure_initialized(zend_generator *generator) /* {{{ */
876 {
877 if (UNEXPECTED(Z_TYPE(generator->value) == IS_UNDEF) && EXPECTED(generator->execute_data) && EXPECTED(generator->node.parent == NULL)) {
878 zend_generator_resume(generator);
879 generator->flags |= ZEND_GENERATOR_AT_FIRST_YIELD;
880 }
881 }
882 /* }}} */
883
zend_generator_rewind(zend_generator * generator)884 static inline void zend_generator_rewind(zend_generator *generator) /* {{{ */
885 {
886 zend_generator_ensure_initialized(generator);
887
888 if (!(generator->flags & ZEND_GENERATOR_AT_FIRST_YIELD)) {
889 zend_throw_exception(NULL, "Cannot rewind a generator that was already run", 0);
890 }
891 }
892 /* }}} */
893
894 /* {{{ Rewind the generator */
ZEND_METHOD(Generator,rewind)895 ZEND_METHOD(Generator, rewind)
896 {
897 zend_generator *generator;
898
899 ZEND_PARSE_PARAMETERS_NONE();
900
901 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
902
903 zend_generator_rewind(generator);
904 }
905 /* }}} */
906
907 /* {{{ Check whether the generator is valid */
ZEND_METHOD(Generator,valid)908 ZEND_METHOD(Generator, valid)
909 {
910 zend_generator *generator;
911
912 ZEND_PARSE_PARAMETERS_NONE();
913
914 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
915
916 zend_generator_ensure_initialized(generator);
917
918 zend_generator_get_current(generator);
919
920 RETURN_BOOL(EXPECTED(generator->execute_data != NULL));
921 }
922 /* }}} */
923
924 /* {{{ Get the current value */
ZEND_METHOD(Generator,current)925 ZEND_METHOD(Generator, current)
926 {
927 zend_generator *generator, *root;
928
929 ZEND_PARSE_PARAMETERS_NONE();
930
931 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
932
933 zend_generator_ensure_initialized(generator);
934
935 root = zend_generator_get_current(generator);
936 if (EXPECTED(generator->execute_data != NULL && Z_TYPE(root->value) != IS_UNDEF)) {
937 RETURN_COPY_DEREF(&root->value);
938 }
939 }
940 /* }}} */
941
942 /* {{{ Get the current key */
ZEND_METHOD(Generator,key)943 ZEND_METHOD(Generator, key)
944 {
945 zend_generator *generator, *root;
946
947 ZEND_PARSE_PARAMETERS_NONE();
948
949 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
950
951 zend_generator_ensure_initialized(generator);
952
953 root = zend_generator_get_current(generator);
954 if (EXPECTED(generator->execute_data != NULL && Z_TYPE(root->key) != IS_UNDEF)) {
955 RETURN_COPY_DEREF(&root->key);
956 }
957 }
958 /* }}} */
959
960 /* {{{ Advances the generator */
ZEND_METHOD(Generator,next)961 ZEND_METHOD(Generator, next)
962 {
963 zend_generator *generator;
964
965 ZEND_PARSE_PARAMETERS_NONE();
966
967 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
968
969 zend_generator_ensure_initialized(generator);
970
971 zend_generator_resume(generator);
972 }
973 /* }}} */
974
975 /* {{{ Sends a value to the generator */
ZEND_METHOD(Generator,send)976 ZEND_METHOD(Generator, send)
977 {
978 zval *value;
979 zend_generator *generator, *root;
980
981 ZEND_PARSE_PARAMETERS_START(1, 1)
982 Z_PARAM_ZVAL(value)
983 ZEND_PARSE_PARAMETERS_END();
984
985 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
986
987 zend_generator_ensure_initialized(generator);
988
989 /* The generator is already closed, thus can't send anything */
990 if (UNEXPECTED(!generator->execute_data)) {
991 return;
992 }
993
994 root = zend_generator_get_current(generator);
995 /* Put sent value in the target VAR slot, if it is used */
996 if (root->send_target && !(root->flags & ZEND_GENERATOR_CURRENTLY_RUNNING)) {
997 ZVAL_COPY(root->send_target, value);
998 }
999
1000 zend_generator_resume(generator);
1001
1002 root = zend_generator_get_current(generator);
1003 if (EXPECTED(generator->execute_data)) {
1004 RETURN_COPY_DEREF(&root->value);
1005 }
1006 }
1007 /* }}} */
1008
1009 /* {{{ Throws an exception into the generator */
ZEND_METHOD(Generator,throw)1010 ZEND_METHOD(Generator, throw)
1011 {
1012 zval *exception;
1013 zend_generator *generator;
1014
1015 ZEND_PARSE_PARAMETERS_START(1, 1)
1016 Z_PARAM_OBJECT_OF_CLASS(exception, zend_ce_throwable);
1017 ZEND_PARSE_PARAMETERS_END();
1018
1019 Z_TRY_ADDREF_P(exception);
1020
1021 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
1022
1023 zend_generator_ensure_initialized(generator);
1024
1025 if (generator->execute_data) {
1026 zend_generator *root = zend_generator_get_current(generator);
1027
1028 zend_generator_throw_exception(root, exception);
1029
1030 zend_generator_resume(generator);
1031
1032 root = zend_generator_get_current(generator);
1033 if (generator->execute_data) {
1034 RETURN_COPY_DEREF(&root->value);
1035 }
1036 } else {
1037 /* If the generator is already closed throw the exception in the
1038 * current context */
1039 zend_throw_exception_object(exception);
1040 }
1041 }
1042 /* }}} */
1043
1044 /* {{{ Retrieves the return value of the generator */
ZEND_METHOD(Generator,getReturn)1045 ZEND_METHOD(Generator, getReturn)
1046 {
1047 zend_generator *generator;
1048
1049 ZEND_PARSE_PARAMETERS_NONE();
1050
1051 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
1052
1053 zend_generator_ensure_initialized(generator);
1054 if (UNEXPECTED(EG(exception))) {
1055 return;
1056 }
1057
1058 if (Z_ISUNDEF(generator->retval)) {
1059 /* Generator hasn't returned yet -> error! */
1060 zend_throw_exception(NULL,
1061 "Cannot get return value of a generator that hasn't returned", 0);
1062 return;
1063 }
1064
1065 ZVAL_COPY(return_value, &generator->retval);
1066 }
1067 /* }}} */
1068
1069 /* get_iterator implementation */
1070
zend_generator_iterator_dtor(zend_object_iterator * iterator)1071 static void zend_generator_iterator_dtor(zend_object_iterator *iterator) /* {{{ */
1072 {
1073 zval_ptr_dtor(&iterator->data);
1074 }
1075 /* }}} */
1076
zend_generator_iterator_valid(zend_object_iterator * iterator)1077 static int zend_generator_iterator_valid(zend_object_iterator *iterator) /* {{{ */
1078 {
1079 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1080
1081 zend_generator_ensure_initialized(generator);
1082
1083 zend_generator_get_current(generator);
1084
1085 return generator->execute_data ? SUCCESS : FAILURE;
1086 }
1087 /* }}} */
1088
zend_generator_iterator_get_data(zend_object_iterator * iterator)1089 static zval *zend_generator_iterator_get_data(zend_object_iterator *iterator) /* {{{ */
1090 {
1091 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data), *root;
1092
1093 zend_generator_ensure_initialized(generator);
1094
1095 root = zend_generator_get_current(generator);
1096
1097 return &root->value;
1098 }
1099 /* }}} */
1100
zend_generator_iterator_get_key(zend_object_iterator * iterator,zval * key)1101 static void zend_generator_iterator_get_key(zend_object_iterator *iterator, zval *key) /* {{{ */
1102 {
1103 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data), *root;
1104
1105 zend_generator_ensure_initialized(generator);
1106
1107 root = zend_generator_get_current(generator);
1108
1109 if (EXPECTED(Z_TYPE(root->key) != IS_UNDEF)) {
1110 zval *zv = &root->key;
1111
1112 ZVAL_COPY_DEREF(key, zv);
1113 } else {
1114 ZVAL_NULL(key);
1115 }
1116 }
1117 /* }}} */
1118
zend_generator_iterator_move_forward(zend_object_iterator * iterator)1119 static void zend_generator_iterator_move_forward(zend_object_iterator *iterator) /* {{{ */
1120 {
1121 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1122
1123 zend_generator_ensure_initialized(generator);
1124
1125 zend_generator_resume(generator);
1126 }
1127 /* }}} */
1128
zend_generator_iterator_rewind(zend_object_iterator * iterator)1129 static void zend_generator_iterator_rewind(zend_object_iterator *iterator) /* {{{ */
1130 {
1131 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1132
1133 zend_generator_rewind(generator);
1134 }
1135 /* }}} */
1136
zend_generator_iterator_get_gc(zend_object_iterator * iterator,zval ** table,int * n)1137 static HashTable *zend_generator_iterator_get_gc(
1138 zend_object_iterator *iterator, zval **table, int *n)
1139 {
1140 *table = &iterator->data;
1141 *n = 1;
1142 return NULL;
1143 }
1144
1145 static const zend_object_iterator_funcs zend_generator_iterator_functions = {
1146 zend_generator_iterator_dtor,
1147 zend_generator_iterator_valid,
1148 zend_generator_iterator_get_data,
1149 zend_generator_iterator_get_key,
1150 zend_generator_iterator_move_forward,
1151 zend_generator_iterator_rewind,
1152 NULL,
1153 zend_generator_iterator_get_gc,
1154 };
1155
1156 /* by_ref is int due to Iterator API */
zend_generator_get_iterator(zend_class_entry * ce,zval * object,int by_ref)1157 zend_object_iterator *zend_generator_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
1158 {
1159 zend_object_iterator *iterator;
1160 zend_generator *generator = (zend_generator*)Z_OBJ_P(object);
1161
1162 if (!generator->execute_data) {
1163 zend_throw_exception(NULL, "Cannot traverse an already closed generator", 0);
1164 return NULL;
1165 }
1166
1167 if (UNEXPECTED(by_ref) && !(generator->execute_data->func->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE)) {
1168 zend_throw_exception(NULL, "You can only iterate a generator by-reference if it declared that it yields by-reference", 0);
1169 return NULL;
1170 }
1171
1172 iterator = emalloc(sizeof(zend_object_iterator));
1173 zend_iterator_init(iterator);
1174
1175 iterator->funcs = &zend_generator_iterator_functions;
1176 ZVAL_OBJ_COPY(&iterator->data, Z_OBJ_P(object));
1177
1178 return iterator;
1179 }
1180 /* }}} */
1181
zend_register_generator_ce(void)1182 void zend_register_generator_ce(void) /* {{{ */
1183 {
1184 zend_ce_generator = register_class_Generator(zend_ce_iterator);
1185 zend_ce_generator->create_object = zend_generator_create;
1186 /* get_iterator has to be assigned *after* implementing the interface */
1187 zend_ce_generator->get_iterator = zend_generator_get_iterator;
1188 zend_ce_generator->default_object_handlers = &zend_generator_handlers;
1189
1190 memcpy(&zend_generator_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1191 zend_generator_handlers.free_obj = zend_generator_free_storage;
1192 zend_generator_handlers.dtor_obj = zend_generator_dtor_storage;
1193 zend_generator_handlers.get_gc = zend_generator_get_gc;
1194 zend_generator_handlers.clone_obj = NULL;
1195 zend_generator_handlers.get_constructor = zend_generator_get_constructor;
1196
1197 zend_ce_ClosedGeneratorException = register_class_ClosedGeneratorException(zend_ce_exception);
1198 }
1199 /* }}} */
1200