xref: /PHP-8.2/Zend/zend_closures.c (revision 8fb51d4f)
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 #include "zend_closures_arginfo.h"
30 
31 typedef struct _zend_closure {
32 	zend_object       std;
33 	zend_function     func;
34 	zval              this_ptr;
35 	zend_class_entry *called_scope;
36 	zif_handler       orig_internal_handler;
37 } zend_closure;
38 
39 /* non-static since it needs to be referenced */
40 ZEND_API zend_class_entry *zend_ce_closure;
41 static zend_object_handlers closure_handlers;
42 
ZEND_METHOD(Closure,__invoke)43 ZEND_METHOD(Closure, __invoke) /* {{{ */
44 {
45 	zend_function *func = EX(func);
46 	zval *args;
47 	uint32_t num_args;
48 	HashTable *named_args;
49 
50 	ZEND_PARSE_PARAMETERS_START(0, -1)
51 		Z_PARAM_VARIADIC_WITH_NAMED(args, num_args, named_args)
52 	ZEND_PARSE_PARAMETERS_END();
53 
54 	if (call_user_function_named(CG(function_table), NULL, ZEND_THIS, return_value, num_args, args, named_args) == FAILURE) {
55 		RETVAL_FALSE;
56 	}
57 
58 	/* destruct the function also, then - we have allocated it in get_method */
59 	zend_string_release_ex(func->internal_function.function_name, 0);
60 	efree(func);
61 
62 	/* Set the func pointer to NULL. Prior to PHP 8.3, this was only done for debug builds,
63 	 * because debug builds check certain properties after the call and needed to know this
64 	 * had been freed.
65 	 * However, extensions can proxy zend_execute_internal, and it's a bit surprising to have
66 	 * an invalid func pointer sitting on there, so this was changed in PHP 8.3.
67 	 */
68 	execute_data->func = NULL;
69 }
70 /* }}} */
71 
zend_valid_closure_binding(zend_closure * closure,zval * newthis,zend_class_entry * scope)72 static bool zend_valid_closure_binding(
73 		zend_closure *closure, zval *newthis, zend_class_entry *scope) /* {{{ */
74 {
75 	zend_function *func = &closure->func;
76 	bool is_fake_closure = (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) != 0;
77 	if (newthis) {
78 		if (func->common.fn_flags & ZEND_ACC_STATIC) {
79 			zend_error(E_WARNING, "Cannot bind an instance to a static closure");
80 			return 0;
81 		}
82 
83 		if (is_fake_closure && func->common.scope &&
84 				!instanceof_function(Z_OBJCE_P(newthis), func->common.scope)) {
85 			/* Binding incompatible $this to an internal method is not supported. */
86 			zend_error(E_WARNING, "Cannot bind method %s::%s() to object of class %s",
87 					ZSTR_VAL(func->common.scope->name),
88 					ZSTR_VAL(func->common.function_name),
89 					ZSTR_VAL(Z_OBJCE_P(newthis)->name));
90 			return 0;
91 		}
92 	} else if (is_fake_closure && func->common.scope
93 			&& !(func->common.fn_flags & ZEND_ACC_STATIC)) {
94 		zend_error(E_WARNING, "Cannot unbind $this of method");
95 		return 0;
96 	} else if (!is_fake_closure && !Z_ISUNDEF(closure->this_ptr)
97 			&& (func->common.fn_flags & ZEND_ACC_USES_THIS)) {
98 		zend_error(E_WARNING, "Cannot unbind $this of closure using $this");
99 		return 0;
100 	}
101 
102 	if (scope && scope != func->common.scope && scope->type == ZEND_INTERNAL_CLASS) {
103 		/* rebinding to internal class is not allowed */
104 		zend_error(E_WARNING, "Cannot bind closure to scope of internal class %s",
105 				ZSTR_VAL(scope->name));
106 		return 0;
107 	}
108 
109 	if (is_fake_closure && scope != func->common.scope) {
110 		if (func->common.scope == NULL) {
111 			zend_error(E_WARNING, "Cannot rebind scope of closure created from function");
112 		} else {
113 			zend_error(E_WARNING, "Cannot rebind scope of closure created from method");
114 		}
115 		return 0;
116 	}
117 
118 	return 1;
119 }
120 /* }}} */
121 
122 /* {{{ Call closure, binding to a given object with its class as the scope */
ZEND_METHOD(Closure,call)123 ZEND_METHOD(Closure, call)
124 {
125 	zval *newthis, closure_result;
126 	zend_closure *closure;
127 	zend_fcall_info fci;
128 	zend_fcall_info_cache fci_cache;
129 	zend_object *newobj;
130 	zend_class_entry *newclass;
131 
132 	fci.param_count = 0;
133 	fci.params = NULL;
134 
135 	ZEND_PARSE_PARAMETERS_START(1, -1)
136 		Z_PARAM_OBJECT(newthis)
137 		Z_PARAM_VARIADIC_WITH_NAMED(fci.params, fci.param_count, fci.named_params)
138 	ZEND_PARSE_PARAMETERS_END();
139 
140 	closure = (zend_closure *) Z_OBJ_P(ZEND_THIS);
141 
142 	newobj = Z_OBJ_P(newthis);
143 	newclass = newobj->ce;
144 
145 	if (!zend_valid_closure_binding(closure, newthis, newclass)) {
146 		return;
147 	}
148 
149 	fci_cache.called_scope = newclass;
150 	fci_cache.object = fci.object = newobj;
151 
152 	fci.size = sizeof(fci);
153 	ZVAL_OBJ(&fci.function_name, &closure->std);
154 	ZVAL_UNDEF(&closure_result);
155 	fci.retval = &closure_result;
156 
157 	if (closure->func.common.fn_flags & ZEND_ACC_GENERATOR) {
158 		zval new_closure;
159 		zend_create_closure(&new_closure, &closure->func, newclass, closure->called_scope, newthis);
160 		closure = (zend_closure *) Z_OBJ(new_closure);
161 		fci_cache.function_handler = &closure->func;
162 
163 		zend_call_function(&fci, &fci_cache);
164 
165 		/* copied upon generator creation */
166 		GC_DELREF(&closure->std);
167 	} else {
168 		zend_closure *fake_closure;
169 		zend_function *my_function;
170 
171 		fake_closure = emalloc(sizeof(zend_closure));
172 		memset(&fake_closure->std, 0, sizeof(fake_closure->std));
173 		fake_closure->std.gc.refcount = 1;
174 		fake_closure->std.gc.u.type_info = GC_NULL;
175 		ZVAL_UNDEF(&fake_closure->this_ptr);
176 		fake_closure->called_scope = NULL;
177 		my_function = &fake_closure->func;
178 		if (ZEND_USER_CODE(closure->func.type)) {
179 			memcpy(my_function, &closure->func, sizeof(zend_op_array));
180 		} else {
181 			memcpy(my_function, &closure->func, sizeof(zend_internal_function));
182 		}
183 		/* use scope of passed object */
184 		my_function->common.scope = newclass;
185 		if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
186 			my_function->internal_function.handler = closure->orig_internal_handler;
187 		}
188 		fci_cache.function_handler = my_function;
189 
190 		/* Runtime cache relies on bound scope to be immutable, hence we need a separate rt cache in case scope changed */
191 		if (ZEND_USER_CODE(my_function->type)
192 		 && (closure->func.common.scope != newclass
193 		  || (closure->func.common.fn_flags & ZEND_ACC_HEAP_RT_CACHE))) {
194 			void *ptr;
195 
196 			my_function->op_array.fn_flags |= ZEND_ACC_HEAP_RT_CACHE;
197 			ptr = emalloc(my_function->op_array.cache_size);
198 			ZEND_MAP_PTR_INIT(my_function->op_array.run_time_cache, ptr);
199 			memset(ptr, 0, my_function->op_array.cache_size);
200 		}
201 
202 		zend_call_function(&fci, &fci_cache);
203 
204 		if (ZEND_USER_CODE(my_function->type)) {
205 			if (fci_cache.function_handler->common.fn_flags & ZEND_ACC_HEAP_RT_CACHE) {
206 				efree(ZEND_MAP_PTR(my_function->op_array.run_time_cache));
207 			}
208 		}
209 		efree_size(fake_closure, sizeof(zend_closure));
210 	}
211 
212 	if (Z_TYPE(closure_result) != IS_UNDEF) {
213 		if (Z_ISREF(closure_result)) {
214 			zend_unwrap_reference(&closure_result);
215 		}
216 		ZVAL_COPY_VALUE(return_value, &closure_result);
217 	}
218 }
219 /* }}} */
220 
do_closure_bind(zval * return_value,zval * zclosure,zval * newthis,zend_object * scope_obj,zend_string * scope_str)221 static void do_closure_bind(zval *return_value, zval *zclosure, zval *newthis, zend_object *scope_obj, zend_string *scope_str)
222 {
223 	zend_class_entry *ce, *called_scope;
224 	zend_closure *closure = (zend_closure *) Z_OBJ_P(zclosure);
225 
226 	if (scope_obj) {
227 		ce = scope_obj->ce;
228 	} else if (scope_str) {
229 		if (zend_string_equals(scope_str, ZSTR_KNOWN(ZEND_STR_STATIC))) {
230 			ce = closure->func.common.scope;
231 		} else if ((ce = zend_lookup_class(scope_str)) == NULL) {
232 			zend_error(E_WARNING, "Class \"%s\" not found", ZSTR_VAL(scope_str));
233 			RETURN_NULL();
234 		}
235 	} else {
236 		ce = NULL;
237 	}
238 
239 	if (!zend_valid_closure_binding(closure, newthis, ce)) {
240 		return;
241 	}
242 
243 	if (newthis) {
244 		called_scope = Z_OBJCE_P(newthis);
245 	} else {
246 		called_scope = ce;
247 	}
248 
249 	zend_create_closure(return_value, &closure->func, ce, called_scope, newthis);
250 }
251 
252 /* {{{ Create a closure from another one and bind to another object and scope */
ZEND_METHOD(Closure,bind)253 ZEND_METHOD(Closure, bind)
254 {
255 	zval *zclosure, *newthis;
256 	zend_object *scope_obj = NULL;
257 	zend_string *scope_str = ZSTR_KNOWN(ZEND_STR_STATIC);
258 
259 	ZEND_PARSE_PARAMETERS_START(2, 3)
260 		Z_PARAM_OBJECT_OF_CLASS(zclosure, zend_ce_closure)
261 		Z_PARAM_OBJECT_OR_NULL(newthis)
262 		Z_PARAM_OPTIONAL
263 		Z_PARAM_OBJ_OR_STR_OR_NULL(scope_obj, scope_str)
264 	ZEND_PARSE_PARAMETERS_END();
265 
266 	do_closure_bind(return_value, zclosure, newthis, scope_obj, scope_str);
267 }
268 
269 /* {{{ Create a closure from another one and bind to another object and scope */
ZEND_METHOD(Closure,bindTo)270 ZEND_METHOD(Closure, bindTo)
271 {
272 	zval *newthis;
273 	zend_object *scope_obj = NULL;
274 	zend_string *scope_str = ZSTR_KNOWN(ZEND_STR_STATIC);
275 
276 	ZEND_PARSE_PARAMETERS_START(1, 2)
277 		Z_PARAM_OBJECT_OR_NULL(newthis)
278 		Z_PARAM_OPTIONAL
279 		Z_PARAM_OBJ_OR_STR_OR_NULL(scope_obj, scope_str)
280 	ZEND_PARSE_PARAMETERS_END();
281 
282 	do_closure_bind(return_value, getThis(), newthis, scope_obj, scope_str);
283 }
284 
ZEND_NAMED_FUNCTION(zend_closure_call_magic)285 static ZEND_NAMED_FUNCTION(zend_closure_call_magic) /* {{{ */ {
286 	zend_fcall_info fci;
287 	zend_fcall_info_cache fcc;
288 	zval params[2];
289 
290 	memset(&fci, 0, sizeof(zend_fcall_info));
291 	memset(&fcc, 0, sizeof(zend_fcall_info_cache));
292 
293 	fci.size = sizeof(zend_fcall_info);
294 	fci.retval = return_value;
295 
296 	fcc.function_handler = (EX(func)->internal_function.fn_flags & ZEND_ACC_STATIC) ?
297 		EX(func)->internal_function.scope->__callstatic : EX(func)->internal_function.scope->__call;
298 	fci.named_params = NULL;
299 	fci.params = params;
300 	fci.param_count = 2;
301 	ZVAL_STR(&fci.params[0], EX(func)->common.function_name);
302 	if (EX_CALL_INFO() & ZEND_CALL_HAS_EXTRA_NAMED_PARAMS) {
303 		zend_string *name;
304 		zval *named_param_zval;
305 		array_init_size(&fci.params[1], ZEND_NUM_ARGS() + zend_hash_num_elements(EX(extra_named_params)));
306 		/* Avoid conversion from packed to mixed later. */
307 		zend_hash_real_init_mixed(Z_ARRVAL(fci.params[1]));
308 		zend_copy_parameters_array(ZEND_NUM_ARGS(), &fci.params[1]);
309 		ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(EX(extra_named_params), name, named_param_zval) {
310 			Z_TRY_ADDREF_P(named_param_zval);
311 			zend_hash_add_new(Z_ARRVAL(fci.params[1]), name, named_param_zval);
312 		} ZEND_HASH_FOREACH_END();
313 	} else if (ZEND_NUM_ARGS()) {
314 		array_init_size(&fci.params[1], ZEND_NUM_ARGS());
315 		zend_copy_parameters_array(ZEND_NUM_ARGS(), &fci.params[1]);
316 	} else {
317 		ZVAL_EMPTY_ARRAY(&fci.params[1]);
318 	}
319 
320 	fcc.object = fci.object = Z_OBJ_P(ZEND_THIS);
321 	fcc.called_scope = zend_get_called_scope(EG(current_execute_data));
322 
323 	zend_call_function(&fci, &fcc);
324 
325 	zval_ptr_dtor(&fci.params[1]);
326 }
327 /* }}} */
328 
zend_create_closure_from_callable(zval * return_value,zval * callable,char ** error)329 static zend_result zend_create_closure_from_callable(zval *return_value, zval *callable, char **error) /* {{{ */ {
330 	zend_fcall_info_cache fcc;
331 	zend_function *mptr;
332 	zval instance;
333 	zend_internal_function call;
334 
335 	if (!zend_is_callable_ex(callable, NULL, 0, NULL, &fcc, error)) {
336 		return FAILURE;
337 	}
338 
339 	mptr = fcc.function_handler;
340 	if (mptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
341 		/* For Closure::fromCallable([$closure, "__invoke"]) return $closure. */
342 		if (fcc.object && fcc.object->ce == zend_ce_closure
343 				&& zend_string_equals(mptr->common.function_name, ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE))) {
344 			RETVAL_OBJ_COPY(fcc.object);
345 			zend_free_trampoline(mptr);
346 			return SUCCESS;
347 		}
348 
349 		if (!mptr->common.scope) {
350 			return FAILURE;
351 		}
352 		if (mptr->common.fn_flags & ZEND_ACC_STATIC) {
353 			if (!mptr->common.scope->__callstatic) {
354 				return FAILURE;
355 			}
356 		} else {
357 			if (!mptr->common.scope->__call) {
358 				return FAILURE;
359 			}
360 		}
361 
362 		memset(&call, 0, sizeof(zend_internal_function));
363 		call.type = ZEND_INTERNAL_FUNCTION;
364 		call.fn_flags = mptr->common.fn_flags & ZEND_ACC_STATIC;
365 		call.handler = zend_closure_call_magic;
366 		call.function_name = mptr->common.function_name;
367 		call.scope = mptr->common.scope;
368 
369 		zend_free_trampoline(mptr);
370 		mptr = (zend_function *) &call;
371 	}
372 
373 	if (fcc.object) {
374 		ZVAL_OBJ(&instance, fcc.object);
375 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, &instance);
376 	} else {
377 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, fcc.called_scope, NULL);
378 	}
379 
380 	if (&mptr->internal_function == &call) {
381 		zend_string_release(mptr->common.function_name);
382 	}
383 
384 	return SUCCESS;
385 }
386 /* }}} */
387 
388 /* {{{ Create a closure from a callable using the current scope. */
ZEND_METHOD(Closure,fromCallable)389 ZEND_METHOD(Closure, fromCallable)
390 {
391 	zval *callable;
392 	char *error = NULL;
393 
394 	ZEND_PARSE_PARAMETERS_START(1, 1)
395 		Z_PARAM_ZVAL(callable)
396 	ZEND_PARSE_PARAMETERS_END();
397 
398 	if (Z_TYPE_P(callable) == IS_OBJECT && instanceof_function(Z_OBJCE_P(callable), zend_ce_closure)) {
399 		/* It's already a closure */
400 		RETURN_COPY(callable);
401 	}
402 
403 	if (zend_create_closure_from_callable(return_value, callable, &error) == FAILURE) {
404 		if (error) {
405 			zend_type_error("Failed to create closure from callable: %s", error);
406 			efree(error);
407 		} else {
408 			zend_type_error("Failed to create closure from callable");
409 		}
410 	}
411 }
412 /* }}} */
413 
zend_closure_get_constructor(zend_object * object)414 static ZEND_COLD zend_function *zend_closure_get_constructor(zend_object *object) /* {{{ */
415 {
416 	zend_throw_error(NULL, "Instantiation of class Closure is not allowed");
417 	return NULL;
418 }
419 /* }}} */
420 
421 /* int return due to Object Handler API */
zend_closure_compare(zval * o1,zval * o2)422 static int zend_closure_compare(zval *o1, zval *o2) /* {{{ */
423 {
424 	ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
425 
426 	zend_closure *lhs = (zend_closure*) Z_OBJ_P(o1);
427 	zend_closure *rhs = (zend_closure*) Z_OBJ_P(o2);
428 
429 	if (!((lhs->func.common.fn_flags & ZEND_ACC_FAKE_CLOSURE) && (rhs->func.common.fn_flags & ZEND_ACC_FAKE_CLOSURE))) {
430 		return ZEND_UNCOMPARABLE;
431 	}
432 
433 	if (Z_TYPE(lhs->this_ptr) != Z_TYPE(rhs->this_ptr)) {
434 		return ZEND_UNCOMPARABLE;
435 	}
436 
437 	if (Z_TYPE(lhs->this_ptr) == IS_OBJECT && Z_OBJ(lhs->this_ptr) != Z_OBJ(rhs->this_ptr)) {
438 		return ZEND_UNCOMPARABLE;
439 	}
440 
441 	if (lhs->called_scope != rhs->called_scope) {
442 		return ZEND_UNCOMPARABLE;
443 	}
444 
445 	if (lhs->func.type != rhs->func.type) {
446 		return ZEND_UNCOMPARABLE;
447 	}
448 
449 	if (lhs->func.common.scope != rhs->func.common.scope) {
450 		return ZEND_UNCOMPARABLE;
451 	}
452 
453 	if (!zend_string_equals(lhs->func.common.function_name, rhs->func.common.function_name)) {
454 		return ZEND_UNCOMPARABLE;
455 	}
456 
457 	return 0;
458 }
459 /* }}} */
460 
zend_get_closure_invoke_method(zend_object * object)461 ZEND_API zend_function *zend_get_closure_invoke_method(zend_object *object) /* {{{ */
462 {
463 	zend_closure *closure = (zend_closure *)object;
464 	zend_function *invoke = (zend_function*)emalloc(sizeof(zend_function));
465 	const uint32_t keep_flags =
466 		ZEND_ACC_RETURN_REFERENCE | ZEND_ACC_VARIADIC | ZEND_ACC_HAS_RETURN_TYPE;
467 
468 	invoke->common = closure->func.common;
469 	/* We return ZEND_INTERNAL_FUNCTION, but arg_info representation is the
470 	 * same as for ZEND_USER_FUNCTION (uses zend_string* instead of char*).
471 	 * This is not a problem, because ZEND_ACC_HAS_TYPE_HINTS is never set,
472 	 * and we won't check arguments on internal function. We also set
473 	 * ZEND_ACC_USER_ARG_INFO flag to prevent invalid usage by Reflection */
474 	invoke->type = ZEND_INTERNAL_FUNCTION;
475 	invoke->internal_function.fn_flags =
476 		ZEND_ACC_PUBLIC | ZEND_ACC_CALL_VIA_HANDLER | (closure->func.common.fn_flags & keep_flags);
477 	if (closure->func.type != ZEND_INTERNAL_FUNCTION || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO)) {
478 		invoke->internal_function.fn_flags |=
479 			ZEND_ACC_USER_ARG_INFO;
480 	}
481 	invoke->internal_function.handler = ZEND_MN(Closure___invoke);
482 	invoke->internal_function.module = 0;
483 	invoke->internal_function.scope = zend_ce_closure;
484 	invoke->internal_function.function_name = ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE);
485 	return invoke;
486 }
487 /* }}} */
488 
zend_get_closure_method_def(zend_object * obj)489 ZEND_API const zend_function *zend_get_closure_method_def(zend_object *obj) /* {{{ */
490 {
491 	zend_closure *closure = (zend_closure *) obj;
492 	return &closure->func;
493 }
494 /* }}} */
495 
zend_get_closure_this_ptr(zval * obj)496 ZEND_API zval* zend_get_closure_this_ptr(zval *obj) /* {{{ */
497 {
498 	zend_closure *closure = (zend_closure *)Z_OBJ_P(obj);
499 	return &closure->this_ptr;
500 }
501 /* }}} */
502 
zend_closure_get_method(zend_object ** object,zend_string * method,const zval * key)503 static zend_function *zend_closure_get_method(zend_object **object, zend_string *method, const zval *key) /* {{{ */
504 {
505 	if (zend_string_equals_literal_ci(method, ZEND_INVOKE_FUNC_NAME)) {
506 		return zend_get_closure_invoke_method(*object);
507 	}
508 
509 	return zend_std_get_method(object, method, key);
510 }
511 /* }}} */
512 
zend_closure_free_storage(zend_object * object)513 static void zend_closure_free_storage(zend_object *object) /* {{{ */
514 {
515 	zend_closure *closure = (zend_closure *)object;
516 
517 	zend_object_std_dtor(&closure->std);
518 
519 	if (closure->func.type == ZEND_USER_FUNCTION) {
520 		/* We don't own the static variables of fake closures. */
521 		if (!(closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE)) {
522 			zend_destroy_static_vars(&closure->func.op_array);
523 			closure->func.op_array.static_variables = NULL;
524 		}
525 		destroy_op_array(&closure->func.op_array);
526 	} else if (closure->func.type == ZEND_INTERNAL_FUNCTION) {
527 		zend_string_release(closure->func.common.function_name);
528 	}
529 
530 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
531 		zval_ptr_dtor(&closure->this_ptr);
532 	}
533 }
534 /* }}} */
535 
zend_closure_new(zend_class_entry * class_type)536 static zend_object *zend_closure_new(zend_class_entry *class_type) /* {{{ */
537 {
538 	zend_closure *closure;
539 
540 	closure = emalloc(sizeof(zend_closure));
541 	memset(closure, 0, sizeof(zend_closure));
542 
543 	zend_object_std_init(&closure->std, class_type);
544 
545 	return (zend_object*)closure;
546 }
547 /* }}} */
548 
zend_closure_clone(zend_object * zobject)549 static zend_object *zend_closure_clone(zend_object *zobject) /* {{{ */
550 {
551 	zend_closure *closure = (zend_closure *)zobject;
552 	zval result;
553 
554 	zend_create_closure(&result, &closure->func,
555 		closure->func.common.scope, closure->called_scope, &closure->this_ptr);
556 	return Z_OBJ(result);
557 }
558 /* }}} */
559 
zend_closure_get_closure(zend_object * obj,zend_class_entry ** ce_ptr,zend_function ** fptr_ptr,zend_object ** obj_ptr,bool check_only)560 static zend_result zend_closure_get_closure(zend_object *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr, bool check_only) /* {{{ */
561 {
562 	zend_closure *closure = (zend_closure*)obj;
563 
564 	*fptr_ptr = &closure->func;
565 	*ce_ptr = closure->called_scope;
566 
567 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
568 		*obj_ptr = Z_OBJ(closure->this_ptr);
569 	} else {
570 		*obj_ptr = NULL;
571 	}
572 
573 	return SUCCESS;
574 }
575 /* }}} */
576 
577 /* *is_temp is int due to Object Handler API */
zend_closure_get_debug_info(zend_object * object,int * is_temp)578 static HashTable *zend_closure_get_debug_info(zend_object *object, int *is_temp) /* {{{ */
579 {
580 	zend_closure *closure = (zend_closure *)object;
581 	zval val;
582 	struct _zend_arg_info *arg_info = closure->func.common.arg_info;
583 	HashTable *debug_info;
584 	bool zstr_args = (closure->func.type == ZEND_USER_FUNCTION) || (closure->func.common.fn_flags & ZEND_ACC_USER_ARG_INFO);
585 
586 	*is_temp = 1;
587 
588 	debug_info = zend_new_array(8);
589 
590 	if (closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE) {
591 		if (closure->func.common.scope) {
592 			zend_string *class_name = closure->func.common.scope->name;
593 			zend_string *func_name = closure->func.common.function_name;
594 			zend_string *combined = zend_string_concat3(
595 				ZSTR_VAL(class_name), ZSTR_LEN(class_name),
596 				"::", strlen("::"),
597 				ZSTR_VAL(func_name), ZSTR_LEN(func_name)
598 			);
599 			ZVAL_STR(&val, combined);
600 		} else {
601 			ZVAL_STR_COPY(&val, closure->func.common.function_name);
602 		}
603 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_FUNCTION), &val);
604 	}
605 
606 	if (closure->func.type == ZEND_USER_FUNCTION && closure->func.op_array.static_variables) {
607 		zval *var;
608 		zend_string *key;
609 		HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
610 
611 		array_init(&val);
612 
613 		ZEND_HASH_MAP_FOREACH_STR_KEY_VAL(static_variables, key, var) {
614 			zval copy;
615 
616 			if (Z_ISREF_P(var) && Z_REFCOUNT_P(var) == 1) {
617 				var = Z_REFVAL_P(var);
618 			}
619 			ZVAL_COPY(&copy, var);
620 
621 			zend_hash_add_new(Z_ARRVAL(val), key, &copy);
622 		} ZEND_HASH_FOREACH_END();
623 
624 		if (zend_hash_num_elements(Z_ARRVAL(val))) {
625 			zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_STATIC), &val);
626 		} else {
627 			zval_ptr_dtor(&val);
628 		}
629 	}
630 
631 	if (Z_TYPE(closure->this_ptr) != IS_UNDEF) {
632 		Z_ADDREF(closure->this_ptr);
633 		zend_hash_update(debug_info, ZSTR_KNOWN(ZEND_STR_THIS), &closure->this_ptr);
634 	}
635 
636 	if (arg_info &&
637 		(closure->func.common.num_args ||
638 		 (closure->func.common.fn_flags & ZEND_ACC_VARIADIC))) {
639 		uint32_t i, num_args, required = closure->func.common.required_num_args;
640 
641 		array_init(&val);
642 
643 		num_args = closure->func.common.num_args;
644 		if (closure->func.common.fn_flags & ZEND_ACC_VARIADIC) {
645 			num_args++;
646 		}
647 		for (i = 0; i < num_args; i++) {
648 			zend_string *name;
649 			zval info;
650 			ZEND_ASSERT(arg_info->name && "Argument should have name");
651 			if (zstr_args) {
652 				name = zend_strpprintf(0, "%s$%s",
653 						ZEND_ARG_SEND_MODE(arg_info) ? "&" : "",
654 						ZSTR_VAL(arg_info->name));
655 			} else {
656 				name = zend_strpprintf(0, "%s$%s",
657 						ZEND_ARG_SEND_MODE(arg_info) ? "&" : "",
658 						((zend_internal_arg_info*)arg_info)->name);
659 			}
660 			ZVAL_NEW_STR(&info, zend_strpprintf(0, "%s", i >= required ? "<optional>" : "<required>"));
661 			zend_hash_update(Z_ARRVAL(val), name, &info);
662 			zend_string_release_ex(name, 0);
663 			arg_info++;
664 		}
665 		zend_hash_str_update(debug_info, "parameter", sizeof("parameter")-1, &val);
666 	}
667 
668 	return debug_info;
669 }
670 /* }}} */
671 
zend_closure_get_gc(zend_object * obj,zval ** table,int * n)672 static HashTable *zend_closure_get_gc(zend_object *obj, zval **table, int *n) /* {{{ */
673 {
674 	zend_closure *closure = (zend_closure *)obj;
675 
676 	*table = Z_TYPE(closure->this_ptr) != IS_NULL ? &closure->this_ptr : NULL;
677 	*n = Z_TYPE(closure->this_ptr) != IS_NULL ? 1 : 0;
678 	/* Fake closures don't own the static variables they reference. */
679 	return (closure->func.type == ZEND_USER_FUNCTION
680 			&& !(closure->func.op_array.fn_flags & ZEND_ACC_FAKE_CLOSURE)) ?
681 		ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr) : NULL;
682 }
683 /* }}} */
684 
685 /* {{{ Private constructor preventing instantiation */
ZEND_METHOD(Closure,__construct)686 ZEND_COLD ZEND_METHOD(Closure, __construct)
687 {
688 	zend_throw_error(NULL, "Instantiation of class Closure is not allowed");
689 }
690 /* }}} */
691 
zend_register_closure_ce(void)692 void zend_register_closure_ce(void) /* {{{ */
693 {
694 	zend_ce_closure = register_class_Closure();
695 	zend_ce_closure->create_object = zend_closure_new;
696 	zend_ce_closure->default_object_handlers = &closure_handlers;
697 
698 	memcpy(&closure_handlers, &std_object_handlers, sizeof(zend_object_handlers));
699 	closure_handlers.free_obj = zend_closure_free_storage;
700 	closure_handlers.get_constructor = zend_closure_get_constructor;
701 	closure_handlers.get_method = zend_closure_get_method;
702 	closure_handlers.compare = zend_closure_compare;
703 	closure_handlers.clone_obj = zend_closure_clone;
704 	closure_handlers.get_debug_info = zend_closure_get_debug_info;
705 	closure_handlers.get_closure = zend_closure_get_closure;
706 	closure_handlers.get_gc = zend_closure_get_gc;
707 }
708 /* }}} */
709 
ZEND_NAMED_FUNCTION(zend_closure_internal_handler)710 static ZEND_NAMED_FUNCTION(zend_closure_internal_handler) /* {{{ */
711 {
712 	zend_closure *closure = (zend_closure*)ZEND_CLOSURE_OBJECT(EX(func));
713 	closure->orig_internal_handler(INTERNAL_FUNCTION_PARAM_PASSTHRU);
714 	// Assign to EX(this) so that it is released after observer checks etc.
715 	ZEND_ADD_CALL_FLAG(execute_data, ZEND_CALL_RELEASE_THIS);
716 	Z_OBJ(EX(This)) = &closure->std;
717 }
718 /* }}} */
719 
zend_create_closure_ex(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr,bool is_fake)720 static void zend_create_closure_ex(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr, bool is_fake) /* {{{ */
721 {
722 	zend_closure *closure;
723 	void *ptr;
724 
725 	object_init_ex(res, zend_ce_closure);
726 
727 	closure = (zend_closure *)Z_OBJ_P(res);
728 
729 	if ((scope == NULL) && this_ptr && (Z_TYPE_P(this_ptr) != IS_UNDEF)) {
730 		/* use dummy scope if we're binding an object without specifying a scope */
731 		/* maybe it would be better to create one for this purpose */
732 		scope = zend_ce_closure;
733 	}
734 
735 	if (func->type == ZEND_USER_FUNCTION) {
736 		memcpy(&closure->func, func, sizeof(zend_op_array));
737 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
738 		closure->func.common.fn_flags &= ~ZEND_ACC_IMMUTABLE;
739 
740 		zend_string_addref(closure->func.op_array.function_name);
741 		if (closure->func.op_array.refcount) {
742 			(*closure->func.op_array.refcount)++;
743 		}
744 
745 		/* For fake closures, we want to reuse the static variables of the original function. */
746 		if (!is_fake) {
747 			if (closure->func.op_array.static_variables) {
748 				closure->func.op_array.static_variables =
749 					zend_array_dup(closure->func.op_array.static_variables);
750 			}
751 			ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr,
752 				closure->func.op_array.static_variables);
753 		} else if (func->op_array.static_variables) {
754 			HashTable *ht = ZEND_MAP_PTR_GET(func->op_array.static_variables_ptr);
755 
756 			if (!ht) {
757 				ht = zend_array_dup(func->op_array.static_variables);
758 				ZEND_MAP_PTR_SET(func->op_array.static_variables_ptr, ht);
759 			}
760 			ZEND_MAP_PTR_INIT(closure->func.op_array.static_variables_ptr, ht);
761 		}
762 
763 		/* Runtime cache is scope-dependent, so we cannot reuse it if the scope changed */
764 		ptr = ZEND_MAP_PTR_GET(func->op_array.run_time_cache);
765 		if (!ptr
766 			|| func->common.scope != scope
767 			|| (func->common.fn_flags & ZEND_ACC_HEAP_RT_CACHE)
768 		) {
769 			if (!ptr
770 			 && (func->common.fn_flags & ZEND_ACC_CLOSURE)
771 			 && (func->common.scope == scope ||
772 			     !(func->common.fn_flags & ZEND_ACC_IMMUTABLE))) {
773 				/* If a real closure is used for the first time, we create a shared runtime cache
774 				 * and remember which scope it is for. */
775 				if (func->common.scope != scope) {
776 					func->common.scope = scope;
777 				}
778 				ptr = zend_arena_alloc(&CG(arena), func->op_array.cache_size);
779 				ZEND_MAP_PTR_SET(func->op_array.run_time_cache, ptr);
780 				closure->func.op_array.fn_flags &= ~ZEND_ACC_HEAP_RT_CACHE;
781 			} else {
782 				/* Otherwise, we use a non-shared runtime cache */
783 				ptr = emalloc(func->op_array.cache_size);
784 				closure->func.op_array.fn_flags |= ZEND_ACC_HEAP_RT_CACHE;
785 			}
786 			memset(ptr, 0, func->op_array.cache_size);
787 		}
788 		ZEND_MAP_PTR_INIT(closure->func.op_array.run_time_cache, ptr);
789 	} else {
790 		memcpy(&closure->func, func, sizeof(zend_internal_function));
791 		closure->func.common.fn_flags |= ZEND_ACC_CLOSURE;
792 		/* wrap internal function handler to avoid memory leak */
793 		if (UNEXPECTED(closure->func.internal_function.handler == zend_closure_internal_handler)) {
794 			/* avoid infinity recursion, by taking handler from nested closure */
795 			zend_closure *nested = (zend_closure*)((char*)func - XtOffsetOf(zend_closure, func));
796 			ZEND_ASSERT(nested->std.ce == zend_ce_closure);
797 			closure->orig_internal_handler = nested->orig_internal_handler;
798 		} else {
799 			closure->orig_internal_handler = closure->func.internal_function.handler;
800 		}
801 		closure->func.internal_function.handler = zend_closure_internal_handler;
802 		zend_string_addref(closure->func.op_array.function_name);
803 		if (!func->common.scope) {
804 			/* if it's a free function, we won't set scope & this since they're meaningless */
805 			this_ptr = NULL;
806 			scope = NULL;
807 		}
808 	}
809 
810 	ZVAL_UNDEF(&closure->this_ptr);
811 	/* Invariant:
812 	 * If the closure is unscoped or static, it has no bound object. */
813 	closure->func.common.scope = scope;
814 	closure->called_scope = called_scope;
815 	if (scope) {
816 		closure->func.common.fn_flags |= ZEND_ACC_PUBLIC;
817 		if (this_ptr && Z_TYPE_P(this_ptr) == IS_OBJECT && (closure->func.common.fn_flags & ZEND_ACC_STATIC) == 0) {
818 			ZVAL_OBJ_COPY(&closure->this_ptr, Z_OBJ_P(this_ptr));
819 		}
820 	}
821 }
822 /* }}} */
823 
zend_create_closure(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr)824 ZEND_API void zend_create_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr)
825 {
826 	zend_create_closure_ex(res, func, scope, called_scope, this_ptr,
827 		/* is_fake */ (func->common.fn_flags & ZEND_ACC_FAKE_CLOSURE) != 0);
828 }
829 
zend_create_fake_closure(zval * res,zend_function * func,zend_class_entry * scope,zend_class_entry * called_scope,zval * this_ptr)830 ZEND_API void zend_create_fake_closure(zval *res, zend_function *func, zend_class_entry *scope, zend_class_entry *called_scope, zval *this_ptr) /* {{{ */
831 {
832 	zend_closure *closure;
833 
834 	zend_create_closure_ex(res, func, scope, called_scope, this_ptr, /* is_fake */ true);
835 
836 	closure = (zend_closure *)Z_OBJ_P(res);
837 	closure->func.common.fn_flags |= ZEND_ACC_FAKE_CLOSURE;
838 }
839 /* }}} */
840 
841 /* __call and __callStatic name the arguments "$arguments" in the docs. */
842 static zend_internal_arg_info trampoline_arg_info[] = {ZEND_ARG_VARIADIC_TYPE_INFO(false, arguments, IS_MIXED, false)};
843 
zend_closure_from_frame(zval * return_value,zend_execute_data * call)844 void zend_closure_from_frame(zval *return_value, zend_execute_data *call) { /* {{{ */
845 	zval instance;
846 	zend_internal_function trampoline;
847 	zend_function *mptr = call->func;
848 
849 	if (ZEND_CALL_INFO(call) & ZEND_CALL_CLOSURE) {
850 		RETURN_OBJ(ZEND_CLOSURE_OBJECT(mptr));
851 	}
852 
853 	if (mptr->common.fn_flags & ZEND_ACC_CALL_VIA_TRAMPOLINE) {
854 		if ((ZEND_CALL_INFO(call) & ZEND_CALL_HAS_THIS) &&
855 			(Z_OBJCE(call->This) == zend_ce_closure)
856 			&& zend_string_equals(mptr->common.function_name, ZSTR_KNOWN(ZEND_STR_MAGIC_INVOKE))) {
857 	        zend_free_trampoline(mptr);
858 	        RETURN_OBJ_COPY(Z_OBJ(call->This));
859 	    }
860 
861 		memset(&trampoline, 0, sizeof(zend_internal_function));
862 		trampoline.type = ZEND_INTERNAL_FUNCTION;
863 		trampoline.fn_flags = mptr->common.fn_flags & (ZEND_ACC_STATIC | ZEND_ACC_VARIADIC);
864 		trampoline.handler = zend_closure_call_magic;
865 		trampoline.function_name = mptr->common.function_name;
866 		trampoline.scope = mptr->common.scope;
867 		if (trampoline.fn_flags & ZEND_ACC_VARIADIC) {
868 			trampoline.arg_info = trampoline_arg_info;
869 		}
870 
871 		zend_free_trampoline(mptr);
872 		mptr = (zend_function *) &trampoline;
873 	}
874 
875 	if (ZEND_CALL_INFO(call) & ZEND_CALL_HAS_THIS) {
876 		ZVAL_OBJ(&instance, Z_OBJ(call->This));
877 
878 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, Z_OBJCE(instance), &instance);
879 	} else {
880 		zend_create_fake_closure(return_value, mptr, mptr->common.scope, Z_CE(call->This), NULL);
881 	}
882 
883 	if (&mptr->internal_function == &trampoline) {
884 		zend_string_release(mptr->common.function_name);
885 	}
886 } /* }}} */
887 
zend_closure_bind_var(zval * closure_zv,zend_string * var_name,zval * var)888 void zend_closure_bind_var(zval *closure_zv, zend_string *var_name, zval *var) /* {{{ */
889 {
890 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
891 	HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
892 	zend_hash_update(static_variables, var_name, var);
893 }
894 /* }}} */
895 
zend_closure_bind_var_ex(zval * closure_zv,uint32_t offset,zval * val)896 void zend_closure_bind_var_ex(zval *closure_zv, uint32_t offset, zval *val) /* {{{ */
897 {
898 	zend_closure *closure = (zend_closure *) Z_OBJ_P(closure_zv);
899 	HashTable *static_variables = ZEND_MAP_PTR_GET(closure->func.op_array.static_variables_ptr);
900 	zval *var = (zval*)((char*)static_variables->arData + offset);
901 	zval_ptr_dtor(var);
902 	ZVAL_COPY_VALUE(var, val);
903 }
904 /* }}} */
905