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: Christian Seiler <chris_se@gmx.net>                         |
16    |          Dmitry Stogov <dmitry@php.net>                              |
17    |          Marcus Boerger <helly@php.net>                              |
18    +----------------------------------------------------------------------+
19 */
20 
21 #include "zend.h"
22 #include "zend_API.h"
23 #include "zend_closures.h"
24 #include "zend_exceptions.h"
25 #include "zend_interfaces.h"
26 #include "zend_objects.h"
27 #include "zend_objects_API.h"
28 #include "zend_globals.h"
29 
30 #define ZEND_CLOSURE_PRINT_NAME "Closure object"
31 
32 #define ZEND_CLOSURE_PROPERTY_ERROR() \
33 	zend_throw_error(NULL, "Closure object cannot have properties")
34 
35 typedef struct _zend_closure {
36 	zend_object       std;
37 	zend_function     func;
38 	zval              this_ptr;
39 	zend_class_entry *called_scope;
40 	zif_handler       orig_internal_handler;
41 } zend_closure;
42 
43 /* non-static since it needs to be referenced */
44 ZEND_API zend_class_entry *zend_ce_closure;
45 static zend_object_handlers closure_handlers;
46 
ZEND_METHODnull47 ZEND_METHOD(Closure, __invoke) /* {{{ */
48 {
49 	zend_function *func = EX(func);
50 	zval *arguments = ZEND_CALL_ARG(execute_data, 1);
51 
52 	if (call_user_function(CG(function_table), NULL, ZEND_THIS, return_value, ZEND_NUM_ARGS(), arguments) == FAILURE) {
53 		RETVAL_FALSE;
54 	}
55 
56 	/* destruct the function also, then - we have allocated it in get_method */
57 	zend_string_release_ex(func->internal_function.function_name, 0);
58 	efree(func);
59 #if ZEND_DEBUG
60 	execute_data->func = NULL;
61 #endif
62 }
63 /* }}} */
64 
zend_valid_closure_binding( zend_closure *closure, zval *newthis, zend_class_entry *scope)65 static zend_bool zend_valid_closure_binding(
66 		zend_closure *closure, zval *newthis, zend_class_entry *scope) /* {{{ */
67 {
68 	zend_function *func = &closure->func;
69 	zend_bool is_fake_closure = (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) != 0;
70 	if (newthis) {
71 		if (func->common.fn_flags & ZEND_ACC_STATIC) {
72 			zend_error(E_WARNING, "Cannot bind an instance to a static closure");
73 			return 0;
74 		}
75 
76 		if (is_fake_closure && func->common.scope &&
77 				!instanceof_function(Z_OBJCE_P(newthis), func->common.scope)) {
78 			/* Binding incompatible $this to an internal method is not supported. */
79 			zend_error(E_WARNING, "Cannot bind method %s::%s() to object of class %s",
80 					ZSTR_VAL(func->common.scope->name),
81 					ZSTR_VAL(func->common.function_name),
82 					ZSTR_VAL(Z_OBJCE_P(newthis)->name));
83 			return 0;
84 		}
85 	} else if (is_fake_closure && func->common.scope
86 			&& !(func->common.fn_flags & ZEND_ACC_STATIC)) {
87 		if (func->type == ZEND_INTERNAL_FUNCTION) {
88 			zend_error(E_WARNING, "Cannot unbind $this of internal method");
89 			return 0;
90 		} else {
91 			zend_error(E_DEPRECATED, "Unbinding $this of a method is deprecated");
92 		}
93 	} else if (!is_fake_closure && !Z_ISUNDEF(closure->this_ptr)
94 			&& (func->common.fn_flags & ZEND_ACC_USES_THIS)) {
95 		// TODO: Only deprecate if it had $this *originally*?
96 		zend_error(E_DEPRECATED, "Unbinding $this of closure is deprecated");
97 	}
98 
99 	if (scope && scope != func->common.scope && scope->type == ZEND_INTERNAL_CLASS) {
100 		/* rebinding to internal class is not allowed */
101 		zend_error(E_WARNING, "Cannot bind closure to scope of internal class %s",
102 				ZSTR_VAL(scope->name));
103 		return 0;
104 	}
105 
106 	if (is_fake_closure && scope != func->common.scope) {
107 		if (func->common.scope == NULL) {
108 			zend_error(E_WARNING, "Cannot rebind scope of closure created from function");
109 		} else {
110 			zend_error(E_WARNING, "Cannot rebind scope of closure created from method");
111 		}
112 		return 0;
113 	}
114 
115 	return 1;
116 }
117 /* }}} */
118 
119 /* {{{ proto mixed Closure::call(object to [, mixed parameter] [, mixed ...] )
120    Call closure, binding to a given object with its class as the scope */
ZEND_METHODnull121 ZEND_METHOD(Closure, call)
122 {
123 	zval *newthis, closure_result;
124 	zend_closure *closure;
125 	zend_fcall_info fci;
126 	zend_fcall_info_cache fci_cache;
127 	zend_function my_function;
128 	zend_object *newobj;
129 
130 	fci.param_count = 0;
131 	fci.params = NULL;
132 
133 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "o*", &newthis, &fci.params, &fci.param_count) == FAILURE) {
134 		return;
135 	}
136 
137 	closure = (zend_closure *) Z_OBJ_P(ZEND_THIS);
138 
139 	newobj = Z_OBJ_P(newthis);
140 
141 	if (!zend_valid_closure_binding(closure, newthis, Z_OBJCE_P(newthis))) {
142 		return;
143 	}
144 
145 	if (closure->func.common.fn_flags & ZEND_ACC_GENERATOR) {
146 		zval new_closure;
147 		zend_create_closure(&new_closure, &closure->func, Z_OBJCE_P(newthis), closure->called_scope, newthis);
148 		closure = (zend_closure *) Z_OBJ(new_closure);
149 		fci_cache.function_handler = &closure->func;
150 	} else {
151 		memcpy(&my_function, &closure->func, closure->func.type == ZEND_USER_FUNCTION ? sizeof(zend_op_array) : sizeof(zend_internal_function));
152 		my_function.common.fn_flags &= ~ZEND_ACC_CLOSURE;
153 		/* use scope of passed object */
154 		my_function.common.scope = Z_OBJCE_P(newthis);
155 		fci_cache.function_handler = &my_function;
156 
157 		/* Runtime cache relies on bound scope to be immutable, hence we need a separate rt cache in case scope changed */
158 		if (ZEND_USER_CODE(my_function.type)
159 		 && (closure->func.common.scope != Z_OBJCE_P(newthis)
160 		  || (closure->func.common.fn_flags & ZEND_ACC_HEAP_RT_CACHE))) {
161 			void *ptr;
162 
163 			my_function.op_array.fn_flags |= ZEND_ACC_HEAP_RT_CACHE;
164 			ptr = emalloc(sizeof(void*) + my_function.op_array.cache_size);
165 			ZEND_MAP_PTR_INIT(my_function.op_array.run_time_cache, ptr);
166 			ptr = (char*)ptr + sizeof(void*);
167 			ZEND_MAP_PTR_SET(my_function.op_array.run_time_cache, ptr);
168 			memset(ptr, 0, my_function.op_array.cache_size);
169 		}
170 	}
171 
172 	fci_cache.called_scope = newobj->ce;
173 	fci_cache.object = fci.object = newobj;
174 
175 	fci.size = sizeof(fci);
176 	ZVAL_OBJ(&fci.function_name, &closure->std);
177 	fci.retval = &closure_result;
178 	fci.no_separation = 1;
179 
180 	if (zend_call_function(&fci, &fci_cache) == SUCCESS && Z_TYPE(closure_result) != IS_UNDEF) {
181 		if (Z_ISREF(closure_result)) {
182 			zend_unwrap_reference(&closure_result);
183 		}
184 		ZVAL_COPY_VALUE(return_value, &closure_result);
185 	}
186 
187 	if (fci_cache.function_handler->common.fn_flags & ZEND_ACC_GENERATOR) {
188 		/* copied upon generator creation */
189 		GC_DELREF(&closure->std);
190 	} else if (ZEND_USER_CODE(my_function.type)
191 	 && fci_cache.function_handler->common.fn_flags & ZEND_ACC_HEAP_RT_CACHE) {
192 		efree(ZEND_MAP_PTR(my_function.op_array.run_time_cache));
193 	}
194 }
195 /* }}} */
196 
197 /* {{{ proto Closure Closure::bind(callable old, object to [, mixed scope])
198    Create a closure from another one and bind to another object and scope */
ZEND_METHODnull199 ZEND_METHOD(Closure, bind)
200 {
201 	zval *newthis, *zclosure, *scope_arg = NULL;
202 	zend_closure *closure;
203 	zend_class_entry *ce, *called_scope;
204 
205 	if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Oo!|z", &zclosure, zend_ce_closure, &newthis, &scope_arg) == FAILURE) {
206 		return;
207 	}
208 
209 	closure = (zend_closure *)Z_OBJ_P(zclosure);
210 
211 	if (scope_arg != NULL) { /* scope argument was given */
212 		if (Z_TYPE_P(scope_arg) == IS_OBJECT) {
213 			ce = Z_OBJCE_P(scope_arg);
214 		} else if (Z_TYPE_P(scope_arg) == IS_NULL) {
215 			ce = NULL;
216 		} else {
217 			zend_string *tmp_class_name;
218 			zend_string *class_name = zval_get_tmp_string(scope_arg, &tmp_class_name);
219 			if (zend_string_equals_literal(class_name, "static")) {
220 				ce = closure->func.common.scope;
221 			} else if ((ce = zend_lookup_class(class_name)) == NULL) {
222 				zend_error(E_WARNING, "Class '%s' not found", ZSTR_VAL(class_name));
223 				zend_tmp_string_release(tmp_class_name);
224 				RETURN_NULL();
225 			}
226 			zend_tmp_string_release(tmp_class_name);
227 		}
228 	} else { /* scope argument not given; do not change the scope by default */
229 		ce = closure->func.common.scope;
230 	}
231 
232 	if (!zend_valid_closure_binding(closure, newthis, ce)) {
233 		return;
234 	}
235 
236 	if (newthis) {
237 		called_scope = Z_OBJCE_P(newthis);
238 	} else {
239 		called_scope = ce;
240 	}
241 
242 	zend_create_closure(return_value, &closure->func, ce, called_scope, newthis);
243 }
244 /* }}} */
245 
ZEND_NAMED_FUNCTIONnull246 static ZEND_NAMED_FUNCTION(zend_closure_call_magic) /* {{{ */ {
247 	zend_fcall_info fci;
248 	zend_fcall_info_cache fcc;
249 	zval params[2];
250 
251 	memset(&fci, 0, sizeof(zend_fcall_info));
252 	memset(&fcc, 0, sizeof(zend_fcall_info_cache));
253 
254 	fci.size = sizeof(zend_fcall_info);
255 	fci.retval = return_value;
256 
257 	fcc.function_handler = (EX(func)->internal_function.fn_flags & ZEND_ACC_STATIC) ?
258 		EX(func)->internal_function.scope->__callstatic : EX(func)->internal_function.scope->__call;
259 	fci.params = params;
260 	fci.param_count = 2;
261 	ZVAL_STR(&fci.params[0], EX(func)->common.function_name);
262 	if (ZEND_NUM_ARGS()) {
263 		array_init_size(&fci.params[1], ZEND_NUM_ARGS());
264 		zend_copy_parameters_array(ZEND_NUM_ARGS(), &fci.params[1]);
265 	} else {
266 		ZVAL_EMPTY_ARRAY(&fci.params[1]);
267 	}
268 
269 	fcc.object = fci.object = Z_OBJ_P(ZEND_THIS);
270 
271 	zend_call_function(&fci, &fcc);
272 
273 	zval_ptr_dtor(&fci.params[0]);
274 	zval_ptr_dtor(&fci.params[1]);
275 }
276 /* }}} */
277 
zend_create_closure_from_callable(zval *return_value, zval *callable, char **error)278 static int zend_create_closure_from_callable(zval *return_value, zval *callable, char **error) /* {{{ */ {
279 	zend_fcall_info_cache fcc;
280 	zend_function *mptr;
281 	zval instance;
282 	zend_internal_function call;
283 
284 	if (!zend_is_callable_ex(callable, NULL, 0, NULL, &fcc, error)) {
285 		return FAILURE;
286 	}
287 
288 	mptr = fcc.function_handler;
289 	if (mptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
290 		/* For Closure::fromCallable([$closure, "__invoke"]) return $closure. */
291 		if (fcc.object && fcc.object->ce == zend_ce_closure
292 				&& zend_string_equals_literal(mptr->common.function_name, "__invoke")) {
293 			ZVAL_OBJ(return_value, fcc.object);
294 			GC_ADDREF(fcc.object);
295 			zend_free_trampoline(mptr);
296 			return SUCCESS;
297 		}
298 
299 		if (!mptr->common.scope) {
300 			return FAILURE;
301 		}
302 		if (mptr->common.fn_flags & ZEND_ACC_STATIC) {
303 			if (!mptr->common.scope->__callstatic) {
304 				return FAILURE;
305 			}
306 		} else {
307 			if (!mptr->common.scope->__call) {
308 				return FAILURE;
309 			}
310 		}
311 
312 		memset(&call, 0, sizeof(zend_internal_function));
313 		call.type = ZEND_INTERNAL_FUNCTION;
314 		call.fn_flags = mptr->common.fn_flags & ZEND_ACC_STATIC;
315 		call.handler = zend_closure_call_magic;
316 		call.function_name = mptr->common.function_name;
317 		call.scope = mptr->common.scope;
318 
319 		zend_free_trampoline(mptr);
320 		mptr = (zend_function *) &call;
321 	}
322 
323 	if (fcc.object) {
324 		ZVAL_OBJ(&instance, fcc.object);
325 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, &instance);
326 	} else {
327 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, NULL);
328 	}
329 
330 	return SUCCESS;
331 }
332 /* }}} */
333 
334 /* {{{ proto Closure Closure::fromCallable(callable callable)
335    Create a closure from a callable using the current scope. */
ZEND_METHODnull336 ZEND_METHOD(Closure, fromCallable)
337 {
338 	zval *callable;
339 	int success;
340 	char *error = NULL;
341 
342 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callable) == FAILURE) {
343 		return;
344 	}
345 
346 	if (Z_TYPE_P(callable) == IS_OBJECT && instanceof_function(Z_OBJCE_P(callable), zend_ce_closure)) {
347 		/* It's already a closure */
348 		RETURN_ZVAL(callable, 1, 0);
349 	}
350 
351 	/* create closure as if it were called from parent scope */
352 	EG(current_execute_data) = EX(prev_execute_data);
353 	success = zend_create_closure_from_callable(return_value, callable, &error);
354 	EG(current_execute_data) = execute_data;
355 
356 	if (success == FAILURE || error) {
357 		if (error) {
358 			zend_type_error("Failed to create closure from callable: %s", error);
359 			efree(error);
360 		} else {
361 			zend_type_error("Failed to create closure from callable");
362 		}
363 	}
364 }
365 /* }}} */
366 
zend_closure_get_constructor(zend_object *object)367 static ZEND_COLD zend_function *zend_closure_get_constructor(zend_object *object) /* {{{ */
368 {
369 	zend_throw_error(NULL, "Instantiation of 'Closure' is not allowed");
370 	return NULL;
371 }
372 /* }}} */
373 
zend_closure_compare_objects(zval *o1, zval *o2)374 static int zend_closure_compare_objects(zval *o1, zval *o2) /* {{{ */
375 {
376 	return (Z_OBJ_P(o1) != Z_OBJ_P(o2));
377 }
378 /* }}} */
379 
zend_get_closure_invoke_method(zend_object *object)380 ZEND_API zend_function *zend_get_closure_invoke_method(zend_object *object) /* {{{ */
381 {
382 	zend_closure *closure = (zend_closure *)object;
383 	zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function));
384 	const uint32_t keep_flags =
385 		ZEND_ACC_RETURN_REFERENCE | ZEND_ACC_VARIADIC | ZEND_ACC_HAS_RETURN_TYPE;
386 
387 	invoke->common = closure->func.common;
388 	/* We return ZEND_INTERNAL_FUNCTION, but arg_info representation is the
389 	 * same as for ZEND_USER_FUNCTION (uses zend_string* instead of char*).
390 	 * This is not a problem, because ZEND_ACC_HAS_TYPE_HINTS is never set,
391 	 * and we won't check arguments on internal function. We also set
392 	 * ZEND_ACC_USER_ARG_INFO flag to prevent invalid usage by Reflection */
393 	invoke->type = ZEND_INTERNAL_FUNCTION;
394 	invoke->internal_function.fn_flags =
395 		ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & keep_flags);
396 	if (closure->func.type != ZEND_INTERNAL_FUNCTION || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO)) {
397 		invoke->internal_function.fn_flags |=
398 			ZEND_ACC_USER_ARG_INFO;
399 	}
400 	invoke->internal_function.handler = ZEND_MN(Closure___invoke);
401 	invoke->internal_function.module = 0;
402 	invoke->internal_function.scope = zend_ce_closure;
403 	invoke->internal_function.function_name = ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE);
404 	return invoke;
405 }
406 /* }}} */
407 
zend_get_closure_method_def(zval *obj)408 ZEND_API const zend_function *zend_get_closure_method_def(zval *obj) /* {{{ */
409 {
410 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
411 	return &closure->func;
412 }
413 /* }}} */
414 
zend_get_closure_this_ptr(zval *obj)415 ZEND_API zval* zend_get_closure_this_ptr(zval *obj) /* {{{ */
416 {
417 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
418 	return &closure->this_ptr;
419 }
420 /* }}} */
421 
zend_closure_get_method(zend_object **object, zend_string *method, const zval *key)422 static zend_function *zend_closure_get_method(zend_object **object, zend_string *method, const zval *key) /* {{{ */
423 {
424 	if (zend_string_equals_literal_ci(method, ZEND_INVOKE_FUNC_NAME)) {
425 		return zend_get_closure_invoke_method(*object);
426 	}
427 
428 	return zend_std_get_method(object, method, key);
429 }
430 /* }}} */
431 
zend_closure_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv)432 static ZEND_COLD zval *zend_closure_read_property(zval *object, zval *member, int type, void **cache_slot, zval *rv) /* {{{ */
433 {
434 	ZEND_CLOSURE_PROPERTY_ERROR();
435 	return &EG(uninitialized_zval);
436 }
437 /* }}} */
438 
zend_closure_write_property(zval *object, zval *member, zval *value, void **cache_slot)439 static ZEND_COLD zval *zend_closure_write_property(zval *object, zval *member, zval *value, void **cache_slot) /* {{{ */
440 {
441 	ZEND_CLOSURE_PROPERTY_ERROR();
442 	return &EG(error_zval);
443 }
444 /* }}} */
445 
zend_closure_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot)446 static ZEND_COLD zval *zend_closure_get_property_ptr_ptr(zval *object, zval *member, int type, void **cache_slot) /* {{{ */
447 {
448 	ZEND_CLOSURE_PROPERTY_ERROR();
449 	return NULL;
450 }
451 /* }}} */
452 
zend_closure_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot)453 static ZEND_COLD int zend_closure_has_property(zval *object, zval *member, int has_set_exists, void **cache_slot) /* {{{ */
454 {
455 	if (has_set_exists != ZEND_PROPERTY_EXISTS) {
456 		ZEND_CLOSURE_PROPERTY_ERROR();
457 	}
458 	return 0;
459 }
460 /* }}} */
461 
zend_closure_unset_property(zval *object, zval *member, void **cache_slot)462 static ZEND_COLD void zend_closure_unset_property(zval *object, zval *member, void **cache_slot) /* {{{ */
463 {
464 	ZEND_CLOSURE_PROPERTY_ERROR();
465 }
466 /* }}} */
467 
zend_closure_free_storage(zend_object *object)468 static void zend_closure_free_storage(zend_object *object) /* {{{ */
469 {
470 	zend_closure *closure = (zend_closure *)object;
471 
472 	zend_object_std_dtor(&closure->std);
473 
474 	if (closure->func.type == ZEND_USER_FUNCTION) {
475 		destroy_op_array(&closure->func.op_array);
476 	}
477 
478 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
479 		zval_ptr_dtor(&closure->this_ptr);
480 	}
481 }
482 /* }}} */
483 
zend_closure_new(zend_class_entry *class_type)484 static zend_object *zend_closure_new(zend_class_entry *class_type) /* {{{ */
485 {
486 	zend_closure *closure;
487 
488 	closure = emalloc(sizeof(zend_closure));
489 	memset(closure, 0, sizeof(zend_closure));
490 
491 	zend_object_std_init(&closure->std, class_type);
492 	closure->std.handlers = &closure_handlers;
493 
494 	return (zend_object*)closure;
495 }
496 /* }}} */
497 
zend_closure_clone(zval *zobject)498 static zend_object *zend_closure_clone(zval *zobject) /* {{{ */
499 {
500 	zend_closure *closure = (zend_closure *)Z_OBJ_P(zobject);
501 	zval result;
502 
503 	zend_create_closure(&result, &closure->func,
504 		closure->func.common.scope, closure->called_scope, &closure->this_ptr);
505 	return Z_OBJ(result);
506 }
507 /* }}} */
508 
zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr)509 int zend_closure_get_closure(zval *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr) /* {{{ */
510 {
511 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
512 	*fptr_ptr = &closure->func;
513 	*ce_ptr = closure->called_scope;
514 
515 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
516 		*obj_ptr = Z_OBJ(closure->this_ptr);
517 	} else {
518 		*obj_ptr = NULL;
519 	}
520 
521 	return SUCCESS;
522 }
523 /* }}} */
524 
zend_closure_get_debug_info(zval *object, int *is_temp)525 static HashTable *zend_closure_get_debug_info(zval *object, int *is_temp) /* {{{ */
526 {
527 	zend_closure *closure = (zend_closure *)Z_OBJ_P(object);
528 	zval val;
529 	struct _zend_arg_info *arg_info = closure->func.common.arg_info;
530 	HashTable *debug_info;
531 	zend_bool zstr_args = (closure->func.type == ZEND_USER_FUNCTION) || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO);
532 
533 	*is_temp = 1;
534 
535 	debug_info = zend_new_array(8);
536 
537 	if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
538 		zval *var;
539 		HashTable *static_variables =
540 			ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
541 		ZVAL_ARR(&val, zend_array_dup(static_variables));
542 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_STATIC), &val);
543 		ZEND_HASH_FOREACH_VAL(Z_ARRVAL(val), var) {
544 			if (Z_TYPE_P(var) == IS_CONSTANT_AST) {
545 				zval_ptr_dtor(var);
546 				ZVAL_STRING(var, "<constant ast>");
547 			}
548 		} ZEND_HASH_FOREACH_END();
549 	}
550 
551 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
552 		Z_ADDREF(closure->this_ptr);
553 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_THIS), &closure->this_ptr);
554 	}
555 
556 	if (arg_info &&
557 		(closure->func.common.num_args ||
558 		 (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
559 		uint32_t i, num_args, required = closure->func.common.required_num_args;
560 
561 		array_init(&val);
562 
563 		num_args = closure->func.common.num_args;
564 		if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
565 			num_args++;
566 		}
567 		for (i = 0; i < num_args; i++) {
568 			zend_string *name;
569 			zval info;
570 			if (arg_info->name) {
571 				if (zstr_args) {
572 					name = zend_strpprintf(0, "%s$%s",
573 							arg_info->pass_by_reference ? "&" : "",
574 							ZSTR_VAL(arg_info->name));
575 				} else {
576 					name = zend_strpprintf(0, "%s$%s",
577 							arg_info->pass_by_reference ? "&" : "",
578 							((zend_internal_arg_info*)arg_info)->name);
579 				}
580 			} else {
581 				name = zend_strpprintf(0, "%s$param%d",
582 						arg_info->pass_by_reference ? "&" : "",
583 						i + 1);
584 			}
585 			ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
586 			zend_hash_update(Z_ARRVAL(val), name, &info);
587 			zend_string_release_ex(name, 0);
588 			arg_info++;
589 		}
590 		zend_hash_str_update(debug_info, "parameter", sizeof("parameter")-1, &val);
591 	}
592 
593 	return debug_info;
594 }
595 /* }}} */
596 
zend_closure_get_gc(zval *obj, zval **table, int *n)597 static HashTable *zend_closure_get_gc(zval *obj, zval **table, int *n) /* {{{ */
598 {
599 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
600 
601 	*table = Z_TYPE(closure->this_ptr) != IS_NULL ? &closure->this_ptr : NULL;
602 	*n = Z_TYPE(closure->this_ptr) != IS_NULL ? 1 : 0;
603 	return (closure->func.type == ZEND_USER_FUNCTION) ?
604 		ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr) : NULL;
605 }
606 /* }}} */
607 
608 /* {{{ proto Closure::__construct()
609    Private constructor preventing instantiation */
ZEND_METHODnull610 ZEND_COLD ZEND_METHOD(Closure, __construct)
611 {
612 	zend_throw_error(NULL, "Instantiation of 'Closure' is not allowed");
613 }
614 /* }}} */
615 
616 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bindto, 0, 0, 1)
617 	ZEND_ARG_INFO(0, newthis)
618 	ZEND_ARG_INFO(0, newscope)
619 ZEND_END_ARG_INFO()
620 
621 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_bind, 0, 0, 2)
622 	ZEND_ARG_INFO(0, closure)
623 	ZEND_ARG_INFO(0, newthis)
624 	ZEND_ARG_INFO(0, newscope)
625 ZEND_END_ARG_INFO()
626 
627 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_call, 0, 0, 1)
628 	ZEND_ARG_INFO(0, newthis)
629 	ZEND_ARG_VARIADIC_INFO(0, parameters)
630 ZEND_END_ARG_INFO()
631 
632 ZEND_BEGIN_ARG_INFO_EX(arginfo_closure_fromcallable, 0, 0, 1)
633 	ZEND_ARG_INFO(0, callable)
634 ZEND_END_ARG_INFO()
635 
636 static const zend_function_entry closure_functions[] = {
637 	ZEND_ME(Closure, __construct, NULL, ZEND_ACC_PRIVATE)
638 	ZEND_ME(Closure, bind, arginfo_closure_bind, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
639 	ZEND_MALIAS(Closure, bindTo, bind, arginfo_closure_bindto, ZEND_ACC_PUBLIC)
640 	ZEND_ME(Closure, call, arginfo_closure_call, ZEND_ACC_PUBLIC)
641 	ZEND_ME(Closure, fromCallable, arginfo_closure_fromcallable, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
642 	ZEND_FE_END
643 };
644 
zend_register_closure_ce(void)645 void zend_register_closure_ce(void) /* {{{ */
646 {
647 	zend_class_entry ce;
648 
649 	INIT_CLASS_ENTRY(ce, "Closure", closure_functions);
650 	zend_ce_closure = zend_register_internal_class(&ce);
651 	zend_ce_closure->ce_flags |= ZEND_ACC_FINAL;
652 	zend_ce_closure->create_object = zend_closure_new;
653 	zend_ce_closure->serialize = zend_class_serialize_deny;
654 	zend_ce_closure->unserialize = zend_class_unserialize_deny;
655 
656 	memcpy(&closure_handlers, &std_object_handlers, sizeof(zend_object_handlers));
657 	closure_handlers.free_obj = zend_closure_free_storage;
658 	closure_handlers.get_constructor = zend_closure_get_constructor;
659 	closure_handlers.get_method = zend_closure_get_method;
660 	closure_handlers.write_property = zend_closure_write_property;
661 	closure_handlers.read_property = zend_closure_read_property;
662 	closure_handlers.get_property_ptr_ptr = zend_closure_get_property_ptr_ptr;
663 	closure_handlers.has_property = zend_closure_has_property;
664 	closure_handlers.unset_property = zend_closure_unset_property;
665 	closure_handlers.compare_objects = zend_closure_compare_objects;
666 	closure_handlers.clone_obj = zend_closure_clone;
667 	closure_handlers.get_debug_info = zend_closure_get_debug_info;
668 	closure_handlers.get_closure = zend_closure_get_closure;
669 	closure_handlers.get_gc = zend_closure_get_gc;
670 }
671 /* }}} */
672 
ZEND_NAMED_FUNCTIONnull673 static ZEND_NAMED_FUNCTION(zend_closure_internal_handler) /* {{{ */
674 {
675 	zend_closure *closure = (zend_closure*)ZEND_CLOSURE_OBJECT(EX(func));
676 	closure->orig_internal_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
677 	OBJ_RELEASE((zend_object*)closure);
678 	EX(func) = NULL;
679 }
680 /* }}} */
681 
zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr)682 ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
683 {
684 	zend_closure *closure;
685 
686 	object_init_ex(res, zend_ce_closure);
687 
688 	closure = (zend_closure *)Z_OBJ_P(res);
689 
690 	if ((scope == NULL) && this_ptr && (Z_TYPE_P(this_ptr) != IS_UNDEF)) {
691 		/* use dummy scope if we're binding an object without specifying a scope */
692 		/* maybe it would be better to create one for this purpose */
693 		scope = zend_ce_closure;
694 	}
695 
696 	if (func->type == ZEND_USER_FUNCTION) {
697 		memcpy(&closure->func, func, sizeof(zend_op_array));
698 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
699 		closure->func.common.fn_flags &= ~ZEND_ACC_IMMUTABLE;
700 
701 		if (closure->func.op_array.static_variables) {
702 			closure->func.op_array.static_variables =
703 				zend_array_dup(closure->func.op_array.static_variables);
704 		}
705 		ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr,
706 			&closure->func.op_array.static_variables);
707 
708 		/* Runtime cache is scope-dependent, so we cannot reuse it if the scope changed */
709 		if (!ZEND_MAP_PTR_GET(closure->func.op_array.run_time_cache)
710 			|| func->common.scope != scope
711 			|| (func->common.fn_flags & ZEND_ACC_HEAP_RT_CACHE)
712 		) {
713 			void *ptr;
714 
715 			if (!ZEND_MAP_PTR_GET(func->op_array.run_time_cache)
716 			 && (func->common.fn_flags & ZEND_ACC_CLOSURE)
717 			 && (func->common.scope == scope ||
718 			     !(func->common.fn_flags & ZEND_ACC_IMMUTABLE))) {
719 				/* If a real closure is used for the first time, we create a shared runtime cache
720 				 * and remember which scope it is for. */
721 				if (func->common.scope != scope) {
722 					func->common.scope = scope;
723 				}
724 				closure->func.op_array.fn_flags &= ~ZEND_ACC_HEAP_RT_CACHE;
725 				ptr = zend_arena_alloc(&CG(arena), func->op_array.cache_size);
726 				ZEND_MAP_PTR_SET(func->op_array.run_time_cache, ptr);
727 				ZEND_MAP_PTR_SET(closure->func.op_array.run_time_cache, ptr);
728 			} else {
729 				/* Otherwise, we use a non-shared runtime cache */
730 				closure->func.op_array.fn_flags |= ZEND_ACC_HEAP_RT_CACHE;
731 				ptr = emalloc(sizeof(void*) + func->op_array.cache_size);
732 				ZEND_MAP_PTR_INIT(closure->func.op_array.run_time_cache, ptr);
733 				ptr = (char*)ptr + sizeof(void*);
734 				ZEND_MAP_PTR_SET(closure->func.op_array.run_time_cache, ptr);
735 			}
736 			memset(ptr, 0, func->op_array.cache_size);
737 		}
738 		if (closure->func.op_array.refcount) {
739 			(*closure->func.op_array.refcount)++;
740 		}
741 	} else {
742 		memcpy(&closure->func, func, sizeof(zend_internal_function));
743 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
744 		/* wrap internal function handler to avoid memory leak */
745 		if (UNEXPECTED(closure->func.internal_function.handler == zend_closure_internal_handler)) {
746 			/* avoid infinity recursion, by taking handler from nested closure */
747 			zend_closure *nested = (zend_closure*)((char*)func - XtOffsetOf(zend_closure, func));
748 			ZEND_ASSERT(nested->std.ce == zend_ce_closure);
749 			closure->orig_internal_handler = nested->orig_internal_handler;
750 		} else {
751 			closure->orig_internal_handler = closure->func.internal_function.handler;
752 		}
753 		closure->func.internal_function.handler = zend_closure_internal_handler;
754 		if (!func->common.scope) {
755 			/* if it's a free function, we won't set scope & this since they're meaningless */
756 			this_ptr = NULL;
757 			scope = NULL;
758 		}
759 	}
760 
761 	ZVAL_UNDEF(&closure->this_ptr);
762 	/* Invariant:
763 	 * If the closure is unscoped or static, it has no bound object. */
764 	closure->func.common.scope = scope;
765 	closure->called_scope = called_scope;
766 	if (scope) {
767 		closure->func.common.fn_flags |= ZEND_ACC_PUBLIC;
768 		if (this_ptr && Z_TYPE_P(this_ptr) == IS_OBJECT && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) {
769 			Z_ADDREF_P(this_ptr);
770 			ZVAL_OBJ(&closure->this_ptr, Z_OBJ_P(this_ptr));
771 		}
772 	}
773 }
774 /* }}} */
775 
zend_create_fake_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr)776 ZEND_API void zend_create_fake_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
777 {
778 	zend_closure *closure;
779 
780 	zend_create_closure(res, func, scope, called_scope, this_ptr);
781 
782 	closure = (zend_closure *)Z_OBJ_P(res);
783 	closure->func.common.fn_flags |= ZEND_ACC_FAKE_CLOSURE;
784 }
785 /* }}} */
786 
zend_closure_bind_var(zval *closure_zv, zend_string *var_name, zval *var)787 void zend_closure_bind_var(zval *closure_zv, zend_string *var_name, zval *var) /* {{{ */
788 {
789 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
790 	HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
791 	zend_hash_update(static_variables, var_name, var);
792 }
793 /* }}} */
794 
zend_closure_bind_var_ex(zval *closure_zv, uint32_t offset, zval *val)795 void zend_closure_bind_var_ex(zval *closure_zv, uint32_t offset, zval *val) /* {{{ */
796 {
797 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
798 	HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
799 	zval *var = (zval*)((char*)static_variables->arData + offset);
800 	zval_ptr_dtor(var);
801 	ZVAL_COPY_VALUE(var, val);
802 }
803 /* }}} */
804