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;
450
451 generator = emalloc(sizeof(zend_generator));
452 memset(generator, 0, sizeof(zend_generator));
453
454 /* The key will be incremented on first use, so it'll start at 0 */
455 generator->largest_used_integer_key = -1;
456
457 ZVAL_UNDEF(&generator->retval);
458 ZVAL_UNDEF(&generator->values);
459
460 /* By default we have a tree of only one node */
461 generator->node.parent = NULL;
462 generator->node.children = 0;
463 generator->node.ptr.root = NULL;
464
465 zend_object_std_init(&generator->std, class_type);
466 generator->std.handlers = &zend_generator_handlers;
467
468 return (zend_object*)generator;
469 }
470 /* }}} */
471
zend_generator_get_constructor(zend_object * object)472 static ZEND_COLD zend_function *zend_generator_get_constructor(zend_object *object) /* {{{ */
473 {
474 zend_throw_error(NULL, "The \"Generator\" class is reserved for internal use and cannot be manually instantiated");
475
476 return NULL;
477 }
478 /* }}} */
479
zend_generator_check_placeholder_frame(zend_execute_data * ptr)480 ZEND_API zend_execute_data *zend_generator_check_placeholder_frame(zend_execute_data *ptr)
481 {
482 if (!ptr->func && Z_TYPE(ptr->This) == IS_OBJECT) {
483 if (Z_OBJCE(ptr->This) == zend_ce_generator) {
484 zend_generator *generator = (zend_generator *) Z_OBJ(ptr->This);
485 zend_execute_data *prev = ptr->prev_execute_data;
486 ZEND_ASSERT(generator->node.parent && "Placeholder only used with delegation");
487 while (generator->node.parent->node.parent) {
488 generator->execute_data->prev_execute_data = prev;
489 prev = generator->execute_data;
490 generator = generator->node.parent;
491 }
492 generator->execute_data->prev_execute_data = prev;
493 ptr = generator->execute_data;
494 }
495 }
496 return ptr;
497 }
498
zend_generator_throw_exception(zend_generator * generator,zval * exception)499 static void zend_generator_throw_exception(zend_generator *generator, zval *exception)
500 {
501 zend_execute_data *original_execute_data = EG(current_execute_data);
502
503 /* Throw the exception in the context of the generator. Decrementing the opline
504 * to pretend the exception happened during the YIELD opcode. */
505 EG(current_execute_data) = generator->execute_data;
506 generator->execute_data->opline--;
507 ZEND_ASSERT(generator->execute_data->opline->opcode == ZEND_YIELD
508 || generator->execute_data->opline->opcode == ZEND_YIELD_FROM);
509 generator->execute_data->prev_execute_data = original_execute_data;
510
511 if (exception) {
512 zend_throw_exception_object(exception);
513 } else {
514 zend_rethrow_exception(EG(current_execute_data));
515 }
516
517 generator->execute_data->opline++;
518
519 /* if we don't stop an array/iterator yield from, the exception will only reach the generator after the values were all iterated over */
520 if (UNEXPECTED(Z_TYPE(generator->values) != IS_UNDEF)) {
521 zval_ptr_dtor(&generator->values);
522 ZVAL_UNDEF(&generator->values);
523 }
524
525 EG(current_execute_data) = original_execute_data;
526 }
527
zend_generator_add_child(zend_generator * generator,zend_generator * child)528 static void zend_generator_add_child(zend_generator *generator, zend_generator *child)
529 {
530 zend_generator_node *node = &generator->node;
531
532 if (node->children == 0) {
533 node->child.single = child;
534 } else {
535 if (node->children == 1) {
536 HashTable *ht = emalloc(sizeof(HashTable));
537 zend_hash_init(ht, 0, NULL, NULL, 0);
538 zend_hash_index_add_new_ptr(ht,
539 (zend_ulong) node->child.single, node->child.single);
540 node->child.ht = ht;
541 }
542
543 zend_hash_index_add_new_ptr(node->child.ht, (zend_ulong) child, child);
544 }
545
546 ++node->children;
547 }
548
zend_generator_yield_from(zend_generator * generator,zend_generator * from)549 void zend_generator_yield_from(zend_generator *generator, zend_generator *from)
550 {
551 ZEND_ASSERT(!generator->node.parent && "Already has parent?");
552 zend_generator *leaf = clear_link_to_leaf(generator);
553 if (leaf && !from->node.parent && !from->node.ptr.leaf) {
554 from->node.ptr.leaf = leaf;
555 leaf->node.ptr.root = from;
556 }
557 generator->node.parent = from;
558 zend_generator_add_child(from, generator);
559 generator->flags |= ZEND_GENERATOR_DO_INIT;
560 }
561
zend_generator_update_root(zend_generator * generator)562 ZEND_API zend_generator *zend_generator_update_root(zend_generator *generator)
563 {
564 zend_generator *root = generator->node.parent;
565 while (root->node.parent) {
566 root = root->node.parent;
567 }
568
569 clear_link_to_leaf(root);
570 root->node.ptr.leaf = generator;
571 generator->node.ptr.root = root;
572 return root;
573 }
574
get_new_root(zend_generator * generator,zend_generator * root)575 static zend_generator *get_new_root(zend_generator *generator, zend_generator *root)
576 {
577 while (!root->execute_data && root->node.children == 1) {
578 root = root->node.child.single;
579 }
580
581 if (root->execute_data) {
582 return root;
583 }
584
585 /* We have reached a multi-child node haven't found the root yet. We don't know which
586 * child to follow, so perform the search from the other direction instead. */
587 while (generator->node.parent->execute_data) {
588 generator = generator->node.parent;
589 }
590
591 return generator;
592 }
593
zend_generator_update_current(zend_generator * generator)594 ZEND_API zend_generator *zend_generator_update_current(zend_generator *generator)
595 {
596 zend_generator *old_root = generator->node.ptr.root;
597 ZEND_ASSERT(!old_root->execute_data && "Nothing to update?");
598
599 zend_generator *new_root = get_new_root(generator, old_root);
600
601 ZEND_ASSERT(old_root->node.ptr.leaf == generator);
602 generator->node.ptr.root = new_root;
603 new_root->node.ptr.leaf = generator;
604 old_root->node.ptr.leaf = NULL;
605
606 zend_generator *new_root_parent = new_root->node.parent;
607 ZEND_ASSERT(new_root_parent);
608 zend_generator_remove_child(&new_root_parent->node, new_root);
609
610 if (EXPECTED(EG(exception) == NULL) && EXPECTED((OBJ_FLAGS(&generator->std) & IS_OBJ_DESTRUCTOR_CALLED) == 0)) {
611 zend_op *yield_from = (zend_op *) new_root->execute_data->opline - 1;
612
613 if (yield_from->opcode == ZEND_YIELD_FROM) {
614 if (Z_ISUNDEF(new_root_parent->retval)) {
615 /* Throw the exception in the context of the generator */
616 zend_execute_data *original_execute_data = EG(current_execute_data);
617 EG(current_execute_data) = new_root->execute_data;
618
619 if (new_root == generator) {
620 new_root->execute_data->prev_execute_data = original_execute_data;
621 } else {
622 new_root->execute_data->prev_execute_data = &generator->execute_fake;
623 generator->execute_fake.prev_execute_data = original_execute_data;
624 }
625
626 /* ZEND_YIELD(_FROM) already advance, so decrement opline to throw from correct place */
627 new_root->execute_data->opline--;
628 zend_throw_exception(zend_ce_ClosedGeneratorException, "Generator yielded from aborted, no return value available", 0);
629
630 EG(current_execute_data) = original_execute_data;
631
632 if (!((old_root ? old_root : generator)->flags & ZEND_GENERATOR_CURRENTLY_RUNNING)) {
633 new_root->node.parent = NULL;
634 OBJ_RELEASE(&new_root_parent->std);
635 zend_generator_resume(generator);
636 return zend_generator_get_current(generator);
637 }
638 } else {
639 zval_ptr_dtor(&new_root->value);
640 ZVAL_COPY(&new_root->value, &new_root_parent->value);
641 ZVAL_COPY(ZEND_CALL_VAR(new_root->execute_data, yield_from->result.var), &new_root_parent->retval);
642 }
643 }
644 }
645
646 new_root->node.parent = NULL;
647 OBJ_RELEASE(&new_root_parent->std);
648
649 return new_root;
650 }
651
zend_generator_get_next_delegated_value(zend_generator * generator)652 static zend_result zend_generator_get_next_delegated_value(zend_generator *generator) /* {{{ */
653 {
654 zval *value;
655 if (Z_TYPE(generator->values) == IS_ARRAY) {
656 HashTable *ht = Z_ARR(generator->values);
657 HashPosition pos = Z_FE_POS(generator->values);
658
659 if (HT_IS_PACKED(ht)) {
660 do {
661 if (UNEXPECTED(pos >= ht->nNumUsed)) {
662 /* Reached end of array */
663 goto failure;
664 }
665
666 value = &ht->arPacked[pos];
667 pos++;
668 } while (Z_ISUNDEF_P(value));
669
670 zval_ptr_dtor(&generator->value);
671 ZVAL_COPY(&generator->value, value);
672
673 zval_ptr_dtor(&generator->key);
674 ZVAL_LONG(&generator->key, pos - 1);
675 } else {
676 Bucket *p;
677
678 do {
679 if (UNEXPECTED(pos >= ht->nNumUsed)) {
680 /* Reached end of array */
681 goto failure;
682 }
683
684 p = &ht->arData[pos];
685 value = &p->val;
686 pos++;
687 } while (Z_ISUNDEF_P(value));
688
689 zval_ptr_dtor(&generator->value);
690 ZVAL_COPY(&generator->value, value);
691
692 zval_ptr_dtor(&generator->key);
693 if (p->key) {
694 ZVAL_STR_COPY(&generator->key, p->key);
695 } else {
696 ZVAL_LONG(&generator->key, p->h);
697 }
698 }
699 Z_FE_POS(generator->values) = pos;
700 } else {
701 zend_object_iterator *iter = (zend_object_iterator *) Z_OBJ(generator->values);
702
703 if (iter->index++ > 0) {
704 iter->funcs->move_forward(iter);
705 if (UNEXPECTED(EG(exception) != NULL)) {
706 goto failure;
707 }
708 }
709
710 if (iter->funcs->valid(iter) == FAILURE) {
711 /* reached end of iteration */
712 goto failure;
713 }
714
715 value = iter->funcs->get_current_data(iter);
716 if (UNEXPECTED(EG(exception) != NULL) || UNEXPECTED(!value)) {
717 goto failure;
718 }
719
720 zval_ptr_dtor(&generator->value);
721 ZVAL_COPY(&generator->value, value);
722
723 zval_ptr_dtor(&generator->key);
724 if (iter->funcs->get_current_key) {
725 iter->funcs->get_current_key(iter, &generator->key);
726 if (UNEXPECTED(EG(exception) != NULL)) {
727 ZVAL_UNDEF(&generator->key);
728 goto failure;
729 }
730 } else {
731 ZVAL_LONG(&generator->key, iter->index);
732 }
733 }
734
735 return SUCCESS;
736
737 failure:
738 zval_ptr_dtor(&generator->values);
739 ZVAL_UNDEF(&generator->values);
740
741 return FAILURE;
742 }
743 /* }}} */
744
zend_generator_resume(zend_generator * orig_generator)745 ZEND_API void zend_generator_resume(zend_generator *orig_generator) /* {{{ */
746 {
747 zend_generator *generator = zend_generator_get_current(orig_generator);
748
749 /* The generator is already closed, thus can't resume */
750 if (UNEXPECTED(!generator->execute_data)) {
751 return;
752 }
753
754 try_again:
755 if (generator->flags & ZEND_GENERATOR_CURRENTLY_RUNNING) {
756 zend_throw_error(NULL, "Cannot resume an already running generator");
757 return;
758 }
759
760 if (UNEXPECTED((orig_generator->flags & ZEND_GENERATOR_DO_INIT) != 0 && !Z_ISUNDEF(generator->value))) {
761 /* We must not advance Generator if we yield from a Generator being currently run */
762 orig_generator->flags &= ~ZEND_GENERATOR_DO_INIT;
763 return;
764 }
765
766 if (EG(active_fiber)) {
767 orig_generator->flags |= ZEND_GENERATOR_IN_FIBER;
768 generator->flags |= ZEND_GENERATOR_IN_FIBER;
769 }
770
771 /* Drop the AT_FIRST_YIELD flag */
772 orig_generator->flags &= ~ZEND_GENERATOR_AT_FIRST_YIELD;
773
774 /* Backup executor globals */
775 zend_execute_data *original_execute_data = EG(current_execute_data);
776 uint32_t original_jit_trace_num = EG(jit_trace_num);
777
778 /* Set executor globals */
779 EG(current_execute_data) = generator->execute_data;
780 EG(jit_trace_num) = 0;
781
782 /* We want the backtrace to look as if the generator function was
783 * called from whatever method we are current running (e.g. next()).
784 * So we have to link generator call frame with caller call frame. */
785 if (generator == orig_generator) {
786 generator->execute_data->prev_execute_data = original_execute_data;
787 } else {
788 /* We need some execute_data placeholder in stacktrace to be replaced
789 * by the real stack trace when needed */
790 generator->execute_data->prev_execute_data = &orig_generator->execute_fake;
791 orig_generator->execute_fake.prev_execute_data = original_execute_data;
792 }
793
794 /* Ensure this is run after executor_data swap to have a proper stack trace */
795 if (UNEXPECTED(!Z_ISUNDEF(generator->values))) {
796 if (EXPECTED(zend_generator_get_next_delegated_value(generator) == SUCCESS)) {
797 /* Restore executor globals */
798 EG(current_execute_data) = original_execute_data;
799 EG(jit_trace_num) = original_jit_trace_num;
800
801 orig_generator->flags &= ~(ZEND_GENERATOR_DO_INIT | ZEND_GENERATOR_IN_FIBER);
802 generator->flags &= ~ZEND_GENERATOR_IN_FIBER;
803 return;
804 }
805 if (UNEXPECTED(EG(exception))) {
806 /* Decrementing opline_before_exception to pretend the exception
807 * happened during the YIELD_FROM opcode. */
808 if (generator->execute_data) {
809 ZEND_ASSERT(generator->execute_data->opline == EG(exception_op));
810 ZEND_ASSERT((EG(opline_before_exception)-1)->opcode == ZEND_YIELD_FROM);
811 EG(opline_before_exception)--;
812 }
813 }
814 /* If there are no more delegated values, resume the generator
815 * after the "yield from" expression. */
816 }
817
818 if (UNEXPECTED(generator->frozen_call_stack)) {
819 /* Restore frozen call-stack */
820 zend_generator_restore_call_stack(generator);
821 }
822
823 /* Resume execution */
824 generator->flags |= ZEND_GENERATOR_CURRENTLY_RUNNING;
825 if (!ZEND_OBSERVER_ENABLED) {
826 zend_execute_ex(generator->execute_data);
827 } else {
828 zend_observer_generator_resume(generator->execute_data);
829 zend_execute_ex(generator->execute_data);
830 if (generator->execute_data) {
831 /* On the final return, this will be called from ZEND_GENERATOR_RETURN */
832 zend_observer_fcall_end(generator->execute_data, &generator->value);
833 }
834 }
835 generator->flags &= ~(ZEND_GENERATOR_CURRENTLY_RUNNING | ZEND_GENERATOR_IN_FIBER);
836
837 generator->frozen_call_stack = NULL;
838 if (EXPECTED(generator->execute_data) &&
839 UNEXPECTED(generator->execute_data->call)) {
840 /* Frize call-stack */
841 generator->frozen_call_stack = zend_generator_freeze_call_stack(generator->execute_data);
842 }
843
844 /* Restore executor globals */
845 EG(current_execute_data) = original_execute_data;
846 EG(jit_trace_num) = original_jit_trace_num;
847
848 /* If an exception was thrown in the generator we have to internally
849 * rethrow it in the parent scope.
850 * In case we did yield from, the Exception must be rethrown into
851 * its calling frame (see above in if (check_yield_from). */
852 if (UNEXPECTED(EG(exception) != NULL)) {
853 if (generator == orig_generator) {
854 zend_generator_close(generator, 0);
855 if (!EG(current_execute_data)) {
856 zend_throw_exception_internal(NULL);
857 } else if (EG(current_execute_data)->func &&
858 ZEND_USER_CODE(EG(current_execute_data)->func->common.type)) {
859 zend_rethrow_exception(EG(current_execute_data));
860 }
861 } else {
862 generator = zend_generator_get_current(orig_generator);
863 zend_generator_throw_exception(generator, NULL);
864 orig_generator->flags &= ~ZEND_GENERATOR_DO_INIT;
865 goto try_again;
866 }
867 }
868
869 /* yield from was used, try another resume. */
870 if (UNEXPECTED((generator != orig_generator && !Z_ISUNDEF(generator->retval)) || (generator->execute_data && (generator->execute_data->opline - 1)->opcode == ZEND_YIELD_FROM))) {
871 generator = zend_generator_get_current(orig_generator);
872 goto try_again;
873 }
874
875 orig_generator->flags &= ~(ZEND_GENERATOR_DO_INIT | ZEND_GENERATOR_IN_FIBER);
876 }
877 /* }}} */
878
zend_generator_ensure_initialized(zend_generator * generator)879 static inline void zend_generator_ensure_initialized(zend_generator *generator) /* {{{ */
880 {
881 if (UNEXPECTED(Z_TYPE(generator->value) == IS_UNDEF) && EXPECTED(generator->execute_data) && EXPECTED(generator->node.parent == NULL)) {
882 zend_generator_resume(generator);
883 generator->flags |= ZEND_GENERATOR_AT_FIRST_YIELD;
884 }
885 }
886 /* }}} */
887
zend_generator_rewind(zend_generator * generator)888 static inline void zend_generator_rewind(zend_generator *generator) /* {{{ */
889 {
890 zend_generator_ensure_initialized(generator);
891
892 if (!(generator->flags & ZEND_GENERATOR_AT_FIRST_YIELD)) {
893 zend_throw_exception(NULL, "Cannot rewind a generator that was already run", 0);
894 }
895 }
896 /* }}} */
897
898 /* {{{ Rewind the generator */
ZEND_METHOD(Generator,rewind)899 ZEND_METHOD(Generator, rewind)
900 {
901 zend_generator *generator;
902
903 ZEND_PARSE_PARAMETERS_NONE();
904
905 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
906
907 zend_generator_rewind(generator);
908 }
909 /* }}} */
910
911 /* {{{ Check whether the generator is valid */
ZEND_METHOD(Generator,valid)912 ZEND_METHOD(Generator, valid)
913 {
914 zend_generator *generator;
915
916 ZEND_PARSE_PARAMETERS_NONE();
917
918 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
919
920 zend_generator_ensure_initialized(generator);
921
922 zend_generator_get_current(generator);
923
924 RETURN_BOOL(EXPECTED(generator->execute_data != NULL));
925 }
926 /* }}} */
927
928 /* {{{ Get the current value */
ZEND_METHOD(Generator,current)929 ZEND_METHOD(Generator, current)
930 {
931 zend_generator *generator, *root;
932
933 ZEND_PARSE_PARAMETERS_NONE();
934
935 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
936
937 zend_generator_ensure_initialized(generator);
938
939 root = zend_generator_get_current(generator);
940 if (EXPECTED(generator->execute_data != NULL && Z_TYPE(root->value) != IS_UNDEF)) {
941 RETURN_COPY_DEREF(&root->value);
942 }
943 }
944 /* }}} */
945
946 /* {{{ Get the current key */
ZEND_METHOD(Generator,key)947 ZEND_METHOD(Generator, key)
948 {
949 zend_generator *generator, *root;
950
951 ZEND_PARSE_PARAMETERS_NONE();
952
953 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
954
955 zend_generator_ensure_initialized(generator);
956
957 root = zend_generator_get_current(generator);
958 if (EXPECTED(generator->execute_data != NULL && Z_TYPE(root->key) != IS_UNDEF)) {
959 RETURN_COPY_DEREF(&root->key);
960 }
961 }
962 /* }}} */
963
964 /* {{{ Advances the generator */
ZEND_METHOD(Generator,next)965 ZEND_METHOD(Generator, next)
966 {
967 zend_generator *generator;
968
969 ZEND_PARSE_PARAMETERS_NONE();
970
971 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
972
973 zend_generator_ensure_initialized(generator);
974
975 zend_generator_resume(generator);
976 }
977 /* }}} */
978
979 /* {{{ Sends a value to the generator */
ZEND_METHOD(Generator,send)980 ZEND_METHOD(Generator, send)
981 {
982 zval *value;
983 zend_generator *generator, *root;
984
985 ZEND_PARSE_PARAMETERS_START(1, 1)
986 Z_PARAM_ZVAL(value)
987 ZEND_PARSE_PARAMETERS_END();
988
989 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
990
991 zend_generator_ensure_initialized(generator);
992
993 /* The generator is already closed, thus can't send anything */
994 if (UNEXPECTED(!generator->execute_data)) {
995 return;
996 }
997
998 root = zend_generator_get_current(generator);
999 /* Put sent value in the target VAR slot, if it is used */
1000 if (root->send_target && !(root->flags & ZEND_GENERATOR_CURRENTLY_RUNNING)) {
1001 ZVAL_COPY(root->send_target, value);
1002 }
1003
1004 zend_generator_resume(generator);
1005
1006 root = zend_generator_get_current(generator);
1007 if (EXPECTED(generator->execute_data)) {
1008 RETURN_COPY_DEREF(&root->value);
1009 }
1010 }
1011 /* }}} */
1012
1013 /* {{{ Throws an exception into the generator */
ZEND_METHOD(Generator,throw)1014 ZEND_METHOD(Generator, throw)
1015 {
1016 zval *exception;
1017 zend_generator *generator;
1018
1019 ZEND_PARSE_PARAMETERS_START(1, 1)
1020 Z_PARAM_OBJECT_OF_CLASS(exception, zend_ce_throwable);
1021 ZEND_PARSE_PARAMETERS_END();
1022
1023 Z_TRY_ADDREF_P(exception);
1024
1025 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
1026
1027 zend_generator_ensure_initialized(generator);
1028
1029 if (generator->execute_data) {
1030 zend_generator *root = zend_generator_get_current(generator);
1031
1032 zend_generator_throw_exception(root, exception);
1033
1034 zend_generator_resume(generator);
1035
1036 root = zend_generator_get_current(generator);
1037 if (generator->execute_data) {
1038 RETURN_COPY_DEREF(&root->value);
1039 }
1040 } else {
1041 /* If the generator is already closed throw the exception in the
1042 * current context */
1043 zend_throw_exception_object(exception);
1044 }
1045 }
1046 /* }}} */
1047
1048 /* {{{ Retrieves the return value of the generator */
ZEND_METHOD(Generator,getReturn)1049 ZEND_METHOD(Generator, getReturn)
1050 {
1051 zend_generator *generator;
1052
1053 ZEND_PARSE_PARAMETERS_NONE();
1054
1055 generator = (zend_generator *) Z_OBJ_P(ZEND_THIS);
1056
1057 zend_generator_ensure_initialized(generator);
1058 if (UNEXPECTED(EG(exception))) {
1059 return;
1060 }
1061
1062 if (Z_ISUNDEF(generator->retval)) {
1063 /* Generator hasn't returned yet -> error! */
1064 zend_throw_exception(NULL,
1065 "Cannot get return value of a generator that hasn't returned", 0);
1066 return;
1067 }
1068
1069 ZVAL_COPY(return_value, &generator->retval);
1070 }
1071 /* }}} */
1072
1073 /* get_iterator implementation */
1074
zend_generator_iterator_dtor(zend_object_iterator * iterator)1075 static void zend_generator_iterator_dtor(zend_object_iterator *iterator) /* {{{ */
1076 {
1077 zval_ptr_dtor(&iterator->data);
1078 }
1079 /* }}} */
1080
zend_generator_iterator_valid(zend_object_iterator * iterator)1081 static int zend_generator_iterator_valid(zend_object_iterator *iterator) /* {{{ */
1082 {
1083 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1084
1085 zend_generator_ensure_initialized(generator);
1086
1087 zend_generator_get_current(generator);
1088
1089 return generator->execute_data ? SUCCESS : FAILURE;
1090 }
1091 /* }}} */
1092
zend_generator_iterator_get_data(zend_object_iterator * iterator)1093 static zval *zend_generator_iterator_get_data(zend_object_iterator *iterator) /* {{{ */
1094 {
1095 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data), *root;
1096
1097 zend_generator_ensure_initialized(generator);
1098
1099 root = zend_generator_get_current(generator);
1100
1101 return &root->value;
1102 }
1103 /* }}} */
1104
zend_generator_iterator_get_key(zend_object_iterator * iterator,zval * key)1105 static void zend_generator_iterator_get_key(zend_object_iterator *iterator, zval *key) /* {{{ */
1106 {
1107 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data), *root;
1108
1109 zend_generator_ensure_initialized(generator);
1110
1111 root = zend_generator_get_current(generator);
1112
1113 if (EXPECTED(Z_TYPE(root->key) != IS_UNDEF)) {
1114 zval *zv = &root->key;
1115
1116 ZVAL_COPY_DEREF(key, zv);
1117 } else {
1118 ZVAL_NULL(key);
1119 }
1120 }
1121 /* }}} */
1122
zend_generator_iterator_move_forward(zend_object_iterator * iterator)1123 static void zend_generator_iterator_move_forward(zend_object_iterator *iterator) /* {{{ */
1124 {
1125 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1126
1127 zend_generator_ensure_initialized(generator);
1128
1129 zend_generator_resume(generator);
1130 }
1131 /* }}} */
1132
zend_generator_iterator_rewind(zend_object_iterator * iterator)1133 static void zend_generator_iterator_rewind(zend_object_iterator *iterator) /* {{{ */
1134 {
1135 zend_generator *generator = (zend_generator*)Z_OBJ(iterator->data);
1136
1137 zend_generator_rewind(generator);
1138 }
1139 /* }}} */
1140
zend_generator_iterator_get_gc(zend_object_iterator * iterator,zval ** table,int * n)1141 static HashTable *zend_generator_iterator_get_gc(
1142 zend_object_iterator *iterator, zval **table, int *n)
1143 {
1144 *table = &iterator->data;
1145 *n = 1;
1146 return NULL;
1147 }
1148
1149 static const zend_object_iterator_funcs zend_generator_iterator_functions = {
1150 zend_generator_iterator_dtor,
1151 zend_generator_iterator_valid,
1152 zend_generator_iterator_get_data,
1153 zend_generator_iterator_get_key,
1154 zend_generator_iterator_move_forward,
1155 zend_generator_iterator_rewind,
1156 NULL,
1157 zend_generator_iterator_get_gc,
1158 };
1159
1160 /* by_ref is int due to Iterator API */
zend_generator_get_iterator(zend_class_entry * ce,zval * object,int by_ref)1161 zend_object_iterator *zend_generator_get_iterator(zend_class_entry *ce, zval *object, int by_ref) /* {{{ */
1162 {
1163 zend_object_iterator *iterator;
1164 zend_generator *generator = (zend_generator*)Z_OBJ_P(object);
1165
1166 if (!generator->execute_data) {
1167 zend_throw_exception(NULL, "Cannot traverse an already closed generator", 0);
1168 return NULL;
1169 }
1170
1171 if (UNEXPECTED(by_ref) && !(generator->execute_data->func->op_array.fn_flags & ZEND_ACC_RETURN_REFERENCE)) {
1172 zend_throw_exception(NULL, "You can only iterate a generator by-reference if it declared that it yields by-reference", 0);
1173 return NULL;
1174 }
1175
1176 iterator = emalloc(sizeof(zend_object_iterator));
1177 zend_iterator_init(iterator);
1178
1179 iterator->funcs = &zend_generator_iterator_functions;
1180 ZVAL_OBJ_COPY(&iterator->data, Z_OBJ_P(object));
1181
1182 return iterator;
1183 }
1184 /* }}} */
1185
zend_register_generator_ce(void)1186 void zend_register_generator_ce(void) /* {{{ */
1187 {
1188 zend_ce_generator = register_class_Generator(zend_ce_iterator);
1189 zend_ce_generator->create_object = zend_generator_create;
1190 /* get_iterator has to be assigned *after* implementing the interface */
1191 zend_ce_generator->get_iterator = zend_generator_get_iterator;
1192
1193 memcpy(&zend_generator_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1194 zend_generator_handlers.free_obj = zend_generator_free_storage;
1195 zend_generator_handlers.dtor_obj = zend_generator_dtor_storage;
1196 zend_generator_handlers.get_gc = zend_generator_get_gc;
1197 zend_generator_handlers.clone_obj = NULL;
1198 zend_generator_handlers.get_constructor = zend_generator_get_constructor;
1199
1200 zend_ce_ClosedGeneratorException = register_class_ClosedGeneratorException(zend_ce_exception);
1201 }
1202 /* }}} */
1203